|
| 1 | +import invariant from "invariant"; |
| 2 | +import type { JsonValue } from "type-fest"; |
| 3 | + |
| 4 | +import { jsonParseSafe } from "@code-chronicles/util/jsonParseSafe"; |
| 5 | + |
| 6 | +type ProxiedPropertyKey = "innerHTML" | "innerText" | "textContent"; |
| 7 | + |
| 8 | +type MiddlewareFn = ( |
| 9 | + data: JsonValue, |
| 10 | + script: HTMLScriptElement, |
| 11 | + property: ProxiedPropertyKey, |
| 12 | +) => JsonValue; |
| 13 | + |
| 14 | +function inject<TProto extends { constructor: Function }>( |
| 15 | + proto: TProto, |
| 16 | + property: ProxiedPropertyKey, |
| 17 | + middlewareFn: MiddlewareFn, |
| 18 | +): void { |
| 19 | + const prevDescriptor = Object.getOwnPropertyDescriptor(proto, property); |
| 20 | + |
| 21 | + invariant( |
| 22 | + prevDescriptor && prevDescriptor.get, |
| 23 | + `\`${proto.constructor.name}.prototype.${property}\` property descriptor didn't have the expected form!`, |
| 24 | + ); |
| 25 | + const prevDescriptorGet = prevDescriptor.get; |
| 26 | + |
| 27 | + Object.defineProperty(HTMLScriptElement.prototype, property, { |
| 28 | + ...prevDescriptor, |
| 29 | + get(this: HTMLScriptElement) { |
| 30 | + const data = prevDescriptorGet.call(this); |
| 31 | + |
| 32 | + // If the data doesn't parse as JSON, we pass it through unchanged. |
| 33 | + // If it does parse as JSON, we'll run the middleware. |
| 34 | + const parsedData = jsonParseSafe(data); |
| 35 | + if (parsedData) { |
| 36 | + return JSON.stringify(middlewareFn(parsedData.data, this, property)); |
| 37 | + } |
| 38 | + |
| 39 | + return data; |
| 40 | + }, |
| 41 | + }); |
| 42 | +} |
| 43 | + |
| 44 | +/** |
| 45 | + * Injects a function to process and possibly replace JSON data stored within |
| 46 | + * <script> tags. The middleware will run when properties such as `innerHTML` |
| 47 | + * get accessed, and it must return the possibly updated JSON data. |
| 48 | + */ |
| 49 | +export function injectJsonScriptMiddleware(middlewareFn: MiddlewareFn): void { |
| 50 | + inject(Element.prototype, "innerHTML", middlewareFn); |
| 51 | + inject(HTMLElement.prototype, "innerText", middlewareFn); |
| 52 | + inject(Node.prototype, "textContent", middlewareFn); |
| 53 | +} |
0 commit comments