import { acceleratedCanvasTrackerSource } from "../pageMotionBlur.js"; import { findSceneTemplate, templateContent } from "@hyperframes/parsers/sub-composition-validity"; import { parseHTML } from "linkedom"; export const RUNTIME_BOOTSTRAP_ATTR = "data-hyperframes-preview-runtime"; const RUNTIME_FILES = [ "hyperframe.runtime.iife.js", "hyperframes-runtime.modular.inline.js", "hyperframe-runtime.modular-runtime.inline.js", ]; const SIMPLE_RUNTIME_FLAG_ASSIGNMENTS = [ /^window\.__playerReady\s*=\s*(?:true|false)\s*;?$/, /^window\.__renderReady\s*=\s*(?:true|false)\s*;?$/, ]; const LEADING_COMMENTS = /^(?:\s|))*/; export interface SceneRootLookup { root: Element | null; hasTemplate: boolean; hasLiveRoot: boolean; } export function locateSceneRoot(html: string): SceneRootLookup { const { document } = parseHTML(html); const liveRoot = document.querySelector("[data-composition-id]") as Element | null; const templates = Array.from(document.querySelectorAll("template")); const scene = findSceneTemplate(templates); const sceneRoot = (scene && templateContent(scene)?.querySelector("[data-composition-id]")) ?? null; return { root: sceneRoot, hasTemplate: templates.length > 0, hasLiveRoot: liveRoot !== null, }; } export function isTemplateEntry(html: string): boolean { const { root, hasTemplate, hasLiveRoot } = locateSceneRoot(html); return hasTemplate && root !== null && !hasLiveRoot; } export function isFullHtmlDocument(html: string): boolean { return /^(?:/])/i.test(html.replace(LEADING_COMMENTS, "")); } /** * Parse a full HTML document or wrap a fragment so linkedom consistently puts * fragment content under document.body. */ export function parseHTMLContent(html: string): Document { if (isFullHtmlDocument(html)) { return parseHTML(html).document; } return parseHTML(`${html}`).document; } /** ASCII-only chunks bound match arrays; starting at uppercase preserves unchanged spans. */ function lowerAscii(text: string): string { return text.replace(/[A-Z][\s\S]{0,65535}/g, (chunk) => chunk.replace(/[A-Z]+/g, (letters) => letters.toLowerCase()), ); } function startsWithLower(text: string, token: string, at: number): boolean { if (at < 0 || at + token.length > text.length) return false; for (let i = 0; i < token.length; i += 1) { const code = text.charCodeAt(at + i); if ((code >= 65 && code <= 90 ? code + 32 : code) !== token.charCodeAt(i)) return false; } return true; } function indexOfLower(text: string, token: string, from: number): number { for ( let at = text.indexOf(token.charAt(0), from); at !== -1; at = text.indexOf(token.charAt(0), at + 1) ) { if (startsWithLower(text, token, at)) return at; } return -1; } function lastIndexOfLower(text: string, token: string): number { for ( let at = text.lastIndexOf(token.charAt(0)); at !== -1; at = at === 0 ? -1 : text.lastIndexOf(token.charAt(0), at - 1) ) { if (startsWithLower(text, token, at)) return at; } return -1; } export function stripEmbeddedRuntimeScripts(html: string): string { if (!html) return html; let output = ""; let cursor = 0; while (cursor < html.length) { const scriptStart = findScriptStart(html, cursor); if (scriptStart === -1) { output += html.slice(cursor); break; } output += html.slice(cursor, scriptStart); const startTagEnd = findTagEnd(html, scriptStart + 1); if (startTagEnd === -1) { output += html.slice(scriptStart); break; } const closeTagEnd = findScriptCloseTagEnd(html, startTagEnd + 1); const scriptEnd = closeTagEnd === -1 ? html.length : closeTagEnd; const block = html.slice(scriptStart, scriptEnd); if (!shouldStripRuntimeScriptBlock(block, html.slice(scriptStart, startTagEnd + 1))) { output += block; } cursor = scriptEnd; } return output; } function findScriptStart(html: string, from: number): number { let index = indexOfLower(html, "") return index; if (state === "equals" && (char === '"' || char === "'")) { quote = char; state = "between"; continue; } state = nextTagState(state, char, index === from); } return -1; } function nextTagState(state: TagState, char: string, first: boolean): TagState { if (isHtmlWhitespace(char)) return stateAfterWhitespace(state); if (char === "/" && !first) return stateAfterSlash(state); if (char === "=" && state === "name") return "equals"; if (state === "equals") return "value"; return state === "between" ? "name" : state; } function stateAfterWhitespace(state: TagState): TagState { return state === "tagName" || state === "value" ? "between" : state; } function stateAfterSlash(state: TagState): TagState { return state === "equals" || state === "value" ? "value" : "between"; } function findScriptCloseTagEnd(html: string, from: number): number { let index = indexOfLower(html, "" ? cursor + 1 : -1; } function shouldStripRuntimeScriptBlock(block: string, startTag: string): boolean { const script = parseHTML(`${startTag}`).document.querySelector("script"); if ( script?.hasAttribute(RUNTIME_BOOTSTRAP_ATTR) || isRuntimeFileUrl(script?.getAttribute("src")) ) { return true; } const scriptSource = getScriptSource(block).trim(); return SIMPLE_RUNTIME_FLAG_ASSIGNMENTS.some((pattern) => pattern.test(scriptSource)); } export function isRuntimeFileUrl(src: string | null | undefined): boolean { const path = lowerAscii(src?.split(/[?#]/, 1)[0] ?? ""); return RUNTIME_FILES.some((file) => path === file || path.endsWith(`/${file}`)); } function getScriptSource(block: string): string { const startTagEnd = findTagEnd(block, 1); if (startTagEnd === -1) return ""; const closeTagStart = lastIndexOfLower(block, "" || char === "/" || isHtmlWhitespace(char); } function isHtmlWhitespace(char: string): boolean { return char === " " || char === "\n" || char === "\t" || char === "\r" || char === "\f"; } export function escapeInlineScriptSource(source: string): string { return escapeCaseInsensitiveToken( escapeCaseInsensitiveToken(source, " `<\\/${match.slice(2)}`), "", open) || html.startsWith("", open)) { return html.indexOf(">", open) + 1; } COMMENT_END.lastIndex = open + 4; const end = COMMENT_END.exec(html); return end ? end.index + end[0].length : -1; } function skipRawText( html: string, open: number, tagEnd: number, unclosedRawText: Set, ): number { const rawText = RAW_TEXT_TAGS.find((name) => isTagAt(html, open, `<${name}`)); if (!rawText) return tagEnd + 1; const close = unclosedRawText.has(rawText) ? -1 : findRawTextClose(html, rawText, tagEnd + 1); if (close !== -1) return close; unclosedRawText.add(rawText); return html.charAt(tagEnd - 1) === "/" ? tagEnd + 1 : -1; } function findRawTextClose(html: string, name: string, from: number): number { const close = ` isTagAt(html, open, " 0) idInTemplate = true; else if (isDocumentWrapper(html, open)) idOnWrapper = true; else return true; } } return idOnWrapper && !idInTemplate; } function insertBeforeDocumentTag(html: string, tag: DocumentTag, markup: string): string | null { const at = tag === "`, `` or ``; null if it has none. */ export function insertBeforeCloseTag( html: string, name: "head" | "body" | "template", markup: string, ): string | null { return insertBeforeDocumentTag(html, `]*>/i); if (htmlOpenMatch?.index != null) { const insertPos = htmlOpenMatch.index + htmlOpenMatch[0].length; return `${html.slice(0, insertPos)}${tag}${html.slice(insertPos)}`; } const doctypeIdx = indexOfLower(html, "= 0) { const insertPos = html.indexOf(">", doctypeIdx) + 1; return html.slice(0, insertPos) + tag + html.slice(insertPos); } return tag + html; } const ACCEL_TRACKER_ATTR = "data-hf-accel-tracker"; const OPTS_INTO_MOTION_BLUR = /\sdata-motion-blur\s*=\s*["']?on[\s"'>]/i; export function insertRuntimeTag(html: string, tag: string, atHeadStart = false): string { const withRuntime = atHeadStart ? injectTagsAtHeadStart(html, tag) : insertTagInHead(html, tag); if (!OPTS_INTO_MOTION_BLUR.test(html) || html.includes(ACCEL_TRACKER_ATTR)) return withRuntime; const tracker = ``; return injectTagsAtHeadStart(withRuntime, tracker); } /** * Insert raw tag markup at the very start of ``, ahead of every author * script (inline or external). Falls back to just before ``, then to the * top of the document, for fragments that carry neither. */ export function injectTagsAtHeadStart(html: string, tags: string): string { const headOpen = findDocumentTag(html, " 0) { const headTags = inlineScriptTags(headScripts); const withHead = insertBeforeCloseTag(html, "head", `${headTags}\n`); html = withHead ?? insertBeforeDocumentTag(html, " 0) { const bodyTags = inlineScriptTags(bodyScripts); html = insertBeforeCloseTag(html, "body", `${bodyTags}\n`) ?? `${html}\n${bodyTags}`; } return html; }