|
| 1 | +import type { |
| 2 | + ConsentLevel, |
| 3 | + Environment, |
| 4 | +} from '@imtbl/audience-core'; |
| 5 | +import { |
| 6 | + CONSENT_PATH, |
| 7 | + COOKIE_NAME, |
| 8 | + SESSION_COOKIE, |
| 9 | + getBaseUrl, |
| 10 | + deleteCookie, |
| 11 | + truncateSource, |
| 12 | +} from '@imtbl/audience-core'; |
| 13 | + |
| 14 | +export interface ConsentCallbacks { |
| 15 | + onPurgeQueue?: () => void; |
| 16 | + onStripIdentity?: () => void; |
| 17 | + onClearCookies?: () => void; |
| 18 | +} |
| 19 | + |
| 20 | +export class ConsentManager { |
| 21 | + private level: ConsentLevel; |
| 22 | + |
| 23 | + private readonly baseUrl: string; |
| 24 | + |
| 25 | + private readonly publishableKey: string; |
| 26 | + |
| 27 | + private readonly source: string; |
| 28 | + |
| 29 | + private readonly cookieDomain?: string; |
| 30 | + |
| 31 | + constructor( |
| 32 | + environment: Environment, |
| 33 | + publishableKey: string, |
| 34 | + initialConsent: ConsentLevel, |
| 35 | + rawSource: string, |
| 36 | + cookieDomain?: string, |
| 37 | + ) { |
| 38 | + this.baseUrl = getBaseUrl(environment); |
| 39 | + this.publishableKey = publishableKey; |
| 40 | + this.source = truncateSource(rawSource); |
| 41 | + this.cookieDomain = cookieDomain; |
| 42 | + this.level = initialConsent; |
| 43 | + } |
| 44 | + |
| 45 | + getLevel(): ConsentLevel { |
| 46 | + return this.level; |
| 47 | + } |
| 48 | + |
| 49 | + setLevel( |
| 50 | + level: ConsentLevel, |
| 51 | + anonymousId: string, |
| 52 | + callbacks?: ConsentCallbacks, |
| 53 | + ): void { |
| 54 | + const { level: previous } = this; |
| 55 | + this.level = level; |
| 56 | + |
| 57 | + // Downgrade: full/anonymous -> none — purge everything |
| 58 | + if (level === 'none') { |
| 59 | + callbacks?.onPurgeQueue?.(); |
| 60 | + callbacks?.onClearCookies?.(); |
| 61 | + } else if (level === 'anonymous' && previous === 'full') { |
| 62 | + // Downgrade: full -> anonymous — strip PII, keep anonymous events |
| 63 | + callbacks?.onStripIdentity?.(); |
| 64 | + } |
| 65 | + |
| 66 | + // Sync to server (fire-and-forget) |
| 67 | + this.syncToServer(anonymousId, level); |
| 68 | + } |
| 69 | + |
| 70 | + clearCookies(): void { |
| 71 | + deleteCookie(COOKIE_NAME, this.cookieDomain); |
| 72 | + deleteCookie(SESSION_COOKIE, this.cookieDomain); |
| 73 | + } |
| 74 | + |
| 75 | + private async syncToServer(anonymousId: string, status: ConsentLevel): Promise<void> { |
| 76 | + try { |
| 77 | + await fetch(`${this.baseUrl}${CONSENT_PATH}`, { |
| 78 | + method: 'PUT', |
| 79 | + headers: { |
| 80 | + 'Content-Type': 'application/json', |
| 81 | + 'x-immutable-publishable-key': this.publishableKey, |
| 82 | + }, |
| 83 | + body: JSON.stringify({ anonymousId, status, source: this.source }), |
| 84 | + }); |
| 85 | + } catch { |
| 86 | + // Fire-and-forget — consent sync failure shouldn't break the SDK |
| 87 | + } |
| 88 | + } |
| 89 | +} |
0 commit comments