UNPKG

@schibsted/sourcepoint

Version:

Package containing scripts used by Schibsteds' sites to integrate with Sourcepoint CMP

2 lines (1 loc) 19.4 kB
!function(){const e=["jsSdkVersion","id","realm","clientId","pulseTracker","referrer","state","pulseObjectName","showInWebview","identityObject","identityObjectName","disableSentry","disableNativeConsentCheck","enableUserCentric","groupId"],n=["jsSdkVersion","id","realm","clientId","pulseTracker","referrer","state","pulseObjectName","showInWebview","identityObject","identityObjectName","disableSentry","disableNativeConsentCheck","enableUserCentric","groupId"],t=["jsSdkVersion","id","realm","clientId","pulseTracker","referrer","state","pulseObjectName","showInWebview","identityObject","identityObjectName","disableSentry","disableNativeConsentCheck","enableUserCentric","enableEcosystemConsent","groupId"];function o(e,n){if(null==e)return{};var t={};for(var o in e)if({}.hasOwnProperty.call(e,o)){if(n.includes(o))continue;t[o]=e[o]}return t}function s(e,n){var t,o;if(null!=(t=e.psi)&&t.identityObject)return e.psi.identityObject;if(null!=n&&n.identityObject)return n.identityObject;const s=(null==(o=e.psi)?void 0:o.identityObjectName)||(null==n?void 0:n.identityObjectName)||"Identity";return e[s]?e[s]:console.warn("@schibsted/sourcepoint: No Schibsted Account integration detected.")}async function r(e,n,t){return void 0===n&&(n={}),void 0===t&&(t=1e4),new Promise(((o,r)=>{if(e.schIdentity)return o(e.schIdentity);const i=setTimeout((()=>{r(new Error("@schibsted/sourcepoint: Timeout of "+t+"ms exceeded while waiting for schIdentity instance"))}),t);e.addEventListener("schIdentity:ready",(e=>{let{detail:n}=e;I("schIdentity instance resolved from schIdentity:ready event ",!!n.instance),clearTimeout(i),o(n.instance)}),{once:!0});const c=s(e,n);c&&(console.warn("@schibsted/sourcepoint: schIdentity instance not found, falling back to legacy Identity instance. Please update to the latest Schibsted Account SDK."),clearTimeout(i),o(c))}))}function i(e){const n=Array.from({length:20},(()=>String.fromCharCode(Math.floor(25*Math.random()+97)))).join(""),t=btoa(JSON.stringify(n));s(e)&&s(e).login({state:t})}const c=["Mixed","PSI","SCC","TCF","PMC"],a="default",u="cmp",d="cache",l="accepted",p="rejected",f="unknown",g=Object.freeze({purposes:{CMP_ANALYTICS:{optIn:!1,status:f},CMP_MARKETING:{optIn:!1,status:f},CMP_ADVERTISING:{optIn:!1,status:f},CMP_PERSONALIZATION:{optIn:!1,status:f}},source:a});function m(e,n,t,o){I("Pulse: "+t+"(actor, data):",n,o),y(e,(e=>{e&&"function"==typeof e.track&&e.track(t,{schema:"http://schema.schibsted.com/events/tracker-event.json/314.json",object:Object.assign({},o,m.pulseCommonData),provider:{component:"CMP"},actor:n})}))}function y(e,n){var t,o;if(null!=(t=e.psi)&&t.pulseTracker)return n(e.psi.pulseTracker);const s=(null==(o=e.psi)?void 0:o.pulseObjectName)||"pulse";return"function"!=typeof e[s]?console.error("No Pulse integration detected. Aborting."):e[s]((e=>{"function"==typeof n&&n(e)}))}function b(){var e;const n=null==(e=m.pulseCommonData)?void 0:e.messageName;if(n)return c.find((e=>n.includes(e)))}function v(e){return"CMP_"+("personalisation"===e?"personalization":e).toUpperCase()}function h(e,n,t){const o=Object.keys(_(e)).filter((n=>_(e)[n])),s=Object.keys(_(e)).filter((n=>!_(e)[n]));return o.map((e=>{const t=n.purposes[v(e)];t.optIn=!0,t.status=l})),s.map((e=>{n.purposes[v(e)].status=p})),n.source=t,n}function _(e){const n=P((e._scc_||e._tcf_).getPermissionSync("CMP:advertising")),t=P((e._scc_||e._tcf_).getPermissionSync("CMP:analytics")),o=P((e._scc_||e._tcf_).getPermissionSync("CMP:marketing")),s=P((e._scc_||e._tcf_).getPermissionSync("CMP:personalisation"));var r;return r={advertising:n,analytics:t,marketing:o,personalisation:s},Object.entries(r).filter((e=>{let[n,t]=e;return null!=t})).reduce(((e,n)=>{let[t,o]=n;return Object.assign({},e,{[t]:o})}),{})}function w(e,n){const t=n.performance.now();return e?Math.round((t-e)/1e3):null}function I(){"undefined"!=typeof document&&document.location.href.indexOf("sp_debug=1")>0&&console.debug("[CMP]",...arguments)}function C(e,n,t,o,s){const r=new URL(e);r.searchParams.append("utm_source","cmp"),r.searchParams.append("utm_medium","psi"),r.searchParams.append("referrer",o||window.location.href),t&&r.searchParams.append("client_id",t),n&&r.searchParams.append("environment_id",n),s&&r.searchParams.append("state",s),window.location.href=r.href}function P(e){return null===e?null:Boolean(parseInt(e))}const S=(e,n)=>Object.keys(n).filter((n=>void 0!==e[n])).forEach((t=>"object"==typeof n[t]?Object.keys(n[t]).forEach((o=>e[t][o]=n[t][o])):e[t]=n[t]));function O(e,n,t){const o=new Date;o.setTime(o.getTime()+24*t*60*60*1e3);let s="expires="+o.toUTCString();document.cookie=e+"="+n+";"+s+";path=/"}function j(e){let n=e+"=",t=decodeURIComponent(document.cookie).split(";");for(let e=0;e<t.length;e++){let o=t[e];for(;" "==o.charAt(0);)o=o.substring(1);if(0==o.indexOf(n))return o.substring(n.length,o.length)}return""}function M(e){document.cookie=e+"=; Max-Age=-99999999;"}function E(e,n,t){e.targetingParams=e.targetingParams||{},e.targetingParams[n]=t}const T=function(e){if("number"==typeof e||void 0===e)return config.userId=e;throw new Error("Id value "+e+" is invalid")},k=function(e){return(e=>{try{return Boolean(new URL(e))}catch(e){return!1}})(e)?window.psi.isLoggedInUser?C(e,null,window.psi.clientId,window.psi.referrer,window.psi.state):y(window,(n=>{n.getEnvironmentId().then((n=>{C(e,n,window.psi.clientId,window.psi.referrer,window.psi.state)}))})):console.error("The URL passed to the configuration is invalid. Please, correct it.")},N=function(){return i(window)};function L(e,n){const t=e.baseEndpoint+"/unified/wrapperMessagingWithoutDetection.js",o=n.getElementsByTagName("script"),s=o[o.length-1],r=n.createElement("link");S(r,{rel:"preload",as:"script",crossorigin:"crossorigin",href:t}),n.head.appendChild(r);const i=n.createElement("script");S(i,{async:!0,src:t,onload:()=>(I("dispatching cmp:loaded event"),void document.dispatchEvent(new Event("cmp:loaded")))}),s.insertAdjacentElement("afterend",i)}function A(){I("dispatching cmp:ready event"),document.dispatchEvent(new Event("cmp:ready"))}function U(e){const n=e.createElement("script");n.innerHTML='"use strict";function _typeof(t){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}!function(){var t=function(){var t,e,o=[],n=window,r=n;for(;r;){try{if(r.frames.__tcfapiLocator){t=r;break}}catch(t){}if(r===n.top)break;r=r.parent}t||(!function t(){var e=n.document,o=!!n.frames.__tcfapiLocator;if(!o)if(e.body){var r=e.createElement("iframe");r.style.cssText="display:none",r.name="__tcfapiLocator",e.body.appendChild(r)}else setTimeout(t,5);return!o}(),n.__tcfapi=function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];if(!n.length)return o;"setGdprApplies"===n[0]?n.length>3&&2===parseInt(n[1],10)&&"boolean"==typeof n[3]&&(e=n[3],"function"==typeof n[2]&&n[2]("set",!0)):"ping"===n[0]?"function"==typeof n[2]&&n[2]({gdprApplies:e,cmpLoaded:!1,cmpStatus:"stub"}):o.push(n)},n.addEventListener("message",(function(t){var e="string"==typeof t.data,o={};if(e)try{o=JSON.parse(t.data)}catch(t){}else o=t.data;var n="object"===_typeof(o)&&null!==o?o.__tcfapiCall:null;n&&window.__tcfapi(n.command,n.version,(function(o,r){var a={__tcfapiReturn:{returnValue:o,success:r,callId:n.callId}};t&&t.source&&t.source.postMessage&&t.source.postMessage(e?JSON.stringify(a):a,"*")}),n.parameter)}),!1))};"undefined"!=typeof module?module.exports=t:t()}();',e.head.appendChild(n)}const R="__CONFIGURATION_PLACEHOLDER__";let D=null,x=!1,H=!1;function F(e,n){if(n&&("object"!=typeof(t=n)||t.constructor!==Object))return console.error("Provided object is incorrect");var t;if(0===Object.keys(_(e)).length){if(!n)return g;const e=JSON.parse(JSON.stringify(n));return e.source=a,e}return h(e,JSON.parse(JSON.stringify(n||g)),d)}function W(e,n){n.events=n.events||{};const t=n.events.onMessageReceiveData,o=n.events.onMessageChoiceSelect,s=n.events.onMessageReady,r=n.events.onPrivacyManagerAction,i=n.events.onConsentReady;let c,a=!0;const d={id:n.userId,realm:n.realm};n.events.onMessageReceiveData=function(e,o){I("Sourcepoint: onMessageReceiveData(data)",o),D=!0,m.pulseCommonData={"@id":"sdrn:privacy:cmp:"+(o.messageId||""),"@type":"CMP",messageName:o.msgDescription||"",propertyId:n.propertyId,messageId:o.messageId||void 0,bucket:o.bucket||void 0,jsSdkVersion:n.jsSdkVersion,partitionId:o.prtnUUID||"",language:n.consentLanguage},"function"==typeof t&&t(o)},n.events.onMessageReady=function(){var n;null==(n=window._tcf_)||null==(n=n.TCFCallbacks)||n.map((e=>{e()})),I("Sourcepoint: onMessageReady()");const t=b();if(I("Pulse: Detected message type: "+t),!D)return m(e,d,"View",{name:"CMP: Privacy Manager displayed",messageType:b()});c=e.performance.now(),m(e,d,"View",{name:"CMP: Message displayed",messageType:t}),"function"==typeof s&&s()},n.events.onMessageChoiceSelect=function(n,t,s){if(I("Sourcepoint: onMessageReady(choice_id="+t+", choice_type_id="+s+")"),5===s){const n=w(c,e);m(e,d,"engagementEvent",Object.assign({name:"CMP: Link to Privacy / Cookie Policy clicked",elementType:"anchor",isFirstLayer:D,messageType:b()},n&&{duration:n})),D=null}if(9===s){a=!1,D=null;const n=w(c,e);m(e,d,"engagementEvent",Object.assign({name:"CMP: Open Privacy Settings",elementType:"button",messageType:b()},n&&{duration:n}))}if(11===s&&(a=!0),12===s&&(D=!1),15===s){const n=w(c,e);m(e,d,"engagementEvent",Object.assign({name:"CMP: Dismiss message",elementType:"button",messageType:b()},n&&{duration:n}))}"function"==typeof o&&o(t,s)},n.events.onPrivacyManagerAction=function(e,n){I("Sourcepoint: onPrivacyManagerAction()"),x=!0,D=!1,"none"===n.purposeConsent?(H=!0,a=!1):(H=!1,a=!0),"function"==typeof r&&r()},n.events.onConsentReady=function(n,t,o,s){var r,l;null==(r=window._tcf_)||null==(r=r.consentedCallback)||r.map((e=>{e(s.consentedToAll)})),null==(l=window._tcf_)||null==(l=l.TCFCallbacks)||l.map((e=>{e()})),I("Sourcepoint: onConsentReady(message_type="+n+", consentUUID="+t+", euconsent)",o),I("Sourcepoint: getMessageType() "+b());const p=w(c,e);if(void 0===b()&&!x)return;const f="PSI"===b()?null:_(e);if(function(e){const n=JSON.parse(JSON.stringify(g));y(e,(t=>{try{t.setConsents(h(e,n,u))}catch(e){console.error("Consents couldn't be set. The provided version of Pulse SDK does not support the setConsents event")}}))}(e),H&&m(e,d,"engagementEvent",Object.assign({name:"CMP: Reject all",elementType:"button",messageType:b()},p&&{duration:p})),!a)return!1;m(e,d,"engagementEvent",Object.assign({name:"CMP: Accept",elementType:"button",messageType:b(),consentedToAll:null==s?void 0:s.consentedToAll,isFirstLayer:D||!!D},f&&{consents:f},p&&{duration:p})),D=null,x=!1,H=!1,"function"==typeof i&&i(n,t,o,s)}}function J(e,n,t){if(!n.groupPmId)throw new Error("groupPmId is required");const o="CMP:advertising",s="CMP:analytics",r="CMP:marketing",i="CMP:personalisation",c="CMP:performance_marketing";let a=[];const u={};function d(n){return I(t+": getPermissionFromCache(category="+n+")"),e.localStorage.getItem(n)}u[o]=[],u[s]=[],u[r]=[],u[i]=[],u[c]=[];let l=null;const p={subscribers:u,consentedCallback:[],TCFCallbacks:[],showPrivacyManager:function(){I("${type}: showPrivacyManager()"),m.pulseCommonData.messageName="",x=!0,D=!1,e._sp_.gdpr.loadPrivacyManagerModal(n.groupPmId)},getPermissionSync:function(e){return I(t+": getPermissionSync(category="+e+")"),d(e)},getPermission:function(e,n){I(t+": getPermission(category="+e+")");const o=p.subscribe(e,function(){let e=!1;return t=>{e?"function"==typeof o&&o():(e=!0,n(t),n=function(){})}}())},notify:(f={[o]:d(o),[s]:d(s),[r]:d(r),[i]:d(i),[c]:d(c)},(e,n)=>{if(f[e]===n)return void I(t+": notify(category="+e+", value="+n+") - IGNORED");null===l&&(l=setTimeout((()=>{const e=a;for(let n=0;n<e.length;n++)e[n]();l=null}),10)),I(t+": notify(category="+e+", value="+n+")"),f[e]=n;const o=p.subscribers[e];for(let e=0;e<o.length;e++)o[e](n)}),subscribe:function(e,n){if(I(t+": subscribe(category="+e+")"),!p.subscribers[e])return void console.error("Unable to subscribe - undefined consent category!");p.subscribers[e].push(n);const o=d(e);return null!==o&&n(o),()=>{p.subscribers[e]=p.subscribers[e].filter((e=>e!==n))}},subscribeAny:function(e){return I("subscribeAny"),a.push(e),()=>{a=a.filter((n=>n!==e))}},getCachedOrDefaultConsentsForPulse:function(n){return F(e,n)},isConsentedToAll:function(e){p.consentedCallback.push(e)},getConsentedToAllSync:function(){const e=d("_sp_user_consent_"+n.propertyId);try{var t;if(0===Object.keys(localStorage).filter((e=>e.startsWith("CMP:"))).length)return null;const n=null==(t=JSON.parse(e))||null==(t=t.gdpr)?void 0:t.consentStatus;if((null==n?void 0:n.vendorListAdditions)||(null==n?void 0:n.legalBasisChanges))return null;const o=null==n?void 0:n.consentedAll;return void 0===o?null:o}catch(e){return null}},onTcfReady:function(e){p.TCFCallbacks.push(e)}};var f;return e._SourcePoint_Consent_Callback=p.notify,p}function V(e){e.events=e.events||{},e.events.onError=function(n,t,o){try{n&&window._cmp_.sentry.setTag("message_type",n),t&&window._cmp_.sentry.setTag("errorCode",t),window._cmp_.sentry.setTag("propertyId",e.propertyId),window._cmp_.sentry.captureException(o)}catch(e){console.error("Can not send the error to Sentry, "+e)}},e.events.onMessageChoiceError=function(e,n){try{e&&window._cmp_.sentry.setTag("message_type",e),window._cmp_.sentry.captureException(n)}catch(n){console.error("Can not send the error to Sentry, "+n)}}}const G=["Hermes","_app_","tv.nu","FinnApp","Omni"];function z(e){return G.some((n=>e.userAgent.includes(n)))}function B(e,n,t){return z(n)&&!t.disableNativeConsentCheck&&!function(e){var n;const t=new URLSearchParams(null==(n=e.location)?void 0:n.search),o=t.has("_sp_pass_consent");try{if(o)return e.sessionStorage.setItem("_sp_pass_consent","true"),!0;if("true"===e.sessionStorage.getItem("_sp_pass_consent")){t.set("_sp_pass_consent","true");const n=e.location.pathname+"?"+t.toString()+e.location.hash;return e.history.replaceState({},"",n),!0}}catch(e){return o}return!1}(e)}function K(e,n,t,o,r){var i,c,a;if(!o.baseEndpoint||!o.propertyId||!o.consentLanguage)throw new Error("One of missing: baseEndpoint, propertyId, consentLanguage");W(e,o),V(o),o.accountId=o.accountId||1047,o.custom={},o.gdpr={includeTcfApi:"tcf"===r},o.propertyHref&&(o.joinHref=!0);const u=o.userId||(null==(i=s(e,o))?void 0:i._session.userId);u&&E(o,"loggedin","true");const d=o.clientId||(null==(c=s(e,o))?void 0:c.clientId);z(t)&&E(o,"mobile-webview",!o.showInWebview||o.showInWebview);const l=null==n||null==(a=n.referrer)?void 0:a.split("/")[2];l&&E(o,"referrer-hostname",l),function(){const e=/(_sch_cmp_[_a-z0-9]+)=(.+)/i;n.cookie.split(";").filter((n=>e.test(n))).map((e=>e.split("=").map((e=>e.trim())))).forEach((e=>{let[n,t]=e;return E(o,n,t)}))}(),o.propertyHref&&n.location.search&&-1===o.propertyHref.indexOf("?")&&(o.propertyHref+=n.location.search);const{pulseTracker:p,referrer:f,state:g,pulseObjectName:m,showInWebview:y,identityObject:b,identityObjectName:v,enableUserCentric:h,groupId:_}=o;e.psi=e.psi||{},e.psi.isLoggedInUser=!!u,e.psi.setUserId=T,e.psi.openPrivacySettings=k,e.psi.pulseTracker=p,e.psi.clientId=d,e.psi.referrer=f,e.psi.state=g,e.psi.pulseObjectName=m,e.psi.showInWebview=y,e.psi.identityObject=b,e.psi.identityObjectName=v,e.psi.triggerLogin=N,e.psi.enableUserCentric=h,e.psi.groupId=_}function q(e,n){e._sp_=e._sp_||{},e._sp_.config=n,I("Sourcepoint initiated with config: ",n)}async function Y(e,n,i,c){!function(e,n,t,o){var r,i;if(!o.baseEndpoint||!o.propertyId||!o.consentLanguage)throw new Error("One of missing: baseEndpoint, propertyId, consentLanguage");e._sp_=e._sp_||{},e._sp_.config=e._sp_.config||{},W(e,o),V(o),o.propertyHref&&(o.joinHref=!0);o.accountId=o.accountId||1047,o.custom={},o.gdpr={includeTcfApi:!0};["baseEndpoint","propertyId","consentLanguage","accountId","propertyHref","joinHref","gdpr","custom"].forEach((n=>{void 0!==o[n]&&(e._sp_.config[n]=o[n])}));const c=o.userId||(null==(r=s(e,o))||null==(r=r._session)?void 0:r.userId),a=o.clientId||(null==(i=s(e,o))?void 0:i.clientId),{pulseTracker:u,referrer:d,state:l,pulseObjectName:p,showInWebview:f,identityObject:g,identityObjectName:m,enableUserCentric:y,groupId:b}=o;e.psi=e.psi||{},e.psi.isLoggedInUser=!!c,e.psi.setUserId=T,e.psi.openPrivacySettings=k,e.psi.pulseTracker=u,e.psi.clientId=a,e.psi.referrer=d,e.psi.state=l,e.psi.pulseObjectName=p,e.psi.showInWebview=f,e.psi.identityObject=g,e.psi.identityObjectName=m,e.psi.triggerLogin=N,e.psi.enableUserCentric=y,e.psi.groupId=b}(e,0,0,c);const{enableEcosystemConsent:a}=c,u=o(c,t);if(!a)return I("Ecosystem Consent is disabled"),Z(e,u);try{const n=await r(e);if(!n)return console.warn("Ecosystem Consent: No Schibsted Account integration detected."),Z(e,u);const t=await async function(e){if(!e)return null;try{if(!(j("CMP:isLoggedIn")||await e.isLoggedIn()))return null;e.on("logout",(function(){M("CMP:isLoggedIn")})),j("CMP:isLoggedIn")||O("CMP:isLoggedIn",!0);const n=await e.getUserId();if(!n)return console.warn("Ecosystem Consent: Invalid userId received from getUserId()"),null;const t=await async function(e){const n=(new TextEncoder).encode(e),t=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(t)).map((e=>e.toString(16).padStart(2,"0"))).join("")}(n);return t}catch(e){return console.error("Ecosystem Consent - Identity error: ",e),null}}(n);return t?(I("Ecosystem Consent: AuthId resolved for authenticated user"),E(c,"ecosystem-consent",!0),Z(e,Object.assign({authId:t,targetingParams:c.targetingParams},u))):(I("Ecosystem Consent: No authId available, falling back to standard config"),Z(e,u))}catch(n){return console.error("Ecosystem Consent setup error: ",n),Z(e,u)}}function Z(e,n){e._sp_=e._sp_||{},e._sp_.config=e._sp_.config||{},Object.assign(e._sp_.config,n),I("Ecosystem Consent initiated with config: ",e._sp_.config)}B(window,navigator,R)?(console.warn("CMP: Native consent is not passed. Sourcepoint will not be initialized."),window._sp_={config:{accountId:1047,baseEndpoint:"https://cdn.privacy-mgmt.com"}}):(U(document),function(e,n){if(n.disableSentry)return;const t=e.createElement("script");S(t,{async:!0,type:"module",src:"https://static.privacy.schibsted.com/dist/index.js",fetchPriority:"low"}),e.head.appendChild(t)}(document,R),function(e,n){e._tcf_=J(e,n)}(window,R),R.enableEcosystemConsent?Y(window,document,navigator,R).then((()=>{A()})):R.enableUserCentric?async function(e,t,s,i,c){K(e,t,s,i,c);const a=o(i,n);try{const n=await r(e);if(!j("CMP:isLoggedIn")&&!await n.isLoggedIn())return q(e,a);n.on("logout",(function(){M("CMP:isLoggedIn")})),j("CMP:isLoggedIn")||O("CMP:isLoggedIn",!0),E(i,"loggedin",!0);const t={externalParty:"sourcepoint",optionalSuffix:i.groupId},o=await n.getExternalId(t.externalParty,t.optionalSuffix),s=E(i,"enableUserCentric",!0);q(e,Object.assign({authId:o,targetingParams:s},a))}catch(n){console.error("Identity: ",n),q(e,a)}}(window,document,navigator,R,"tcf").then((()=>{A()})):(function(n,t,s,r,i){K(n,t,s,r,i),q(n,o(r,e))}(window,document,navigator,R,"tcf"),A())),function(){if(!B(window,navigator,R)){if(U(document),R.enableEcosystemConsent){const e=800;let n=!1;const t=()=>{n||(n=!0,L(R,document))};return document.addEventListener("cmp:ready",t,{once:!0}),void setTimeout(t,e)}L(R,document)}}()}();