-
Notifications
You must be signed in to change notification settings - Fork 8
GPT integration #282
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
GPT integration #282
Changes from all commits
df9fbdd
597bef9
132e160
b72c02b
5adf82d
e98e4ba
7a05e33
b3900a0
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,167 @@ | ||
| import { log } from '../../core/log'; | ||
|
|
||
| import { installGptGuard } from './script_guard'; | ||
|
|
||
| /** | ||
| * Google Publisher Tags (GPT) Integration Shim | ||
| * | ||
| * Hooks into the googletag.cmd command queue so the Trusted Server can | ||
| * observe and augment ad-slot definitions before GPT processes them. | ||
| * The shim ensures the googletag stub exists early (matching GPT's own | ||
| * bootstrap pattern) and patches `cmd.push` to wrap queued callbacks. | ||
| * | ||
| * Current capabilities: | ||
| * - Installs a script guard that rewrites dynamically inserted GPT | ||
| * `<script>` elements to the first-party proxy endpoint. | ||
| * - Takes over the `googletag.cmd` array so that every callback runs | ||
| * through a wrapper that can inject targeting, logging, or consent | ||
| * signals before the real GPT processes the command. | ||
| * | ||
| * Future enhancements (driven by config or tsjs API): | ||
| * - Inject synthetic ID as page-level key-value targeting. | ||
| * - Gate ad requests on consent status. | ||
| * - Rewrite ad-unit paths for A/B testing. | ||
| */ | ||
|
|
||
| // ------------------------------------------------------------------ | ||
| // googletag type stubs (minimal surface needed by the shim) | ||
| // ------------------------------------------------------------------ | ||
|
|
||
| interface GoogleTagSlot { | ||
| getAdUnitPath(): string; | ||
| getSlotElementId(): string; | ||
| setTargeting(key: string, value: string | string[]): GoogleTagSlot; | ||
| } | ||
|
|
||
| interface GoogleTagPubAdsService { | ||
| setTargeting(key: string, value: string | string[]): GoogleTagPubAdsService; | ||
| getTargeting(key: string): string[]; | ||
| enableSingleRequest(): void; | ||
| } | ||
|
|
||
| interface GoogleTag { | ||
| cmd: Array<() => void>; | ||
| pubads(): GoogleTagPubAdsService; | ||
| defineSlot( | ||
| adUnitPath: string, | ||
| size: Array<number | number[]>, | ||
| elementId: string | ||
| ): GoogleTagSlot | null; | ||
| enableServices(): void; | ||
| display(elementId: string): void; | ||
| _loaded_?: boolean; | ||
| } | ||
|
|
||
| type GptWindow = Window & { | ||
| googletag?: Partial<GoogleTag>; | ||
| }; | ||
|
|
||
| // ------------------------------------------------------------------ | ||
| // Shim implementation | ||
| // ------------------------------------------------------------------ | ||
|
|
||
| /** | ||
| * Ensure the `googletag` stub exists on `window`. | ||
| * | ||
| * This mirrors the official GPT bootstrap snippet: | ||
| * ```js | ||
| * window.googletag = window.googletag || {}; | ||
| * googletag.cmd = googletag.cmd || []; | ||
| * ``` | ||
| * By running before the publisher's own snippet we can patch `cmd` early. | ||
| */ | ||
| function ensureGoogleTagStub(win: GptWindow): Partial<GoogleTag> { | ||
| const tag = (win.googletag = win.googletag ?? {}); | ||
| tag.cmd = tag.cmd ?? []; | ||
| return tag; | ||
| } | ||
|
|
||
| /** | ||
| * Wrap a queued GPT callback to add instrumentation and future hook points. | ||
| * | ||
| * Today the wrapper only logs; as the integration matures it will inject | ||
| * synthetic ID targeting and consent gates. | ||
| */ | ||
| function wrapCommand(fn: () => void): () => void { | ||
| return () => { | ||
| try { | ||
| fn(); | ||
| } catch (err) { | ||
| log.error('GPT shim: queued command threw', err); | ||
| } | ||
| }; | ||
| } | ||
|
|
||
| /** | ||
| * Patch `googletag.cmd` so every pushed callback runs through [`wrapCommand`]. | ||
| * | ||
| * Preserves the existing `tag.cmd` array identity so that GPT's own custom | ||
| * `cmd.push` behaviour (immediate execution when the library is already | ||
| * loaded) is not lost. The original `push` is saved and delegated to after | ||
| * wrapping each callback. | ||
| * | ||
| * Already-queued callbacks are re-wrapped in place so GPT processes them | ||
| * through our wrapper when it drains the queue. | ||
| */ | ||
| function patchCommandQueue(tag: Partial<GoogleTag>): void { | ||
| // Ensure the queue exists. | ||
| if (!Array.isArray(tag.cmd)) { | ||
| tag.cmd = []; | ||
| } | ||
|
|
||
| const queue = tag.cmd; | ||
|
|
||
| // Guard against double-patching (idempotent install). | ||
| if ((queue as { __tsPushed?: boolean }).__tsPushed) { | ||
| log.debug('GPT shim: command queue already patched, skipping'); | ||
| return; | ||
| } | ||
|
|
||
| const originalPush = queue.push.bind(queue); | ||
|
|
||
| // Override push on the *existing* array — preserves object identity so | ||
| // GPT (if already loaded) keeps its reference. | ||
| queue.push = function (...callbacks: Array<() => void>): number { | ||
| const wrapped = callbacks.map(wrapCommand); | ||
| return originalPush(...wrapped); | ||
| }; | ||
|
|
||
| // Mark as patched to prevent double-wrapping. | ||
| (queue as { __tsPushed?: boolean }).__tsPushed = true; | ||
|
|
||
| // Re-wrap any callbacks that were queued before we patched. | ||
| for (let i = 0; i < queue.length; i++) { | ||
| queue[i] = wrapCommand(queue[i]); | ||
| } | ||
|
|
||
| log.debug('GPT shim: command queue patched', { pendingCommands: queue.length }); | ||
| } | ||
|
|
||
| /** | ||
| * Install the GPT integration shim. | ||
| * | ||
| * Sets up the script guard for dynamic script interception and patches the | ||
| * `googletag.cmd` command queue. | ||
| */ | ||
| export function installGptShim(): boolean { | ||
| if (typeof window === 'undefined') { | ||
| return false; | ||
| } | ||
|
|
||
| const win = window as GptWindow; | ||
|
|
||
| // Install DOM interception guard first so any dynamic GPT script insertions | ||
| // are rewritten before the browser fetches them. | ||
| installGptGuard(); | ||
|
|
||
| const tag = ensureGoogleTagStub(win); | ||
| patchCommandQueue(tag); | ||
|
|
||
| log.info('GPT shim installed'); | ||
| return true; | ||
| } | ||
|
|
||
| // Self-initialise on import (guarded for SSR safety) | ||
| if (typeof window !== 'undefined') { | ||
| installGptShim(); | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔧 Coverage gap: self-init path is untested. Please add tests for enabled/disabled runtime gating and verify we do not install the shim when GPT integration is disabled. |
||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔧 Coverage gap:
patchCommandQueuehas no direct tests. Please add tests that cover preservinggoogletag.cmdbehavior when GPT is already loaded, idempotent install (no double wrapping), and pending callback wrapping semantics.