/** * Putting the bar on a page. * * One `` } /** A full, uncompressed HTML document: the only response the script goes into. */ export function isInjectableDocument(response: Response): boolean { if (!response.body || response.status === 204 || response.status === 304) return false if (response.headers.has('content-encoding')) return false if (response.headers.get('x-stx-fragment') === 'true') return false return response.headers.get('content-type')?.toLowerCase().startsWith('text/html') === true } /** * The response with the bar's script appended to its ``, or undefined * when it is not a document the script belongs in. * * Streamed through `HTMLRewriter`, so the page is not buffered, and an HTML * response with no `` (a partial some handler returned as `text/html`) * passes through untouched. */ export function injectDebugbar(response: Response, options: InjectOptions): Response | undefined { if (!isInjectableDocument(response)) return undefined const script = debugbarScriptTag(options) let done = false const rewritten = new HTMLRewriter().on('body', { element(body) { if (done) return done = true body.append(script, { html: true }) }, }).transform(response) rewritten.headers.delete('content-length') return rewritten } /** * `response` carrying the record id, as `X-Debugbar-Id` and as a * `Server-Timing` entry. * * The second is for requests a page makes before the bar's script has run: * the bar cannot have been watching them, but the browser keeps each * response's `Server-Timing` on its resource timing entry, where the bar * finds the id afterwards. */ export function withRecordId(response: Response, id: string): Response { const stamped = withHeader(response, DEBUGBAR_ID_HEADER, id) const timing = stamped.headers.get('server-timing') const entry = `debugbar;desc="${id}"` return withHeader(stamped, 'Server-Timing', timing ? `${timing}, ${entry}` : entry) } /** `response` carrying `name: value`, copied when its headers cannot be written. */ export function withHeader(response: Response, name: string, value: string): Response { try { response.headers.set(name, value) return response } catch { const headers = new Headers(response.headers) headers.set(name, value) return new Response(response.body, { status: response.status, statusText: response.statusText, headers }) } }