diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..38bcb77
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,35 @@
+name: CI
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ branches: [main]
+
+jobs:
+ test:
+ name: Test & Build (Bun)
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v4
+
+ - name: Setup Bun
+ uses: oven-sh/setup-bun@v2
+ with:
+ bun-version: latest
+
+ - name: Install dependencies
+ run: bun install
+
+ - name: Biome Linter & Formatter Check
+ run: bun run check
+
+ - name: TypeScript Typecheck
+ run: bun run typecheck
+
+ - name: Run Tests
+ run: bun test
+
+ - name: Build Package
+ run: bun run build
diff --git a/.gitignore b/.gitignore
index 04c01ba..da3f531 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,3 @@
node_modules/
-dist/
\ No newline at end of file
+dist/
+TODO.md
\ No newline at end of file
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..b4df074
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,30 @@
+# Changelog
+
+All notable changes to this project will be documented in this file.
+
+The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
+and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+
+## [1.4.0] - 2026-11-15
+
+### Added
+- **Google Consent Mode v2 Default Signals**: `ConsentProvider` and `AdSenseScript` now automatically initialize `gtag('consent', 'default', ...)` on mount.
+- **IAB TCF & GPP Compliance**: Added `gdprApplies` handling to avoid blocking non-EEA traffic, updated purpose checking, and added GPP section query support for CCPA/CPRA opt-out signals.
+- **Active GAM & Ezoic Adapters**: Implemented actual `googletag` command queue dispatching for Google Ad Manager and `ezstandalone` queue lifecycle for Ezoic.
+- **Unfill Detection**: Added `MutationObserver` on `data-ad-status` attributes to immediately trigger fallbacks when AdSense unfill occurs.
+- **Dev Sanity Warnings**: Emits helpful development warnings when ad units or clients are missing or defaulting to dummy placeholders.
+- **Deterministic Keys**: `injectPortableTextAds` and `injectPortableTextAffiliate` now use deterministic paragraph-based keys, eliminating React hydration mismatches.
+- **CI Workflow**: Restored automated GitHub Actions continuous integration workflow.
+- **Package Metadata**: Added `sideEffects: false`, `engines`, and `./package.json` to exports.
+
+### Fixed
+- **Quickstart Ad Delivery**: Fixed issue where `ConsentProvider` defaulted to unknown status and blocked ad tags from rendering in quickstart examples.
+- **RSC Module Boundaries**: Fixed `"use client"` directive being stamped across root exports, allowing Server Components to cleanly import transformers and config client.
+- **Dead CLS Guard & Unfill Effects**: Fixed effect dependency bugs in `AdSenseSlot` that prevented unfill detection and CLS warnings from executing.
+- **Paragraph Spacing**: Fixed `startOffset` placement calculation and implemented missing `minParagraphsTotal` checks in in-article inserters.
+- **Feed Cache Safety**: Replaced unbounded map in `feed-inserter` with a bounded LRU cache that correctly invalidates on items changes or rule toggles.
+- **Timer Leaks**: Fixed un-cleared intervals in `useAdMetrics` when crossing viewability thresholds.
+- **Tailwind Coupling**: Replaced Tailwind v4-exclusive utilities with standard fallbacks and added solid inline styles for unstyled environments.
+
+## [1.3.2] - Previous Release
+- Enhanced PortableTextBlock types and Sanity integration.
diff --git a/biome.json b/biome.json
new file mode 100644
index 0000000..fe2907f
--- /dev/null
+++ b/biome.json
@@ -0,0 +1,25 @@
+{
+ "$schema": "https://biomejs.dev/schemas/2.6.6/schema.json",
+ "vcs": {
+ "enabled": true,
+ "clientKind": "git",
+ "useIgnoreFile": true
+ },
+ "files": {
+ "ignoreUnknown": true
+ },
+ "formatter": {
+ "enabled": true,
+ "indentStyle": "tab",
+ "lineWidth": 80
+ },
+ "linter": {
+ "enabled": true,
+ "rules": {
+ "preset": "recommended",
+ "performance": {
+ "noImgElement": "off"
+ }
+ }
+ }
+}
diff --git a/package.json b/package.json
index 26b5918..d11226f 100644
--- a/package.json
+++ b/package.json
@@ -26,7 +26,12 @@
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
+ "sideEffects": false,
+ "engines": {
+ "node": ">=18.0.0"
+ },
"exports": {
+ "./package.json": "./package.json",
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
@@ -65,7 +70,7 @@
"url": "https://github.com/LinuxCTRL/adinject-react/issues"
},
"scripts": {
- "build": "tsup && node -e 'const fs = require(\"fs\"); [\"dist/index.js\", \"dist/index.mjs\", \"dist/client/index.js\", \"dist/client/index.mjs\"].forEach(f => { if (fs.existsSync(f)) { const c = fs.readFileSync(f, \"utf8\"); if (!c.startsWith(\"\\\"use client\\\"\")) fs.writeFileSync(f, \"\\\"use client\\\";\\n\" + c); } });'",
+ "build": "tsup && node -e 'const fs = require(\"fs\"); [\"dist/client/index.js\", \"dist/client/index.mjs\"].forEach(f => { if (fs.existsSync(f)) { const c = fs.readFileSync(f, \"utf8\"); if (!c.startsWith(\"\\\"use client\\\"\")) fs.writeFileSync(f, \"\\\"use client\\\";\\n\" + c); } });'",
"dev": "tsup --watch",
"test": "bun test",
"typecheck": "tsc --noEmit",
@@ -83,12 +88,16 @@
}
},
"devDependencies": {
- "@types/node": "^26.3.0",
+ "@biomejs/biome": "^2.6.6",
+ "@types/node": "^26.6.6",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"tsup": "^8.3.6",
"typescript": "^5.7.3"
+ },
+ "allowScripts": {
+ "esbuild": true
}
-}
\ No newline at end of file
+}
diff --git a/src/adapters/index.tsx b/src/adapters/index.tsx
index a384833..91757e3 100644
--- a/src/adapters/index.tsx
+++ b/src/adapters/index.tsx
@@ -1,7 +1,32 @@
import type React from "react";
+import { useEffect } from "react";
import { AdSenseSlot } from "../client/AdSenseSlot";
import type { AdDimensions, AdFormat, FallbackBanner } from "../types";
+declare global {
+ interface Window {
+ googletag?: {
+ cmd: Array<() => void>;
+ defineSlot?: (
+ adUnitPath: string,
+ size: unknown,
+ divId: string,
+ ) => {
+ addService: (service: unknown) => unknown;
+ };
+ pubads?: () => unknown;
+ enableServices?: () => void;
+ display?: (divId: string) => void;
+ };
+ ezstandalone?: {
+ cmd?: Array<() => void>;
+ define?: (...slots: number[]) => void;
+ enable?: () => void;
+ display?: () => void;
+ };
+ }
+}
+
export interface AdAdapterSlotProps {
slot: string;
client?: string;
@@ -97,6 +122,77 @@ export function adsenseAdapter(opts: {
});
}
+function GamSlotContainer({
+ divId,
+ adUnitPath,
+ props,
+}: {
+ divId: string;
+ adUnitPath: string;
+ props: AdAdapterSlotProps;
+}) {
+ useEffect(() => {
+ if (typeof window === "undefined") return;
+ window.googletag = window.googletag || { cmd: [] };
+ window.googletag.cmd = window.googletag.cmd || [];
+ window.googletag.cmd.push(() => {
+ if (window.googletag?.defineSlot && window.googletag?.pubads) {
+ window.googletag
+ .defineSlot(adUnitPath, "fluid", divId)
+ ?.addService(window.googletag.pubads());
+ window.googletag.enableServices?.();
+ }
+ window.googletag?.display?.(divId);
+ });
+ }, [divId, adUnitPath]);
+
+ return (
+
+ );
+}
+
+function EzoicSlotContainer({
+ slot,
+ props,
+}: {
+ slot: string;
+ props: AdAdapterSlotProps;
+}) {
+ useEffect(() => {
+ if (typeof window === "undefined") return;
+ const placeholderId = Number.parseInt(slot, 10);
+ if (Number.isNaN(placeholderId)) return;
+
+ window.ezstandalone = window.ezstandalone || {};
+ window.ezstandalone.cmd = window.ezstandalone.cmd || [];
+ window.ezstandalone.cmd.push(() => {
+ window.ezstandalone?.define?.(placeholderId);
+ window.ezstandalone?.enable?.();
+ window.ezstandalone?.display?.();
+ });
+ }, [slot]);
+
+ return (
+
+ );
+}
+
/**
* Built-in Google Ad Manager (GAM / GPT) Adapter
*/
@@ -157,17 +253,7 @@ export function gamAdapter(opts: {
}
return (
-
+
);
},
});
@@ -212,15 +298,7 @@ export function ezoicAdapter(opts: {
);
}
- return (
-
- );
+ return ;
},
});
}
diff --git a/src/api/config-client.ts b/src/api/config-client.ts
index 8ed8af3..2a52bad 100644
--- a/src/api/config-client.ts
+++ b/src/api/config-client.ts
@@ -43,7 +43,8 @@ const swrCache = new Map<
*/
export async function fetchAdInjectConfig({
projectId,
- baseUrl = typeof process !== "undefined" && process.env?.NEXT_PUBLIC_ADINJECT_API_URL
+ baseUrl = typeof process !== "undefined" &&
+ process.env?.NEXT_PUBLIC_ADINJECT_API_URL
? process.env.NEXT_PUBLIC_ADINJECT_API_URL
: "https://adinject.io",
revalidate = 300,
diff --git a/src/client/AdFallback.tsx b/src/client/AdFallback.tsx
index 71eeaee..012be6a 100644
--- a/src/client/AdFallback.tsx
+++ b/src/client/AdFallback.tsx
@@ -30,11 +30,23 @@ export function AdFallback({ fallback, className = "" }: AdFallbackProps) {
? `Advertisement: ${fallback.title}`
: "Sponsored Advertisement"
}
- className={`group relative flex flex-col md:flex-row items-center gap-4 rounded-xl border border-primary/20 bg-linear-to-r from-primary/5 via-card to-background p-4 text-card-foreground shadow-xs transition-all hover:border-primary/40 hover:shadow-md ${className}`}
- style={{ textDecoration: "none" }}
+ className={`adinject-fallback-card group relative flex flex-col md:flex-row items-center gap-4 rounded-xl border border-primary/20 bg-gradient-to-r from-primary/5 via-card to-background p-4 text-card-foreground shadow-sm transition-all hover:border-primary/40 hover:shadow-md ${className}`}
+ style={{
+ textDecoration: "none",
+ borderRadius: "12px",
+ border: "1px solid rgba(var(--primary-rgb, 59, 130, 246), 0.2)",
+ backgroundColor: "rgba(var(--card-rgb, 255, 255, 255), 0.95)",
+ color: "inherit",
+ }}
>
{fallback.imageUrl && (
-
+
{/* eslint-disable-next-line @next/next/no-img-element */}

{
@@ -56,11 +57,29 @@ export function AdInjectFeed
({
startOffset = 1,
maxAds = 4,
gridSpan = "card",
- testMode = false,
+ testMode,
className = "",
renderItem,
renderAd,
}: AdInjectFeedProps) {
+ const adInjectContext = useAdInject();
+ const effectiveTestMode =
+ testMode ?? adUnit?.testMode ?? adInjectContext.testMode ?? false;
+ const effectiveClient =
+ adUnit?.client || adInjectContext.client || "ca-pub-XXXXXXXX";
+ const effectiveFallback = adUnit?.fallback || adInjectContext.defaultFallback;
+
+ const resolvedAdUnit: AdUnit = adUnit || {
+ id: "default-feed-unit",
+ name: "In-Feed Ad Unit",
+ client: effectiveClient,
+ slot: "0000000000",
+ format: "fluid",
+ responsive: true,
+ testMode: effectiveTestMode,
+ fallback: effectiveFallback,
+ };
+
React.useEffect(() => {
if (adapter?.loadScript) {
loadScriptOnce(adapter.name, adapter.loadScript);
@@ -83,9 +102,9 @@ export function AdInjectFeed({
startOffset: rule?.startOffset ?? startOffset,
maxAdsPerFeed: rule?.maxAdsPerFeed ?? maxAds,
gridSpan: rule?.gridSpan ?? gridSpan,
- adUnitId: rule?.adUnitId || adUnit?.id || "default",
+ adUnitId: rule?.adUnitId || resolvedAdUnit.id,
},
- adUnit,
+ adUnit: resolvedAdUnit,
});
return (
diff --git a/src/client/AdSenseScript.tsx b/src/client/AdSenseScript.tsx
index 5c1b4fe..7cb6706 100644
--- a/src/client/AdSenseScript.tsx
+++ b/src/client/AdSenseScript.tsx
@@ -17,27 +17,59 @@ export interface AdSenseScriptProps {
export function AdSenseScript({
client,
crossOrigin = "anonymous",
+ strategy = "afterInteractive",
nonce,
}: AdSenseScriptProps) {
useEffect(() => {
- if (!client) return;
+ if (!client || typeof document === "undefined") return;
const scriptId = `adinject-adsense-script-${client}`;
if (document.getElementById(scriptId)) {
return; // Deduplicate
}
- const script = document.createElement("script");
- script.id = scriptId;
- script.src = `https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${encodeURIComponent(
- client,
- )}`;
- script.async = true;
- script.crossOrigin = crossOrigin;
- if (nonce) script.nonce = nonce;
-
- document.head.appendChild(script);
- }, [client, crossOrigin, nonce]);
+ // Ensure dataLayer exists before AdSense script executes
+ if (typeof window !== "undefined") {
+ window.dataLayer = window.dataLayer || [];
+ }
+
+ const inject = () => {
+ if (document.getElementById(scriptId)) return;
+ const script = document.createElement("script");
+ script.id = scriptId;
+ script.src = `https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${encodeURIComponent(
+ client,
+ )}`;
+ script.async = true;
+ script.crossOrigin = crossOrigin;
+ if (nonce) script.nonce = nonce;
+
+ document.head.appendChild(script);
+ };
+
+ if (strategy === "lazyOnload") {
+ if (document.readyState === "complete") {
+ if ("requestIdleCallback" in window) {
+ const handle = window.requestIdleCallback(inject);
+ return () => window.cancelIdleCallback(handle);
+ }
+ const timer = setTimeout(inject, 200);
+ return () => clearTimeout(timer);
+ }
+
+ const onWindowLoad = () => {
+ if ("requestIdleCallback" in window) {
+ window.requestIdleCallback(inject);
+ } else {
+ setTimeout(inject, 200);
+ }
+ };
+ window.addEventListener("load", onWindowLoad, { once: true });
+ return () => window.removeEventListener("load", onWindowLoad);
+ }
+
+ inject();
+ }, [client, crossOrigin, strategy, nonce]);
return null;
}
diff --git a/src/client/AdSenseSlot.tsx b/src/client/AdSenseSlot.tsx
index d5f1104..470d70d 100644
--- a/src/client/AdSenseSlot.tsx
+++ b/src/client/AdSenseSlot.tsx
@@ -3,6 +3,7 @@
import type React from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import type {
+ AdAnalyticsEvent,
AdConsentFallback,
AdDimensions,
AdFormat,
@@ -42,6 +43,8 @@ export interface AdSenseSlotProps {
className?: string;
style?: React.CSSProperties;
onStatusChange?: (status: AdStatus) => void;
+ /** Optional analytics event callback */
+ onAnalyticsEvent?: (event: AdAnalyticsEvent) => void;
}
const DEFAULT_DIMENSIONS: Record = {
@@ -75,6 +78,7 @@ export function AdSenseSlot({
className = "",
style,
onStatusChange,
+ onAnalyticsEvent,
}: AdSenseSlotProps) {
const adInjectContext = useAdInject();
const effectiveClient = client || adInjectContext.client || "ca-pub-XXXXXXXX";
@@ -96,13 +100,61 @@ export function AdSenseSlot({
(newStatus: AdStatus) => {
setStatus(newStatus);
onStatusChange?.(newStatus);
+ if (onAnalyticsEvent) {
+ const eventMap: Partial> = {
+ rendered: "impression",
+ unfilled: "fallback_rendered",
+ error: "error",
+ };
+ const eventType = eventMap[newStatus];
+ if (eventType) {
+ onAnalyticsEvent({
+ type: eventType,
+ slot,
+ adUnitId: `unit-${slot}`,
+ pathname:
+ typeof window !== "undefined" ? window.location.pathname : "/",
+ device:
+ typeof window !== "undefined" && window.innerWidth < 768
+ ? "mobile"
+ : "desktop",
+ timestamp: Date.now(),
+ metadata: { format, client: effectiveClient },
+ });
+ }
+ }
},
- [onStatusChange],
+ [onStatusChange, onAnalyticsEvent, slot, format, effectiveClient],
);
const { status: consentStatus } = useConsent();
const isConsentGranted = consentStatus === "granted";
+ // Dev-mode configuration sanity check
+ useEffect(() => {
+ if (process.env.NODE_ENV !== "production") {
+ if (!client && !adInjectContext.client) {
+ console.warn(
+ `[AdInject Warning] AdSenseSlot #${slot} has no client ID configured. Pass client="ca-pub-..." or wrap with {
+ if (debug) {
+ console.log(
+ `[AdInject Debug] Slot #${slot}: status=${status}, client=${effectiveClient}, testMode=${effectiveTestMode}, consent=${consentStatus}`,
+ );
+ }
+ }, [debug, slot, status, effectiveClient, effectiveTestMode, consentStatus]);
+
// 1. IntersectionObserver for zero-jank lazy loading
useEffect(() => {
if (!lazyLoad) {
@@ -156,9 +208,26 @@ export function AdSenseSlot({
return () => clearTimeout(pushTimer);
}, [isVisible, effectiveTestMode, updateStatus, isConsentGranted]);
- // 3. Fallback unfill detection check
+ // 3. Fallback unfill detection check (MutationObserver + safety timeout)
useEffect(() => {
- if (effectiveTestMode || !isPushedRef.current) return;
+ if (effectiveTestMode || status !== "rendered") return;
+
+ const insEl = containerRef.current?.querySelector(".adsbygoogle");
+ let observer: MutationObserver | null = null;
+
+ if (insEl && typeof MutationObserver !== "undefined") {
+ observer = new MutationObserver(() => {
+ const adStatus = insEl.getAttribute("data-ad-status");
+ if (adStatus === "unfilled") {
+ updateStatus("unfilled");
+ observer?.disconnect();
+ }
+ });
+ observer.observe(insEl, {
+ attributes: true,
+ attributeFilter: ["data-ad-status"],
+ });
+ }
const checkTimer = setTimeout(() => {
const el = containerRef.current?.querySelector(".adsbygoogle");
@@ -170,15 +239,18 @@ export function AdSenseSlot({
}
}, 2500);
- return () => clearTimeout(checkTimer);
- }, [effectiveTestMode, updateStatus]);
+ return () => {
+ if (observer) observer.disconnect();
+ clearTimeout(checkTimer);
+ };
+ }, [status, effectiveTestMode, updateStatus]);
// 4. Dev-Mode CLS Regression Guard
useEffect(() => {
if (
process.env.NODE_ENV === "production" ||
effectiveTestMode ||
- !isPushedRef.current
+ status !== "rendered"
)
return;
@@ -199,7 +271,7 @@ export function AdSenseSlot({
}, 3500);
return () => clearTimeout(clsCheckTimer);
- }, [effectiveTestMode, slot, effectiveDimensions.minHeight]);
+ }, [status, effectiveTestMode, slot, effectiveDimensions.minHeight]);
const containerStyle: React.CSSProperties = {
width: "100%",
@@ -216,6 +288,8 @@ export function AdSenseSlot({
ref={containerRef}
a11yLabel={a11yLabel}
minHeight={effectiveDimensions.minHeight}
+ width={effectiveDimensions.width}
+ height={effectiveDimensions.height}
aspectRatio={effectiveDimensions.aspectRatio}
className={`adinject-slot-container ${className}`}
style={containerStyle}
diff --git a/src/client/AdSlotFrame.tsx b/src/client/AdSlotFrame.tsx
index 1d92921..8c66a96 100644
--- a/src/client/AdSlotFrame.tsx
+++ b/src/client/AdSlotFrame.tsx
@@ -12,6 +12,10 @@ export interface AdSlotFrameProps extends React.HTMLAttributes {
as?: "aside" | "div" | "section";
/** Reserved minHeight for zero CLS */
minHeight?: number | string;
+ /** Reserved width */
+ width?: number | string;
+ /** Reserved height */
+ height?: number | string;
/** Reserved aspectRatio for zero CLS */
aspectRatio?: string;
/** Extra class names */
@@ -34,6 +38,8 @@ export const AdSlotFrame = forwardRef(
a11yRole = "complementary",
as: Component = "aside",
minHeight,
+ width,
+ height,
aspectRatio,
className = "",
style,
@@ -44,6 +50,8 @@ export const AdSlotFrame = forwardRef(
) => {
const combinedStyle: React.CSSProperties = {
minHeight,
+ width,
+ height,
aspectRatio,
position: "relative",
boxSizing: "border-box",
diff --git a/src/client/AffiliateCard.tsx b/src/client/AffiliateCard.tsx
index 6c474d6..1f05a74 100644
--- a/src/client/AffiliateCard.tsx
+++ b/src/client/AffiliateCard.tsx
@@ -216,10 +216,14 @@ export function AffiliateCard({
// 4. Default "card" Variant (grid / catalog native)
return (
ⓘ
diff --git a/src/client/ConsentProvider.tsx b/src/client/ConsentProvider.tsx
index c7ffa40..ad6524f 100644
--- a/src/client/ConsentProvider.tsx
+++ b/src/client/ConsentProvider.tsx
@@ -40,24 +40,26 @@ const ConsentContext = createContext
({
});
/**
- * Updates Google Consent Mode v2 via gtag('consent', 'update', ...)
+ * Updates Google Consent Mode v2 via gtag('consent', 'default' | 'update', ...)
*/
-function syncGoogleConsentMode(status: ConsentStatus) {
+function syncGoogleConsentMode(status: ConsentStatus, isDefault = false) {
if (typeof window === "undefined") return;
const consentValue = status === "granted" ? "granted" : "denied";
+ const command = isDefault ? "default" : "update";
+ window.dataLayer = window.dataLayer || [];
if (typeof window.gtag === "function") {
- window.gtag("consent", "update", {
+ window.gtag("consent", command, {
ad_storage: consentValue,
ad_user_data: consentValue,
ad_personalization: consentValue,
analytics_storage: consentValue,
});
- } else if (Array.isArray(window.dataLayer)) {
+ } else {
window.dataLayer.push([
"consent",
- "update",
+ command,
{
ad_storage: consentValue,
ad_user_data: consentValue,
@@ -75,10 +77,24 @@ export function ConsentProvider({
mode = "google-consent-v2",
getConsent,
listenEvent,
- initialStatus = "unknown",
+ initialStatus,
children,
}: ConsentProviderProps) {
- const [status, setStatus] = useState(initialStatus);
+ // If a custom CMP check (getConsent) or event listener is supplied without an explicit initialStatus,
+ // wait in "unknown" until resolved; otherwise default to "granted" so quickstart renders ads.
+ const resolvedInitialStatus: ConsentStatus =
+ initialStatus ??
+ (getConsent || listenEvent || mode === "tcf" || mode === "gpp"
+ ? "unknown"
+ : "granted");
+ const [status, setStatus] = useState(resolvedInitialStatus);
+
+ // On mount, establish initial consent signals for Google Consent Mode v2
+ useEffect(() => {
+ if (mode === "google-consent-v2") {
+ syncGoogleConsentMode(resolvedInitialStatus, true);
+ }
+ }, [mode, resolvedInitialStatus]);
const grant = useCallback(() => {
setStatus("granted");
@@ -127,16 +143,46 @@ export function ConsentProvider({
window.__gpp("addEventListener", (evt: unknown) => {
const gppEvt = evt as {
eventName?: string;
- pingData?: { applicableSections?: number[]; gppVersion?: string };
+ pingData?: {
+ applicableSections?: number[];
+ gppVersion?: string;
+ signalStatus?: "ready" | "not ready";
+ };
};
if (
gppEvt?.eventName === "sectionChange" ||
gppEvt?.eventName === "signalStatus"
) {
- const applicableSections = gppEvt?.pingData?.applicableSections || [];
- const hasConsent =
- applicableSections.length > 0 && !!gppEvt?.pingData?.gppVersion;
- setStatus(hasConsent ? "granted" : "denied");
+ const pingData = gppEvt?.pingData;
+ if (pingData?.signalStatus === "not ready") return;
+
+ const applicableSections = pingData?.applicableSections || [];
+ // If no specific privacy sections apply to user, consent is granted
+ if (applicableSections.length === 0) {
+ setStatus("granted");
+ return;
+ }
+
+ // Check section data for opt-outs
+ try {
+ window.__gpp?.(
+ "getSection",
+ (sectionData: unknown, success: boolean) => {
+ if (success && sectionData) {
+ const data = sectionData as Record;
+ const isOptedOut =
+ data.SaleOptOut === 1 ||
+ data.SharingOptOut === 1 ||
+ data.PersonalDataConsents === 0;
+ setStatus(isOptedOut ? "denied" : "granted");
+ } else {
+ setStatus("granted");
+ }
+ },
+ );
+ } catch {
+ setStatus("granted");
+ }
}
});
}
@@ -147,12 +193,23 @@ export function ConsentProvider({
"addEventListener",
2,
(tcData: unknown, success: boolean) => {
+ if (!success || !tcData) return;
const tcf = tcData as {
- eventStatus?: string;
+ gdprApplies?: boolean;
+ eventStatus?: "tcloaded" | "cmpuishown" | "useractioncomplete";
purpose?: { consents?: Record };
};
- if (success && tcf?.eventStatus === "tcloaded") {
- const hasConsent = tcf?.purpose?.consents?.[1] === true;
+ if (
+ tcf.eventStatus === "tcloaded" ||
+ tcf.eventStatus === "useractioncomplete"
+ ) {
+ // If GDPR does not apply (e.g. non-EEA traffic), consent is granted
+ if (tcf.gdprApplies === false) {
+ setStatus("granted");
+ return;
+ }
+ // Purpose 1: Store and/or access information on a device
+ const hasConsent = tcf.purpose?.consents?.[1] === true;
setStatus(hasConsent ? "granted" : "denied");
}
},
diff --git a/src/client/InArticleAds.tsx b/src/client/InArticleAds.tsx
index 42ff36c..feb2fa0 100644
--- a/src/client/InArticleAds.tsx
+++ b/src/client/InArticleAds.tsx
@@ -22,6 +22,8 @@ export interface InArticleAdsProps {
interval?: number;
/** Minimum paragraphs before the first ad (default: 1) */
startOffset?: number;
+ /** Minimum total paragraphs required in the article before any ad is injected (default: 0) */
+ minParagraphsTotal?: number;
/** Maximum total ads injected in the article (default: 4) */
maxAds?: number;
/** AdSense slot ID (inherits client from AdInjectProvider) */
@@ -52,6 +54,7 @@ export function InArticleAds({
markdown,
interval = 3,
startOffset = 1,
+ minParagraphsTotal = 0,
maxAds = 4,
slot,
adUnit,
@@ -95,8 +98,9 @@ export function InArticleAds({
enabled: true,
deviceFilter: "all" as const,
paragraphInterval: interval,
- minWordsBeforeFirstAd: startOffset * 10,
- minParagraphsTotal: startOffset + 1,
+ startOffset,
+ minWordsBeforeFirstAd: 0,
+ minParagraphsTotal,
maxAdsPerArticle: maxAds,
adUnitId: targetAdUnit.id,
};
@@ -127,6 +131,7 @@ export function InArticleAds({
markdown,
interval,
startOffset,
+ minParagraphsTotal,
maxAds,
adUnit,
effectiveSlot,
diff --git a/src/client/InFeedAdCard.tsx b/src/client/InFeedAdCard.tsx
index af6c069..9b18ddb 100644
--- a/src/client/InFeedAdCard.tsx
+++ b/src/client/InFeedAdCard.tsx
@@ -113,7 +113,7 @@ export function InFeedAdCard({
client: adUnit.client,
format: isFullWidth ? "horizontal" : adUnit.format || "rectangle",
responsive: adUnit.responsive ?? true,
- testMode: testMode || adUnit.testMode,
+ testMode: testMode ?? adUnit.testMode,
fallback: adUnit.fallback,
className: "w-full",
})
@@ -123,7 +123,7 @@ export function InFeedAdCard({
slot={adUnit.slot}
format={isFullWidth ? "horizontal" : adUnit.format || "rectangle"}
responsive={adUnit.responsive ?? true}
- testMode={testMode || adUnit.testMode}
+ testMode={testMode ?? adUnit.testMode}
debug={debug}
fallback={adUnit.fallback}
className="w-full"
diff --git a/src/client/useAdMetrics.ts b/src/client/useAdMetrics.ts
index 89a6e51..84cf684 100644
--- a/src/client/useAdMetrics.ts
+++ b/src/client/useAdMetrics.ts
@@ -94,21 +94,29 @@ export function useAdMetrics(
onImpression?.();
}
- startTimeRef.current = Date.now();
- intervalTimer = setInterval(() => {
- if (startTimeRef.current) {
- const elapsed = Date.now() - startTimeRef.current;
- setViewableDurationMs(elapsed);
-
- if (elapsed >= viewableTimeMs && !viewableTriggeredRef.current) {
- viewableTriggeredRef.current = true;
- setIsViewable(true);
- onViewable?.();
+ if (!intervalTimer) {
+ startTimeRef.current = Date.now();
+ intervalTimer = setInterval(() => {
+ if (startTimeRef.current) {
+ const elapsed = Date.now() - startTimeRef.current;
+ setViewableDurationMs(elapsed);
+
+ if (
+ elapsed >= viewableTimeMs &&
+ !viewableTriggeredRef.current
+ ) {
+ viewableTriggeredRef.current = true;
+ setIsViewable(true);
+ onViewable?.();
+ }
}
- }
- }, 200);
+ }, 200);
+ }
} else {
- if (intervalTimer) clearInterval(intervalTimer);
+ if (intervalTimer) {
+ clearInterval(intervalTimer);
+ intervalTimer = null;
+ }
startTimeRef.current = null;
}
},
diff --git a/src/rules/rule-evaluator.ts b/src/rules/rule-evaluator.ts
index 2d8da67..2840ae5 100644
--- a/src/rules/rule-evaluator.ts
+++ b/src/rules/rule-evaluator.ts
@@ -26,6 +26,25 @@ export function matchesPathPattern(
return pathname === pattern;
}
+/**
+ * Returns true when a paragraph (1-based) should receive an ad slot.
+ *
+ * `startOffset` is the paragraph number after which the first ad is placed
+ * (default: 1), and `interval` is the number of paragraphs between ads.
+ *
+ * Example: startOffset=1, interval=3 -> ads after paragraphs 1, 4, 7, ...
+ */
+export function isParagraphAdPosition(
+ paragraphNumber: number,
+ startOffset = 1,
+ interval = 1,
+): boolean {
+ const offset = Math.max(1, Math.floor(startOffset || 1));
+ const step = Math.max(1, Math.floor(interval || 1));
+ if (paragraphNumber < offset) return false;
+ return (paragraphNumber - offset) % step === 0;
+}
+
/**
* Evaluates device filters
*/
diff --git a/src/transformers/feed-inserter.ts b/src/transformers/feed-inserter.ts
index 1685aa6..3e3372d 100644
--- a/src/transformers/feed-inserter.ts
+++ b/src/transformers/feed-inserter.ts
@@ -9,8 +9,91 @@ export interface InjectFeedAdsOptions {
idempotencyKey?: string;
}
-// Module-level idempotency cache for string keys
-const keyCache = new Map[]>();
+interface CacheEntry {
+ itemsRef: T[];
+ itemsLength: number;
+ ruleEnabled: boolean;
+ ruleId?: string;
+ interval?: number;
+ startOffset?: number;
+ maxAds?: number;
+ adUnitId?: string;
+ result: FeedItem[];
+}
+
+const MAX_CACHE_ENTRIES = 200;
+const keyCache = new Map>();
+
+/**
+ * Resets the module-level feed cache (mainly for testing)
+ */
+export function clearFeedCache(): void {
+ keyCache.clear();
+}
+
+function getCachedResult(
+ key: string,
+ items: T[],
+ rule?: PlacementRule,
+ adUnit?: AdUnit,
+): FeedItem[] | null {
+ const entry = keyCache.get(key) as CacheEntry | undefined;
+ if (!entry) return null;
+
+ // Invalidate if items reference changed and contents/length changed
+ if (entry.itemsRef !== items && entry.itemsLength !== items.length) {
+ return null;
+ }
+
+ // Invalidate if rule enabled state changed
+ const ruleEnabled = rule ? rule.enabled : true;
+ if (entry.ruleEnabled !== ruleEnabled) {
+ return null;
+ }
+
+ // Invalidate if spacing parameters changed
+ if (
+ entry.interval !== (rule?.itemInterval ?? 4) ||
+ entry.startOffset !== (rule?.startOffset ?? 2) ||
+ entry.maxAds !== (rule?.maxAdsPerFeed ?? 4) ||
+ entry.adUnitId !== (adUnit?.id ?? rule?.adUnitId)
+ ) {
+ return null;
+ }
+
+ // Refresh position in Map for LRU
+ keyCache.delete(key);
+ keyCache.set(key, entry as CacheEntry);
+
+ return entry.result;
+}
+
+function setCachedResult(
+ key: string,
+ items: T[],
+ rule: PlacementRule | undefined,
+ adUnit: AdUnit | undefined,
+ result: FeedItem[],
+) {
+ if (keyCache.size >= MAX_CACHE_ENTRIES) {
+ const oldestKey = keyCache.keys().next().value;
+ if (oldestKey !== undefined) {
+ keyCache.delete(oldestKey);
+ }
+ }
+
+ keyCache.set(key, {
+ itemsRef: items,
+ itemsLength: items.length,
+ ruleEnabled: rule ? rule.enabled : true,
+ ruleId: rule?.id,
+ interval: rule?.itemInterval ?? 4,
+ startOffset: rule?.startOffset ?? 2,
+ maxAds: rule?.maxAdsPerFeed ?? 4,
+ adUnitId: adUnit?.id ?? rule?.adUnitId,
+ result,
+ });
+}
/**
* Injects Google AdSense / affiliate ad placeholders between items in an array
@@ -34,11 +117,15 @@ export function injectFeedAds({
}: InjectFeedAdsOptions): FeedItem[] {
if (!items || items.length === 0) return [];
- if (idempotencyKey && keyCache.has(idempotencyKey)) {
- return keyCache.get(idempotencyKey) as FeedItem[];
+ if (idempotencyKey) {
+ const cached = getCachedResult(idempotencyKey, items, rule, adUnit);
+ if (cached) return cached;
}
// Default ad unit if not provided
+ const isDev =
+ typeof process === "undefined" || process.env?.NODE_ENV !== "production";
+
const fallbackUnit: AdUnit = adUnit ||
(rule && adUnits?.[rule.adUnitId]) || {
id: "default-feed-unit",
@@ -47,7 +134,7 @@ export function injectFeedAds({
slot: "0000000000",
format: "fluid",
responsive: true,
- testMode: true,
+ testMode: isDev,
};
// Idempotency guard: If items array was already injected with ads, strip previous ad slots
@@ -78,8 +165,9 @@ export function injectFeedAds({
type: "item",
data,
}));
- if (idempotencyKey)
- keyCache.set(idempotencyKey, rawItems as FeedItem[]);
+ if (idempotencyKey) {
+ setCachedResult(idempotencyKey, items, rule, adUnit, rawItems);
+ }
return rawItems;
}
@@ -122,7 +210,7 @@ export function injectFeedAds({
}
if (idempotencyKey) {
- keyCache.set(idempotencyKey, result as FeedItem[]);
+ setCachedResult(idempotencyKey, items, rule, adUnit, result);
}
return result;
diff --git a/src/transformers/html-inserter.ts b/src/transformers/html-inserter.ts
index 6731993..13ca355 100644
--- a/src/transformers/html-inserter.ts
+++ b/src/transformers/html-inserter.ts
@@ -1,3 +1,4 @@
+import { isParagraphAdPosition } from "../rules/rule-evaluator";
import type {
AdInjectionResult,
AdUnit,
@@ -63,6 +64,16 @@ export function injectHtmlAds({
};
}
+ const totalParagraphsInDocument = (html.match(/<\/p>/gi) || []).length;
+ if (totalParagraphsInDocument < Math.max(0, rule.minParagraphsTotal ?? 0)) {
+ return {
+ content: html,
+ insertedAds: [],
+ totalWords: countWordsInHtml(html),
+ totalParagraphs: totalParagraphsInDocument,
+ };
+ }
+
const defaultTemplate = (slot: InjectedAdSlot) => `
@@ -101,8 +112,12 @@ export function injectHtmlAds({
const canInject =
adsInsertedCount < rule.maxAdsPerArticle &&
- wordCountAccumulator >= rule.minWordsBeforeFirstAd &&
- totalParagraphCount % rule.paragraphInterval === 0 &&
+ wordCountAccumulator >= (rule.minWordsBeforeFirstAd ?? 0) &&
+ isParagraphAdPosition(
+ totalParagraphCount,
+ rule.startOffset ?? 1,
+ rule.paragraphInterval,
+ ) &&
!isExcludedParagraph(precedingParagraph, rule.excludedSelectors);
if (canInject) {
@@ -148,6 +163,11 @@ export function splitHtmlForAds({
return [{ type: "html", content: html }];
}
+ const totalParagraphsInDocument = (html.match(/<\/p>/gi) || []).length;
+ if (totalParagraphsInDocument < Math.max(0, rule.minParagraphsTotal ?? 0)) {
+ return [{ type: "html", content: html }];
+ }
+
const parts = html.split(/(<\/p>)/i);
const chunks: HtmlChunk[] = [];
let currentHtmlBuffer = "";
@@ -168,8 +188,12 @@ export function splitHtmlForAds({
const canInject =
adsInsertedCount < rule.maxAdsPerArticle &&
- wordCountAccumulator >= rule.minWordsBeforeFirstAd &&
- totalParagraphCount % rule.paragraphInterval === 0 &&
+ wordCountAccumulator >= (rule.minWordsBeforeFirstAd ?? 0) &&
+ isParagraphAdPosition(
+ totalParagraphCount,
+ rule.startOffset ?? 1,
+ rule.paragraphInterval,
+ ) &&
!isExcludedParagraph(precedingParagraph, rule.excludedSelectors);
if (canInject) {
diff --git a/src/transformers/markdown-inserter.ts b/src/transformers/markdown-inserter.ts
index fc4f5cd..6283031 100644
--- a/src/transformers/markdown-inserter.ts
+++ b/src/transformers/markdown-inserter.ts
@@ -1,3 +1,4 @@
+import { isParagraphAdPosition } from "../rules/rule-evaluator";
import type {
AdInjectionResult,
AdUnit,
@@ -39,12 +40,32 @@ export function injectMarkdownAds({
};
}
+ const rawBlocks = markdown.split(/\n\s*\n/);
+ const totalParagraphCount = rawBlocks.filter(
+ (block) =>
+ block &&
+ block.trim().length > 0 &&
+ !block.startsWith("#") &&
+ !block.startsWith("```") &&
+ !block.startsWith(">") &&
+ !block.startsWith("- ") &&
+ !block.startsWith("1. "),
+ ).length;
+
+ if (totalParagraphCount < Math.max(0, rule.minParagraphsTotal ?? 0)) {
+ return {
+ content: markdown,
+ insertedAds: [],
+ totalWords: countWordsInMarkdown(markdown),
+ totalParagraphs: totalParagraphCount,
+ };
+ }
+
const defaultMarker = (slot: InjectedAdSlot) =>
`\n\n
\n\n`;
const renderMarker = customAdMarker || defaultMarker;
- const rawBlocks = markdown.split(/\n\s*\n/);
const transformedBlocks: string[] = [];
const insertedAds: InjectedAdSlot[] = [];
@@ -71,8 +92,12 @@ export function injectMarkdownAds({
const shouldInject =
adsInserted < rule.maxAdsPerArticle &&
- wordCountAccumulator >= rule.minWordsBeforeFirstAd &&
- paragraphIndex % rule.paragraphInterval === 0 &&
+ wordCountAccumulator >= (rule.minWordsBeforeFirstAd ?? 0) &&
+ isParagraphAdPosition(
+ paragraphIndex,
+ rule.startOffset ?? 1,
+ rule.paragraphInterval,
+ ) &&
i < rawBlocks.length - 1;
if (shouldInject) {
diff --git a/src/transformers/portable-text-adapter.tsx b/src/transformers/portable-text-adapter.tsx
index bebdd16..a808e29 100644
--- a/src/transformers/portable-text-adapter.tsx
+++ b/src/transformers/portable-text-adapter.tsx
@@ -105,7 +105,7 @@ export function injectPortableTextAds({
const adBlock: InjectedAdBlock = {
_type: "adinject.adSlot",
- _key: `ad_slot_${rule.id}_${adsInserted}_${Date.now()}`,
+ _key: `adinject_slot_${rule.id}_${adsInserted}_p${paragraphIndex}`,
adUnit,
slotIndex: adsInserted,
ruleId: rule.id,
@@ -166,7 +166,7 @@ export function injectPortableTextAffiliate
>({
if (paragraphIndex === afterParagraph && !injected) {
const affiliateBlock: InjectedAffiliateBlock = {
_type: type,
- _key: `affiliate_${Date.now()}_${i}`,
+ _key: `adinject_${type.replace(/[^a-zA-Z0-9]/g, "_")}_p${paragraphIndex}_${i}`,
data,
};
result.push(affiliateBlock);
@@ -179,7 +179,7 @@ export function injectPortableTextAffiliate>({
if (!injected && result.length > 0) {
result.push({
_type: type,
- _key: `affiliate_${Date.now()}_end`,
+ _key: `adinject_${type.replace(/[^a-zA-Z0-9]/g, "_")}_end`,
data,
});
}
diff --git a/tests/client-lifecycle.test.ts b/tests/client-lifecycle.test.ts
new file mode 100644
index 0000000..196b407
--- /dev/null
+++ b/tests/client-lifecycle.test.ts
@@ -0,0 +1,103 @@
+import { describe, expect, it } from "bun:test";
+import { loadScriptOnce } from "../src/adapters";
+import { clearFeedCache, injectFeedAds } from "../src/transformers/feed-inserter";
+import type { AdUnit, PlacementRule } from "../src/types";
+
+describe("Client Lifecycle & Cache Guards", () => {
+ const sampleRule: PlacementRule = {
+ id: "rule-cache-test",
+ name: "Cache Rule",
+ enabled: true,
+ deviceFilter: "all",
+ paragraphInterval: 2,
+ minWordsBeforeFirstAd: 10,
+ minParagraphsTotal: 2,
+ maxAdsPerArticle: 3,
+ itemInterval: 2,
+ startOffset: 1,
+ maxAdsPerFeed: 2,
+ adUnitId: "unit-1",
+ };
+
+ const sampleUnit: AdUnit = {
+ id: "unit-1",
+ name: "Ad Unit 1",
+ client: "ca-pub-1234",
+ slot: "5678",
+ };
+
+ it("should clear cache when clearFeedCache is invoked", () => {
+ clearFeedCache();
+ const items = ["A", "B", "C", "D"];
+ const run1 = injectFeedAds({
+ items,
+ rule: sampleRule,
+ adUnit: sampleUnit,
+ idempotencyKey: "test-clear",
+ });
+
+ clearFeedCache();
+
+ const run2 = injectFeedAds({
+ items,
+ rule: sampleRule,
+ adUnit: sampleUnit,
+ idempotencyKey: "test-clear",
+ });
+
+ expect(run1).not.toBe(run2); // New array reference created after cache clear
+ expect(run1).toEqual(run2);
+ });
+
+ it("should enforce LRU bounded eviction after max entries", () => {
+ clearFeedCache();
+ // Fill cache with 205 entries (max is 200)
+ for (let i = 0; i < 205; i++) {
+ injectFeedAds({
+ items: ["item1", "item2"],
+ rule: sampleRule,
+ adUnit: sampleUnit,
+ idempotencyKey: `key-${i}`,
+ });
+ }
+
+ // Key 0 should have been evicted by LRU
+ const firstRunKey0 = injectFeedAds({
+ items: ["item1", "item2"],
+ rule: sampleRule,
+ adUnit: sampleUnit,
+ idempotencyKey: "key-0",
+ });
+
+ // Key 204 should still be cached
+ const runKey204 = injectFeedAds({
+ items: ["item1", "item2"],
+ rule: sampleRule,
+ adUnit: sampleUnit,
+ idempotencyKey: "key-204",
+ });
+ const runKey204Again = injectFeedAds({
+ items: ["item1", "item2"],
+ rule: sampleRule,
+ adUnit: sampleUnit,
+ idempotencyKey: "key-204",
+ });
+
+ expect(runKey204).toBe(runKey204Again); // cached
+ });
+
+ it("should deduplicate script loading via loadScriptOnce", () => {
+ let loadCount = 0;
+ const loader = () => {
+ loadCount++;
+ };
+
+ // Simulate window environment
+ (globalThis as any).window = globalThis;
+
+ loadScriptOnce("test-adapter-dedup", loader);
+ loadScriptOnce("test-adapter-dedup", loader);
+
+ expect(loadCount).toBe(1);
+ });
+});
diff --git a/tests/consent-and-adapters.test.tsx b/tests/consent-and-adapters.test.tsx
index 9948ec5..9f6db1f 100644
--- a/tests/consent-and-adapters.test.tsx
+++ b/tests/consent-and-adapters.test.tsx
@@ -45,6 +45,16 @@ describe("Consent Provider & Ad Adapters", () => {
expect(html).toContain("Google AdSense Test Slot");
});
+ it("should render live ad ins tag by default in quickstart without explicit initialStatus", () => {
+ const html = renderToString(
+
+
+ ,
+ );
+ expect(html).toContain('class="adsbygoogle"');
+ expect(html).not.toContain("Consent Required for Personalized Ads");
+ });
+
it("should render affiliate fallback when consent is denied", () => {
const html = renderToString(
diff --git a/tests/html-markdown-portable.test.ts b/tests/html-markdown-portable.test.ts
index 3333ec0..9cf08ae 100644
--- a/tests/html-markdown-portable.test.ts
+++ b/tests/html-markdown-portable.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "bun:test";
-import { injectHtmlAds } from "../src/transformers/html-inserter";
+import { injectHtmlAds, splitHtmlForAds } from "../src/transformers/html-inserter";
import { injectMarkdownAds } from "../src/transformers/markdown-inserter";
import {
injectPortableTextAds,
@@ -47,6 +47,52 @@ describe("Content Transformers", () => {
const result = injectHtmlAds({ html: shortHtml, rule, adUnit });
expect(result.insertedAds.length).toBe(0);
});
+
+ it("should respect minParagraphsTotal threshold", () => {
+ const html = `
+ Paragraph 1 with plenty of words to easily exceed word limits.
+ Paragraph 2 with plenty of words to easily exceed word limits.
+ `;
+ const result = injectHtmlAds({
+ html,
+ rule: { ...rule, minParagraphsTotal: 4 },
+ adUnit,
+ });
+ expect(result.insertedAds.length).toBe(0);
+ });
+
+ it("should place first ad after startOffset paragraph", () => {
+ const html = `
+ Paragraph 1 with plenty of words to easily exceed word limits.
+ Paragraph 2 with plenty of words to easily exceed word limits.
+ Paragraph 3 with plenty of words to easily exceed word limits.
+ Paragraph 4 with plenty of words to easily exceed word limits.
+ `;
+ const result = injectHtmlAds({
+ html,
+ rule: { ...rule, startOffset: 2, paragraphInterval: 2, minParagraphsTotal: 2 },
+ adUnit,
+ });
+ expect(result.insertedAds.length).toBe(2);
+ expect(result.insertedAds[0]?.insertedAfterParagraph).toBe(2);
+ expect(result.insertedAds[1]?.insertedAfterParagraph).toBe(4);
+ });
+
+ it("should split html chunks cleanly with splitHtmlForAds", () => {
+ const html = `
+ Paragraph 1 with rich content for testing splitHtmlForAds.
+ Paragraph 2 with rich content for testing splitHtmlForAds.
+ Paragraph 3 with rich content for testing splitHtmlForAds.
+ `;
+ const chunks = splitHtmlForAds({
+ html,
+ rule: { ...rule, paragraphInterval: 1, startOffset: 1, minParagraphsTotal: 2 },
+ adUnit,
+ });
+ expect(chunks.length).toBeGreaterThan(1);
+ const adChunks = chunks.filter((c) => c.type === "ad");
+ expect(adChunks.length).toBeGreaterThan(0);
+ });
});
describe("injectMarkdownAds", () => {
@@ -64,6 +110,37 @@ Paragraph 4 summarizes the recipe and nutritional info.
const result = injectMarkdownAds({ markdown, rule, adUnit });
expect(result.insertedAds.length).toBeGreaterThan(0);
});
+
+ it("should respect minParagraphsTotal and startOffset in Markdown", () => {
+ const markdown = `
+Paragraph 1 with plenty of words to easily exceed word limits.
+
+Paragraph 2 with plenty of words to easily exceed word limits.
+ `;
+ const resultTooShort = injectMarkdownAds({
+ markdown,
+ rule: { ...rule, minParagraphsTotal: 4 },
+ adUnit,
+ });
+ expect(resultTooShort.insertedAds.length).toBe(0);
+
+ const markdownFour = `
+Paragraph 1 with plenty of words.
+
+Paragraph 2 with plenty of words.
+
+Paragraph 3 with plenty of words.
+
+Paragraph 4 with plenty of words.
+ `;
+ const resultOffset = injectMarkdownAds({
+ markdown: markdownFour,
+ rule: { ...rule, startOffset: 2, paragraphInterval: 2, minParagraphsTotal: 2 },
+ adUnit,
+ });
+ expect(resultOffset.insertedAds.length).toBe(1); // after para 2 (para 4 is the last block, skipped by i < rawBlocks.length - 1)
+ expect(resultOffset.insertedAds[0]?.insertedAfterParagraph).toBe(2);
+ });
});
describe("injectPortableTextAds & injectPortableTextAffiliate", () => {
diff --git a/tests/idempotency-and-density.test.ts b/tests/idempotency-and-density.test.ts
index 141375e..718946e 100644
--- a/tests/idempotency-and-density.test.ts
+++ b/tests/idempotency-and-density.test.ts
@@ -149,6 +149,36 @@ describe("Idempotency & Density Guards", () => {
expect(run1).toBe(run2); // exact cached reference
});
+ it("should invalidate feed cache when items length changes or rule enables", () => {
+ const initialItems = ["Item 1", "Item 2", "Item 3"];
+ const runDisabled = injectFeedAds({
+ items: initialItems,
+ rule: { ...sampleRule, enabled: false },
+ adUnit: sampleAdUnit,
+ idempotencyKey: "dynamic-feed-test",
+ });
+ expect(runDisabled.filter((i) => i.type === "ad").length).toBe(0);
+
+ // Rule enabled with same key should NOT return poisoned disabled cache
+ const runEnabled = injectFeedAds({
+ items: initialItems,
+ rule: { ...sampleRule, enabled: true },
+ adUnit: sampleAdUnit,
+ idempotencyKey: "dynamic-feed-test",
+ });
+ expect(runEnabled.filter((i) => i.type === "ad").length).toBeGreaterThan(0);
+
+ // More items appended should invalidate stale cache
+ const expandedItems = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6"];
+ const runExpanded = injectFeedAds({
+ items: expandedItems,
+ rule: sampleRule,
+ adUnit: sampleAdUnit,
+ idempotencyKey: "dynamic-feed-test",
+ });
+ expect(runExpanded.length).toBeGreaterThan(runEnabled.length);
+ });
+
it("should stamp data-adinject-affiliate attribute on autolinked anchors", () => {
const html = "Get your air fryer ready for dinner.
";
const result = injectHtmlAffiliateKeywords(html, {
diff --git a/tsup.config.ts b/tsup.config.ts
index ef08d4b..1721cc6 100644
--- a/tsup.config.ts
+++ b/tsup.config.ts
@@ -11,13 +11,10 @@ export default defineConfig({
format: ["cjs", "esm"],
dts: true,
clean: true,
- splitting: false,
+ splitting: true,
treeshake: true,
sourcemap: true,
minify: false,
- banner: {
- js: '"use client";',
- },
external: ["react", "react-dom", "next", "next/script", "next/navigation"],
});