@financial-times/cmp-client 3.2.0 → 3.3.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +17 -2
  2. package/dist/cmp-static.js +660 -0
  3. package/dist/index.cjs +205 -2761
  4. package/dist/index.js +205 -2761
  5. package/dist/src/client.d.ts.map +1 -1
  6. package/dist/src/cmp-static.d.ts +2 -0
  7. package/dist/src/cmp-static.d.ts.map +1 -0
  8. package/dist/src/consent-ready/index.d.ts.map +1 -1
  9. package/dist/src/consent-ready/utils/__fixtures__/helpers.d.ts +27 -0
  10. package/dist/src/consent-ready/utils/__fixtures__/helpers.d.ts.map +1 -0
  11. package/dist/src/consent-ready/utils/__fixtures__/strings.d.ts +4 -8
  12. package/dist/src/consent-ready/utils/__fixtures__/strings.d.ts.map +1 -1
  13. package/dist/src/consent-ready/utils/__tests__/consent.test.d.ts +2 -0
  14. package/dist/src/consent-ready/utils/__tests__/consent.test.d.ts.map +1 -0
  15. package/dist/src/consent-ready/utils/consent.d.ts +6 -0
  16. package/dist/src/consent-ready/utils/consent.d.ts.map +1 -0
  17. package/dist/src/consent-ready/utils/get-consent-payload.d.ts +7 -7
  18. package/dist/src/consent-ready/utils/get-consent-payload.d.ts.map +1 -1
  19. package/dist/src/consent-ready/utils/get-parsed-consent.d.ts +6 -5
  20. package/dist/src/consent-ready/utils/get-parsed-consent.d.ts.map +1 -1
  21. package/dist/src/consent-ready/utils/validators.d.ts +0 -1
  22. package/dist/src/consent-ready/utils/validators.d.ts.map +1 -1
  23. package/dist/src/html/cmp-footer-link.d.ts +8 -4
  24. package/dist/src/html/cmp-footer-link.d.ts.map +1 -1
  25. package/dist/src/html/cmp-scripts.d.ts.map +1 -1
  26. package/dist/src/index.d.ts +1 -1
  27. package/dist/src/index.d.ts.map +1 -1
  28. package/dist/src/lib/constants.d.ts +33 -2
  29. package/dist/src/lib/constants.d.ts.map +1 -1
  30. package/dist/src/lib/properties.d.ts +36 -0
  31. package/dist/src/lib/properties.d.ts.map +1 -1
  32. package/dist/src/tracking/index.d.ts +1 -1
  33. package/dist/src/tracking/index.d.ts.map +1 -1
  34. package/dist/src/tracking/state.d.ts +6 -0
  35. package/dist/src/tracking/state.d.ts.map +1 -1
  36. package/dist/src/utils/__tests__/url.test.d.ts +2 -0
  37. package/dist/src/utils/__tests__/url.test.d.ts.map +1 -0
  38. package/dist/src/utils/url.d.ts +126 -0
  39. package/dist/src/utils/url.d.ts.map +1 -0
  40. package/package.json +11 -11
  41. package/typings/globals.d.ts +4 -0
  42. package/typings/types.d.ts +54 -4
  43. package/dist/src/consent-ready/utils/has-consent-changed.d.ts +0 -3
  44. package/dist/src/consent-ready/utils/has-consent-changed.d.ts.map +0 -1
  45. package/dist/src/html/__tests__/cmp-footer-links.test.d.ts +0 -2
  46. package/dist/src/html/__tests__/cmp-footer-links.test.d.ts.map +0 -1
  47. package/dist/src/lib/enableNonEssentialCookiesOption.d.ts +0 -2
  48. package/dist/src/lib/enableNonEssentialCookiesOption.d.ts.map +0 -1
  49. package/dist/src/utils/cookie.d.ts +0 -2
  50. package/dist/src/utils/cookie.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,11 +1,3 @@
1
- var __defProp = Object.defineProperty;
2
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
- var __publicField = (obj, key, value) => {
4
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
- return value;
6
- };
7
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r;
8
- const version = "3.2.0";
9
1
  const events = {
10
2
  onMessageChoiceSelect: (...args) => {
11
3
  console.log("[debug] onMessageChoiceSelect", args);
@@ -29,8 +21,8 @@ const events = {
29
21
  console.log("[debug] onSPPMObjectReady", args);
30
22
  },
31
23
  onConsentReady: async (...args) => {
32
- const [legislation2, consentUUID, consentString, consentMeta] = args;
33
- console.log("[debug] onConsentReady", { legislation: legislation2, consentString, consentMeta, consentUUID });
24
+ const [legislation, consentUUID, consentString, consentMeta] = args;
25
+ console.log("[debug] onConsentReady", { legislation, consentString, consentMeta, consentUUID });
34
26
  },
35
27
  onError: (...args) => {
36
28
  console.log("[debug] onError", args);
@@ -39,9 +31,9 @@ const events = {
39
31
  function logCmpEvents() {
40
32
  window._sp_queue = window._sp_queue ?? [];
41
33
  window._sp_queue.push(() => {
42
- var _a2, _b2;
34
+ var _a, _b;
43
35
  for (const [eventId, eventHandler] of Object.entries(events)) {
44
- (_b2 = (_a2 = window._sp_).addEventListener) == null ? void 0 : _b2.call(_a2, eventId, eventHandler);
36
+ (_b = (_a = window._sp_).addEventListener) == null ? void 0 : _b.call(_a, eventId, eventHandler);
45
37
  }
46
38
  });
47
39
  }
@@ -59,67 +51,103 @@ const FT_DOTCOM_TEST = {
59
51
  ...defaults,
60
52
  accountId: 1906,
61
53
  baseEndpoint: "https://consent-manager.ft.com",
62
- propertyHref: "https://local.ft.com"
54
+ propertyHref: "https://local.ft.com",
55
+ _clientOptions: {
56
+ privacyManagerId: 827767,
57
+ manageCookiesLinkOverride: "ft.com/preferences/manage-cookies"
58
+ }
63
59
  };
64
60
  const FT_DOTCOM_PROD = {
65
61
  ...defaults,
66
62
  accountId: 1906,
67
63
  baseEndpoint: "https://consent-manager.ft.com",
68
- propertyId: 31642
64
+ propertyId: 31642,
65
+ _clientOptions: {
66
+ privacyManagerId: 827767,
67
+ manageCookiesLinkOverride: "ft.com/preferences/manage-cookies",
68
+ rootDomain: "ft.com"
69
+ }
69
70
  };
70
71
  const SP_PWMNET = {
71
72
  ...defaults,
72
73
  accountId: 1906,
73
74
  baseEndpoint: "https://consent-manager.pwmnet.com",
74
- propertyId: 33414
75
+ propertyId: 33414,
76
+ _clientOptions: {
77
+ rootDomain: "pwmnet.com"
78
+ }
75
79
  };
76
80
  const SP_FDI_INTELLIGENCE = {
77
81
  ...defaults,
78
82
  accountId: 1906,
79
83
  baseEndpoint: "https://consent-manager.fdiintelligence.com",
80
- propertyId: 34061
84
+ propertyId: 34061,
85
+ _clientOptions: {
86
+ rootDomain: "fdiintelligence.com"
87
+ }
81
88
  };
82
89
  const SP_THE_BANKER = {
83
90
  ...defaults,
84
91
  accountId: 1906,
85
92
  baseEndpoint: "https://consent-manager.thebanker.com",
86
- propertyId: 34060
93
+ propertyId: 34060,
94
+ _clientOptions: {
95
+ rootDomain: "thebanker.com"
96
+ }
87
97
  };
88
98
  const SP_BANKING_RR = {
89
99
  ...defaults,
90
100
  accountId: 1906,
91
101
  baseEndpoint: "https://consent-manager.bankingriskandregulation.com",
92
- propertyId: 34059
102
+ propertyId: 34059,
103
+ _clientOptions: {
104
+ rootDomain: "bankingriskandregulation.com"
105
+ }
93
106
  };
94
107
  const SP_SUSTAINABLE_VIEWS = {
95
108
  ...defaults,
96
109
  accountId: 1906,
97
110
  baseEndpoint: "https://consent-manager.sustainableviews.com",
98
- propertyId: 34058
111
+ propertyId: 34058,
112
+ _clientOptions: {
113
+ rootDomain: "sustainableviews.com"
114
+ }
99
115
  };
100
116
  const SP_FT_ADVISER = {
101
117
  ...defaults,
102
118
  accountId: 1906,
103
119
  baseEndpoint: "https://consent-manager.ftadviser.com",
104
- propertyId: 33416
120
+ propertyId: 33416,
121
+ _clientOptions: {
122
+ rootDomain: "ftadviser.com"
123
+ }
105
124
  };
106
125
  const SP_INVESTORS_CHRONICLE = {
107
126
  ...defaults,
108
127
  accountId: 1906,
109
128
  baseEndpoint: "https://consent-manager.investorschronicle.co.uk",
110
- propertyId: 33415
129
+ propertyId: 33415,
130
+ _clientOptions: {
131
+ rootDomain: "investorschronicle.co.uk"
132
+ }
111
133
  };
112
134
  const MM_IGNITES_ASIA = {
113
135
  ...defaults,
114
136
  accountId: 1906,
115
137
  baseEndpoint: "https://cdn.privacy-mgmt.com",
116
- propertyId: 33947
138
+ propertyId: 33947,
139
+ _clientOptions: {
140
+ rootDomain: "ignitesasia.com"
141
+ }
117
142
  };
118
143
  const MM_IGNITES_EUROPE = {
119
144
  ...defaults,
120
145
  accountId: 1906,
121
146
  baseEndpoint: "https://cdn.privacy-mgmt.com",
122
- propertyId: 33946
147
+ propertyId: 33946,
148
+ _clientOptions: {
149
+ rootDomain: "igniteseurope.com"
150
+ }
123
151
  };
124
152
  const properties = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
125
153
  __proto__: null,
@@ -135,18 +163,20 @@ const properties = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.definePr
135
163
  SP_SUSTAINABLE_VIEWS,
136
164
  SP_THE_BANKER
137
165
  }, Symbol.toStringTag, { value: "Module" }));
138
- function updateFooterLinkCMP() {
139
- const cookieLink = document.querySelector(
140
- "[href='https://www.ft.com/preferences/manage-cookies']"
141
- );
142
- if (cookieLink) {
143
- cookieLink.href = "#";
144
- cookieLink.setAttribute("onclick", "window._sp_.gdpr.loadPrivacyManagerModal(827767);");
145
- cookieLink.dataset.cmpLink = "updated";
146
- return true;
166
+ function updateFooterLinkCMP(propertyConfig = FT_DOTCOM_PROD) {
167
+ const { privacyManagerId, manageCookiesLinkOverride, manageCookiesSelector } = propertyConfig._clientOptions || {};
168
+ const footer = document.querySelector(manageCookiesSelector ?? "#site-footer");
169
+ if (footer && manageCookiesLinkOverride) {
170
+ footer.addEventListener("click", (event) => {
171
+ var _a, _b, _c;
172
+ const link = event.target.closest("a");
173
+ if ((_a = link == null ? void 0 : link.getAttribute("href")) == null ? void 0 : _a.endsWith(manageCookiesLinkOverride)) {
174
+ event.preventDefault();
175
+ (_c = (_b = window._sp_) == null ? void 0 : _b.gdpr) == null ? void 0 : _c.loadPrivacyManagerModal(privacyManagerId);
176
+ }
177
+ });
147
178
  } else {
148
- console.warn("CMP Footer Link was not found and not updated");
149
- return false;
179
+ console.warn("No footer found for", manageCookiesSelector);
150
180
  }
151
181
  }
152
182
  const request = (url, { credentials = "omit" } = {}) => {
@@ -225,10 +255,6 @@ const CONSENT_COOKIE_NAME = "FTConsent";
225
255
  const SOURCEPOINT_FOW_ID = "sourcepointCmp/VngD.XycZut.595cp9fWdp5XYP9vlFvk";
226
256
  const FT_COOKIE_DOMAIN = ".ft.com";
227
257
  const FT_CONSENT_PROXY_HOST = "https://consent.ft.com";
228
- const legislation = {
229
- CCPA: "ccpa",
230
- GDPR: "gdpr"
231
- };
232
258
  const iabCustomCategories = {
233
259
  permutiveAds: {
234
260
  purposes: [2, 4, 8, 9],
@@ -248,6 +274,12 @@ const iabCustomCategories = {
248
274
  customVendors: [],
249
275
  specialFeatures: []
250
276
  },
277
+ programmaticAds: {
278
+ purposes: [2],
279
+ iabVendors: [],
280
+ customVendors: [],
281
+ specialFeatures: []
282
+ },
251
283
  personalisedMarketing: {
252
284
  purposes: [1, 4, 8, 9, 10],
253
285
  iabVendors: [],
@@ -255,6 +287,7 @@ const iabCustomCategories = {
255
287
  specialFeatures: []
256
288
  }
257
289
  };
290
+ const iabCategoryNames = Object.keys(iabCustomCategories);
258
291
  function createContentScript(cmpScript, content) {
259
292
  const s = document.createElement("script");
260
293
  s.dataset.cmpScript = cmpScript;
@@ -270,8 +303,8 @@ const scriptSources = {
270
303
  cmpFrames: "https://consent-manager.ft.com/unified/wrapperMessagingWithoutDetection.js"
271
304
  };
272
305
  const scriptContent = {
273
- tcfStub: `"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()}();`,
274
- uspStub: `"use strict";(function () { var e = false; var c = window; var t = document; function r() { if (!c.frames["__uspapiLocator"]) { if (t.body) { var a = t.body; var e = t.createElement("iframe"); e.style.cssText = "display:none"; e.name = "__uspapiLocator"; a.appendChild(e) } else { setTimeout(r, 5) } } } r(); function p() { var a = arguments; __uspapi.a = __uspapi.a || []; if (!a.length) { return __uspapi.a } else if (a[0] === "ping") { a[2]({ gdprAppliesGlobally: e, cmpLoaded: false }, true) } else { __uspapi.a.push([].slice.apply(a)) } } function l(t) { var r = typeof t.data === "string"; try { var a = r ? JSON.parse(t.data) : t.data; if (a.__cmpCall) { var n = a.__cmpCall; c.__uspapi(n.command, n.parameter, function (a, e) { var c = { __cmpReturn: { returnValue: a, success: e, callId: n.callId } }; t.source.postMessage(r ? JSON.stringify(c) : c, "*") }) } } catch (a) { } } if (typeof __uspapi !== "function") { c.__uspapi = p; __uspapi.msgHandler = l; c.addEventListener("message", l, false) } })();`
306
+ tcfStub: `"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",r.title = "__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()}();`,
307
+ uspStub: `"use strict";(function () { var e = false; var c = window; var t = document; function r() { if (!c.frames["__uspapiLocator"]) { if (t.body) { var a = t.body; var e = t.createElement("iframe"); e.style.cssText = "display:none"; e.name = "__uspapiLocator"; e.title = "__uspapiLocator";a.appendChild(e) } else { setTimeout(r, 5) } } } r(); function p() { var a = arguments; __uspapi.a = __uspapi.a || []; if (!a.length) { return __uspapi.a } else if (a[0] === "ping") { a[2]({ gdprAppliesGlobally: e, cmpLoaded: false }, true) } else { __uspapi.a.push([].slice.apply(a)) } } function l(t) { var r = typeof t.data === "string"; try { var a = r ? JSON.parse(t.data) : t.data; if (a.__cmpCall) { var n = a.__cmpCall; c.__uspapi(n.command, n.parameter, function (a, e) { var c = { __cmpReturn: { returnValue: a, success: e, callId: n.callId } }; t.source.postMessage(r ? JSON.stringify(c) : c, "*") }) } } catch (a) { } } if (typeof __uspapi !== "function") { c.__uspapi = p; __uspapi.msgHandler = l; c.addEventListener("message", l, false) } })();`
275
308
  };
276
309
  function getCmpScripts() {
277
310
  const fragment = document.createDocumentFragment();
@@ -281,11 +314,12 @@ function getCmpScripts() {
281
314
  return fragment;
282
315
  }
283
316
  function bootstrapCmp(config) {
284
- window._sp_ = { config };
317
+ const { _clientOptions, ...spConfig } = config;
318
+ window._sp_ = { config: spConfig };
285
319
  window._sp_queue ?? (window._sp_queue = []);
286
320
  document.head.appendChild(getCmpScripts());
287
321
  }
288
- function getConsentPayload(parsedConsent, { shouldUpdateConsentStore, formOfWordsId, cookieDomain }) {
322
+ function getConsentPayload(parsedConsent, updateConsentStore, { formOfWordsId, cookieDomain }) {
289
323
  const categoryNames = Object.keys(parsedConsent);
290
324
  const data = categoryNames.reduce(
291
325
  (payload, categoryName) => {
@@ -301,9 +335,7 @@ function getConsentPayload(parsedConsent, { shouldUpdateConsentStore, formOfWord
301
335
  },
302
336
  {}
303
337
  );
304
- if (!shouldUpdateConsentStore) {
305
- return { data, cookieDomain };
306
- } else {
338
+ if (updateConsentStore) {
307
339
  return {
308
340
  setConsentCookie: true,
309
341
  formOfWordsId,
@@ -312,2549 +344,46 @@ function getConsentPayload(parsedConsent, { shouldUpdateConsentStore, formOfWord
312
344
  data
313
345
  };
314
346
  }
347
+ return { data, cookieDomain };
315
348
  }
316
- class DecodingError extends Error {
317
- /**
318
- * constructor - constructs an DecodingError
319
- *
320
- * @param {string} msg - Decoding Error Message
321
- * @return {undefined}
322
- */
323
- constructor(msg) {
324
- super(msg);
325
- this.name = "DecodingError";
326
- }
327
- }
328
- class EncodingError extends Error {
329
- /**
330
- * constructor - constructs an EncodingError
331
- *
332
- * @param {string} msg - Encoding Error Message
333
- * @return {undefined}
334
- */
335
- constructor(msg) {
336
- super(msg);
337
- this.name = "EncodingError";
338
- }
339
- }
340
- class GVLError extends Error {
341
- /**
342
- * constructor - constructs a GVLError
343
- *
344
- * @param {string} msg - Error message to display
345
- * @return {undefined}
346
- */
347
- constructor(msg) {
348
- super(msg);
349
- this.name = "GVLError";
350
- }
351
- }
352
- class TCModelError extends Error {
353
- /**
354
- * constructor - constructs an TCModelError
355
- *
356
- * @param {string} fieldName - the errored field
357
- * @param {string} passedValue - what was passed
358
- * @return {undefined}
359
- */
360
- constructor(fieldName, passedValue, msg = "") {
361
- super(`invalid value ${passedValue} passed for ${fieldName} ${msg}`);
362
- this.name = "TCModelError";
363
- }
364
- }
365
- class Base64Url {
366
- /**
367
- * encodes an arbitrary-length bitfield string into base64url
368
- *
369
- * @static
370
- * @param {string} str - arbitrary-length bitfield string to be encoded to base64url
371
- * @return {string} - base64url encoded result
372
- */
373
- static encode(str) {
374
- if (!/^[0-1]+$/.test(str)) {
375
- throw new EncodingError("Invalid bitField");
376
- }
377
- const padding = str.length % this.LCM;
378
- str += padding ? "0".repeat(this.LCM - padding) : "";
379
- let result = "";
380
- for (let i = 0; i < str.length; i += this.BASIS) {
381
- result += this.DICT[parseInt(str.substr(i, this.BASIS), 2)];
382
- }
383
- return result;
384
- }
385
- /**
386
- * decodes a base64url encoded bitfield string
387
- *
388
- * @static
389
- * @param {string} str - base64url encoded bitfield string to be decoded
390
- * @return {string} - bitfield string
391
- */
392
- static decode(str) {
393
- if (!/^[A-Za-z0-9\-_]+$/.test(str)) {
394
- throw new DecodingError("Invalidly encoded Base64URL string");
395
- }
396
- let result = "";
397
- for (let i = 0; i < str.length; i++) {
398
- const strBits = this.REVERSE_DICT.get(str[i]).toString(2);
399
- result += "0".repeat(this.BASIS - strBits.length) + strBits;
400
- }
401
- return result;
402
- }
403
- }
404
- /**
405
- * Base 64 URL character set. Different from standard Base64 char set
406
- * in that '+' and '/' are replaced with '-' and '_'.
407
- */
408
- __publicField(Base64Url, "DICT", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");
409
- __publicField(Base64Url, "REVERSE_DICT", /* @__PURE__ */ new Map([
410
- ["A", 0],
411
- ["B", 1],
412
- ["C", 2],
413
- ["D", 3],
414
- ["E", 4],
415
- ["F", 5],
416
- ["G", 6],
417
- ["H", 7],
418
- ["I", 8],
419
- ["J", 9],
420
- ["K", 10],
421
- ["L", 11],
422
- ["M", 12],
423
- ["N", 13],
424
- ["O", 14],
425
- ["P", 15],
426
- ["Q", 16],
427
- ["R", 17],
428
- ["S", 18],
429
- ["T", 19],
430
- ["U", 20],
431
- ["V", 21],
432
- ["W", 22],
433
- ["X", 23],
434
- ["Y", 24],
435
- ["Z", 25],
436
- ["a", 26],
437
- ["b", 27],
438
- ["c", 28],
439
- ["d", 29],
440
- ["e", 30],
441
- ["f", 31],
442
- ["g", 32],
443
- ["h", 33],
444
- ["i", 34],
445
- ["j", 35],
446
- ["k", 36],
447
- ["l", 37],
448
- ["m", 38],
449
- ["n", 39],
450
- ["o", 40],
451
- ["p", 41],
452
- ["q", 42],
453
- ["r", 43],
454
- ["s", 44],
455
- ["t", 45],
456
- ["u", 46],
457
- ["v", 47],
458
- ["w", 48],
459
- ["x", 49],
460
- ["y", 50],
461
- ["z", 51],
462
- ["0", 52],
463
- ["1", 53],
464
- ["2", 54],
465
- ["3", 55],
466
- ["4", 56],
467
- ["5", 57],
468
- ["6", 58],
469
- ["7", 59],
470
- ["8", 60],
471
- ["9", 61],
472
- ["-", 62],
473
- ["_", 63]
474
- ]));
475
- /**
476
- * log2(64) = 6
477
- */
478
- __publicField(Base64Url, "BASIS", 6);
479
- __publicField(Base64Url, "LCM", 24);
480
- const _ConsentLanguages = class _ConsentLanguages {
481
- has(key) {
482
- return _ConsentLanguages.langSet.has(key);
483
- }
484
- parseLanguage(lang) {
485
- lang = lang.toUpperCase();
486
- const primaryLanguage = lang.split("-")[0];
487
- if (lang.length >= 2 && primaryLanguage.length == 2) {
488
- if (_ConsentLanguages.langSet.has(lang)) {
489
- return lang;
490
- } else if (_ConsentLanguages.langSet.has(primaryLanguage)) {
491
- return primaryLanguage;
492
- }
493
- const fullPrimaryLang = primaryLanguage + "-" + primaryLanguage;
494
- if (_ConsentLanguages.langSet.has(fullPrimaryLang)) {
495
- return fullPrimaryLang;
496
- }
497
- for (const supportedLang of _ConsentLanguages.langSet) {
498
- if (supportedLang.indexOf(lang) !== -1 || supportedLang.indexOf(primaryLanguage) !== -1) {
499
- return supportedLang;
500
- }
501
- }
502
- }
503
- throw new Error(`unsupported language ${lang}`);
504
- }
505
- forEach(callback) {
506
- _ConsentLanguages.langSet.forEach(callback);
507
- }
508
- get size() {
509
- return _ConsentLanguages.langSet.size;
510
- }
511
- };
512
- __publicField(_ConsentLanguages, "langSet", /* @__PURE__ */ new Set([
513
- "AR",
514
- "BG",
515
- "BS",
516
- "CA",
517
- "CS",
518
- "DA",
519
- "DE",
520
- "EL",
521
- "EN",
522
- "ES",
523
- "ET",
524
- "EU",
525
- "FI",
526
- "FR",
527
- "GL",
528
- "HR",
529
- "HU",
530
- "IT",
531
- "JA",
532
- "LT",
533
- "LV",
534
- "MT",
535
- "NL",
536
- "NO",
537
- "PL",
538
- "PT-BR",
539
- "PT-PT",
540
- "RO",
541
- "RU",
542
- "SK",
543
- "SL",
544
- "SR-LATN",
545
- "SR-CYRL",
546
- "SV",
547
- "TR",
548
- "ZH"
549
- ]));
550
- let ConsentLanguages = _ConsentLanguages;
551
- class Fields {
552
- }
553
- __publicField(Fields, "cmpId", "cmpId");
554
- __publicField(Fields, "cmpVersion", "cmpVersion");
555
- __publicField(Fields, "consentLanguage", "consentLanguage");
556
- __publicField(Fields, "consentScreen", "consentScreen");
557
- __publicField(Fields, "created", "created");
558
- __publicField(Fields, "supportOOB", "supportOOB");
559
- __publicField(Fields, "isServiceSpecific", "isServiceSpecific");
560
- __publicField(Fields, "lastUpdated", "lastUpdated");
561
- __publicField(Fields, "numCustomPurposes", "numCustomPurposes");
562
- __publicField(Fields, "policyVersion", "policyVersion");
563
- __publicField(Fields, "publisherCountryCode", "publisherCountryCode");
564
- __publicField(Fields, "publisherCustomConsents", "publisherCustomConsents");
565
- __publicField(Fields, "publisherCustomLegitimateInterests", "publisherCustomLegitimateInterests");
566
- __publicField(Fields, "publisherLegitimateInterests", "publisherLegitimateInterests");
567
- __publicField(Fields, "publisherConsents", "publisherConsents");
568
- __publicField(Fields, "publisherRestrictions", "publisherRestrictions");
569
- __publicField(Fields, "purposeConsents", "purposeConsents");
570
- __publicField(Fields, "purposeLegitimateInterests", "purposeLegitimateInterests");
571
- __publicField(Fields, "purposeOneTreatment", "purposeOneTreatment");
572
- __publicField(Fields, "specialFeatureOptins", "specialFeatureOptins");
573
- __publicField(Fields, "useNonStandardTexts", "useNonStandardTexts");
574
- __publicField(Fields, "vendorConsents", "vendorConsents");
575
- __publicField(Fields, "vendorLegitimateInterests", "vendorLegitimateInterests");
576
- __publicField(Fields, "vendorListVersion", "vendorListVersion");
577
- __publicField(Fields, "vendorsAllowed", "vendorsAllowed");
578
- __publicField(Fields, "vendorsDisclosed", "vendorsDisclosed");
579
- __publicField(Fields, "version", "version");
580
- class Cloneable {
581
- /**
582
- * clone - returns a copy of the classes with new values and not references
583
- *
584
- * @return {T}
585
- */
586
- clone() {
587
- const myClone = new this.constructor();
588
- const keys = Object.keys(this);
589
- keys.forEach((key) => {
590
- const value = this.deepClone(this[key]);
591
- if (value !== void 0) {
592
- myClone[key] = value;
593
- }
594
- });
595
- return myClone;
596
- }
597
- /**
598
- * deepClone - recursive function that makes copies of reference values
599
- *
600
- * @param {unknown} item
601
- * @return {unknown}
602
- */
603
- deepClone(item) {
604
- const itsType = typeof item;
605
- if (itsType === "number" || itsType === "string" || itsType === "boolean") {
606
- return item;
607
- } else if (item !== null && itsType === "object") {
608
- if (typeof item.clone === "function") {
609
- return item.clone();
610
- } else if (item instanceof Date) {
611
- return new Date(item.getTime());
612
- } else if (item[Symbol.iterator] !== void 0) {
613
- const ar = [];
614
- for (const subItem of item) {
615
- ar.push(this.deepClone(subItem));
616
- }
617
- if (item instanceof Array) {
618
- return ar;
619
- } else {
620
- return new item.constructor(ar);
621
- }
622
- } else {
623
- const retr = {};
624
- for (const prop in item) {
625
- if (item.hasOwnProperty(prop)) {
626
- retr[prop] = this.deepClone(item[prop]);
627
- }
628
- }
629
- return retr;
630
- }
631
- }
632
- }
633
- }
634
- var RestrictionType;
635
- (function(RestrictionType2) {
636
- RestrictionType2[RestrictionType2["NOT_ALLOWED"] = 0] = "NOT_ALLOWED";
637
- RestrictionType2[RestrictionType2["REQUIRE_CONSENT"] = 1] = "REQUIRE_CONSENT";
638
- RestrictionType2[RestrictionType2["REQUIRE_LI"] = 2] = "REQUIRE_LI";
639
- })(RestrictionType || (RestrictionType = {}));
640
- const _PurposeRestriction = class _PurposeRestriction extends Cloneable {
641
- /**
642
- * constructor
643
- *
644
- * @param {number} purposeId? - may optionally pass the purposeId into the
645
- * constructor
646
- * @param {RestrictionType} restrictionType? - may
647
- * optionally pass the restrictionType into the constructor
648
- * @return {undefined}
649
- */
650
- constructor(purposeId, restrictionType) {
651
- super();
652
- __publicField(this, "purposeId_");
653
- __publicField(this, "restrictionType");
654
- if (purposeId !== void 0) {
655
- this.purposeId = purposeId;
656
- }
657
- if (restrictionType !== void 0) {
658
- this.restrictionType = restrictionType;
659
- }
660
- }
661
- static unHash(hash) {
662
- const splitUp = hash.split(this.hashSeparator);
663
- const purpRestriction = new _PurposeRestriction();
664
- if (splitUp.length !== 2) {
665
- throw new TCModelError("hash", hash);
666
- }
667
- purpRestriction.purposeId = parseInt(splitUp[0], 10);
668
- purpRestriction.restrictionType = parseInt(splitUp[1], 10);
669
- return purpRestriction;
670
- }
671
- get hash() {
672
- if (!this.isValid()) {
673
- throw new Error("cannot hash invalid PurposeRestriction");
674
- }
675
- return `${this.purposeId}${_PurposeRestriction.hashSeparator}${this.restrictionType}`;
676
- }
677
- /**
678
- * @return {number} The purpose Id associated with a publisher
679
- * purpose-by-vendor restriction that resulted in a different consent or LI
680
- * status than the consent or LI purposes allowed lists.
681
- */
682
- get purposeId() {
683
- return this.purposeId_;
684
- }
685
- /**
686
- * @param {number} idNum - The purpose Id associated with a publisher
687
- * purpose-by-vendor restriction that resulted in a different consent or LI
688
- * status than the consent or LI purposes allowed lists.
689
- */
690
- set purposeId(idNum) {
691
- this.purposeId_ = idNum;
692
- }
693
- isValid() {
694
- return Number.isInteger(this.purposeId) && this.purposeId > 0 && (this.restrictionType === RestrictionType.NOT_ALLOWED || this.restrictionType === RestrictionType.REQUIRE_CONSENT || this.restrictionType === RestrictionType.REQUIRE_LI);
695
- }
696
- isSameAs(otherPR) {
697
- return this.purposeId === otherPR.purposeId && this.restrictionType === otherPR.restrictionType;
698
- }
699
- };
700
- __publicField(_PurposeRestriction, "hashSeparator", "-");
701
- let PurposeRestriction = _PurposeRestriction;
702
- class PurposeRestrictionVector extends Cloneable {
703
- constructor() {
704
- super(...arguments);
705
- /**
706
- * if this originatd from an encoded string we'll need a place to store the
707
- * bit length; it can be set and got from here
708
- */
709
- __publicField(this, "bitLength", 0);
710
- /**
711
- * a map indexed by a string which will be a 'hash' of the purpose and
712
- * restriction type.
713
- */
714
- __publicField(this, "map", /* @__PURE__ */ new Map());
715
- __publicField(this, "gvl_");
716
- }
717
- has(hash) {
718
- return this.map.has(hash);
719
- }
720
- isOkToHave(restrictionType, purposeId, vendorId) {
721
- var _a2;
722
- let result = true;
723
- if ((_a2 = this.gvl) == null ? void 0 : _a2.vendors) {
724
- const vendor = this.gvl.vendors[vendorId];
725
- if (vendor) {
726
- if (restrictionType === RestrictionType.NOT_ALLOWED) {
727
- result = vendor.legIntPurposes.includes(purposeId) || vendor.purposes.includes(purposeId);
728
- } else if (vendor.flexiblePurposes.length) {
729
- switch (restrictionType) {
730
- case RestrictionType.REQUIRE_CONSENT:
731
- result = vendor.flexiblePurposes.includes(purposeId) && vendor.legIntPurposes.includes(purposeId);
732
- break;
733
- case RestrictionType.REQUIRE_LI:
734
- result = vendor.flexiblePurposes.includes(purposeId) && vendor.purposes.includes(purposeId);
735
- break;
736
- }
737
- } else {
738
- result = false;
739
- }
740
- } else {
741
- result = false;
742
- }
743
- }
744
- return result;
745
- }
746
- /**
747
- * add - adds a given Vendor ID under a given Purpose Restriction
748
- *
749
- * @param {number} vendorId
750
- * @param {PurposeRestriction} purposeRestriction
751
- * @return {void}
752
- */
753
- add(vendorId, purposeRestriction) {
754
- if (this.isOkToHave(purposeRestriction.restrictionType, purposeRestriction.purposeId, vendorId)) {
755
- const hash = purposeRestriction.hash;
756
- if (!this.has(hash)) {
757
- this.map.set(hash, /* @__PURE__ */ new Set());
758
- this.bitLength = 0;
759
- }
760
- this.map.get(hash).add(vendorId);
761
- }
762
- }
763
- /**
764
- * restrictPurposeToLegalBasis - adds all Vendors under a given Purpose Restriction
765
- *
766
- * @param {PurposeRestriction} purposeRestriction
767
- * @return {void}
768
- */
769
- restrictPurposeToLegalBasis(purposeRestriction) {
770
- const vendors = Array.from(this.gvl.vendorIds);
771
- const hash = purposeRestriction.hash;
772
- const lastEntry = vendors[vendors.length - 1];
773
- const values = [...Array(lastEntry).keys()].map((i) => i + 1);
774
- if (!this.has(hash)) {
775
- this.map.set(hash, new Set(values));
776
- this.bitLength = 0;
777
- } else {
778
- for (let i = 1; i <= lastEntry; i++) {
779
- this.map.get(hash).add(i);
780
- }
781
- }
782
- }
783
- /**
784
- * getVendors - returns array of vendor ids optionally narrowed by a given
785
- * Purpose Restriction. If no purpose restriction is passed then all vendor
786
- * ids will be returned. One can expect this result to be a unique set of
787
- * ids no duplicates.
788
- *
789
- * @param {PurposeRestriction} [purposeRestriction] - optionally passed to
790
- * get only Vendor IDs restricted under the given Purpose Restriction
791
- * @return {number[]} - Unique ID set of vendors
792
- */
793
- getVendors(purposeRestriction) {
794
- let vendorIds = [];
795
- if (purposeRestriction) {
796
- const hash = purposeRestriction.hash;
797
- if (this.has(hash)) {
798
- vendorIds = Array.from(this.map.get(hash));
799
- }
800
- } else {
801
- const vendorSet = /* @__PURE__ */ new Set();
802
- this.map.forEach((set) => {
803
- set.forEach((vendorId) => {
804
- vendorSet.add(vendorId);
805
- });
806
- });
807
- vendorIds = Array.from(vendorSet);
808
- }
809
- return vendorIds.sort((a, b) => a - b);
810
- }
811
- getRestrictionType(vendorId, purposeId) {
812
- let rType;
813
- this.getRestrictions(vendorId).forEach((purposeRestriction) => {
814
- if (purposeRestriction.purposeId === purposeId) {
815
- if (rType === void 0 || rType > purposeRestriction.restrictionType) {
816
- rType = purposeRestriction.restrictionType;
817
- }
818
- }
819
- });
820
- return rType;
821
- }
822
- /**
823
- * vendorHasRestriction - determines whether a given Vendor ID is under a
824
- * given Purpose Restriction
825
- *
826
- * @param {number} vendorId
827
- * @param {PurposeRestriction} purposeRestriction
828
- * @return {boolean} - true if the give Vendor ID is under the given Purpose
829
- * Restriction
830
- */
831
- vendorHasRestriction(vendorId, purposeRestriction) {
832
- let has = false;
833
- const restrictions = this.getRestrictions(vendorId);
834
- for (let i = 0; i < restrictions.length && !has; i++) {
835
- has = purposeRestriction.isSameAs(restrictions[i]);
836
- }
837
- return has;
838
- }
839
- /**
840
- * getMaxVendorId - gets the Maximum Vendor ID regardless of Purpose
841
- * Restriction
842
- *
843
- * @return {number} - maximum Vendor ID
844
- */
845
- getMaxVendorId() {
846
- let retr = 0;
847
- this.map.forEach((set) => {
848
- retr = Math.max(Array.from(set)[set.size - 1], retr);
849
- });
850
- return retr;
851
- }
852
- getRestrictions(vendorId) {
853
- const retr = [];
854
- this.map.forEach((set, hash) => {
855
- if (vendorId) {
856
- if (set.has(vendorId)) {
857
- retr.push(PurposeRestriction.unHash(hash));
858
- }
859
- } else {
860
- retr.push(PurposeRestriction.unHash(hash));
861
- }
862
- });
863
- return retr;
864
- }
865
- getPurposes() {
866
- const purposeIds = /* @__PURE__ */ new Set();
867
- this.map.forEach((set, hash) => {
868
- purposeIds.add(PurposeRestriction.unHash(hash).purposeId);
869
- });
870
- return Array.from(purposeIds);
871
- }
872
- /**
873
- * remove - removes Vendor ID from a Purpose Restriction
874
- *
875
- * @param {number} vendorId
876
- * @param {PurposeRestriction} purposeRestriction
877
- * @return {void}
878
- */
879
- remove(vendorId, purposeRestriction) {
880
- const hash = purposeRestriction.hash;
881
- const set = this.map.get(hash);
882
- if (set) {
883
- set.delete(vendorId);
884
- if (set.size == 0) {
885
- this.map.delete(hash);
886
- this.bitLength = 0;
887
- }
888
- }
889
- }
890
- /**
891
- * Essential for being able to determine whether we can actually set a
892
- * purpose restriction since they have to have a flexible legal basis
893
- *
894
- * @param {GVL} value - the GVL instance
895
- */
896
- set gvl(value) {
897
- if (!this.gvl_) {
898
- this.gvl_ = value;
899
- this.map.forEach((set, hash) => {
900
- const purposeRestriction = PurposeRestriction.unHash(hash);
901
- const vendors = Array.from(set);
902
- vendors.forEach((vendorId) => {
903
- if (!this.isOkToHave(purposeRestriction.restrictionType, purposeRestriction.purposeId, vendorId)) {
904
- set.delete(vendorId);
905
- }
906
- });
907
- });
908
- }
909
- }
910
- /**
911
- * gvl returns local copy of the GVL these restrictions apply to
912
- *
913
- * @return {GVL}
914
- */
915
- get gvl() {
916
- return this.gvl_;
917
- }
918
- /**
919
- * isEmpty - whether or not this vector has any restrictions in it
920
- *
921
- * @return {boolean}
922
- */
923
- isEmpty() {
924
- return this.map.size === 0;
925
- }
926
- /**
927
- * numRestrictions - returns the number of Purpose Restrictions.
928
- *
929
- * @return {number}
930
- */
931
- get numRestrictions() {
932
- return this.map.size;
933
- }
934
- }
935
- var DeviceDisclosureStorageAccessType;
936
- (function(DeviceDisclosureStorageAccessType2) {
937
- DeviceDisclosureStorageAccessType2["COOKIE"] = "cookie";
938
- DeviceDisclosureStorageAccessType2["WEB"] = "web";
939
- DeviceDisclosureStorageAccessType2["APP"] = "app";
940
- })(DeviceDisclosureStorageAccessType || (DeviceDisclosureStorageAccessType = {}));
941
- var Segment;
942
- (function(Segment2) {
943
- Segment2["CORE"] = "core";
944
- Segment2["VENDORS_DISCLOSED"] = "vendorsDisclosed";
945
- Segment2["VENDORS_ALLOWED"] = "vendorsAllowed";
946
- Segment2["PUBLISHER_TC"] = "publisherTC";
947
- })(Segment || (Segment = {}));
948
- class SegmentIDs {
949
- }
950
- /**
951
- * 0 = default - reserved for core string (does not need to be present in the core string)
952
- * 1 = OOB vendors disclosed
953
- * 2 = OOB vendors allowed
954
- * 3 = PublisherTC
955
- */
956
- __publicField(SegmentIDs, "ID_TO_KEY", [
957
- Segment.CORE,
958
- Segment.VENDORS_DISCLOSED,
959
- Segment.VENDORS_ALLOWED,
960
- Segment.PUBLISHER_TC
961
- ]);
962
- __publicField(SegmentIDs, "KEY_TO_ID", {
963
- [Segment.CORE]: 0,
964
- [Segment.VENDORS_DISCLOSED]: 1,
965
- [Segment.VENDORS_ALLOWED]: 2,
966
- [Segment.PUBLISHER_TC]: 3
967
- });
968
- class Vector extends Cloneable {
969
- constructor() {
970
- super(...arguments);
971
- /**
972
- * if this originatd from an encoded string we'll need a place to store the
973
- * bit length; it can be set and got from here
974
- */
975
- __publicField(this, "bitLength", 0);
976
- __publicField(this, "maxId_", 0);
977
- __publicField(this, "set_", /* @__PURE__ */ new Set());
978
- }
979
- *[Symbol.iterator]() {
980
- for (let i = 1; i <= this.maxId; i++) {
981
- yield [i, this.has(i)];
982
- }
983
- }
984
- /**
985
- * values()
986
- *
987
- * @return {IterableIterator<number>} - returns an iterator of the positive
988
- * values in the set
989
- */
990
- values() {
991
- return this.set_.values();
992
- }
993
- /**
994
- * maxId
995
- *
996
- * @return {number} - the highest id in this Vector
997
- */
998
- get maxId() {
999
- return this.maxId_;
1000
- }
1001
- /**
1002
- * get
1003
- *
1004
- * @param {number} id - key for value to check
1005
- * @return {boolean} - value of that key, if never set it will be false
1006
- */
1007
- has(id) {
1008
- return this.set_.has(id);
1009
- }
1010
- /**
1011
- * unset
1012
- *
1013
- * @param {SingleIDOrCollection} id - id or ids to unset
1014
- * @return {void}
1015
- */
1016
- unset(id) {
1017
- if (Array.isArray(id)) {
1018
- id.forEach((id2) => this.unset(id2));
1019
- } else if (typeof id === "object") {
1020
- this.unset(Object.keys(id).map((strId) => Number(strId)));
1021
- } else {
1022
- this.set_.delete(Number(id));
1023
- this.bitLength = 0;
1024
- if (id === this.maxId) {
1025
- this.maxId_ = 0;
1026
- this.set_.forEach((id2) => {
1027
- this.maxId_ = Math.max(this.maxId, id2);
1028
- });
1029
- }
1030
- }
1031
- }
1032
- isIntMap(item) {
1033
- let result = typeof item === "object";
1034
- result = result && Object.keys(item).every((key) => {
1035
- let itemResult = Number.isInteger(parseInt(key, 10));
1036
- itemResult = itemResult && this.isValidNumber(item[key].id);
1037
- itemResult = itemResult && item[key].name !== void 0;
1038
- return itemResult;
1039
- });
1040
- return result;
1041
- }
1042
- isValidNumber(item) {
1043
- return parseInt(item, 10) > 0;
1044
- }
1045
- isSet(item) {
1046
- let result = false;
1047
- if (item instanceof Set) {
1048
- result = Array.from(item).every(this.isValidNumber);
1049
- }
1050
- return result;
1051
- }
1052
- /**
1053
- * set - sets an item assumed to be a truthy value by its presence
1054
- *
1055
- * @param {SingleIDOrCollection} item - May be a single id (positive integer)
1056
- * or collection of ids in a set, GVL Int Map, or Array.
1057
- *
1058
- * @return {void}
1059
- */
1060
- set(item) {
1061
- if (Array.isArray(item)) {
1062
- item.forEach((item2) => this.set(item2));
1063
- } else if (this.isSet(item)) {
1064
- this.set(Array.from(item));
1065
- } else if (this.isIntMap(item)) {
1066
- this.set(Object.keys(item).map((strId) => Number(strId)));
1067
- } else if (this.isValidNumber(item)) {
1068
- this.set_.add(item);
1069
- this.maxId_ = Math.max(this.maxId, item);
1070
- this.bitLength = 0;
1071
- } else {
1072
- throw new TCModelError("set()", item, "must be positive integer array, positive integer, Set<number>, or IntMap");
1073
- }
1074
- }
1075
- empty() {
1076
- this.set_ = /* @__PURE__ */ new Set();
1077
- }
1078
- /**
1079
- * forEach - to traverse from id=1 to id=maxId in a sequential non-sparse manner
1080
- *
1081
- *
1082
- * @param {forEachCallback} callback - callback to execute
1083
- * @return {void}
1084
- *
1085
- * @callback forEachCallback
1086
- * @param {boolean} value - whether or not this id exists in the vector
1087
- * @param {number} id - the id number of the current iteration
1088
- */
1089
- forEach(callback) {
1090
- for (let i = 1; i <= this.maxId; i++) {
1091
- callback(this.has(i), i);
1092
- }
1093
- }
1094
- get size() {
1095
- return this.set_.size;
1096
- }
1097
- setAll(intMap) {
1098
- this.set(intMap);
1099
- }
1100
- }
1101
- class BitLength {
1102
- }
1103
- _a = Fields.cmpId, _b = Fields.cmpVersion, _c = Fields.consentLanguage, _d = Fields.consentScreen, _e = Fields.created, _f = Fields.isServiceSpecific, _g = Fields.lastUpdated, _h = Fields.policyVersion, _i = Fields.publisherCountryCode, _j = Fields.publisherLegitimateInterests, _k = Fields.publisherConsents, _l = Fields.purposeConsents, _m = Fields.purposeLegitimateInterests, _n = Fields.purposeOneTreatment, _o = Fields.specialFeatureOptins, _p = Fields.useNonStandardTexts, _q = Fields.vendorListVersion, _r = Fields.version;
1104
- __publicField(BitLength, _a, 12);
1105
- __publicField(BitLength, _b, 12);
1106
- __publicField(BitLength, _c, 12);
1107
- __publicField(BitLength, _d, 6);
1108
- __publicField(BitLength, _e, 36);
1109
- __publicField(BitLength, _f, 1);
1110
- __publicField(BitLength, _g, 36);
1111
- __publicField(BitLength, _h, 6);
1112
- __publicField(BitLength, _i, 12);
1113
- __publicField(BitLength, _j, 24);
1114
- __publicField(BitLength, _k, 24);
1115
- __publicField(BitLength, _l, 24);
1116
- __publicField(BitLength, _m, 24);
1117
- __publicField(BitLength, _n, 1);
1118
- __publicField(BitLength, _o, 12);
1119
- __publicField(BitLength, _p, 1);
1120
- __publicField(BitLength, _q, 12);
1121
- __publicField(BitLength, _r, 6);
1122
- __publicField(BitLength, "anyBoolean", 1);
1123
- __publicField(BitLength, "encodingType", 1);
1124
- __publicField(BitLength, "maxId", 16);
1125
- __publicField(BitLength, "numCustomPurposes", 6);
1126
- __publicField(BitLength, "numEntries", 12);
1127
- __publicField(BitLength, "numRestrictions", 12);
1128
- __publicField(BitLength, "purposeId", 6);
1129
- __publicField(BitLength, "restrictionType", 2);
1130
- __publicField(BitLength, "segmentType", 3);
1131
- __publicField(BitLength, "singleOrRange", 1);
1132
- __publicField(BitLength, "vendorId", 16);
1133
- class BooleanEncoder {
1134
- static encode(value) {
1135
- return String(Number(value));
1136
- }
1137
- static decode(value) {
1138
- return value === "1";
1139
- }
1140
- }
1141
- class IntEncoder {
1142
- static encode(value, numBits) {
1143
- let bitString;
1144
- if (typeof value === "string") {
1145
- value = parseInt(value, 10);
1146
- }
1147
- bitString = value.toString(2);
1148
- if (bitString.length > numBits || value < 0) {
1149
- throw new EncodingError(`${value} too large to encode into ${numBits}`);
1150
- }
1151
- if (bitString.length < numBits) {
1152
- bitString = "0".repeat(numBits - bitString.length) + bitString;
1153
- }
1154
- return bitString;
1155
- }
1156
- static decode(value, numBits) {
1157
- if (numBits !== value.length) {
1158
- throw new DecodingError("invalid bit length");
1159
- }
1160
- return parseInt(value, 2);
1161
- }
1162
- }
1163
- class DateEncoder {
1164
- static encode(value, numBits) {
1165
- return IntEncoder.encode(Math.round(value.getTime() / 100), numBits);
1166
- }
1167
- static decode(value, numBits) {
1168
- if (numBits !== value.length) {
1169
- throw new DecodingError("invalid bit length");
1170
- }
1171
- const date = /* @__PURE__ */ new Date();
1172
- date.setTime(IntEncoder.decode(value, numBits) * 100);
1173
- return date;
1174
- }
1175
- }
1176
- class FixedVectorEncoder {
1177
- static encode(value, numBits) {
1178
- let bitString = "";
1179
- for (let i = 1; i <= numBits; i++) {
1180
- bitString += BooleanEncoder.encode(value.has(i));
1181
- }
1182
- return bitString;
1183
- }
1184
- static decode(value, numBits) {
1185
- if (value.length !== numBits) {
1186
- throw new DecodingError("bitfield encoding length mismatch");
1187
- }
1188
- const vector = new Vector();
1189
- for (let i = 1; i <= numBits; i++) {
1190
- if (BooleanEncoder.decode(value[i - 1])) {
1191
- vector.set(i);
1192
- }
1193
- }
1194
- vector.bitLength = value.length;
1195
- return vector;
1196
- }
1197
- }
1198
- class LangEncoder {
1199
- static encode(value, numBits) {
1200
- value = value.toUpperCase();
1201
- const ASCII_START = 65;
1202
- const firstLetter = value.charCodeAt(0) - ASCII_START;
1203
- const secondLetter = value.charCodeAt(1) - ASCII_START;
1204
- if (firstLetter < 0 || firstLetter > 25 || secondLetter < 0 || secondLetter > 25) {
1205
- throw new EncodingError(`invalid language code: ${value}`);
1206
- }
1207
- if (numBits % 2 === 1) {
1208
- throw new EncodingError(`numBits must be even, ${numBits} is not valid`);
1209
- }
1210
- numBits = numBits / 2;
1211
- const firstLetterBString = IntEncoder.encode(firstLetter, numBits);
1212
- const secondLetterBString = IntEncoder.encode(secondLetter, numBits);
1213
- return firstLetterBString + secondLetterBString;
1214
- }
1215
- static decode(value, numBits) {
1216
- let retr;
1217
- if (numBits === value.length && !(value.length % 2)) {
1218
- const ASCII_START = 65;
1219
- const mid = value.length / 2;
1220
- const firstLetter = IntEncoder.decode(value.slice(0, mid), mid) + ASCII_START;
1221
- const secondLetter = IntEncoder.decode(value.slice(mid), mid) + ASCII_START;
1222
- retr = String.fromCharCode(firstLetter) + String.fromCharCode(secondLetter);
1223
- } else {
1224
- throw new DecodingError("invalid bit length for language");
1225
- }
1226
- return retr;
1227
- }
1228
- }
1229
- class PurposeRestrictionVectorEncoder {
1230
- static encode(prVector) {
1231
- let bitString = IntEncoder.encode(prVector.numRestrictions, BitLength.numRestrictions);
1232
- if (!prVector.isEmpty()) {
1233
- const nextGvlVendor = (vendorId, lastVendorId) => {
1234
- for (let nextId = vendorId + 1; nextId <= lastVendorId; nextId++) {
1235
- if (prVector.gvl.vendorIds.has(nextId)) {
1236
- return nextId;
1237
- }
1238
- }
1239
- return vendorId;
1240
- };
1241
- prVector.getRestrictions().forEach((purpRestriction) => {
1242
- bitString += IntEncoder.encode(purpRestriction.purposeId, BitLength.purposeId);
1243
- bitString += IntEncoder.encode(purpRestriction.restrictionType, BitLength.restrictionType);
1244
- const vendors = prVector.getVendors(purpRestriction);
1245
- const len = vendors.length;
1246
- let numEntries = 0;
1247
- let startId = 0;
1248
- let rangeField = "";
1249
- for (let i = 0; i < len; i++) {
1250
- const vendorId = vendors[i];
1251
- if (startId === 0) {
1252
- numEntries++;
1253
- startId = vendorId;
1254
- }
1255
- if (i === len - 1 || vendors[i + 1] > nextGvlVendor(vendorId, vendors[len - 1])) {
1256
- const isRange = !(vendorId === startId);
1257
- rangeField += BooleanEncoder.encode(isRange);
1258
- rangeField += IntEncoder.encode(startId, BitLength.vendorId);
1259
- if (isRange) {
1260
- rangeField += IntEncoder.encode(vendorId, BitLength.vendorId);
1261
- }
1262
- startId = 0;
1263
- }
1264
- }
1265
- bitString += IntEncoder.encode(numEntries, BitLength.numEntries);
1266
- bitString += rangeField;
1267
- });
1268
- }
1269
- return bitString;
1270
- }
1271
- static decode(encodedString) {
1272
- let index = 0;
1273
- const vector = new PurposeRestrictionVector();
1274
- const numRestrictions = IntEncoder.decode(encodedString.substr(index, BitLength.numRestrictions), BitLength.numRestrictions);
1275
- index += BitLength.numRestrictions;
1276
- for (let i = 0; i < numRestrictions; i++) {
1277
- const purposeId = IntEncoder.decode(encodedString.substr(index, BitLength.purposeId), BitLength.purposeId);
1278
- index += BitLength.purposeId;
1279
- const restrictionType = IntEncoder.decode(encodedString.substr(index, BitLength.restrictionType), BitLength.restrictionType);
1280
- index += BitLength.restrictionType;
1281
- const purposeRestriction = new PurposeRestriction(purposeId, restrictionType);
1282
- const numEntries = IntEncoder.decode(encodedString.substr(index, BitLength.numEntries), BitLength.numEntries);
1283
- index += BitLength.numEntries;
1284
- for (let j = 0; j < numEntries; j++) {
1285
- const isARange = BooleanEncoder.decode(encodedString.substr(index, BitLength.anyBoolean));
1286
- index += BitLength.anyBoolean;
1287
- const startOrOnlyVendorId = IntEncoder.decode(encodedString.substr(index, BitLength.vendorId), BitLength.vendorId);
1288
- index += BitLength.vendorId;
1289
- if (isARange) {
1290
- const endVendorId = IntEncoder.decode(encodedString.substr(index, BitLength.vendorId), BitLength.vendorId);
1291
- index += BitLength.vendorId;
1292
- if (endVendorId < startOrOnlyVendorId) {
1293
- throw new DecodingError(`Invalid RangeEntry: endVendorId ${endVendorId} is less than ${startOrOnlyVendorId}`);
1294
- }
1295
- for (let k = startOrOnlyVendorId; k <= endVendorId; k++) {
1296
- vector.add(k, purposeRestriction);
1297
- }
1298
- } else {
1299
- vector.add(startOrOnlyVendorId, purposeRestriction);
1300
- }
1301
- }
1302
- }
1303
- vector.bitLength = index;
1304
- return vector;
1305
- }
1306
- }
1307
- var VectorEncodingType;
1308
- (function(VectorEncodingType2) {
1309
- VectorEncodingType2[VectorEncodingType2["FIELD"] = 0] = "FIELD";
1310
- VectorEncodingType2[VectorEncodingType2["RANGE"] = 1] = "RANGE";
1311
- })(VectorEncodingType || (VectorEncodingType = {}));
1312
- class VendorVectorEncoder {
1313
- static encode(value) {
1314
- const ranges = [];
1315
- let range = [];
1316
- let retrString = IntEncoder.encode(value.maxId, BitLength.maxId);
1317
- let bitField = "";
1318
- let rangeIsSmaller;
1319
- const headerLength = BitLength.maxId + BitLength.encodingType;
1320
- const bitFieldLength = headerLength + value.maxId;
1321
- const minRangeLength = BitLength.vendorId * 2 + BitLength.singleOrRange + BitLength.numEntries;
1322
- let rangeLength = headerLength + BitLength.numEntries;
1323
- value.forEach((curValue, i) => {
1324
- bitField += BooleanEncoder.encode(curValue);
1325
- rangeIsSmaller = value.maxId > minRangeLength && rangeLength < bitFieldLength;
1326
- if (rangeIsSmaller && curValue) {
1327
- const nextValue = value.has(i + 1);
1328
- if (!nextValue) {
1329
- range.push(i);
1330
- rangeLength += BitLength.vendorId;
1331
- ranges.push(range);
1332
- range = [];
1333
- } else if (range.length === 0) {
1334
- range.push(i);
1335
- rangeLength += BitLength.singleOrRange;
1336
- rangeLength += BitLength.vendorId;
1337
- }
1338
- }
1339
- });
1340
- if (rangeIsSmaller) {
1341
- retrString += String(VectorEncodingType.RANGE);
1342
- retrString += this.buildRangeEncoding(ranges);
1343
- } else {
1344
- retrString += String(VectorEncodingType.FIELD);
1345
- retrString += bitField;
1346
- }
1347
- return retrString;
1348
- }
1349
- static decode(value, version2) {
1350
- let vector;
1351
- let index = 0;
1352
- const maxId = IntEncoder.decode(value.substr(index, BitLength.maxId), BitLength.maxId);
1353
- index += BitLength.maxId;
1354
- const encodingType = IntEncoder.decode(value.charAt(index), BitLength.encodingType);
1355
- index += BitLength.encodingType;
1356
- if (encodingType === VectorEncodingType.RANGE) {
1357
- vector = new Vector();
1358
- if (version2 === 1) {
1359
- if (value.substr(index, 1) === "1") {
1360
- throw new DecodingError("Unable to decode default consent=1");
1361
- }
1362
- index++;
1363
- }
1364
- const numEntries = IntEncoder.decode(value.substr(index, BitLength.numEntries), BitLength.numEntries);
1365
- index += BitLength.numEntries;
1366
- for (let i = 0; i < numEntries; i++) {
1367
- const isIdRange = BooleanEncoder.decode(value.charAt(index));
1368
- index += BitLength.singleOrRange;
1369
- const firstId = IntEncoder.decode(value.substr(index, BitLength.vendorId), BitLength.vendorId);
1370
- index += BitLength.vendorId;
1371
- if (isIdRange) {
1372
- const secondId = IntEncoder.decode(value.substr(index, BitLength.vendorId), BitLength.vendorId);
1373
- index += BitLength.vendorId;
1374
- for (let j = firstId; j <= secondId; j++) {
1375
- vector.set(j);
1376
- }
1377
- } else {
1378
- vector.set(firstId);
1379
- }
1380
- }
1381
- } else {
1382
- const bitField = value.substr(index, maxId);
1383
- index += maxId;
1384
- vector = FixedVectorEncoder.decode(bitField, maxId);
1385
- }
1386
- vector.bitLength = index;
1387
- return vector;
1388
- }
1389
- static buildRangeEncoding(ranges) {
1390
- const numEntries = ranges.length;
1391
- let rangeString = IntEncoder.encode(numEntries, BitLength.numEntries);
1392
- ranges.forEach((range) => {
1393
- const single = range.length === 1;
1394
- rangeString += BooleanEncoder.encode(!single);
1395
- rangeString += IntEncoder.encode(range[0], BitLength.vendorId);
1396
- if (!single) {
1397
- rangeString += IntEncoder.encode(range[1], BitLength.vendorId);
1398
- }
1399
- });
1400
- return rangeString;
1401
- }
1402
- }
1403
- function FieldEncoderMap() {
1404
- return {
1405
- [Fields.version]: IntEncoder,
1406
- [Fields.created]: DateEncoder,
1407
- [Fields.lastUpdated]: DateEncoder,
1408
- [Fields.cmpId]: IntEncoder,
1409
- [Fields.cmpVersion]: IntEncoder,
1410
- [Fields.consentScreen]: IntEncoder,
1411
- [Fields.consentLanguage]: LangEncoder,
1412
- [Fields.vendorListVersion]: IntEncoder,
1413
- [Fields.policyVersion]: IntEncoder,
1414
- [Fields.isServiceSpecific]: BooleanEncoder,
1415
- [Fields.useNonStandardTexts]: BooleanEncoder,
1416
- [Fields.specialFeatureOptins]: FixedVectorEncoder,
1417
- [Fields.purposeConsents]: FixedVectorEncoder,
1418
- [Fields.purposeLegitimateInterests]: FixedVectorEncoder,
1419
- [Fields.purposeOneTreatment]: BooleanEncoder,
1420
- [Fields.publisherCountryCode]: LangEncoder,
1421
- [Fields.vendorConsents]: VendorVectorEncoder,
1422
- [Fields.vendorLegitimateInterests]: VendorVectorEncoder,
1423
- [Fields.publisherRestrictions]: PurposeRestrictionVectorEncoder,
1424
- segmentType: IntEncoder,
1425
- [Fields.vendorsDisclosed]: VendorVectorEncoder,
1426
- [Fields.vendorsAllowed]: VendorVectorEncoder,
1427
- [Fields.publisherConsents]: FixedVectorEncoder,
1428
- [Fields.publisherLegitimateInterests]: FixedVectorEncoder,
1429
- [Fields.numCustomPurposes]: IntEncoder,
1430
- [Fields.publisherCustomConsents]: FixedVectorEncoder,
1431
- [Fields.publisherCustomLegitimateInterests]: FixedVectorEncoder
1432
- };
1433
- }
1434
- class FieldSequence {
1435
- constructor() {
1436
- __publicField(this, "1", {
1437
- [Segment.CORE]: [
1438
- Fields.version,
1439
- Fields.created,
1440
- Fields.lastUpdated,
1441
- Fields.cmpId,
1442
- Fields.cmpVersion,
1443
- Fields.consentScreen,
1444
- Fields.consentLanguage,
1445
- Fields.vendorListVersion,
1446
- Fields.purposeConsents,
1447
- Fields.vendorConsents
1448
- ]
1449
- });
1450
- __publicField(this, "2", {
1451
- [Segment.CORE]: [
1452
- Fields.version,
1453
- Fields.created,
1454
- Fields.lastUpdated,
1455
- Fields.cmpId,
1456
- Fields.cmpVersion,
1457
- Fields.consentScreen,
1458
- Fields.consentLanguage,
1459
- Fields.vendorListVersion,
1460
- Fields.policyVersion,
1461
- Fields.isServiceSpecific,
1462
- Fields.useNonStandardTexts,
1463
- Fields.specialFeatureOptins,
1464
- Fields.purposeConsents,
1465
- Fields.purposeLegitimateInterests,
1466
- Fields.purposeOneTreatment,
1467
- Fields.publisherCountryCode,
1468
- Fields.vendorConsents,
1469
- Fields.vendorLegitimateInterests,
1470
- Fields.publisherRestrictions
1471
- ],
1472
- [Segment.PUBLISHER_TC]: [
1473
- Fields.publisherConsents,
1474
- Fields.publisherLegitimateInterests,
1475
- Fields.numCustomPurposes,
1476
- Fields.publisherCustomConsents,
1477
- Fields.publisherCustomLegitimateInterests
1478
- ],
1479
- [Segment.VENDORS_ALLOWED]: [
1480
- Fields.vendorsAllowed
1481
- ],
1482
- [Segment.VENDORS_DISCLOSED]: [
1483
- Fields.vendorsDisclosed
1484
- ]
1485
- });
1486
- }
1487
- }
1488
- class SegmentSequence {
1489
- constructor(tcModel, options) {
1490
- __publicField(this, "1", [
1491
- Segment.CORE
1492
- ]);
1493
- __publicField(this, "2", [
1494
- Segment.CORE
1495
- ]);
1496
- if (tcModel.version === 2) {
1497
- if (tcModel.isServiceSpecific) {
1498
- this["2"].push(Segment.PUBLISHER_TC);
1499
- } else {
1500
- const isForVendors = !!(options && options.isForVendors);
1501
- if (!isForVendors || tcModel[Fields.supportOOB] === true) {
1502
- this["2"].push(Segment.VENDORS_DISCLOSED);
1503
- }
1504
- if (isForVendors) {
1505
- if (tcModel[Fields.supportOOB] && tcModel[Fields.vendorsAllowed].size > 0) {
1506
- this["2"].push(Segment.VENDORS_ALLOWED);
1507
- }
1508
- this["2"].push(Segment.PUBLISHER_TC);
1509
- }
1510
- }
1511
- }
1512
- }
1513
- }
1514
- class SegmentEncoder {
1515
- static encode(tcModel, segment) {
1516
- let sequence;
1517
- try {
1518
- sequence = this.fieldSequence[String(tcModel.version)][segment];
1519
- } catch (err) {
1520
- throw new EncodingError(`Unable to encode version: ${tcModel.version}, segment: ${segment}`);
1521
- }
1522
- let bitField = "";
1523
- if (segment !== Segment.CORE) {
1524
- bitField = IntEncoder.encode(SegmentIDs.KEY_TO_ID[segment], BitLength.segmentType);
1525
- }
1526
- const fieldEncoderMap = FieldEncoderMap();
1527
- sequence.forEach((key) => {
1528
- const value = tcModel[key];
1529
- const encoder = fieldEncoderMap[key];
1530
- let numBits = BitLength[key];
1531
- if (numBits === void 0) {
1532
- if (this.isPublisherCustom(key)) {
1533
- numBits = Number(tcModel[Fields.numCustomPurposes]);
1534
- }
1535
- }
1536
- try {
1537
- bitField += encoder.encode(value, numBits);
1538
- } catch (err) {
1539
- throw new EncodingError(`Error encoding ${segment}->${key}: ${err.message}`);
1540
- }
1541
- });
1542
- return Base64Url.encode(bitField);
1543
- }
1544
- static decode(encodedString, tcModel, segment) {
1545
- const bitField = Base64Url.decode(encodedString);
1546
- let bStringIdx = 0;
1547
- if (segment === Segment.CORE) {
1548
- tcModel.version = IntEncoder.decode(bitField.substr(bStringIdx, BitLength[Fields.version]), BitLength[Fields.version]);
1549
- }
1550
- if (segment !== Segment.CORE) {
1551
- bStringIdx += BitLength.segmentType;
1552
- }
1553
- const sequence = this.fieldSequence[String(tcModel.version)][segment];
1554
- const fieldEncoderMap = FieldEncoderMap();
1555
- sequence.forEach((key) => {
1556
- const encoder = fieldEncoderMap[key];
1557
- let numBits = BitLength[key];
1558
- if (numBits === void 0) {
1559
- if (this.isPublisherCustom(key)) {
1560
- numBits = Number(tcModel[Fields.numCustomPurposes]);
1561
- }
1562
- }
1563
- if (numBits !== 0) {
1564
- const bits = bitField.substr(bStringIdx, numBits);
1565
- if (encoder === VendorVectorEncoder) {
1566
- tcModel[key] = encoder.decode(bits, tcModel.version);
1567
- } else {
1568
- tcModel[key] = encoder.decode(bits, numBits);
1569
- }
1570
- if (Number.isInteger(numBits)) {
1571
- bStringIdx += numBits;
1572
- } else if (Number.isInteger(tcModel[key].bitLength)) {
1573
- bStringIdx += tcModel[key].bitLength;
1574
- } else {
1575
- throw new DecodingError(key);
1576
- }
1577
- }
1578
- });
1579
- return tcModel;
1580
- }
1581
- static isPublisherCustom(key) {
1582
- return key.indexOf("publisherCustom") === 0;
1583
- }
1584
- }
1585
- __publicField(SegmentEncoder, "fieldSequence", new FieldSequence());
1586
- class SemanticPreEncoder {
1587
- static process(tcModel, options) {
1588
- const gvl = tcModel.gvl;
1589
- if (!gvl) {
1590
- throw new EncodingError("Unable to encode TCModel without a GVL");
1591
- }
1592
- if (!gvl.isReady) {
1593
- throw new EncodingError("Unable to encode TCModel tcModel.gvl.readyPromise is not resolved");
1594
- }
1595
- tcModel = tcModel.clone();
1596
- tcModel.consentLanguage = gvl.language.slice(0, 2).toUpperCase();
1597
- if ((options == null ? void 0 : options.version) > 0 && (options == null ? void 0 : options.version) <= this.processor.length) {
1598
- tcModel.version = options.version;
1599
- } else {
1600
- tcModel.version = this.processor.length;
1601
- }
1602
- const processorFunctionIndex = tcModel.version - 1;
1603
- if (!this.processor[processorFunctionIndex]) {
1604
- throw new EncodingError(`Invalid version: ${tcModel.version}`);
1605
- }
1606
- return this.processor[processorFunctionIndex](tcModel, gvl);
1607
- }
1608
- }
1609
- __publicField(SemanticPreEncoder, "processor", [
1610
- (tcModel) => tcModel,
1611
- (tcModel, gvl) => {
1612
- tcModel.publisherRestrictions.gvl = gvl;
1613
- tcModel.purposeLegitimateInterests.unset([1, 3, 4, 5, 6]);
1614
- const vectorToIntMap = /* @__PURE__ */ new Map();
1615
- vectorToIntMap.set("legIntPurposes", tcModel.vendorLegitimateInterests);
1616
- vectorToIntMap.set("purposes", tcModel.vendorConsents);
1617
- vectorToIntMap.forEach((vector, gvlVendorKey) => {
1618
- vector.forEach((value, vendorId) => {
1619
- if (value) {
1620
- const vendor = gvl.vendors[vendorId];
1621
- if (!vendor || vendor.deletedDate) {
1622
- vector.unset(vendorId);
1623
- } else if (vendor[gvlVendorKey].length === 0) {
1624
- if (gvlVendorKey === "legIntPurposes" && vendor["purposes"].length === 0 && vendor["legIntPurposes"].length === 0 && vendor["specialPurposes"].length > 0)
1625
- ;
1626
- else {
1627
- if (tcModel.isServiceSpecific) {
1628
- if (vendor.flexiblePurposes.length === 0) {
1629
- vector.unset(vendorId);
1630
- } else {
1631
- const restrictions = tcModel.publisherRestrictions.getRestrictions(vendorId);
1632
- let isValid = false;
1633
- for (let i = 0, len = restrictions.length; i < len && !isValid; i++) {
1634
- isValid = restrictions[i].restrictionType === RestrictionType.REQUIRE_CONSENT && gvlVendorKey === "purposes" || restrictions[i].restrictionType === RestrictionType.REQUIRE_LI && gvlVendorKey === "legIntPurposes";
1635
- }
1636
- if (!isValid) {
1637
- vector.unset(vendorId);
1638
- }
1639
- }
1640
- } else {
1641
- vector.unset(vendorId);
1642
- }
1643
- }
1644
- }
1645
- }
1646
- });
1647
- });
1648
- tcModel.vendorsDisclosed.set(gvl.vendors);
1649
- return tcModel;
1650
- }
1651
- ]);
1652
- class Json {
1653
- static absCall(url, body, sendCookies, timeout) {
1654
- return new Promise((resolve, reject) => {
1655
- const req = new XMLHttpRequest();
1656
- const onLoad = () => {
1657
- if (req.readyState == XMLHttpRequest.DONE) {
1658
- if (req.status >= 200 && req.status < 300) {
1659
- let response = req.response;
1660
- if (typeof response === "string") {
1661
- try {
1662
- response = JSON.parse(response);
1663
- } catch (e) {
1664
- }
1665
- }
1666
- resolve(response);
1667
- } else {
1668
- reject(new Error(`HTTP Status: ${req.status} response type: ${req.responseType}`));
1669
- }
1670
- }
1671
- };
1672
- const onError = () => {
1673
- reject(new Error("error"));
1674
- };
1675
- const onAbort = () => {
1676
- reject(new Error("aborted"));
1677
- };
1678
- const onTimeout = () => {
1679
- reject(new Error("Timeout " + timeout + "ms " + url));
1680
- };
1681
- req.withCredentials = sendCookies;
1682
- req.addEventListener("load", onLoad);
1683
- req.addEventListener("error", onError);
1684
- req.addEventListener("abort", onAbort);
1685
- if (body === null) {
1686
- req.open("GET", url, true);
1687
- } else {
1688
- req.open("POST", url, true);
1689
- }
1690
- req.responseType = "json";
1691
- req.timeout = timeout;
1692
- req.ontimeout = onTimeout;
1693
- req.send(body);
1694
- });
1695
- }
1696
- /**
1697
- * @static
1698
- * @param {string} url - full path to POST to
1699
- * @param {object} body - JSON object to post
1700
- * @param {boolean} sendCookies - Whether or not to send the XMLHttpRequest with credentials or not
1701
- * @param {number} [timeout] - optional timeout in milliseconds
1702
- * @return {Promise<object>} - if the server responds the response will be returned here
1703
- */
1704
- static post(url, body, sendCookies = false, timeout = 0) {
1705
- return this.absCall(url, JSON.stringify(body), sendCookies, timeout);
1706
- }
1707
- /**
1708
- * @static
1709
- * @param {string} url - full path to the json
1710
- * @param {boolean} sendCookies - Whether or not to send the XMLHttpRequest with credentials or not
1711
- * @param {number} [timeout] - optional timeout in milliseconds
1712
- * @return {Promise<object>} - resolves with parsed JSON
1713
- */
1714
- static fetch(url, sendCookies = false, timeout = 0) {
1715
- return this.absCall(url, null, sendCookies, timeout);
1716
- }
1717
- }
1718
- const _GVL = class _GVL extends Cloneable {
1719
- /**
1720
- * @param {VersionOrVendorList} [versionOrVendorList] - can be either a
1721
- * [[VendorList]] object or a version number represented as a string or
1722
- * number to download. If nothing is passed the latest version of the GVL
1723
- * will be loaded
1724
- */
1725
- constructor(versionOrVendorList) {
1726
- super();
1727
- /**
1728
- * @param {Promise} resolved when this GVL object is populated with the data
1729
- * or rejected if there is an error.
1730
- */
1731
- __publicField(this, "readyPromise");
1732
- /**
1733
- * @param {number} gvlSpecificationVersion - schema version for the GVL that is used
1734
- */
1735
- __publicField(this, "gvlSpecificationVersion");
1736
- /**
1737
- * @param {number} incremented with each published file change
1738
- */
1739
- __publicField(this, "vendorListVersion");
1740
- /**
1741
- * @param {number} tcfPolicyVersion - The TCF MO will increment this value
1742
- * whenever a GVL change (such as adding a new Purpose or Feature or a change
1743
- * in Purpose wording) legally invalidates existing TC Strings and requires
1744
- * CMPs to re-establish transparency and consent from users. If the policy
1745
- * version number in the latest GVL is different from the value in your TC
1746
- * String, then you need to re-establish transparency and consent for that
1747
- * user. A version 1 format TC String is considered to have a version value
1748
- * of 1.
1749
- */
1750
- __publicField(this, "tcfPolicyVersion");
1751
- /**
1752
- * @param {string | Date} lastUpdated - the date in which the vendor list
1753
- * json file was last updated.
1754
- */
1755
- __publicField(this, "lastUpdated");
1756
- /**
1757
- * @param {IntMap<Purpose>} a collection of [[Purpose]]s
1758
- */
1759
- __publicField(this, "purposes");
1760
- /**
1761
- * @param {IntMap<Purpose>} a collection of [[Purpose]]s
1762
- */
1763
- __publicField(this, "specialPurposes");
1764
- /**
1765
- * @param {IntMap<Feature>} a collection of [[Feature]]s
1766
- */
1767
- __publicField(this, "features");
1768
- /**
1769
- * @param {IntMap<Feature>} a collection of [[Feature]]s
1770
- */
1771
- __publicField(this, "specialFeatures");
1772
- /**
1773
- * @param {boolean} internal reference of when the GVL is ready to be used
1774
- */
1775
- __publicField(this, "isReady_", false);
1776
- /**
1777
- * @param {IntMap<Vendor>} a collection of [[Vendor]]s
1778
- */
1779
- __publicField(this, "vendors_");
1780
- __publicField(this, "vendorIds");
1781
- /**
1782
- * @param {IntMap<Vendor>} a collection of [[Vendor]]. Used as a backup if a whitelist is sets
1783
- */
1784
- __publicField(this, "fullVendorList");
1785
- /**
1786
- * @param {ByPurposeVendorMap} vendors by purpose
1787
- */
1788
- __publicField(this, "byPurposeVendorMap");
1789
- /**
1790
- * @param {IDSetMap} vendors by special purpose
1791
- */
1792
- __publicField(this, "bySpecialPurposeVendorMap");
1793
- /**
1794
- * @param {IDSetMap} vendors by feature
1795
- */
1796
- __publicField(this, "byFeatureVendorMap");
1797
- /**
1798
- * @param {IDSetMap} vendors by special feature
1799
- */
1800
- __publicField(this, "bySpecialFeatureVendorMap");
1801
- /**
1802
- * @param {IntMap<Stack>} a collection of [[Stack]]s
1803
- */
1804
- __publicField(this, "stacks");
1805
- /**
1806
- * @param {IntMap<DataCategory>} a collection of [[DataCategory]]s
1807
- */
1808
- __publicField(this, "dataCategories");
1809
- __publicField(this, "lang_");
1810
- __publicField(this, "cacheLang_");
1811
- __publicField(this, "isLatest", false);
1812
- let url = _GVL.baseUrl;
1813
- this.lang_ = _GVL.DEFAULT_LANGUAGE;
1814
- this.cacheLang_ = _GVL.DEFAULT_LANGUAGE;
1815
- if (this.isVendorList(versionOrVendorList)) {
1816
- this.populate(versionOrVendorList);
1817
- this.readyPromise = Promise.resolve();
1818
- } else {
1819
- if (!url) {
1820
- throw new GVLError("must specify GVL.baseUrl before loading GVL json");
1821
- }
1822
- if (versionOrVendorList > 0) {
1823
- const version2 = versionOrVendorList;
1824
- if (_GVL.CACHE.has(version2)) {
1825
- this.populate(_GVL.CACHE.get(version2));
1826
- this.readyPromise = Promise.resolve();
1827
- } else {
1828
- url += _GVL.versionedFilename.replace("[VERSION]", String(version2));
1829
- this.readyPromise = this.fetchJson(url);
1830
- }
1831
- } else {
1832
- if (_GVL.CACHE.has(_GVL.LATEST_CACHE_KEY)) {
1833
- this.populate(_GVL.CACHE.get(_GVL.LATEST_CACHE_KEY));
1834
- this.readyPromise = Promise.resolve();
1835
- } else {
1836
- this.isLatest = true;
1837
- this.readyPromise = this.fetchJson(url + _GVL.latestFilename);
1838
- }
1839
- }
1840
- }
1841
- }
1842
- /**
1843
- * baseUrl - Entities using the vendor-list.json are required by the iab to
1844
- * host their own copy of it to reduce the load on the iab's infrastructure
1845
- * so a 'base' url must be set to be put together with the versioning scheme
1846
- * of the filenames.
1847
- *
1848
- * @static
1849
- * @param {string} url - the base url to load the vendor-list.json from. This is
1850
- * broken out from the filename because it follows a different scheme for
1851
- * latest file vs versioned files.
1852
- *
1853
- * @throws {GVLError} - If the url is http[s]://vendorlist.consensu.org/...
1854
- * this will throw an error. IAB Europe requires that that CMPs and Vendors
1855
- * cache their own copies of the GVL to minimize load on their
1856
- * infrastructure. For more information regarding caching of the
1857
- * vendor-list.json, please see [the TCF documentation on 'Caching the Global
1858
- * Vendor List'
1859
- * ](https://github.com/InteractiveAdvertisingBureau/GDPR-Transparency-and-Consent-Framework/blob/master/TCFv2/IAB%20Tech%20Lab%20-%20Consent%20string%20and%20vendor%20list%20formats%20v2.md#caching-the-global-vendor-list)
1860
- */
1861
- static set baseUrl(url) {
1862
- const notValid = /^https?:\/\/vendorlist\.consensu\.org\//;
1863
- if (notValid.test(url)) {
1864
- throw new GVLError("Invalid baseUrl! You may not pull directly from vendorlist.consensu.org and must provide your own cache");
1865
- }
1866
- if (url.length > 0 && url[url.length - 1] !== "/") {
1867
- url += "/";
1868
- }
1869
- this.baseUrl_ = url;
1870
- }
1871
- /**
1872
- * baseUrl - Entities using the vendor-list.json are required by the iab to
1873
- * host their own copy of it to reduce the load on the iab's infrastructure
1874
- * so a 'base' url must be set to be put together with the versioning scheme
1875
- * of the filenames.
1876
- *
1877
- * @static
1878
- * @return {string} - returns the previously set baseUrl, the default is
1879
- * `undefined`
1880
- */
1881
- static get baseUrl() {
1882
- return this.baseUrl_;
1883
- }
1884
- /**
1885
- * emptyLanguageCache
1886
- *
1887
- * @param {string} [lang] - Optional language code to remove from
1888
- * the cache. Should be one of the languages in GVL.consentLanguages set.
1889
- * If not then the whole cache will be deleted.
1890
- * @return {boolean} - true if anything was deleted from the cache
1891
- */
1892
- static emptyLanguageCache(lang) {
1893
- let result = false;
1894
- if (lang == null && _GVL.LANGUAGE_CACHE.size > 0) {
1895
- _GVL.LANGUAGE_CACHE = /* @__PURE__ */ new Map();
1896
- result = true;
1897
- } else if (typeof lang === "string" && this.consentLanguages.has(lang.toUpperCase())) {
1898
- _GVL.LANGUAGE_CACHE.delete(lang.toUpperCase());
1899
- result = true;
1900
- }
1901
- return result;
1902
- }
1903
- /**
1904
- * emptyCache
1905
- *
1906
- * @param {number} [vendorListVersion] - version of the vendor list to delete
1907
- * from the cache. If none is specified then the whole cache is deleted.
1908
- * @return {boolean} - true if anything was deleted from the cache
1909
- */
1910
- static emptyCache(vendorListVersion) {
1911
- let retr = false;
1912
- if (Number.isInteger(vendorListVersion) && vendorListVersion >= 0) {
1913
- _GVL.CACHE.delete(vendorListVersion);
1914
- retr = true;
1915
- } else if (vendorListVersion === void 0) {
1916
- _GVL.CACHE = /* @__PURE__ */ new Map();
1917
- retr = true;
1918
- }
1919
- return retr;
1920
- }
1921
- cacheLanguage() {
1922
- if (!_GVL.LANGUAGE_CACHE.has(this.cacheLang_)) {
1923
- _GVL.LANGUAGE_CACHE.set(this.cacheLang_, {
1924
- purposes: this.purposes,
1925
- specialPurposes: this.specialPurposes,
1926
- features: this.features,
1927
- specialFeatures: this.specialFeatures,
1928
- stacks: this.stacks,
1929
- dataCategories: this.dataCategories
1930
- });
1931
- }
1932
- }
1933
- async fetchJson(url) {
1934
- try {
1935
- this.populate(await Json.fetch(url));
1936
- } catch (err) {
1937
- throw new GVLError(err.message);
1938
- }
1939
- }
1940
- /**
1941
- * getJson - Method for getting the JSON that was downloaded to created this
1942
- * `GVL` object
1943
- *
1944
- * @return {VendorList} - The basic JSON structure without the extra
1945
- * functionality and methods of this class.
1946
- */
1947
- getJson() {
1948
- return JSON.parse(JSON.stringify({
1949
- gvlSpecificationVersion: this.gvlSpecificationVersion,
1950
- vendorListVersion: this.vendorListVersion,
1951
- tcfPolicyVersion: this.tcfPolicyVersion,
1952
- lastUpdated: this.lastUpdated,
1953
- purposes: this.purposes,
1954
- specialPurposes: this.specialPurposes,
1955
- features: this.features,
1956
- specialFeatures: this.specialFeatures,
1957
- stacks: this.stacks,
1958
- dataCategories: this.dataCategories,
1959
- vendors: this.fullVendorList
1960
- }));
1961
- }
1962
- /**
1963
- * changeLanguage - retrieves the purpose language translation and sets the
1964
- * internal language variable
1965
- *
1966
- * @param {string} lang - language code to change language to
1967
- * @return {Promise<void | GVLError>} - returns the `readyPromise` and
1968
- * resolves when this GVL is populated with the data from the language file.
1969
- */
1970
- async changeLanguage(lang) {
1971
- let parsedLanguage = lang;
1972
- try {
1973
- parsedLanguage = _GVL.consentLanguages.parseLanguage(lang);
1974
- } catch (e) {
1975
- throw new GVLError("Error during parsing the language: " + e.message);
1976
- }
1977
- const cacheLang = lang.toUpperCase();
1978
- if (parsedLanguage.toLowerCase() === _GVL.DEFAULT_LANGUAGE.toLowerCase() && !_GVL.LANGUAGE_CACHE.has(cacheLang)) {
1979
- return;
1980
- }
1981
- if (parsedLanguage !== this.lang_) {
1982
- this.lang_ = parsedLanguage;
1983
- if (_GVL.LANGUAGE_CACHE.has(cacheLang)) {
1984
- const cached = _GVL.LANGUAGE_CACHE.get(cacheLang);
1985
- for (const prop in cached) {
1986
- if (cached.hasOwnProperty(prop)) {
1987
- this[prop] = cached[prop];
1988
- }
1989
- }
1990
- } else {
1991
- const url = _GVL.baseUrl + _GVL.languageFilename.replace("[LANG]", this.lang_.toLowerCase());
1992
- try {
1993
- await this.fetchJson(url);
1994
- this.cacheLang_ = cacheLang;
1995
- this.cacheLanguage();
1996
- } catch (err) {
1997
- throw new GVLError("unable to load language: " + err.message);
1998
- }
1999
- }
2000
- }
2001
- }
2002
- get language() {
2003
- return this.lang_;
2004
- }
2005
- isVendorList(gvlObject) {
2006
- return gvlObject !== void 0 && gvlObject.vendors !== void 0;
2007
- }
2008
- populate(gvlObject) {
2009
- this.purposes = gvlObject.purposes;
2010
- this.specialPurposes = gvlObject.specialPurposes;
2011
- this.features = gvlObject.features;
2012
- this.specialFeatures = gvlObject.specialFeatures;
2013
- this.stacks = gvlObject.stacks;
2014
- this.dataCategories = gvlObject.dataCategories;
2015
- if (this.isVendorList(gvlObject)) {
2016
- this.gvlSpecificationVersion = gvlObject.gvlSpecificationVersion;
2017
- this.tcfPolicyVersion = gvlObject.tcfPolicyVersion;
2018
- this.vendorListVersion = gvlObject.vendorListVersion;
2019
- this.lastUpdated = gvlObject.lastUpdated;
2020
- if (typeof this.lastUpdated === "string") {
2021
- this.lastUpdated = new Date(this.lastUpdated);
2022
- }
2023
- this.vendors_ = gvlObject.vendors;
2024
- this.fullVendorList = gvlObject.vendors;
2025
- this.mapVendors();
2026
- this.isReady_ = true;
2027
- if (this.isLatest) {
2028
- _GVL.CACHE.set(_GVL.LATEST_CACHE_KEY, this.getJson());
2029
- }
2030
- if (!_GVL.CACHE.has(this.vendorListVersion)) {
2031
- _GVL.CACHE.set(this.vendorListVersion, this.getJson());
2032
- }
2033
- }
2034
- this.cacheLanguage();
2035
- }
2036
- mapVendors(vendorIds) {
2037
- this.byPurposeVendorMap = {};
2038
- this.bySpecialPurposeVendorMap = {};
2039
- this.byFeatureVendorMap = {};
2040
- this.bySpecialFeatureVendorMap = {};
2041
- Object.keys(this.purposes).forEach((purposeId) => {
2042
- this.byPurposeVendorMap[purposeId] = {
2043
- legInt: /* @__PURE__ */ new Set(),
2044
- consent: /* @__PURE__ */ new Set(),
2045
- flexible: /* @__PURE__ */ new Set()
2046
- };
2047
- });
2048
- Object.keys(this.specialPurposes).forEach((purposeId) => {
2049
- this.bySpecialPurposeVendorMap[purposeId] = /* @__PURE__ */ new Set();
2050
- });
2051
- Object.keys(this.features).forEach((featureId) => {
2052
- this.byFeatureVendorMap[featureId] = /* @__PURE__ */ new Set();
2053
- });
2054
- Object.keys(this.specialFeatures).forEach((featureId) => {
2055
- this.bySpecialFeatureVendorMap[featureId] = /* @__PURE__ */ new Set();
2056
- });
2057
- if (!Array.isArray(vendorIds)) {
2058
- vendorIds = Object.keys(this.fullVendorList).map((vId) => +vId);
2059
- }
2060
- this.vendorIds = new Set(vendorIds);
2061
- this.vendors_ = vendorIds.reduce((vendors, vendorId) => {
2062
- const vendor = this.vendors_[String(vendorId)];
2063
- if (vendor && vendor.deletedDate === void 0) {
2064
- vendor.purposes.forEach((purposeId) => {
2065
- const purpGroup = this.byPurposeVendorMap[String(purposeId)];
2066
- purpGroup.consent.add(vendorId);
2067
- });
2068
- vendor.specialPurposes.forEach((purposeId) => {
2069
- this.bySpecialPurposeVendorMap[String(purposeId)].add(vendorId);
2070
- });
2071
- vendor.legIntPurposes.forEach((purposeId) => {
2072
- this.byPurposeVendorMap[String(purposeId)].legInt.add(vendorId);
2073
- });
2074
- if (vendor.flexiblePurposes) {
2075
- vendor.flexiblePurposes.forEach((purposeId) => {
2076
- this.byPurposeVendorMap[String(purposeId)].flexible.add(vendorId);
2077
- });
2078
- }
2079
- vendor.features.forEach((featureId) => {
2080
- this.byFeatureVendorMap[String(featureId)].add(vendorId);
2081
- });
2082
- vendor.specialFeatures.forEach((featureId) => {
2083
- this.bySpecialFeatureVendorMap[String(featureId)].add(vendorId);
2084
- });
2085
- vendors[vendorId] = vendor;
2086
- }
2087
- return vendors;
2088
- }, {});
2089
- }
2090
- getFilteredVendors(purposeOrFeature, id, subType, special) {
2091
- const properPurposeOrFeature = purposeOrFeature.charAt(0).toUpperCase() + purposeOrFeature.slice(1);
2092
- let vendorSet;
2093
- const retr = {};
2094
- if (purposeOrFeature === "purpose" && subType) {
2095
- vendorSet = this["by" + properPurposeOrFeature + "VendorMap"][String(id)][subType];
2096
- } else {
2097
- vendorSet = this["by" + (special ? "Special" : "") + properPurposeOrFeature + "VendorMap"][String(id)];
2098
- }
2099
- vendorSet.forEach((vendorId) => {
2100
- retr[String(vendorId)] = this.vendors[String(vendorId)];
2101
- });
2102
- return retr;
2103
- }
2104
- /**
2105
- * getVendorsWithConsentPurpose
2106
- *
2107
- * @param {number} purposeId
2108
- * @return {IntMap<Vendor>} - list of vendors that have declared the consent purpose id
2109
- */
2110
- getVendorsWithConsentPurpose(purposeId) {
2111
- return this.getFilteredVendors("purpose", purposeId, "consent");
2112
- }
2113
- /**
2114
- * getVendorsWithLegIntPurpose
2115
- *
2116
- * @param {number} purposeId
2117
- * @return {IntMap<Vendor>} - list of vendors that have declared the legInt (Legitimate Interest) purpose id
2118
- */
2119
- getVendorsWithLegIntPurpose(purposeId) {
2120
- return this.getFilteredVendors("purpose", purposeId, "legInt");
2121
- }
2122
- /**
2123
- * getVendorsWithFlexiblePurpose
2124
- *
2125
- * @param {number} purposeId
2126
- * @return {IntMap<Vendor>} - list of vendors that have declared the flexible purpose id
2127
- */
2128
- getVendorsWithFlexiblePurpose(purposeId) {
2129
- return this.getFilteredVendors("purpose", purposeId, "flexible");
2130
- }
2131
- /**
2132
- * getVendorsWithSpecialPurpose
2133
- *
2134
- * @param {number} specialPurposeId
2135
- * @return {IntMap<Vendor>} - list of vendors that have declared the special purpose id
2136
- */
2137
- getVendorsWithSpecialPurpose(specialPurposeId) {
2138
- return this.getFilteredVendors("purpose", specialPurposeId, void 0, true);
2139
- }
2140
- /**
2141
- * getVendorsWithFeature
2142
- *
2143
- * @param {number} featureId
2144
- * @return {IntMap<Vendor>} - list of vendors that have declared the feature id
2145
- */
2146
- getVendorsWithFeature(featureId) {
2147
- return this.getFilteredVendors("feature", featureId);
2148
- }
2149
- /**
2150
- * getVendorsWithSpecialFeature
2151
- *
2152
- * @param {number} specialFeatureId
2153
- * @return {IntMap<Vendor>} - list of vendors that have declared the special feature id
2154
- */
2155
- getVendorsWithSpecialFeature(specialFeatureId) {
2156
- return this.getFilteredVendors("feature", specialFeatureId, void 0, true);
2157
- }
2158
- /**
2159
- * vendors
2160
- *
2161
- * @return {IntMap<Vendor>} - the list of vendors as it would on the JSON file
2162
- * except if `narrowVendorsTo` was called, it would be that narrowed list
2163
- */
2164
- get vendors() {
2165
- return this.vendors_;
2166
- }
2167
- /**
2168
- * narrowVendorsTo - narrows vendors represented in this GVL to the list of ids passed in
2169
- *
2170
- * @param {number[]} vendorIds - list of ids to narrow this GVL to
2171
- * @return {void}
2172
- */
2173
- narrowVendorsTo(vendorIds) {
2174
- this.mapVendors(vendorIds);
2175
- }
2176
- /**
2177
- * isReady - Whether or not this instance is ready to be used. This will be
2178
- * immediately and synchronously true if a vendorlist object is passed into
2179
- * the constructor or once the JSON vendorllist is retrieved.
2180
- *
2181
- * @return {boolean} whether or not the instance is ready to be interacted
2182
- * with and all the data is populated
2183
- */
2184
- get isReady() {
2185
- return this.isReady_;
2186
- }
2187
- /**
2188
- * clone - overrides base `clone()` method since GVL is a special class that
2189
- * represents a JSON structure with some additional functionality.
2190
- *
2191
- * @return {GVL}
2192
- */
2193
- clone() {
2194
- const result = new _GVL(this.getJson());
2195
- if (this.lang_ !== _GVL.DEFAULT_LANGUAGE) {
2196
- result.changeLanguage(this.lang_);
2197
- }
2198
- return result;
2199
- }
2200
- static isInstanceOf(questionableInstance) {
2201
- const isSo = typeof questionableInstance === "object";
2202
- return isSo && typeof questionableInstance.narrowVendorsTo === "function";
2203
- }
2204
- };
2205
- __publicField(_GVL, "LANGUAGE_CACHE", /* @__PURE__ */ new Map());
2206
- __publicField(_GVL, "CACHE", /* @__PURE__ */ new Map());
2207
- __publicField(_GVL, "LATEST_CACHE_KEY", 0);
2208
- __publicField(_GVL, "DEFAULT_LANGUAGE", "EN");
2209
- /**
2210
- * Set of available consent languages published by the IAB
2211
- */
2212
- __publicField(_GVL, "consentLanguages", new ConsentLanguages());
2213
- __publicField(_GVL, "baseUrl_");
2214
- /**
2215
- * @static
2216
- * @param {string} - the latest is assumed to be vendor-list.json because
2217
- * that is what the iab uses, but it could be different... if you want
2218
- */
2219
- __publicField(_GVL, "latestFilename", "vendor-list.json");
2220
- /**
2221
- * @static
2222
- * @param {string} - the versioned name is assumed to be
2223
- * vendor-list-v[VERSION].json where [VERSION] will be replaced with the
2224
- * specified version. But it could be different... if you want just make
2225
- * sure to include the [VERSION] macro if you have a numbering scheme, it's a
2226
- * simple string substitution.
2227
- *
2228
- * eg.
2229
- * ```javascript
2230
- * GVL.baseUrl = "http://www.mydomain.com/iabcmp/";
2231
- * GVL.versionedFilename = "vendorlist?getVersion=[VERSION]";
2232
- * ```
2233
- */
2234
- __publicField(_GVL, "versionedFilename", "archives/vendor-list-v[VERSION].json");
2235
- /**
2236
- * @param {string} - Translations of the names and descriptions for Purposes,
2237
- * Special Purposes, Features, and Special Features to non-English languages
2238
- * are contained in a file where attributes containing English content
2239
- * (except vendor declaration information) are translated. The iab publishes
2240
- * one following the scheme below where the LANG is the iso639-1 language
2241
- * code. For a list of available translations
2242
- * [please go here](https://register.consensu.org/Translation).
2243
- *
2244
- * eg.
2245
- * ```javascript
2246
- * GVL.baseUrl = "http://www.mydomain.com/iabcmp/";
2247
- * GVL.languageFilename = "purposes?getPurposes=[LANG]";
2248
- * ```
2249
- */
2250
- __publicField(_GVL, "languageFilename", "purposes-[LANG].json");
2251
- let GVL = _GVL;
2252
- class TCModel extends Cloneable {
2253
- /**
2254
- * Constructs the TCModel. Passing a [[GVL]] is optional when constructing
2255
- * as this TCModel may be constructed from decoding an existing encoded
2256
- * TCString.
2257
- *
2258
- * @param {GVL} [gvl]
2259
- */
2260
- constructor(gvl) {
2261
- super();
2262
- __publicField(this, "isServiceSpecific_", false);
2263
- __publicField(this, "supportOOB_", true);
2264
- __publicField(this, "useNonStandardTexts_", false);
2265
- __publicField(this, "purposeOneTreatment_", false);
2266
- __publicField(this, "publisherCountryCode_", "AA");
2267
- __publicField(this, "version_", 2);
2268
- __publicField(this, "consentScreen_", 0);
2269
- __publicField(this, "policyVersion_", 4);
2270
- __publicField(this, "consentLanguage_", "EN");
2271
- __publicField(this, "cmpId_", 0);
2272
- __publicField(this, "cmpVersion_", 0);
2273
- __publicField(this, "vendorListVersion_", 0);
2274
- __publicField(this, "numCustomPurposes_", 0);
2275
- // Member Variable for GVL
2276
- __publicField(this, "gvl_");
2277
- __publicField(this, "created");
2278
- __publicField(this, "lastUpdated");
2279
- /**
2280
- * The TCF designates certain Features as special, that is, a CMP must afford
2281
- * the user a means to opt in to their use. These Special Features are
2282
- * published and numbered in the GVL separately from normal Features.
2283
- * Provides for up to 12 special features.
2284
- */
2285
- __publicField(this, "specialFeatureOptins", new Vector());
2286
- /**
2287
- * Renamed from `PurposesAllowed` in TCF v1.1
2288
- * The user’s consent value for each Purpose established on the legal basis
2289
- * of consent. Purposes are published in the Global Vendor List (see. [[GVL]]).
2290
- */
2291
- __publicField(this, "purposeConsents", new Vector());
2292
- /**
2293
- * The user’s permission for each Purpose established on the legal basis of
2294
- * legitimate interest. If the user has exercised right-to-object for a
2295
- * purpose.
2296
- */
2297
- __publicField(this, "purposeLegitimateInterests", new Vector());
2298
- /**
2299
- * The user’s consent value for each Purpose established on the legal basis
2300
- * of consent, for the publisher. Purposes are published in the Global
2301
- * Vendor List.
2302
- */
2303
- __publicField(this, "publisherConsents", new Vector());
2304
- /**
2305
- * The user’s permission for each Purpose established on the legal basis of
2306
- * legitimate interest. If the user has exercised right-to-object for a
2307
- * purpose.
2308
- */
2309
- __publicField(this, "publisherLegitimateInterests", new Vector());
2310
- /**
2311
- * The user’s consent value for each Purpose established on the legal basis
2312
- * of consent, for the publisher. Purposes are published in the Global
2313
- * Vendor List.
2314
- */
2315
- __publicField(this, "publisherCustomConsents", new Vector());
2316
- /**
2317
- * The user’s permission for each Purpose established on the legal basis of
2318
- * legitimate interest. If the user has exercised right-to-object for a
2319
- * purpose that is established in the publisher's custom purposes.
2320
- */
2321
- __publicField(this, "publisherCustomLegitimateInterests", new Vector());
2322
- /**
2323
- * set by a publisher if they wish to collect consent and LI Transparency for
2324
- * purposes outside of the TCF
2325
- */
2326
- __publicField(this, "customPurposes");
2327
- /**
2328
- * Each [[Vendor]] is keyed by id. Their consent value is true if it is in
2329
- * the Vector
2330
- */
2331
- __publicField(this, "vendorConsents", new Vector());
2332
- /**
2333
- * Each [[Vendor]] is keyed by id. Whether their Legitimate Interests
2334
- * Disclosures have been established is stored as boolean.
2335
- * see: [[Vector]]
2336
- */
2337
- __publicField(this, "vendorLegitimateInterests", new Vector());
2338
- /**
2339
- * The value included for disclosed vendors signals which vendors have been
2340
- * disclosed to the user in the interface surfaced by the CMP. This section
2341
- * content is required when writing a TC string to the global (consensu)
2342
- * scope. When a CMP has read from and is updating a TC string from the
2343
- * global consensu.org storage, the CMP MUST retain the existing disclosure
2344
- * information and only add information for vendors that it has disclosed
2345
- * that had not been disclosed by other CMPs in prior interactions with this
2346
- * device/user agent.
2347
- */
2348
- __publicField(this, "vendorsDisclosed", new Vector());
2349
- /**
2350
- * Signals which vendors the publisher permits to use OOB legal bases.
2351
- */
2352
- __publicField(this, "vendorsAllowed", new Vector());
2353
- __publicField(this, "publisherRestrictions", new PurposeRestrictionVector());
2354
- if (gvl) {
2355
- this.gvl = gvl;
2356
- }
2357
- this.updated();
2358
- }
2359
- /**
2360
- * sets the [[GVL]] with side effects of also setting the `vendorListVersion`, `policyVersion`, and `consentLanguage`
2361
- * @param {GVL} gvl
2362
- */
2363
- set gvl(gvl) {
2364
- if (!GVL.isInstanceOf(gvl)) {
2365
- gvl = new GVL(gvl);
2366
- }
2367
- this.gvl_ = gvl;
2368
- this.publisherRestrictions.gvl = gvl;
2369
- }
2370
- /**
2371
- * @return {GVL} the gvl instance set on this TCModel instance
2372
- */
2373
- get gvl() {
2374
- return this.gvl_;
2375
- }
2376
- /**
2377
- * @param {number} integer - A unique ID will be assigned to each Consent
2378
- * Manager Provider (CMP) from the iab.
2379
- *
2380
- * @throws {TCModelError} if the value is not an integer greater than 1 as those are not valid.
2381
- */
2382
- set cmpId(integer) {
2383
- integer = Number(integer);
2384
- if (Number.isInteger(integer) && integer > 1) {
2385
- this.cmpId_ = integer;
2386
- } else {
2387
- throw new TCModelError("cmpId", integer);
2388
- }
2389
- }
2390
- get cmpId() {
2391
- return this.cmpId_;
2392
- }
2393
- /**
2394
- * Each change to an operating CMP should receive a
2395
- * new version number, for logging proof of consent. CmpVersion defined by
2396
- * each CMP.
2397
- *
2398
- * @param {number} integer
2399
- *
2400
- * @throws {TCModelError} if the value is not an integer greater than 1 as those are not valid.
2401
- */
2402
- set cmpVersion(integer) {
2403
- integer = Number(integer);
2404
- if (Number.isInteger(integer) && integer > -1) {
2405
- this.cmpVersion_ = integer;
2406
- } else {
2407
- throw new TCModelError("cmpVersion", integer);
2408
- }
2409
- }
2410
- get cmpVersion() {
2411
- return this.cmpVersion_;
2412
- }
2413
- /**
2414
- * The screen number is CMP and CmpVersion
2415
- * specific, and is for logging proof of consent.(For example, a CMP could
2416
- * keep records so that a publisher can request information about the context
2417
- * in which consent was gathered.)
2418
- *
2419
- * @param {number} integer
2420
- *
2421
- * @throws {TCModelError} if the value is not an integer greater than 0 as those are not valid.
2422
- */
2423
- set consentScreen(integer) {
2424
- integer = Number(integer);
2425
- if (Number.isInteger(integer) && integer > -1) {
2426
- this.consentScreen_ = integer;
2427
- } else {
2428
- throw new TCModelError("consentScreen", integer);
2429
- }
2430
- }
2431
- get consentScreen() {
2432
- return this.consentScreen_;
2433
- }
2434
- /**
2435
- * @param {string} lang - [two-letter ISO 639-1 language
2436
- * code](http://www.loc.gov/standards/iso639-2/php/code_list.php) in which
2437
- * the CMP UI was presented
2438
- *
2439
- * @throws {TCModelError} if the value is not a length-2 string of alpha characters
2440
- */
2441
- set consentLanguage(lang) {
2442
- this.consentLanguage_ = lang;
2443
- }
2444
- get consentLanguage() {
2445
- return this.consentLanguage_;
2446
- }
2447
- /**
2448
- * @param {string} countryCode - [two-letter ISO 3166-1 alpha-2 country
2449
- * code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the publisher,
2450
- * determined by the CMP-settings of the publisher.
2451
- *
2452
- * @throws {TCModelError} if the value is not a length-2 string of alpha characters
2453
- */
2454
- set publisherCountryCode(countryCode) {
2455
- if (/^([A-z]){2}$/.test(countryCode)) {
2456
- this.publisherCountryCode_ = countryCode.toUpperCase();
2457
- } else {
2458
- throw new TCModelError("publisherCountryCode", countryCode);
2459
- }
2460
- }
2461
- get publisherCountryCode() {
2462
- return this.publisherCountryCode_;
2463
- }
2464
- /**
2465
- * Version of the GVL used to create this TCModel. Global
2466
- * Vendor List versions will be released periodically.
2467
- *
2468
- * @param {number} integer
2469
- *
2470
- * @throws {TCModelError} if the value is not an integer greater than 0 as those are not valid.
2471
- */
2472
- set vendorListVersion(integer) {
2473
- integer = Number(integer) >> 0;
2474
- if (integer < 0) {
2475
- throw new TCModelError("vendorListVersion", integer);
2476
- } else {
2477
- this.vendorListVersion_ = integer;
2478
- }
2479
- }
2480
- get vendorListVersion() {
2481
- if (this.gvl) {
2482
- return this.gvl.vendorListVersion;
2483
- } else {
2484
- return this.vendorListVersion_;
2485
- }
2486
- }
2487
- /**
2488
- * From the corresponding field in the GVL that was
2489
- * used for obtaining consent. A new policy version invalidates existing
2490
- * strings and requires CMPs to re-establish transparency and consent from
2491
- * users.
2492
- *
2493
- * If a TCF policy version number is different from the one from the latest
2494
- * GVL, the CMP must re-establish transparency and consent.
2495
- *
2496
- * @param {number} num - You do not need to set this. This comes
2497
- * directly from the [[GVL]].
2498
- *
2499
- */
2500
- set policyVersion(num) {
2501
- this.policyVersion_ = parseInt(num, 10);
2502
- if (this.policyVersion_ < 0) {
2503
- throw new TCModelError("policyVersion", num);
2504
- }
2505
- }
2506
- get policyVersion() {
2507
- if (this.gvl) {
2508
- return this.gvl.tcfPolicyVersion;
2509
- } else {
2510
- return this.policyVersion_;
2511
- }
2512
- }
2513
- set version(num) {
2514
- this.version_ = parseInt(num, 10);
2515
- }
2516
- get version() {
2517
- return this.version_;
2518
- }
2519
- /**
2520
- * Whether the signals encoded in this TC String were from site-specific
2521
- * storage `true` versus ‘global’ consensu.org shared storage `false`. A
2522
- * string intended to be stored in global/shared scope but the CMP is unable
2523
- * to store due to a user agent not accepting third-party cookies would be
2524
- * considered site-specific `true`.
2525
- *
2526
- * @param {boolean} bool - value to set. Some changes to other fields in this
2527
- * model will automatically change this value like adding publisher
2528
- * restrictions.
2529
- */
2530
- set isServiceSpecific(bool) {
2531
- this.isServiceSpecific_ = bool;
2532
- }
2533
- get isServiceSpecific() {
2534
- return this.isServiceSpecific_;
2535
- }
2536
- /**
2537
- * Non-standard stacks means that a CMP is using publisher-customized stack
2538
- * descriptions. Stacks (in terms of purposes in a stack) are pre-set by the
2539
- * IAB. As are titles. Descriptions are pre-set, but publishers can customize
2540
- * them. If they do, they need to set this bit to indicate that they've
2541
- * customized descriptions.
2542
- *
2543
- * @param {boolean} bool - value to set
2544
- */
2545
- set useNonStandardTexts(bool) {
2546
- this.useNonStandardTexts_ = bool;
2547
- }
2548
- get useNonStandardTexts() {
2549
- return this.useNonStandardTexts_;
2550
- }
2551
- /**
2552
- * Whether or not this publisher supports OOB signaling. On Global TC String
2553
- * OOB Vendors Disclosed will be included if the publish wishes to no allow
2554
- * these vendors they should set this to false.
2555
- * @param {boolean} bool - value to set
2556
- */
2557
- set supportOOB(bool) {
2558
- this.supportOOB_ = bool;
2559
- }
2560
- get supportOOB() {
2561
- return this.supportOOB_;
2562
- }
2563
- /**
2564
- * `false` There is no special Purpose 1 status.
2565
- * Purpose 1 was disclosed normally (consent) as expected by Policy. `true`
2566
- * Purpose 1 not disclosed at all. CMPs use PublisherCC to indicate the
2567
- * publisher’s country of establishment to help Vendors determine whether the
2568
- * vendor requires Purpose 1 consent. In global scope TC strings, this field
2569
- * must always have a value of `false`. When a CMP encounters a global scope
2570
- * string with `purposeOneTreatment=true` then that string should be
2571
- * considered invalid and the CMP must re-establish transparency and consent.
2572
- *
2573
- * @param {boolean} bool
2574
- */
2575
- set purposeOneTreatment(bool) {
2576
- this.purposeOneTreatment_ = bool;
2577
- }
2578
- get purposeOneTreatment() {
2579
- return this.purposeOneTreatment_;
2580
- }
2581
- /**
2582
- * setAllVendorConsents - sets all vendors on the GVL Consent (true)
2583
- *
2584
- * @return {void}
2585
- */
2586
- setAllVendorConsents() {
2587
- this.vendorConsents.set(this.gvl.vendors);
2588
- }
2589
- /**
2590
- * unsetAllVendorConsents - unsets all vendors on the GVL Consent (false)
2591
- *
2592
- * @return {void}
2593
- */
2594
- unsetAllVendorConsents() {
2595
- this.vendorConsents.empty();
2596
- }
2597
- /**
2598
- * setAllVendorsDisclosed - sets all vendors on the GVL Vendors Disclosed (true)
2599
- *
2600
- * @return {void}
2601
- */
2602
- setAllVendorsDisclosed() {
2603
- this.vendorsDisclosed.set(this.gvl.vendors);
2604
- }
2605
- /**
2606
- * unsetAllVendorsDisclosed - unsets all vendors on the GVL Consent (false)
2607
- *
2608
- * @return {void}
2609
- */
2610
- unsetAllVendorsDisclosed() {
2611
- this.vendorsDisclosed.empty();
2612
- }
2613
- /**
2614
- * setAllVendorsAllowed - sets all vendors on the GVL Consent (true)
2615
- *
2616
- * @return {void}
2617
- */
2618
- setAllVendorsAllowed() {
2619
- this.vendorsAllowed.set(this.gvl.vendors);
2620
- }
2621
- /**
2622
- * unsetAllVendorsAllowed - unsets all vendors on the GVL Consent (false)
2623
- *
2624
- * @return {void}
2625
- */
2626
- unsetAllVendorsAllowed() {
2627
- this.vendorsAllowed.empty();
2628
- }
2629
- /**
2630
- * setAllVendorLegitimateInterests - sets all vendors on the GVL LegitimateInterests (true)
2631
- *
2632
- * @return {void}
2633
- */
2634
- setAllVendorLegitimateInterests() {
2635
- this.vendorLegitimateInterests.set(this.gvl.vendors);
2636
- }
2637
- /**
2638
- * unsetAllVendorLegitimateInterests - unsets all vendors on the GVL LegitimateInterests (false)
2639
- *
2640
- * @return {void}
2641
- */
2642
- unsetAllVendorLegitimateInterests() {
2643
- this.vendorLegitimateInterests.empty();
2644
- }
2645
- /**
2646
- * setAllPurposeConsents - sets all purposes on the GVL Consent (true)
2647
- *
2648
- * @return {void}
2649
- */
2650
- setAllPurposeConsents() {
2651
- this.purposeConsents.set(this.gvl.purposes);
2652
- }
2653
- /**
2654
- * unsetAllPurposeConsents - unsets all purposes on the GVL Consent (false)
2655
- *
2656
- * @return {void}
2657
- */
2658
- unsetAllPurposeConsents() {
2659
- this.purposeConsents.empty();
2660
- }
2661
- /**
2662
- * setAllPurposeLegitimateInterests - sets all purposes on the GVL LI Transparency (true)
2663
- *
2664
- * @return {void}
2665
- */
2666
- setAllPurposeLegitimateInterests() {
2667
- this.purposeLegitimateInterests.set(this.gvl.purposes);
2668
- }
2669
- /**
2670
- * unsetAllPurposeLegitimateInterests - unsets all purposes on the GVL LI Transparency (false)
2671
- *
2672
- * @return {void}
2673
- */
2674
- unsetAllPurposeLegitimateInterests() {
2675
- this.purposeLegitimateInterests.empty();
2676
- }
2677
- /**
2678
- * setAllSpecialFeatureOptins - sets all special featuresOptins on the GVL (true)
2679
- *
2680
- * @return {void}
2681
- */
2682
- setAllSpecialFeatureOptins() {
2683
- this.specialFeatureOptins.set(this.gvl.specialFeatures);
2684
- }
2685
- /**
2686
- * unsetAllSpecialFeatureOptins - unsets all special featuresOptins on the GVL (true)
2687
- *
2688
- * @return {void}
2689
- */
2690
- unsetAllSpecialFeatureOptins() {
2691
- this.specialFeatureOptins.empty();
2692
- }
2693
- setAll() {
2694
- this.setAllVendorConsents();
2695
- this.setAllPurposeLegitimateInterests();
2696
- this.setAllSpecialFeatureOptins();
2697
- this.setAllPurposeConsents();
2698
- this.setAllVendorLegitimateInterests();
2699
- }
2700
- unsetAll() {
2701
- this.unsetAllVendorConsents();
2702
- this.unsetAllPurposeLegitimateInterests();
2703
- this.unsetAllSpecialFeatureOptins();
2704
- this.unsetAllPurposeConsents();
2705
- this.unsetAllVendorLegitimateInterests();
2706
- }
2707
- get numCustomPurposes() {
2708
- let len = this.numCustomPurposes_;
2709
- if (typeof this.customPurposes === "object") {
2710
- const purposeIds = Object.keys(this.customPurposes).sort((a, b) => Number(a) - Number(b));
2711
- len = parseInt(purposeIds.pop(), 10);
2712
- }
2713
- return len;
2714
- }
2715
- set numCustomPurposes(num) {
2716
- this.numCustomPurposes_ = parseInt(num, 10);
2717
- if (this.numCustomPurposes_ < 0) {
2718
- throw new TCModelError("numCustomPurposes", num);
2719
- }
2720
- }
2721
- /**
2722
- * updated - updates the created and lastUpdated dates with a 'now' day-level UTC timestamp
2723
- *
2724
- * @return {void}
2725
- */
2726
- updated() {
2727
- const date = /* @__PURE__ */ new Date();
2728
- const utcDate = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
2729
- this.created = utcDate;
2730
- this.lastUpdated = utcDate;
2731
- }
2732
- }
2733
- /**
2734
- * Set of available consent languages published by the IAB
2735
- */
2736
- __publicField(TCModel, "consentLanguages", GVL.consentLanguages);
2737
- class TCString {
2738
- /**
2739
- * encodes a model into a TCString
2740
- *
2741
- * @param {TCModel} tcModel - model to convert into encoded string
2742
- * @param {EncodingOptions} options - for encoding options other than default
2743
- * @return {string} - base64url encoded Transparency and Consent String
2744
- */
2745
- static encode(tcModel, options) {
2746
- let out = "";
2747
- let sequence;
2748
- tcModel = SemanticPreEncoder.process(tcModel, options);
2749
- if (Array.isArray(options == null ? void 0 : options.segments)) {
2750
- sequence = options.segments;
2751
- } else {
2752
- sequence = new SegmentSequence(tcModel, options)["" + tcModel.version];
2753
- }
2754
- sequence.forEach((segment, idx) => {
2755
- let dotMaybe = "";
2756
- if (idx < sequence.length - 1) {
2757
- dotMaybe = ".";
2758
- }
2759
- out += SegmentEncoder.encode(tcModel, segment) + dotMaybe;
2760
- });
2761
- return out;
2762
- }
2763
- /**
2764
- * Decodes a string into a TCModel
2765
- *
2766
- * @param {string} encodedTCString - base64url encoded Transparency and
2767
- * Consent String to decode - can also be a single or group of segments of
2768
- * the string
2769
- * @param {string} [tcModel] - model to enhance with the information. If
2770
- * none is passed a new instance of TCModel will be created.
2771
- * @return {TCModel} - Returns populated TCModel
2772
- */
2773
- static decode(encodedTCString, tcModel) {
2774
- const segments = encodedTCString.split(".");
2775
- const len = segments.length;
2776
- if (!tcModel) {
2777
- tcModel = new TCModel();
2778
- }
2779
- for (let i = 0; i < len; i++) {
2780
- const segString = segments[i];
2781
- const firstChar = Base64Url.decode(segString.charAt(0));
2782
- const segTypeBits = firstChar.substr(0, BitLength.segmentType);
2783
- const segment = SegmentIDs.ID_TO_KEY[IntEncoder.decode(segTypeBits, BitLength.segmentType).toString()];
2784
- SegmentEncoder.decode(segString, tcModel, segment);
2785
- }
2786
- return tcModel;
2787
- }
2788
- }
2789
- function isValidGdprValue(val) {
2790
- if (val === null) {
2791
- return true;
2792
- }
2793
- try {
2794
- TCString.decode(val);
2795
- return true;
2796
- } catch (error) {
2797
- return false;
2798
- }
2799
- }
2800
- function isValidUspString(val) {
2801
- if (val === null) {
2802
- return true;
2803
- }
2804
- const regex = /^[1-9][YN-][YN-][YN-]$/;
2805
- return regex.test(val);
2806
- }
2807
- function validateRawConsentState(input) {
2808
- if (typeof input !== "object" || input === null) {
2809
- throw new Error("Invalid consent state object");
2810
- }
2811
- if (!isValidGdprValue(input.gdpr)) {
2812
- throw new Error("Invalid TC string provided");
2813
- }
2814
- if (!isValidUspString(input.ccpa)) {
2815
- throw new Error("Invalid USP string provided");
2816
- }
2817
- if (!["ccpa", "gdpr"].includes(input.activeLegislation)) {
2818
- throw new Error("Active legislation is required");
2819
- }
2820
- if (input.gdpr === void 0 && input.ccpa === void 0) {
2821
- throw new Error("Either GDPR or CCPA consent must be provided");
2822
- }
2823
- return true;
2824
- }
2825
- function validateIabConsentCategory(categoryName) {
2826
- if (!categoryName || categoryName in iabCustomCategories === false) {
2827
- throw new Error("Provided custom category identifier does not exist. Please check");
2828
- }
2829
- }
2830
- function checkConsentFor(categoryName, consentState) {
2831
- validateIabConsentCategory(categoryName);
2832
- validateRawConsentState(consentState);
2833
- const { gdpr, ccpa, activeLegislation } = consentState;
349
+ function checkConsentFor(categoryName, { purpose, vendor, specialFeatureOptins }) {
2834
350
  const customCategory = iabCustomCategories[categoryName];
2835
- if (activeLegislation === legislation.CCPA) {
2836
- const userHasNotOptedOut = (ccpa == null ? void 0 : ccpa[2]) === "N";
2837
- return userHasNotOptedOut;
2838
- }
2839
- const decodedGdprConsent = TCString.decode(gdpr);
2840
- const { purposeConsents, vendorConsents, specialFeatureOptins } = decodedGdprConsent;
2841
351
  const requiredPurposesConsented = customCategory.purposes.every(
2842
- (requiredPurpose) => purposeConsents.has(requiredPurpose)
352
+ (requiredPurpose) => (purpose == null ? void 0 : purpose.consents[requiredPurpose]) === true
2843
353
  );
2844
354
  const requiredIabVendorsConsented = customCategory.iabVendors.every(
2845
- (requiredVendor) => vendorConsents.has(requiredVendor)
355
+ (requiredVendor) => (vendor == null ? void 0 : vendor.consents[requiredVendor]) === true
2846
356
  );
2847
357
  const requiredSpecialFeaturesConsented = customCategory.specialFeatures.every(
2848
- (requiredFeature) => specialFeatureOptins.has(requiredFeature)
358
+ (requiredFeature) => (specialFeatureOptins == null ? void 0 : specialFeatureOptins[requiredFeature]) === true
2849
359
  );
2850
360
  return requiredPurposesConsented && requiredIabVendorsConsented && requiredSpecialFeaturesConsented;
2851
361
  }
2852
- function getParsedConsent(rawConsentState) {
2853
- const categoryNames = Object.keys(iabCustomCategories);
2854
- return categoryNames.reduce((parsedConsent, categoryName) => {
2855
- parsedConsent[categoryName] = checkConsentFor(categoryName, rawConsentState);
2856
- return parsedConsent;
2857
- }, {});
362
+ function parseCCPAConsent(ccpa) {
363
+ const userHasNotOptedOut = (ccpa == null ? void 0 : ccpa[2]) === "N";
364
+ const parsedConsent = {};
365
+ for (const categoryName of iabCategoryNames) {
366
+ parsedConsent[categoryName] = userHasNotOptedOut;
367
+ }
368
+ return parsedConsent;
369
+ }
370
+ async function parseGDPRConsent() {
371
+ const tcData = await new Promise((resolve, reject) => {
372
+ var _a;
373
+ try {
374
+ (_a = window.__tcfapi) == null ? void 0 : _a.call(window, "addEventListener", 2, resolve);
375
+ } catch (error) {
376
+ reject(error);
377
+ }
378
+ });
379
+ const parsedConsent = {};
380
+ for (const categoryName of iabCategoryNames) {
381
+ parsedConsent[categoryName] = checkConsentFor(categoryName, tcData);
382
+ }
383
+ return parsedConsent;
384
+ }
385
+ async function getParsedConsent(activeLegislation, consentString) {
386
+ return activeLegislation === "ccpa" ? parseCCPAConsent(consentString) : await parseGDPRConsent();
2858
387
  }
2859
388
  function getConsentCookieValue() {
2860
389
  const cookies = Object.fromEntries(
@@ -2872,14 +401,22 @@ function getConsentCookieValue() {
2872
401
  })
2873
402
  );
2874
403
  }
2875
- function hasConsentChanged(parsedConsent) {
404
+ function hasConsentChanged(parsedConsent, previousConsent) {
2876
405
  const categories = Object.keys(parsedConsent);
2877
- const previousConsent = getConsentCookieValue();
2878
406
  return categories.some((category) => {
2879
407
  const adaptedCategoryName = `${category.toLowerCase()}Onsite`;
2880
408
  return parsedConsent[category] !== previousConsent[adaptedCategoryName];
2881
409
  });
2882
410
  }
411
+ function shouldUpdateConsentStore({ userId, useConsentStore }) {
412
+ return !!userId && useConsentStore === true;
413
+ }
414
+ function getConsentEndpoint(updateConsentStore, props) {
415
+ if (updateConsentStore) {
416
+ return `${props.consentProxyHost}/__consent/consent-record/${SOURCEPOINT_FOW_SCOPE}/${props.userId}`;
417
+ }
418
+ return `${props.consentProxyHost}/__consent/consent-record-cookie?cookieDomain=${props.cookieDomain}`;
419
+ }
2883
420
  async function saveConsent(consentEndpoint, payload) {
2884
421
  try {
2885
422
  const response = await fetch(consentEndpoint, {
@@ -2898,78 +435,29 @@ async function saveConsent(consentEndpoint, payload) {
2898
435
  }
2899
436
  }
2900
437
  function consentReadyHandlerFn(props) {
2901
- const { userId, consentProxyHost, cookieDomain, formOfWordsId, useConsentStore } = props;
2902
- return async function consentReadyHandler(legislation2, _consentUUID, consentString, consentMeta) {
2903
- const activeLegislation = consentMeta.applies ? legislation2 : "gdpr";
2904
- if (activeLegislation !== legislation2 || !consentString) {
438
+ return async function consentReadyHandler(legislation, _consentUUID, consentString, consentMeta) {
439
+ const activeLegislation = consentMeta.applies ? legislation : "gdpr";
440
+ if (activeLegislation !== legislation || !consentString) {
2905
441
  return;
2906
442
  }
2907
- const parsedConsent = getParsedConsent({
2908
- activeLegislation,
2909
- gdpr: activeLegislation === "gdpr" ? consentString : null,
2910
- ccpa: activeLegislation === "ccpa" ? consentString : null
2911
- });
2912
- const consentHasChanged = hasConsentChanged(parsedConsent);
443
+ const parsedConsent = await getParsedConsent(activeLegislation, consentString);
444
+ const consentHasChanged = hasConsentChanged(parsedConsent, getConsentCookieValue());
2913
445
  if (!consentHasChanged) {
2914
446
  return;
2915
447
  }
2916
- let consentEndpoint = `${consentProxyHost}/__consent/consent-record-cookie?cookieDomain=${cookieDomain}`;
2917
- const shouldUpdateConsentStore = !!userId && useConsentStore;
2918
- if (shouldUpdateConsentStore) {
2919
- consentEndpoint = `${consentProxyHost}/__consent/consent-record/${SOURCEPOINT_FOW_SCOPE}/${userId}`;
2920
- }
2921
- const payload = getConsentPayload(parsedConsent, {
2922
- formOfWordsId,
2923
- cookieDomain,
2924
- shouldUpdateConsentStore
2925
- });
448
+ const updateConsentStore = shouldUpdateConsentStore(props);
449
+ const consentEndpoint = getConsentEndpoint(updateConsentStore, props);
450
+ const payload = getConsentPayload(parsedConsent, updateConsentStore, props);
2926
451
  await saveConsent(consentEndpoint, payload);
2927
452
  document.dispatchEvent(new CustomEvent("oCookieMessage.act", { bubbles: true }));
2928
453
  };
2929
454
  }
2930
- let getRandomValues;
2931
- const rnds8 = new Uint8Array(16);
2932
- function rng() {
2933
- if (!getRandomValues) {
2934
- getRandomValues = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
2935
- if (!getRandomValues) {
2936
- throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
2937
- }
2938
- }
2939
- return getRandomValues(rnds8);
2940
- }
2941
- const byteToHex = [];
2942
- for (let i = 0; i < 256; ++i) {
2943
- byteToHex.push((i + 256).toString(16).slice(1));
2944
- }
2945
- function unsafeStringify(arr, offset = 0) {
2946
- return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];
2947
- }
2948
- const randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
2949
- const native = {
2950
- randomUUID
2951
- };
2952
- function v4(options, buf, offset) {
2953
- if (native.randomUUID && !buf && !options) {
2954
- return native.randomUUID();
2955
- }
2956
- options = options || {};
2957
- const rnds = options.random || (options.rng || rng)();
2958
- rnds[6] = rnds[6] & 15 | 64;
2959
- rnds[8] = rnds[8] & 63 | 128;
2960
- if (buf) {
2961
- offset = offset || 0;
2962
- for (let i = 0; i < 16; ++i) {
2963
- buf[offset + i] = rnds[i];
2964
- }
2965
- return buf;
2966
- }
2967
- return unsafeStringify(rnds);
2968
- }
2969
455
  const COOKIE_MESSAGE = "cookie-message";
2970
456
  const PRIVACY_MANAGER = "manage-cookies";
2971
457
  const INITIAL_STATE = Object.freeze({
2972
- activeComponent: COOKIE_MESSAGE
458
+ activeComponent: COOKIE_MESSAGE,
459
+ messageId: 0,
460
+ privacyManagerId: 0
2973
461
  });
2974
462
  let privateState = INITIAL_STATE;
2975
463
  function isPlainObject(obj) {
@@ -2983,20 +471,17 @@ const setState = (newState) => {
2983
471
  }
2984
472
  privateState = { ...privateState, ...newState };
2985
473
  };
2986
- const ACCEPT_ALL_CHOICE = 11;
2987
- const MANAGE_PREFS_CHOICE = 12;
2988
- const REJECT_ALL_CHOICE = 13;
2989
474
  const cookieToggleFlags = ["adsDisableInternalCMP", "pwm.cmp", "messageSlotBottom"];
2990
- function initTracking(context) {
2991
- const componentId = v4();
475
+ function initTracking(context, cmpBaseEndpoint) {
2992
476
  const flags = extractRelevantFlags(context.flags);
2993
477
  window._sp_queue = window._sp_queue ?? [];
2994
478
  window._sp_queue.push(() => {
2995
- var _a2, _b2;
479
+ var _a, _b;
2996
480
  for (const [eventId, eventHandler] of Object.entries(trackingEventHandlers)) {
2997
- (_b2 = (_a2 = window._sp_).addEventListener) == null ? void 0 : _b2.call(_a2, eventId, eventHandler({ ...context, flags, componentId }));
481
+ (_b = (_a = window._sp_).addEventListener) == null ? void 0 : _b.call(_a, eventId, eventHandler({ ...context, flags }));
2998
482
  }
2999
483
  });
484
+ setupPmTracking({ ...context, flags }, cmpBaseEndpoint);
3000
485
  }
3001
486
  function extractRelevantFlags(flags) {
3002
487
  const output = {};
@@ -3023,19 +508,23 @@ function track(payload) {
3023
508
  function dispatchComponentEvent({
3024
509
  trackingProps,
3025
510
  action,
3026
- triggerAction,
3027
- messageType
511
+ triggerAction
3028
512
  }) {
513
+ let componentId;
3029
514
  const state = getState();
3030
- const { componentId, product, app, flags } = trackingProps;
515
+ const { product, app, flags } = trackingProps;
516
+ if (state.activeComponent === COOKIE_MESSAGE) {
517
+ componentId = state.messageId;
518
+ } else {
519
+ componentId = state.privacyManagerId;
520
+ }
3031
521
  const event = {
3032
522
  detail: {
3033
523
  component: {
3034
524
  id: componentId,
3035
525
  name: state.activeComponent,
3036
526
  type: "overlay",
3037
- subtype: "cmp",
3038
- componentContentId: state[messageType]
527
+ subtype: "cmp"
3039
528
  },
3040
529
  category: "component",
3041
530
  action,
@@ -3046,127 +535,87 @@ function dispatchComponentEvent({
3046
535
  {
3047
536
  cookie_toggle_flag: flags
3048
537
  }
3049
- ]
538
+ ],
539
+ url: window.document.location.href || null
3050
540
  }
3051
541
  };
3052
542
  track(event);
3053
543
  }
3054
544
  const trackingEventHandlers = {
3055
- onMessageChoiceSelect: (trackingProps) => (messageType, _choiceId, choiceTypeId) => {
3056
- if (choiceTypeId === ACCEPT_ALL_CHOICE) {
3057
- dispatchComponentEvent({
3058
- trackingProps,
3059
- action: "click",
3060
- triggerAction: "accept_all",
3061
- messageType
3062
- });
3063
- }
3064
- if (choiceTypeId === MANAGE_PREFS_CHOICE) {
3065
- dispatchComponentEvent({
3066
- trackingProps,
3067
- action: "click",
3068
- triggerAction: "manage_cookies",
3069
- messageType
3070
- });
3071
- setState({
3072
- activeComponent: PRIVACY_MANAGER
3073
- });
3074
- }
3075
- if (choiceTypeId === REJECT_ALL_CHOICE) {
545
+ onMessageChoiceSelect: (trackingProps) => (_messageType, _choiceId, choiceTypeId) => {
546
+ const choiceTypeTriggerMap = {
547
+ 11: "accept_all",
548
+ 12: "manage_cookies",
549
+ 13: "reject_all"
550
+ };
551
+ const triggerAction = choiceTypeTriggerMap[choiceTypeId];
552
+ if (triggerAction) {
3076
553
  dispatchComponentEvent({
3077
554
  trackingProps,
3078
555
  action: "click",
3079
- triggerAction: "reject_all",
3080
- messageType
556
+ triggerAction
3081
557
  });
3082
558
  }
3083
559
  },
3084
- onMessageReady: (trackingProps) => (messageType) => {
560
+ onMessageReady: (trackingProps) => () => {
3085
561
  dispatchComponentEvent({
3086
562
  trackingProps,
3087
- action: "view",
3088
- messageType
563
+ action: "view"
3089
564
  });
3090
565
  },
3091
- onPrivacyManagerAction: (trackingProps) => (messageType, pmData) => {
3092
- const { purposeConsent, vendorConsent } = pmData;
3093
- const isAcceptAll = purposeConsent === "all" && vendorConsent === "all";
3094
- const isRejectAll = purposeConsent === "none" && vendorConsent === "none";
3095
- setState({
3096
- activeComponent: PRIVACY_MANAGER
3097
- });
3098
- if (isAcceptAll) {
3099
- dispatchComponentEvent({
3100
- trackingProps,
3101
- action: "click",
3102
- triggerAction: "accept_all",
3103
- messageType
3104
- });
3105
- } else if (isRejectAll) {
3106
- dispatchComponentEvent({
3107
- trackingProps,
3108
- action: "click",
3109
- triggerAction: "reject_all",
3110
- messageType
3111
- });
3112
- } else {
3113
- dispatchComponentEvent({
3114
- trackingProps,
3115
- action: "click",
3116
- triggerAction: "save_and_close",
3117
- messageType
566
+ onMessageReceiveData: () => (_messageType, data) => {
567
+ const { messageId } = data;
568
+ if (messageId) {
569
+ setState({
570
+ messageId
3118
571
  });
3119
572
  }
3120
573
  },
3121
- onMessageReceiveData: () => (messageType, data) => {
3122
- const { messageId } = data;
3123
- setState({
3124
- [messageType]: messageId
3125
- });
3126
- },
3127
- onError: (trackingProps) => (messageType, errorCode) => {
574
+ onError: (trackingProps) => (_messageType, errorCode) => {
3128
575
  dispatchComponentEvent({
3129
576
  trackingProps,
3130
577
  action: "error",
3131
- triggerAction: errorCode,
3132
- messageType
578
+ triggerAction: errorCode
579
+ });
580
+ },
581
+ onPMCancel: () => () => {
582
+ setState({
583
+ activeComponent: COOKIE_MESSAGE
3133
584
  });
3134
585
  }
3135
586
  };
3136
- function getCookie(name) {
3137
- var _a2, _b2;
3138
- const value = `; ${document.cookie}`;
3139
- const parts = value.split(`; ${name}=`);
3140
- if (parts.length === 2)
3141
- return (_b2 = (_a2 = parts.pop()) == null ? void 0 : _a2.split(";")) == null ? void 0 : _b2.shift();
3142
- }
3143
- function enableNonEssentialCookiesOption() {
3144
- window._sp_queue ?? (window._sp_queue = []);
3145
- window._sp_queue.push(() => {
3146
- var _a2, _b2;
3147
- (_b2 = (_a2 = window._sp_) == null ? void 0 : _a2.addEventListener) == null ? void 0 : _b2.call(
3148
- _a2,
3149
- "onMessageChoiceSelect",
3150
- (_messageType, _choiceId, choiceTypeId) => {
3151
- if (choiceTypeId === 9) {
3152
- document.cookie = "sp_cw=dismissed; expires=Thu, 18 Dec 2023 12:00:00 UTC";
3153
- }
3154
- }
3155
- );
3156
- });
3157
- window._sp_queue.push(() => {
3158
- var _a2, _b2;
3159
- (_b2 = (_a2 = window._sp_) == null ? void 0 : _a2.addEventListener) == null ? void 0 : _b2.call(
3160
- _a2,
3161
- "onPrivacyManagerAction",
3162
- (_messageType, pmData) => {
3163
- if (pmData.purposeConsent == "none" && pmData.vendorConsent == "none") {
3164
- document.cookie = "sp_cw=dismissed; expires=Thu, 18 Dec 2023 12:00:00 UTC";
3165
- }
587
+ function setupPmTracking(trackingProps, cmpBaseEndpoint) {
588
+ window.addEventListener(
589
+ "message",
590
+ function(event) {
591
+ if (event.origin !== cmpBaseEndpoint)
592
+ return;
593
+ const actionTypeMap = {
594
+ 1: "save_and_close",
595
+ 11: "accept_all",
596
+ 13: "reject_all"
597
+ };
598
+ const { data: { fromPM, actionType, messageId = "0" } = {} } = event;
599
+ if (!fromPM)
600
+ return;
601
+ if (+messageId) {
602
+ setState({
603
+ activeComponent: PRIVACY_MANAGER,
604
+ privacyManagerId: +messageId
605
+ });
3166
606
  }
3167
- );
3168
- });
607
+ if (!actionType || !actionTypeMap[actionType])
608
+ return;
609
+ dispatchComponentEvent({
610
+ trackingProps,
611
+ action: "click",
612
+ triggerAction: actionTypeMap[actionType]
613
+ });
614
+ },
615
+ false
616
+ );
3169
617
  }
618
+ const version = "3.3.0-beta.4";
3170
619
  async function initSourcepointCmp({
3171
620
  propertyConfig = FT_DOTCOM_PROD,
3172
621
  userId,
@@ -3177,6 +626,11 @@ async function initSourcepointCmp({
3177
626
  useConsentStore = true,
3178
627
  trackingContext = {}
3179
628
  } = {}) {
629
+ if (typeof window === "undefined") {
630
+ console.error("The CMP client can only be initialised in a browser context");
631
+ return;
632
+ }
633
+ window.FT_CMP_CLIENT_VERSION = version;
3180
634
  if (!userId && useFTSession) {
3181
635
  try {
3182
636
  const response = await getUuid();
@@ -3197,19 +651,11 @@ async function initSourcepointCmp({
3197
651
  );
3198
652
  delete propertyConfig.events;
3199
653
  }
3200
- propertyConfig = {
3201
- ...propertyConfig,
3202
- gdpr: {
3203
- targetingParams: {
3204
- cookiew: getCookie("cw")
3205
- }
3206
- }
3207
- };
3208
654
  bootstrapCmp(propertyConfig);
3209
655
  window._sp_queue.push(() => {
3210
- var _a2, _b2;
3211
- (_b2 = (_a2 = window._sp_) == null ? void 0 : _a2.addEventListener) == null ? void 0 : _b2.call(
3212
- _a2,
656
+ var _a, _b;
657
+ (_b = (_a = window._sp_) == null ? void 0 : _a.addEventListener) == null ? void 0 : _b.call(
658
+ _a,
3213
659
  "onConsentReady",
3214
660
  consentReadyHandlerFn({
3215
661
  userId,
@@ -3220,10 +666,8 @@ async function initSourcepointCmp({
3220
666
  })
3221
667
  );
3222
668
  });
3223
- enableNonEssentialCookiesOption();
3224
- initTracking(trackingContext);
669
+ initTracking(trackingContext, propertyConfig.baseEndpoint);
3225
670
  }
3226
- window.FT_CMP_CLIENT_VERSION = version;
3227
671
  export {
3228
672
  debug,
3229
673
  initSourcepointCmp,