-
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
Open
ChristianPavilonis
wants to merge
11
commits into
main
Choose a base branch
from
feature/gpt-integration
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
GPT integration #282
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
c7e9320
gpt integration
ChristianPavilonis 9f6a901
script guard to catch and proxy pubads_impl.js
ChristianPavilonis 7bbb1d7
doc/js format
ChristianPavilonis 426115a
just one gpt domain for now
ChristianPavilonis 9e89a7c
revert
ChristianPavilonis 6b8488b
update docs and removed legacy rewrites
ChristianPavilonis 7f68e1e
clean up comment and documentation inaccuracies
ChristianPavilonis 590f80b
address some pr comments
ChristianPavilonis 2c31b55
javascript format
ChristianPavilonis a9abda9
Check if integration is enabled before script init
ChristianPavilonis 295b166
format and lint
ChristianPavilonis File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,170 @@ | ||
| 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 when the server-side GPT integration is enabled. | ||
| // The trusted server injects `window.__tsjs_gpt_enabled = true` via an inline | ||
| // script (IntegrationHeadInjector) so the shim stays dormant when the GPT proxy | ||
| // routes are not registered. | ||
| if (typeof window !== 'undefined' && (window as Record<string, unknown>).__tsjs_gpt_enabled) { | ||
| installGptShim(); | ||
ChristianPavilonis marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.