|
| 1 | +import { resolve } from "node:path"; |
| 2 | +import type { StudioApiAdapter } from "../types.js"; |
| 3 | +import { |
| 4 | + createMediaCodecProbeCache, |
| 5 | + scanProjectMediaCodecMap, |
| 6 | + type HtmlSourceLike, |
| 7 | + type MediaCodecMap, |
| 8 | + type MediaCodecProbeCache, |
| 9 | +} from "./mediaCodecMap.js"; |
| 10 | +import { resolveProxy, PROXY_PARAMS_VERSION } from "./proxyTranscoder.js"; |
| 11 | + |
| 12 | +/** |
| 13 | + * Transparent-media-proxy wiring shared by `routes/preview.ts` |
| 14 | + * (docs/plans/2026-07-14-002-feat-transparent-media-proxies-plan.md, unit U3). |
| 15 | + * Split out of the route module to keep it under the repo's 600-line file cap. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * Preview-route-local adapter surface for the auto-proxy feature. Both |
| 20 | + * fields are optional so any existing `StudioApiAdapter` value remains |
| 21 | + * structurally assignable without editing the shared interface: |
| 22 | + * `autoProxy` defaults to true (on) when omitted — a later unit wires the |
| 23 | + * CLI `--no-proxy` flag / `hyperframes.json` setting through it; |
| 24 | + * `mediaCodecProbeCache` lets a host share one probe cache across |
| 25 | + * preview/play/static-server surfaces instead of each constructing its own. |
| 26 | + */ |
| 27 | +export type PreviewApiAdapter = StudioApiAdapter & { |
| 28 | + autoProxy?: boolean; |
| 29 | + mediaCodecProbeCache?: MediaCodecProbeCache; |
| 30 | +}; |
| 31 | + |
| 32 | +export function isAutoProxyEnabled(adapter: PreviewApiAdapter): boolean { |
| 33 | + return adapter.autoProxy !== false; |
| 34 | +} |
| 35 | + |
| 36 | +/** One probe cache per server instance — construct once in `registerPreviewRoutes` |
| 37 | + * and reuse across every request so the mtime-cache benefit in |
| 38 | + * `scanProjectMediaCodecMap` actually applies. A host that wants to share the |
| 39 | + * cache across other surfaces (play, static project server) can pass its own |
| 40 | + * via `adapter.mediaCodecProbeCache`. */ |
| 41 | +export function resolvePreviewMediaCodecProbeCache( |
| 42 | + adapter: PreviewApiAdapter, |
| 43 | +): MediaCodecProbeCache { |
| 44 | + return adapter.mediaCodecProbeCache ?? createMediaCodecProbeCache(); |
| 45 | +} |
| 46 | + |
| 47 | +/** |
| 48 | + * ETag salt for `?hf-proxy=` asset requests, mirroring `variablesEtagSalt` in |
| 49 | + * preview.ts: salted by the raw param value plus the transcoder's params |
| 50 | + * version, so a future proxy-recipe change (which bumps `PROXY_PARAMS_VERSION`) |
| 51 | + * or a different proxy variant invalidates cached 304s without needing to |
| 52 | + * touch the proxy file itself. |
| 53 | + */ |
| 54 | +export function proxyEtagSalt(raw: string | undefined): string { |
| 55 | + if (raw === undefined) return ""; |
| 56 | + return `:proxy:${raw}:${PROXY_PARAMS_VERSION}`; |
| 57 | +} |
| 58 | + |
| 59 | +// Mirrors `injectScriptTagIntoHead` in routes/preview.ts (kept local rather |
| 60 | +// than imported to avoid a helpers → routes dependency edge for one |
| 61 | +// two-line utility). |
| 62 | +function injectScriptTagIntoHead(html: string, scriptTag: string): string { |
| 63 | + if (html.includes("</head>")) return html.replace("</head>", `${scriptTag}\n</head>`); |
| 64 | + return `${scriptTag}\n${html}`; |
| 65 | +} |
| 66 | + |
| 67 | +/** |
| 68 | + * Injects `window.__HF_MEDIA_CODEC_MAP__` (the U1 codec-facts scan) into |
| 69 | + * served composition HTML, and fire-and-forget pre-warms `resolveProxy` for |
| 70 | + * every browser-hostile entry so an element's proactive swap usually hits a |
| 71 | + * warm cache (KTD: protects the per-origin connection budget under held |
| 72 | + * responses). No second concurrency limiter here — the transcoder's own |
| 73 | + * global bound throttles both pre-warm and element-triggered calls. |
| 74 | + * Pre-warm failures are swallowed; an actual `?hf-proxy=` request surfaces |
| 75 | + * them as a 502. Alpha-bearing entries are never pre-warmed: the runtime |
| 76 | + * never proxies them (transparency would be destroyed). |
| 77 | + * |
| 78 | + * The single shared implementation for every auto-proxy surface — the studio |
| 79 | + * preview route (via `injectMediaCodecMap` below) and the CLI's composition / |
| 80 | + * static project servers (via the `./media-proxy-preview` subpath export). |
| 81 | + * Empty maps leave HTML untouched, preserving the normal no-hostile-media |
| 82 | + * preview path. On-demand proxy requests enforce the same eligibility gate. |
| 83 | + */ |
| 84 | +export async function injectMediaCodecMapIntoHtml( |
| 85 | + html: string, |
| 86 | + projectDir: string, |
| 87 | + htmlSources: HtmlSourceLike[], |
| 88 | + probeCache?: MediaCodecProbeCache, |
| 89 | +): Promise<string> { |
| 90 | + let map: MediaCodecMap; |
| 91 | + try { |
| 92 | + map = await scanProjectMediaCodecMap( |
| 93 | + projectDir, |
| 94 | + htmlSources, |
| 95 | + probeCache ? { cache: probeCache } : {}, |
| 96 | + ); |
| 97 | + } catch { |
| 98 | + // Best-effort: a scan failure must never block serving the page. |
| 99 | + return html; |
| 100 | + } |
| 101 | + if (Object.keys(map).length === 0) return html; |
| 102 | + for (const [rootRelativePathname, facts] of Object.entries(map)) { |
| 103 | + if (!facts.browserHostile || facts.hasAlpha) continue; |
| 104 | + resolveProxy(projectDir, resolve(projectDir, rootRelativePathname.replace(/^\/+/, ""))).catch( |
| 105 | + () => { |
| 106 | + // Swallowed: the pre-warm is best-effort. A real `?hf-proxy=` request |
| 107 | + // for this asset re-attempts the transcode and reports failure (502). |
| 108 | + }, |
| 109 | + ); |
| 110 | + } |
| 111 | + // <-escape prevents a src path containing "</script>" from breaking out of |
| 112 | + // the injected tag, mirroring injectPreviewVariables in routes/preview.ts. |
| 113 | + const json = JSON.stringify(map) |
| 114 | + .replace(/</g, "\\u003c") |
| 115 | + .replace(/\u2028/g, "\\u2028") |
| 116 | + .replace(/\u2029/g, "\\u2029"); |
| 117 | + const tag = `<script data-hf-media-codec-map>window.__HF_MEDIA_CODEC_MAP__=${json};</script>`; |
| 118 | + return injectScriptTagIntoHead(html, tag); |
| 119 | +} |
| 120 | + |
| 121 | +/** |
| 122 | + * Adapter-aware wrapper used by the studio preview routes: skipped entirely |
| 123 | + * (no scan, no injection) when auto-proxy is off for this adapter. |
| 124 | + */ |
| 125 | +export async function injectMediaCodecMap( |
| 126 | + html: string, |
| 127 | + adapter: PreviewApiAdapter, |
| 128 | + projectDir: string, |
| 129 | + compSrcPath: string, |
| 130 | + probeCache: MediaCodecProbeCache, |
| 131 | +): Promise<string> { |
| 132 | + if (!isAutoProxyEnabled(adapter)) return html; |
| 133 | + return injectMediaCodecMapIntoHtml(html, projectDir, [{ html, compSrcPath }], probeCache); |
| 134 | +} |
0 commit comments