@financial-times/cmp-client 0.0.0-beta.1

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