UNPKG

@cnaught/analytics-consent-wrapper-cookieyes

Version:

Segment analytics consent wrapper for CookieYes

2 lines (1 loc) 8.95 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).AnalyticsCookieYes={})}(this,(function(e){"use strict";class t extends Error{constructor(e,t){super(t),this.name=e}}class n extends t{constructor(e,t){2===arguments.length&&(e+=` (Received: ${JSON.stringify(t)})`),super("ValidationError",`[Validation] ${e}`)}}function o(e,t){if("function"!=typeof e)throw new n(`${t} is not a function`,e)}function i(e,t){if(null===e||"object"!=typeof e)throw new n(`${t} is not an object`,e)}function a(e){let t=!0;if(e&&"object"==typeof e&&!Array.isArray(e)){t=!1;for(const n in e)if("boolean"!=typeof e[n]){t=!0;break}}if(t)throw new n("Consent Categories should be {[categoryName: string]: boolean}",e)}const s=(e,...t)=>{const n=t.reduce(((e,t)=>n=>t(e(n))),(e=>e));return(...t)=>n(e(...t))};async function r(e,t){return new Promise(((n,o)=>{if(e())return void n();const i=()=>setTimeout((()=>{e()?n():i()}),t);i()}))}const g=new class{get debugLoggingEnabled(){return!0===window.SEGMENT_CONSENT_WRAPPER_DEBUG_MODE}enableDebugLogging(){window.SEGMENT_CONSENT_WRAPPER_DEBUG_MODE=!0}debug(...e){this.debugLoggingEnabled&&console.log("[consent wrapper debug]",...e)}};class l{constructor(){this.isAbortCalled=!1,this.isLoadCalled=!1,this.abortLoadOptions={loadSegmentNormally:!0},this.loadOptions={consentModel:"opt-in"}}load(e){this.isLoadCalled=!0,this.loadOptions={...this.loadOptions,...e},g.debug("ctx.load called",this.loadOptions)}abort(e){this.isAbortCalled=!0,this.abortLoadOptions={...this.abortLoadOptions,...e},g.debug("Abort consent wrapper",this.loadOptions)}validate(){if(this.isAbortCalled&&this.isLoadCalled)throw new n("both abort and load should not be called")}}const d=e=>{return t=Object.values(e).reduce(((e,t)=>e.concat(t))),Array.from(new Set(t));var t},c=(e,t)=>!(!t||t.hasUnmappedDestinations)&&Object.keys(e).filter((t=>e[t])).every((e=>!t.allCategories.includes(e))),u=(e,t,n,o={})=>{const{integrationCategoryMappings:i,shouldEnableIntegration:a}=o,s=(i?i[e]:(e=>{if(e&&"object"==typeof e&&"consentSettings"in e&&"object"==typeof e.consentSettings&&e.consentSettings&&"categories"in e.consentSettings&&Array.isArray(e.consentSettings.categories))return e.consentSettings.categories||void 0})(t.integrations[e]))??[];return a?a(s,n,{creationName:e}):((e,t)=>!e||!e.length||e.every((e=>t[e])))(s,n)};class p{get analytics(){return h(this.uninitializedAnalytics)}get cdnSettings(){return this.cdnSettingsDeferred.promise}async getAllCategories(){return(this.settings.integrationCategoryMappings?d(this.settings.integrationCategoryMappings):(await this.cdnSettings).consentSettings?.allCategories)??[]}async getCategories(){const e=await this.settings.getCategories();return a(e),e}constructor(e,t){var o,a,s,r;this.cdnSettingsDeferred=(s=!1,r=new Promise((function(e,t){o=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];s=!0,e.apply(void 0,t)},a=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];s=!0,t.apply(void 0,e)}})),{resolve:o,reject:a,promise:r,isSettled:function(){return s}}),this.createDisableOption=(e,t)=>!0===t||(n=>c(e,n.consentSettings)||"function"==typeof t&&t(n)),function(e){if(i(e,"analytics"),!("load"in e&&"addSourceMiddleware"in e&&"addDestinationMiddleware"in e&&"track"in e))throw new n("analytics is not an Analytics instance",e)}(e),this.settings=t,this.uninitializedAnalytics=e,this.ogAnalyticsLoad=e.load.bind(e)}async loadWithFilteredDeviceModeDestinations(...[e,t]){const n=await this.getCategories();return this.load(e,{...t,updateCDNSettings:s((e=>((e,t,n)=>{const{remotePlugins:o,integrations:i}=e,{integrationCategoryMappings:a,shouldEnableIntegration:s}=n,r={...e,remotePlugins:[...o||[]],integrations:{...i}},l=n=>u(n,e,t,{integrationCategoryMappings:a,shouldEnableIntegration:s});for(const e in i)l(e)?g.debug(`Enabled (opt-in): ${e}`):(g.debug(`Disabled (opt-in): ${e}`),r.remotePlugins=o?.filter((t=>t.creationName!==e)),delete r.integrations[e]);return r})(e,n,{shouldEnableIntegration:this.settings.shouldEnableIntegration,integrationCategoryMappings:this.settings.integrationCategoryMappings})),t?.updateCDNSettings??(e=>e)),disable:this.createDisableOption(n,t?.disable)})}load(...[e,t]){return this.ogAnalyticsLoad(e,{...t,updateCDNSettings:s(t?.updateCDNSettings||(e=>e),(e=>(g.debug("CDN settings loaded",e),this.cdnSettingsDeferred.resolve(e),e)))})}replaceLoadMethod(e){this.analytics.load=e}page(){this.analytics.page()}configureBlockingMiddlewareForOptOut(){var e,t,n;e=this.cdnSettings,t=this.analytics,n={integrationCategoryMappings:this.settings.integrationCategoryMappings,shouldEnableIntegration:this.settings.shouldEnableIntegration},t.addDestinationMiddleware("*",(async({integration:t,payload:o,next:i})=>{const a=await e,s=o.obj.context.consent.categoryPreferences,r=!u(t,a,s,n);if(g.debug(`Destination middleware called: ${t}`,{DROPPED:r,categoryPreferences:s,payload:o.obj,filterSettings:n}),r)return null;i(o)})),t.addSourceMiddleware((async({payload:t,next:o})=>{const i=await e,a=t.obj.context.consent.categoryPreferences,s=n.integrationCategoryMappings?{hasUnmappedDestinations:!1,allCategories:d(n.integrationCategoryMappings)}:i.consentSettings,r=c(a,s);if(g.debug("Source middleware called",{DROPPED:r,categoryPreferences:a,payload:t.obj,filterSettings:n,consentSettings:s}),r)return null;o(t)}))}configureConsentStampingMiddleware(){const{pruneUnmappedCategories:e}=this.settings,t=(o=async()=>{const t=await this.getCategories();return e?((e,t)=>{if(!t.length)throw new n("Invariant: No consent categories defined in Segment",[]);return o=e,t.reduce(((e,t)=>(t in o&&(e[t]=o[t]),e)),{});var o})(t,await this.getAllCategories()):t},async({payload:e,next:t})=>{e.obj.context.consent={...e.obj.context.consent,categoryPreferences:await o()},t(e)});var o;this.analytics.addSourceMiddleware(t)}consentChange(e){g.debug("Consent change",e);try{a(e)}catch(e){return console.error(e)}this.analytics.track("Segment Consent Preference Updated",void 0,{consent:{categoryPreferences:e}})}}const h=e=>{if(Array.isArray(e)){const t=e._loadOptions??{},n=window[t?.globalAnalyticsKey??"analytics"];if(n?.initialized)return n}return e},y=(...[e])=>{!function(e){if("object"!=typeof e||!e)throw new n("Options should be an object",e);o(e.getCategories,"getCategories"),e.shouldLoadSegment&&o(e.shouldLoadSegment,"shouldLoadSegment"),e.shouldEnableIntegration&&o(e.shouldEnableIntegration,"shouldEnableIntegration"),e.shouldDisableSegment&&o(e.shouldDisableSegment,"shouldDisableSegment"),e.integrationCategoryMappings&&i(e.integrationCategoryMappings,"integrationCategoryMappings"),e.registerOnConsentChanged&&o(e.registerOnConsentChanged,"registerOnConsentChanged")}(e);const{shouldDisableSegment:t,getCategories:a,shouldLoadSegment:s,integrationCategoryMappings:r,shouldEnableIntegration:d,registerOnConsentChanged:c,shouldLoadWrapper:u,enableDebugLogging:h}=e;return e=>{const n=new p(e,{integrationCategoryMappings:r,shouldEnableIntegration:d,getCategories:a});h&&g.enableDebugLogging();const o=u?.()||Promise.resolve();o.then((()=>{c?.((e=>n.consentChange(e)))}));return n.replaceLoadMethod((async(e,i)=>{if(i?.initialPageview&&(n.page(),i={...i,initialPageview:!1}),await(t?.()))return;await o;const a=await(e=>async()=>{const t=new l;return await(e?.(t)),t.validate(),t})(s)();if(a.isAbortCalled)!0===a.abortLoadOptions?.loadSegmentNormally&&n.load(e,i);else{if(n.configureConsentStampingMiddleware(),"opt-in"!==a.loadOptions.consentModel)return"opt-out"===a.loadOptions.consentModel?(n.configureBlockingMiddlewareForOptOut(),void n.load(e,i)):void function(e){throw new Error(`Unhandled discriminated union member: ${JSON.stringify(e)}`)}(a.loadOptions.consentModel);await n.loadWithFilteredDeviceModeDestinations(e,i)}})),e}};function b(){var e;return null===(e=window.getCkyConsent)||void 0===e?void 0:e.call(window)}const f=(e,t={})=>y({shouldLoadWrapper:async()=>{await r((()=>!!window.getCkyConsent),500),t.enableDebugLogging&&console.log("Will load wrapper")},shouldLoadSegment:async e=>{var n,o;const{activeLaw:i,isUserActionCompleted:a,categories:s}=b(),g=null!==(o=null===(n=t.consentModel)||void 0===n?void 0:n.call(t))&&void 0!==o?o:function(e){return"ccpa"===e?"opt-out":"opt-in"}(i);return"opt-in"===g&&(await r((()=>a&&Object.values(s).some((e=>e))),500),t.enableDebugLogging&&console.log("Will load segment")),e.load({consentModel:g})},getCategories:()=>b().categories,registerOnConsentChanged:t.disableConsentChangedEvent?void 0:e=>{var t;t=t=>{const n={};t.detail.accepted.forEach((e=>n[e]=!0)),t.detail.rejected.forEach((e=>n[e]=!1)),e(n)},document.addEventListener("cookieyes_consent_update",t)},integrationCategoryMappings:t.integrationCategoryMappings,enableDebugLogging:t.enableDebugLogging})(e);"undefined"!=typeof window&&(window.withCookieYes=f),e.withCookieYes=f}));