@consent-kit/schema 0.0.0-stage → 0.1.0

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.
package/dist/index.js ADDED
@@ -0,0 +1,2862 @@
1
+ import { Ajv } from 'ajv';
2
+ import { LineCounter, parseDocument, isNode } from 'yaml';
3
+
4
+ // src/errors.ts
5
+ var RULES = {
6
+ "yaml/syntax": "The file is not well-formed YAML.",
7
+ "schema/type": "A value has the wrong JSON type.",
8
+ "schema/required": "A required field is missing.",
9
+ "schema/unknown-property": "A field is not part of the registry format.",
10
+ "schema/enum": "A value is not one of the allowed options.",
11
+ "schema/format": "A value does not have the expected shape.",
12
+ "schema/id-format": "An id is not lowercase kebab/snake case.",
13
+ "schema/exactly-one-of": "Exactly one of two alternative fields must be set.",
14
+ "id/duplicate": "Two entries of the same kind share an id.",
15
+ "collection-point/duplicate-field": "A collection point declares the same field name twice.",
16
+ "artefact/no-purpose": "An artefact is not bound to any purpose.",
17
+ "artefact/unknown-purpose": "An artefact references a purpose that is not declared.",
18
+ "artefact/unknown-processor": "An artefact references a processor that is not declared.",
19
+ "artefact/third-party-without-processor": "A third-party artefact has no processor.",
20
+ "artefact/invalid-pattern": "A `pattern` is not a valid regular expression.",
21
+ "artefact/unsupported-url": "An artefact URL is not an http(s) URL or a site-relative path, or is written in a way browsers read differently.",
22
+ "artefact/consent-not-enforceable": "A stylesheet, font or media file is bound to a consent purpose, which nothing can enforce.",
23
+ "script/multiple-consent-purposes": "A script is bound to more than one consent purpose.",
24
+ "cookie/invalid-duration": 'A cookie duration is not "session" or "<n>d".',
25
+ "storage/invalid-duration": 'A storage duration is not "persistent" or "<n>d".',
26
+ "controller/dpo-not-stated": "The controller neither names a data protection officer nor states that there is none.",
27
+ "controller/missing-supervisory-authority": "The controller names no supervisory authority.",
28
+ "collection-field/no-purpose": "A collection-point field has no purpose.",
29
+ "collection-field/unknown-purpose": "A collection-point field references a purpose that is not declared.",
30
+ "collection-field/missing-provision": "A collection-point field does not say whether providing it is statutory, contractual or voluntary.",
31
+ "collection-field/missing-consequence": "A statutory or contractual field does not say what happens when it is not provided.",
32
+ "purpose/consent-default-not-denied": 'A consent purpose defaults to anything other than "denied".',
33
+ "purpose/default-on-non-consent": "`default` is set on a purpose whose basis is not consent.",
34
+ "purpose/invalid-retention": "A retention value is not one of the supported forms.",
35
+ "purpose/reserved-id": "A purpose uses an id the banner reserves for itself.",
36
+ "purpose/vague-text": "A consent purpose is described only by a stock vague phrase.",
37
+ "purpose/missing-legitimate-interest": "A purpose based on legitimate interests does not state the interest.",
38
+ "purpose/legitimate-interest-on-other-basis": "`legitimateInterest` is set on a purpose whose basis is not legitimate_interest.",
39
+ "purpose/adm-not-stated": "A purpose does not state whether automated decision-making takes place.",
40
+ "purpose/missing-data-subjects": "A purpose names no category of data subjects.",
41
+ "purpose/unknown-processor": "A purpose references a processor that is not declared.",
42
+ "purpose/unknown-data-category": "A purpose uses a data category that the `dataCategories` map does not declare.",
43
+ "purpose/unknown-data-subject": "A purpose uses a data subject category that the `dataSubjectCategories` map does not declare.",
44
+ "purpose/unknown-retention-event": "A retention refers to an event that the `retentionEvents` map does not declare.",
45
+ "processor/missing-transfer-mechanism": "A processor outside the EU/EEA has no transfer mechanism.",
46
+ "processor/unreferenced": "A processor is used by no artefact and listed by no purpose.",
47
+ "csp/unknown-directive": "A `csp.allow` entry names a directive consent-kit does not generate.",
48
+ "csp/invalid-source": "A `csp.allow` source is not a well-formed CSP source expression.",
49
+ "csp/redundant-source": "A `csp.allow` source is `'none'` or repeats what another entry already allows.",
50
+ "csp/invalid-report-uri": "`csp.reportUri` is not an http(s) URL or a site-relative path, or is written in a way browsers read differently.",
51
+ "csp/undeclared-report-endpoint": "`csp.reportUri` points at a third party that no endpoint artefact declares.",
52
+ "receipts/not-stated": "A purpose is based on consent, but the registry does not say where consent receipts go or that it keeps none.",
53
+ "receipts/invalid-endpoint": "`receipts.endpoint` is not an https URL or a site-relative path, or is written in a way browsers read differently.",
54
+ "receipts/undeclared-endpoint": "`receipts.endpoint` points at a third party that no endpoint artefact declares.",
55
+ "receipts/endpoint-needs-consent": "The endpoint artefact that declares `receipts.endpoint` is bound to a consent purpose, so a rejection could not be recorded.",
56
+ "receipts/vague-reason": "The reason given for `receipts.optOut` is a stock phrase that says nothing.",
57
+ "subject-requests/endpoint-not-same-origin": "`subjectRequests.endpoint` is not a site-relative path, so the browser would not send the consent cookie with a request.",
58
+ "subject-requests/unknown-type": "`subjectRequests.types` lists a request type consent-kit does not know.",
59
+ "subject-requests/retention-format": '`subjectRequests.retention` is not a number of days or years ("<n>d" or "<n>y").',
60
+ "subject-requests/unknown-processor": "`subjectRequests.requesterEmail.processor` is not a declared processor.",
61
+ "subject-requests/invalid-notify": "`subjectRequests.notify` is not an email address.",
62
+ "subject-requests/purpose-id-taken": "A purpose uses the id of the built-in purpose that `subjectRequests` adds.",
63
+ "locale/default-not-declared": "`defaultLocale` is not listed in `locales`.",
64
+ "locale/missing-text": "A localized text lacks a declared locale.",
65
+ "locale/undeclared-text": "A localized text uses a locale that is not declared.",
66
+ "preset/unresolved": "The registry uses presets but no preset catalogue was given to the validator.",
67
+ "preset/unknown": "A `presets` entry names a preset or a version the catalogue does not have.",
68
+ "preset/purpose": "A preset purpose slot is unmapped, unknown, or mapped to an undeclared purpose.",
69
+ "preset/parameter": "A preset parameter is missing, unknown or of the wrong shape.",
70
+ "preset/id-collision": "An id a preset expands to is already used by another entry.",
71
+ "preset/override": "An `ids`, `exclude` or `overrides` entry does not match the preset."
72
+ };
73
+
74
+ // src/formats.ts
75
+ var ID_PATTERN = /^[a-z][a-z0-9_-]*$/;
76
+ var LOCALE_PATTERN = /^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;
77
+ var COUNTRY_PATTERN = /^[A-Z]{2}$/;
78
+ var RETENTION_PATTERN = /^(session|until-withdrawn|[1-9][0-9]*[dy](-after-[a-z][a-z0-9_-]*)?)$/;
79
+ var SUBJECT_REQUEST_RETENTION_PATTERN = /^[1-9][0-9]*[dy]$/;
80
+ var EMAIL_PATTERN = /^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)+$/;
81
+ var MAX_EMAIL_LENGTH = 254;
82
+ var COOKIE_DURATION_PATTERN = /^(session|[1-9][0-9]*d)$/;
83
+ var STORAGE_DURATION_PATTERN = /^(persistent|[1-9][0-9]*d)$/;
84
+ var CSP_DIRECTIVES = [
85
+ "default-src",
86
+ "script-src",
87
+ "style-src",
88
+ "font-src",
89
+ "img-src",
90
+ "connect-src",
91
+ "frame-src",
92
+ "media-src",
93
+ "worker-src",
94
+ "manifest-src",
95
+ "object-src",
96
+ "base-uri",
97
+ "form-action",
98
+ "frame-ancestors"
99
+ ];
100
+ var CSP_KEYWORDS = /* @__PURE__ */ new Set([
101
+ "'self'",
102
+ "'unsafe-inline'",
103
+ "'unsafe-eval'",
104
+ "'unsafe-hashes'",
105
+ "'wasm-unsafe-eval'",
106
+ "'strict-dynamic'",
107
+ "'report-sample'"
108
+ ]);
109
+ var CSP_HASH = /^'sha(256|384|512)-[A-Za-z0-9+/_-]+={0,2}'$/;
110
+ var CSP_NONCE = /^'nonce-[A-Za-z0-9+/_{}.-]+={0,2}'$/;
111
+ var CSP_SCHEME = /^[a-z][a-z0-9+.-]*:$/;
112
+ var CSP_HOST = /^([a-z][a-z0-9+.-]*:\/\/)?(\*|(\*\.)?[a-z0-9-]+(\.[a-z0-9-]+)*)(:([0-9]+|\*))?(\/[A-Za-z0-9._~!$&'()*+=:@%/-]*)?$/;
113
+ function isCspSource(value) {
114
+ if (/[\s;,]/.test(value) || value === "") return false;
115
+ if (value.startsWith("'")) return CSP_KEYWORDS.has(value) || CSP_HASH.test(value) || CSP_NONCE.test(value);
116
+ if (CSP_KEYWORDS.has(`'${value}'`) || value === "none" || /^(nonce|sha(256|384|512))-/.test(value)) return false;
117
+ return CSP_SCHEME.test(value) || CSP_HOST.test(value);
118
+ }
119
+ var EEA_COUNTRIES = /* @__PURE__ */ new Set([
120
+ "AT",
121
+ "BE",
122
+ "BG",
123
+ "HR",
124
+ "CY",
125
+ "CZ",
126
+ "DK",
127
+ "EE",
128
+ "FI",
129
+ "FR",
130
+ "DE",
131
+ "GR",
132
+ "HU",
133
+ "IE",
134
+ "IT",
135
+ "LV",
136
+ "LT",
137
+ "LU",
138
+ "MT",
139
+ "NL",
140
+ "PL",
141
+ "PT",
142
+ "RO",
143
+ "SK",
144
+ "SI",
145
+ "ES",
146
+ "SE",
147
+ "IS",
148
+ "LI",
149
+ "NO"
150
+ ]);
151
+ var SITE_PLACEHOLDER = "https://consent-kit-site.invalid";
152
+ function locateUrl(value) {
153
+ if (/[\\\x00-\x20\x7f]/.test(value)) {
154
+ return { where: "invalid", problem: "it contains a backslash, whitespace or a control character, which browsers rewrite or strip, so it does not point where it appears to" };
155
+ }
156
+ let url;
157
+ try {
158
+ url = new URL(value, SITE_PLACEHOLDER);
159
+ } catch {
160
+ return { where: "invalid", problem: "it is not a valid URL" };
161
+ }
162
+ if (url.origin !== SITE_PLACEHOLDER) return { where: "remote", url };
163
+ if (value.startsWith("/")) return { where: "site", pathname: url.pathname };
164
+ if (/^[a-z][a-z0-9+.-]*:/i.test(value)) return { where: "remote", url };
165
+ return { where: "invalid", problem: 'it is neither an absolute URL nor a site-relative path starting with "/"' };
166
+ }
167
+ function isAbsoluteUrl(value) {
168
+ const location = locateUrl(value);
169
+ return location.where === "remote" && /^https?:$/.test(location.url.protocol);
170
+ }
171
+ function pathCovers(declaredPath, targetPath) {
172
+ if (targetPath === declaredPath) return true;
173
+ if (declaredPath.endsWith("/")) return targetPath.startsWith(declaredPath);
174
+ return targetPath.startsWith(`${declaredPath}/`);
175
+ }
176
+
177
+ // src/subject-requests.ts
178
+ var SUBJECT_REQUEST_TYPES = ["access", "erasure"];
179
+ var SUBJECT_REQUESTS_PURPOSE_ID = "subject-requests";
180
+ var SUBJECT_REQUEST_CLOSED_EVENT = "subject-request-closed";
181
+ var SUBJECT_REQUEST_DATA_CATEGORIES = ["requester_email", "request_details"];
182
+ var SUBJECT_REQUEST_DATA_SUBJECT = "requesters";
183
+ function subjectRequestPurpose(registry) {
184
+ const section = registry.subjectRequests;
185
+ if (section === void 0) return void 0;
186
+ return {
187
+ id: SUBJECT_REQUESTS_PURPOSE_ID,
188
+ version: 1,
189
+ basis: "legal_obligation",
190
+ dataCategories: [...SUBJECT_REQUEST_DATA_CATEGORIES],
191
+ retention: `${section.retention}-after-${SUBJECT_REQUEST_CLOSED_EVENT}`,
192
+ automatedDecisionMaking: false,
193
+ dataSubjects: [SUBJECT_REQUEST_DATA_SUBJECT],
194
+ processors: section.requesterEmail === void 0 ? [] : [section.requesterEmail.processor]
195
+ };
196
+ }
197
+
198
+ // src/schema.ts
199
+ var id = { type: "string", pattern: ID_PATTERN.source };
200
+ var nonEmptyString = { type: "string", minLength: 1 };
201
+ var locale = { type: "string", pattern: LOCALE_PATTERN.source };
202
+ var ref = (name) => ({ $ref: `#/definitions/${name}` });
203
+ var ARTEFACT_KINDS = ["script", "cookie", "storage", "iframe", "pixel", "endpoint", "stylesheet", "font", "media"];
204
+ function artefact(kind, required, properties, extra = {}) {
205
+ return {
206
+ type: "object",
207
+ additionalProperties: false,
208
+ required: ["id", "kind", "purposes", ...required],
209
+ properties: {
210
+ id,
211
+ kind: { const: kind },
212
+ purposes: {
213
+ description: "Purpose ids. At least one.",
214
+ type: "array",
215
+ minItems: 1,
216
+ uniqueItems: true,
217
+ items: id
218
+ },
219
+ processor: { ...id, description: "Processor id. Required for anything third-party." },
220
+ description: ref("localizedText"),
221
+ ...properties
222
+ },
223
+ ...extra
224
+ };
225
+ }
226
+ var exactlyOneOf = (a, b) => ({ oneOf: [{ required: [a] }, { required: [b] }] });
227
+ var registrySchema = {
228
+ $schema: "http://json-schema.org/draft-07/schema#",
229
+ title: "consent-kit privacy registry",
230
+ type: "object",
231
+ additionalProperties: false,
232
+ required: [
233
+ "version",
234
+ "controller",
235
+ "locales",
236
+ "defaultLocale",
237
+ "purposes",
238
+ "processors",
239
+ "artefacts",
240
+ "collectionPoints"
241
+ ],
242
+ properties: {
243
+ version: { description: "Registry file format version.", const: 1 },
244
+ controller: ref("controller"),
245
+ locales: { type: "array", minItems: 1, uniqueItems: true, items: locale },
246
+ defaultLocale: locale,
247
+ purposes: { type: "array", items: ref("purpose") },
248
+ processors: { type: "array", items: ref("processor") },
249
+ artefacts: { type: "array", items: ref("artefact") },
250
+ collectionPoints: { type: "array", items: ref("collectionPoint") },
251
+ dataCategories: {
252
+ description: "Data category id to its name. Once present, purposes may only use ids declared here.",
253
+ type: "object",
254
+ propertyNames: { pattern: ID_PATTERN.source },
255
+ additionalProperties: ref("dataCategory")
256
+ },
257
+ dataSubjectCategories: {
258
+ description: "Data subject category id to its name. Once present, purposes may only use ids declared here.",
259
+ type: "object",
260
+ propertyNames: { pattern: ID_PATTERN.source },
261
+ additionalProperties: ref("dataSubjectCategory")
262
+ },
263
+ retentionEvents: {
264
+ description: 'Retention event id to what happens, worded to follow "after". Once present, retentions may only use events declared here.',
265
+ type: "object",
266
+ propertyNames: { pattern: ID_PATTERN.source },
267
+ additionalProperties: ref("localizedText")
268
+ },
269
+ securityMeasures: {
270
+ ...ref("localizedText"),
271
+ description: "General description of the technical and organisational security measures (Art. 30(1)(g) GDPR)."
272
+ },
273
+ csp: ref("csp"),
274
+ receipts: ref("receipts"),
275
+ subjectRequests: ref("subjectRequests"),
276
+ presets: {
277
+ description: "Adopted provider presets. Each expands into a processor and its artefacts.",
278
+ type: "array",
279
+ items: ref("presetUse")
280
+ }
281
+ },
282
+ definitions: {
283
+ localizedText: {
284
+ description: "One string per locale declared in `locales`.",
285
+ type: "object",
286
+ minProperties: 1,
287
+ propertyNames: { pattern: LOCALE_PATTERN.source },
288
+ additionalProperties: nonEmptyString
289
+ },
290
+ controller: {
291
+ type: "object",
292
+ additionalProperties: false,
293
+ required: ["name", "contact"],
294
+ properties: {
295
+ name: nonEmptyString,
296
+ contact: nonEmptyString,
297
+ address: nonEmptyString,
298
+ dpo: {
299
+ description: "The data protection officer, or false: none is designated. One of the two is required.",
300
+ oneOf: [
301
+ { const: false },
302
+ {
303
+ type: "object",
304
+ additionalProperties: false,
305
+ required: ["contact"],
306
+ properties: { name: nonEmptyString, contact: nonEmptyString }
307
+ }
308
+ ]
309
+ },
310
+ supervisoryAuthority: {
311
+ description: "The supervisory authority complaints go to. Required.",
312
+ type: "object",
313
+ additionalProperties: false,
314
+ required: ["name"],
315
+ properties: { name: nonEmptyString, url: nonEmptyString, address: nonEmptyString }
316
+ },
317
+ euRepresentative: {
318
+ description: "Representative in the Union (Art. 27 GDPR), for controllers not established there.",
319
+ type: "object",
320
+ additionalProperties: false,
321
+ required: ["name", "contact"],
322
+ properties: { name: nonEmptyString, contact: nonEmptyString, address: nonEmptyString }
323
+ }
324
+ }
325
+ },
326
+ dataCategory: {
327
+ type: "object",
328
+ additionalProperties: false,
329
+ required: ["title"],
330
+ properties: {
331
+ title: ref("localizedText"),
332
+ special: { description: "True for a special category of personal data (Art. 9 GDPR).", type: "boolean" }
333
+ }
334
+ },
335
+ dataSubjectCategory: {
336
+ type: "object",
337
+ additionalProperties: false,
338
+ required: ["title"],
339
+ properties: { title: ref("localizedText") }
340
+ },
341
+ purpose: {
342
+ type: "object",
343
+ additionalProperties: false,
344
+ required: ["id", "version", "basis", "title", "description", "dataCategories", "retention"],
345
+ properties: {
346
+ id,
347
+ version: {
348
+ description: "Bumped on every material change to this purpose. Starts at 1.",
349
+ type: "integer",
350
+ minimum: 1
351
+ },
352
+ basis: {
353
+ enum: [
354
+ "consent",
355
+ "contract",
356
+ "legal_obligation",
357
+ "legitimate_interest",
358
+ "vital_interests",
359
+ "public_task"
360
+ ]
361
+ },
362
+ title: ref("localizedText"),
363
+ description: ref("localizedText"),
364
+ dataCategories: { type: "array", uniqueItems: true, items: nonEmptyString },
365
+ retention: {
366
+ description: '"session", "until-withdrawn", "<n>d", "<n>y", "<n>d-after-<event>" or "<n>y-after-<event>".',
367
+ type: "string",
368
+ pattern: RETENTION_PATTERN.source
369
+ },
370
+ default: {
371
+ description: 'Only for basis "consent", where it must be "denied" (or omitted).',
372
+ enum: ["denied", "granted"]
373
+ },
374
+ legitimateInterest: {
375
+ ...ref("localizedText"),
376
+ description: 'The interest pursued. Required when basis is "legitimate_interest", and only allowed there.'
377
+ },
378
+ automatedDecisionMaking: {
379
+ description: "Required: false (no automated decision-making or profiling, Art. 22 GDPR), or its logic and consequences.",
380
+ oneOf: [
381
+ { const: false },
382
+ {
383
+ type: "object",
384
+ additionalProperties: false,
385
+ required: ["logic", "consequences"],
386
+ properties: { logic: ref("localizedText"), consequences: ref("localizedText") }
387
+ }
388
+ ]
389
+ },
390
+ dataSubjects: {
391
+ description: 'Required: ids of the categories of data subjects, e.g. "visitors". At least one.',
392
+ type: "array",
393
+ minItems: 1,
394
+ uniqueItems: true,
395
+ items: id
396
+ },
397
+ processors: {
398
+ description: "Processor ids that receive this purpose's data without an artefact. [] states that there are none.",
399
+ type: "array",
400
+ uniqueItems: true,
401
+ items: id
402
+ }
403
+ }
404
+ },
405
+ processor: {
406
+ type: "object",
407
+ additionalProperties: false,
408
+ required: ["id", "name", "country"],
409
+ properties: {
410
+ id,
411
+ name: nonEmptyString,
412
+ role: {
413
+ description: 'Default: "processor".',
414
+ enum: ["processor", "independent_controller", "joint_controller"]
415
+ },
416
+ legalEntity: nonEmptyString,
417
+ country: {
418
+ description: "ISO 3166-1 alpha-2 country code.",
419
+ type: "string",
420
+ pattern: COUNTRY_PATTERN.source
421
+ },
422
+ firstParty: { type: "boolean" },
423
+ transferMechanism: {
424
+ description: "Required when `country` is outside the EU/EEA.",
425
+ enum: ["adequacy", "scc", "dpf", "bcr"]
426
+ },
427
+ dpaUrl: nonEmptyString,
428
+ privacyUrl: nonEmptyString,
429
+ subjectRequestProcess: nonEmptyString
430
+ }
431
+ },
432
+ artefact: {
433
+ type: "object",
434
+ required: ["kind"],
435
+ properties: { kind: { enum: [...ARTEFACT_KINDS] } },
436
+ allOf: ARTEFACT_KINDS.map((kind) => ({
437
+ if: { properties: { kind: { const: kind } }, required: ["kind"] },
438
+ then: ref(`${kind}Artefact`)
439
+ }))
440
+ },
441
+ scriptArtefact: artefact("script", ["src"], {
442
+ src: { ...nonEmptyString, description: "Absolute URL, or a site-relative path." }
443
+ }),
444
+ cookieArtefact: artefact(
445
+ "cookie",
446
+ ["duration"],
447
+ {
448
+ name: nonEmptyString,
449
+ pattern: { ...nonEmptyString, description: 'RegExp source, e.g. "^_ga_".' },
450
+ duration: {
451
+ description: '"session" or a duration such as "365d".',
452
+ type: "string",
453
+ pattern: COOKIE_DURATION_PATTERN.source
454
+ },
455
+ domain: nonEmptyString,
456
+ sameSite: { enum: ["Strict", "Lax", "None"] },
457
+ secure: { type: "boolean" },
458
+ httpOnly: { type: "boolean" }
459
+ },
460
+ exactlyOneOf("name", "pattern")
461
+ ),
462
+ storageArtefact: artefact(
463
+ "storage",
464
+ ["area"],
465
+ {
466
+ area: { enum: ["local", "session", "indexeddb"] },
467
+ key: { ...nonEmptyString, description: "For indexeddb: the database name." },
468
+ pattern: { ...nonEmptyString, description: "RegExp source." },
469
+ duration: {
470
+ description: '"persistent" or a duration such as "30d".',
471
+ type: "string",
472
+ pattern: STORAGE_DURATION_PATTERN.source
473
+ }
474
+ },
475
+ exactlyOneOf("key", "pattern")
476
+ ),
477
+ iframeArtefact: artefact("iframe", ["src"], {
478
+ src: { ...nonEmptyString, description: "Origin or URL prefix the embed loads from." }
479
+ }),
480
+ pixelArtefact: artefact("pixel", ["url"], { url: nonEmptyString }),
481
+ endpointArtefact: artefact("endpoint", ["url"], {
482
+ url: { ...nonEmptyString, description: "Origin or URL prefix first-party code sends data to." }
483
+ }),
484
+ stylesheetArtefact: artefact("stylesheet", ["src"], {
485
+ src: { ...nonEmptyString, description: "Absolute URL of the stylesheet, or an origin or URL prefix." }
486
+ }),
487
+ fontArtefact: artefact("font", ["src"], {
488
+ src: { ...nonEmptyString, description: "Absolute URL of the font file, or an origin or URL prefix." }
489
+ }),
490
+ mediaArtefact: artefact("media", ["src"], {
491
+ src: { ...nonEmptyString, description: "Absolute URL of the audio or video file, or an origin or URL prefix." }
492
+ }),
493
+ csp: {
494
+ description: "Deviations from the strict Content-Security-Policy that consent-kit generates. Absent: strict and enforced.",
495
+ type: "object",
496
+ additionalProperties: false,
497
+ properties: {
498
+ allow: {
499
+ description: "Additional sources per directive, each with a reason.",
500
+ type: "array",
501
+ items: {
502
+ type: "object",
503
+ additionalProperties: false,
504
+ required: ["directive", "sources", "reason"],
505
+ properties: {
506
+ directive: { description: `One of: ${CSP_DIRECTIVES.join(", ")}.`, type: "string" },
507
+ sources: {
508
+ description: `Source expressions as written in the header, e.g. "'unsafe-inline'", "data:", "https://cdn.example".`,
509
+ type: "array",
510
+ minItems: 1,
511
+ uniqueItems: true,
512
+ items: nonEmptyString
513
+ },
514
+ reason: { ...nonEmptyString, description: "Why the site needs it." }
515
+ }
516
+ }
517
+ },
518
+ reportOnly: { description: "Emit Content-Security-Policy-Report-Only: nothing is blocked.", type: "boolean" },
519
+ reportUri: { ...nonEmptyString, description: "report-uri. A third-party URL must be a declared endpoint artefact." },
520
+ reportTo: { description: "report-to group name.", type: "string", pattern: "^[A-Za-z0-9_-]+$" },
521
+ upgradeInsecureRequests: { description: "false leaves out upgrade-insecure-requests.", type: "boolean" }
522
+ }
523
+ },
524
+ receipts: {
525
+ description: "Where proof of each consent decision goes: an endpoint, or an opt-out with a reason. Required once a purpose is based on consent.",
526
+ type: "object",
527
+ additionalProperties: false,
528
+ properties: {
529
+ endpoint: {
530
+ ...nonEmptyString,
531
+ description: "Site-relative path or https URL that receives one JSON receipt per decision. A third-party URL must be a declared endpoint artefact."
532
+ },
533
+ optOut: {
534
+ description: "No receipts are sent. Reported by consent-kit check and the audit.",
535
+ type: "object",
536
+ additionalProperties: false,
537
+ required: ["reason"],
538
+ properties: { reason: { ...nonEmptyString, description: "Why this site keeps no receipts." } }
539
+ }
540
+ },
541
+ ...exactlyOneOf("endpoint", "optOut")
542
+ },
543
+ subjectRequests: {
544
+ description: 'Receiving data subject requests through a form on the site. consent-kit receives, records, notifies and reminds; a person answers. Adds the built-in purpose "subject-requests".',
545
+ type: "object",
546
+ additionalProperties: false,
547
+ required: ["endpoint", "notify", "types", "retention"],
548
+ properties: {
549
+ endpoint: { ...nonEmptyString, description: 'Site-relative path the form posts to, e.g. "/privacy/requests". Never another origin.' },
550
+ notify: { ...nonEmptyString, description: 'The mailbox every request is emailed to, e.g. "privacy@example.com".' },
551
+ types: {
552
+ description: `Which requests the form offers: ${SUBJECT_REQUEST_TYPES.join(", ")}.`,
553
+ type: "array",
554
+ minItems: 1,
555
+ uniqueItems: true,
556
+ items: nonEmptyString
557
+ },
558
+ retention: { ...nonEmptyString, description: 'How long a closed request is kept: "<n>d" or "<n>y". Required, no default.' },
559
+ requesterEmail: {
560
+ description: "Email the requester a confirmation link through this declared processor. Optional.",
561
+ type: "object",
562
+ additionalProperties: false,
563
+ required: ["processor"],
564
+ properties: { processor: { ...id, description: "Processor id of the email provider." } }
565
+ }
566
+ }
567
+ },
568
+ collectionPoint: {
569
+ type: "object",
570
+ additionalProperties: false,
571
+ required: ["id", "fields"],
572
+ properties: {
573
+ id,
574
+ title: ref("localizedText"),
575
+ description: { ...nonEmptyString, description: "Internal note; never printed in a document." },
576
+ fields: { type: "array", items: ref("collectionField") }
577
+ }
578
+ },
579
+ presetUse: {
580
+ type: "object",
581
+ additionalProperties: false,
582
+ required: ["use", "version"],
583
+ properties: {
584
+ use: { ...id, description: 'Preset id in the catalogue, e.g. "plausible".' },
585
+ version: {
586
+ description: 'A major version (1) or an exact version ("1.0.2").',
587
+ type: ["integer", "string"]
588
+ },
589
+ purpose: { ...id, description: "Purpose id, for presets with exactly one purpose slot." },
590
+ purposes: {
591
+ description: "Preset purpose slot to project purpose id.",
592
+ type: "object",
593
+ additionalProperties: id
594
+ },
595
+ with: {
596
+ description: "Values for the preset's parameters.",
597
+ type: "object",
598
+ additionalProperties: { type: ["string", "number", "boolean"] }
599
+ },
600
+ ids: {
601
+ description: "Renames: default processor or artefact id to the id this project uses.",
602
+ type: "object",
603
+ additionalProperties: id
604
+ },
605
+ exclude: {
606
+ description: "Default ids of preset artefacts this project does not use.",
607
+ type: "array",
608
+ uniqueItems: true,
609
+ items: id
610
+ },
611
+ overrides: {
612
+ description: "Local deviations from the documented defaults, by default id. Always recorded.",
613
+ type: "object",
614
+ additionalProperties: false,
615
+ properties: {
616
+ processor: { type: "object" },
617
+ artefacts: { type: "object", additionalProperties: { type: "object" } }
618
+ }
619
+ }
620
+ }
621
+ },
622
+ collectionField: {
623
+ type: "object",
624
+ additionalProperties: false,
625
+ required: ["name", "purpose"],
626
+ properties: {
627
+ name: nonEmptyString,
628
+ purpose: { ...id, description: "Purpose id this field is collected for." },
629
+ required: { type: "boolean" },
630
+ notice: ref("localizedText"),
631
+ provision: {
632
+ description: "Required: whether the data must be provided (Art. 13(2)(e) GDPR).",
633
+ enum: ["statutory", "contractual", "voluntary"]
634
+ },
635
+ consequence: {
636
+ ...ref("localizedText"),
637
+ description: 'What happens if the data is not provided. Required unless provision is "voluntary".'
638
+ }
639
+ }
640
+ }
641
+ }
642
+ };
643
+
644
+ // src/diff/duration.ts
645
+ var DURATION = /^([0-9]+)([dy])(?:-after-(.+))?$/;
646
+ function parseDuration(value) {
647
+ if (value === "session") return { form: "session" };
648
+ if (value === "until-withdrawn") return { form: "until-withdrawn" };
649
+ if (value === "persistent") return { form: "persistent" };
650
+ const match = DURATION.exec(value);
651
+ if (!match) return void 0;
652
+ const count = Number(match[1]);
653
+ if (!Number.isSafeInteger(count)) return void 0;
654
+ const event = match[3];
655
+ if (match[2] === "y") return event === void 0 ? { form: "years", years: count } : { form: "years-after-event", years: count, event };
656
+ return event === void 0 ? { form: "fixed", days: count } : { form: "after-event", days: count, event };
657
+ }
658
+ function durationEvent(parsed) {
659
+ return parsed?.form === "after-event" || parsed?.form === "years-after-event" ? parsed.event : void 0;
660
+ }
661
+ function compareDurations(before, after) {
662
+ if (before === after) return "equal";
663
+ const a = parseDuration(before);
664
+ const b = parseDuration(after);
665
+ if (!a || !b) return "incomparable";
666
+ if (a.form === "session" || b.form === "session") {
667
+ if (a.form === b.form) return "equal";
668
+ return a.form === "session" ? "longer" : "shorter";
669
+ }
670
+ if (a.form === "persistent" || b.form === "persistent") {
671
+ if (a.form === b.form) return "equal";
672
+ return a.form === "persistent" ? "shorter" : "longer";
673
+ }
674
+ if (a.form === "until-withdrawn" && b.form === "until-withdrawn") return "equal";
675
+ if (a.form === "until-withdrawn" || b.form === "until-withdrawn") return "incomparable";
676
+ if (durationEvent(a) !== durationEvent(b)) return "incomparable";
677
+ const spanA = span(a);
678
+ const spanB = span(b);
679
+ if (spanA.min === spanB.min && spanA.max === spanB.max && spanA.exact === spanB.exact) return "equal";
680
+ if (spanB.min > spanA.max) return "longer";
681
+ if (spanB.max < spanA.min) return "shorter";
682
+ return "incomparable";
683
+ }
684
+ function span(parsed) {
685
+ if (parsed.form === "fixed" || parsed.form === "after-event") return { min: parsed.days, max: parsed.days, exact: "days" };
686
+ return { min: parsed.years * 365, max: parsed.years * 366, exact: "years" };
687
+ }
688
+
689
+ // src/vague.ts
690
+ var VAGUE_PURPOSE_PHRASES = [
691
+ // English
692
+ "improving user experience",
693
+ "improving users' experience",
694
+ "improve user experience",
695
+ "better user experience",
696
+ "marketing purposes",
697
+ "marketing",
698
+ "analytics",
699
+ "analytics purposes",
700
+ "statistics",
701
+ "to improve our services",
702
+ "improving our services",
703
+ // German
704
+ "Verbesserung der Nutzererfahrung",
705
+ "Verbesserung des Nutzererlebnisses",
706
+ "Marketingzwecke",
707
+ "Marketing",
708
+ "Analyse",
709
+ "Analysezwecke",
710
+ "Statistik",
711
+ "Verbesserung unserer Dienste",
712
+ "um unsere Dienste zu verbessern"
713
+ ];
714
+ var FILLER_WORDS = /* @__PURE__ */ new Set([
715
+ // English
716
+ "we",
717
+ "use",
718
+ "uses",
719
+ "used",
720
+ "using",
721
+ "this",
722
+ "that",
723
+ "these",
724
+ "it",
725
+ "is",
726
+ "are",
727
+ "for",
728
+ "to",
729
+ "the",
730
+ "a",
731
+ "an",
732
+ "our",
733
+ "your",
734
+ "and",
735
+ "data",
736
+ "information",
737
+ "cookies",
738
+ "in",
739
+ "order",
740
+ "of",
741
+ // German
742
+ "wir",
743
+ "verwenden",
744
+ "nutzen",
745
+ "dies",
746
+ "diese",
747
+ "dieser",
748
+ "daten",
749
+ "informationen",
750
+ "f\xFCr",
751
+ "fuer",
752
+ "zu",
753
+ "zur",
754
+ "zum",
755
+ "um",
756
+ "der",
757
+ "die",
758
+ "das",
759
+ "des",
760
+ "den",
761
+ "dem",
762
+ "und",
763
+ "ihre",
764
+ "ihrer",
765
+ "unsere",
766
+ "unserer",
767
+ "unseres",
768
+ "wird",
769
+ "werden",
770
+ "verwendet",
771
+ "genutzt"
772
+ ]);
773
+ function normalise(text) {
774
+ return text.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, "").split(/\s+/).filter((word) => word !== "" && !FILLER_WORDS.has(word)).join(" ");
775
+ }
776
+ var NORMALISED_PHRASES = new Map(VAGUE_PURPOSE_PHRASES.map((phrase) => [normalise(phrase), phrase]));
777
+ function matchVaguePhrase(text) {
778
+ return NORMALISED_PHRASES.get(normalise(text));
779
+ }
780
+ var VAGUE_REASON_PHRASES = [
781
+ // English
782
+ "n/a",
783
+ "na",
784
+ "none",
785
+ "no reason",
786
+ "not needed",
787
+ "not required",
788
+ "not necessary",
789
+ "not applicable",
790
+ "unnecessary",
791
+ "todo",
792
+ "tbd",
793
+ "later",
794
+ "skip",
795
+ // German
796
+ "keine",
797
+ "kein Grund",
798
+ "nicht n\xF6tig",
799
+ "nicht notwendig",
800
+ "nicht erforderlich",
801
+ "nicht ben\xF6tigt",
802
+ "entf\xE4llt",
803
+ "sp\xE4ter"
804
+ ];
805
+ var NORMALISED_REASONS = new Map(VAGUE_REASON_PHRASES.map((phrase) => [normalise(phrase), phrase]));
806
+ function matchVagueReason(text) {
807
+ const normalised = normalise(text);
808
+ return normalised === "" ? "" : NORMALISED_REASONS.get(normalised);
809
+ }
810
+
811
+ // src/rules.ts
812
+ var RESERVED_PURPOSE_ID = "necessary";
813
+ function checkSemanticRules(registry) {
814
+ const errors = [];
815
+ const report = (rule, path, message) => errors.push({ rule, path, message });
816
+ const sections = ["purposes", "processors", "artefacts", "collectionPoints"];
817
+ for (const section of sections) {
818
+ const firstSeenAt = /* @__PURE__ */ new Map();
819
+ registry[section].forEach((entry, index) => {
820
+ const first = firstSeenAt.get(entry.id);
821
+ if (first === void 0) {
822
+ firstSeenAt.set(entry.id, index);
823
+ return;
824
+ }
825
+ report(
826
+ "id/duplicate",
827
+ `/${section}/${index}/id`,
828
+ `Id "${entry.id}" is already used by /${section}/${first}. Ids must be unique within ${section}; rename one of them.`
829
+ );
830
+ });
831
+ }
832
+ if (!registry.locales.includes(registry.defaultLocale)) {
833
+ report(
834
+ "locale/default-not-declared",
835
+ "/defaultLocale",
836
+ `defaultLocale "${registry.defaultLocale}" is not in locales [${registry.locales.join(", ")}]. Add it to locales or pick one of the declared locales.`
837
+ );
838
+ }
839
+ const checkText = (text, path) => {
840
+ if (text === void 0) return;
841
+ for (const locale2 of registry.locales) {
842
+ if (!(locale2 in text)) {
843
+ report(
844
+ "locale/missing-text",
845
+ path,
846
+ `Missing "${locale2}" text. Every localized text must cover all declared locales [${registry.locales.join(", ")}]; add a "${locale2}" entry.`
847
+ );
848
+ }
849
+ }
850
+ for (const locale2 of Object.keys(text)) {
851
+ if (!registry.locales.includes(locale2)) {
852
+ report(
853
+ "locale/undeclared-text",
854
+ `${path}/${locale2}`,
855
+ `Locale "${locale2}" is not declared. Add it to the top-level locales list or remove this text.`
856
+ );
857
+ }
858
+ }
859
+ };
860
+ const { controller } = registry;
861
+ if (controller.dpo === void 0) {
862
+ report(
863
+ "controller/dpo-not-stated",
864
+ "/controller",
865
+ 'The controller does not say whether a data protection officer is designated. Add "dpo: { contact: <email or address> }" (name optional) under controller, or "dpo: false" if none is designated.'
866
+ );
867
+ }
868
+ if (controller.supervisoryAuthority === void 0) {
869
+ report(
870
+ "controller/missing-supervisory-authority",
871
+ "/controller",
872
+ 'The controller names no supervisory authority, which the privacy policy needs for the right to lodge a complaint. Add "supervisoryAuthority: { name: <authority>, url: <its website> }" under controller.'
873
+ );
874
+ }
875
+ checkText(registry.securityMeasures, "/securityMeasures");
876
+ for (const [id2, category] of Object.entries(registry.dataCategories ?? {})) checkText(category.title, `/dataCategories/${id2}/title`);
877
+ for (const [id2, category] of Object.entries(registry.dataSubjectCategories ?? {})) checkText(category.title, `/dataSubjectCategories/${id2}/title`);
878
+ for (const [id2, text] of Object.entries(registry.retentionEvents ?? {})) checkText(text, `/retentionEvents/${id2}`);
879
+ const glossary = (map) => map === void 0 ? void 0 : new Set(Object.keys(map));
880
+ const dataCategoryIds = glossary(registry.dataCategories);
881
+ const dataSubjectIds = glossary(registry.dataSubjectCategories);
882
+ const retentionEventIds = glossary(registry.retentionEvents);
883
+ const processorIds = new Set(registry.processors.map((processor) => processor.id));
884
+ const referencedProcessors = /* @__PURE__ */ new Set();
885
+ const purposeIds = new Set(registry.purposes.map((purpose) => purpose.id));
886
+ const consentPurposeIds = new Set(
887
+ registry.purposes.filter((purpose) => purpose.basis === "consent").map((purpose) => purpose.id)
888
+ );
889
+ registry.purposes.forEach((purpose, index) => {
890
+ const path = `/purposes/${index}`;
891
+ checkText(purpose.title, `${path}/title`);
892
+ checkText(purpose.description, `${path}/description`);
893
+ if (purpose.id === RESERVED_PURPOSE_ID) {
894
+ report(
895
+ "purpose/reserved-id",
896
+ `${path}/id`,
897
+ `Purpose id "${RESERVED_PURPOSE_ID}" is reserved: the banner uses it for the always-on group that lists purposes without a toggle. Rename this purpose, e.g. to "essential".`
898
+ );
899
+ }
900
+ if (purpose.basis === "consent") {
901
+ if (purpose.default !== void 0 && purpose.default !== "denied") {
902
+ report(
903
+ "purpose/consent-default-not-denied",
904
+ `${path}/default`,
905
+ `Consent purpose "${purpose.id}" defaults to "${purpose.default}". Consent must be opt-in: set default to "denied" or remove it.`
906
+ );
907
+ }
908
+ for (const [locale2, text] of Object.entries(purpose.description)) {
909
+ const phrase = matchVaguePhrase(text);
910
+ if (phrase !== void 0) {
911
+ report(
912
+ "purpose/vague-text",
913
+ `${path}/description/${locale2}`,
914
+ `The description of consent purpose "${purpose.id}" is just the stock phrase "${phrase}", which is too vague for valid consent. Say what is done, with which data, and why.`
915
+ );
916
+ }
917
+ }
918
+ } else if (purpose.default !== void 0) {
919
+ report(
920
+ "purpose/default-on-non-consent",
921
+ `${path}/default`,
922
+ `Purpose "${purpose.id}" has basis "${purpose.basis}", which has no toggle, so default is meaningless. Remove default, or change the basis to "consent".`
923
+ );
924
+ }
925
+ checkText(purpose.legitimateInterest, `${path}/legitimateInterest`);
926
+ if (purpose.basis === "legitimate_interest" && purpose.legitimateInterest === void 0) {
927
+ report(
928
+ "purpose/missing-legitimate-interest",
929
+ path,
930
+ `Purpose "${purpose.id}" is based on legitimate interests but does not state the interest pursued (Art. 13(1)(d) GDPR). Add "legitimateInterest" with one text per locale [${registry.locales.join(", ")}], e.g. "en: Keeping the form free of automated abuse."`
931
+ );
932
+ }
933
+ if (purpose.basis !== "legitimate_interest" && purpose.legitimateInterest !== void 0) {
934
+ report(
935
+ "purpose/legitimate-interest-on-other-basis",
936
+ `${path}/legitimateInterest`,
937
+ `Purpose "${purpose.id}" has basis "${purpose.basis}" but states a legitimate interest, which no document would print. Remove legitimateInterest, or change the basis to "legitimate_interest".`
938
+ );
939
+ }
940
+ if (purpose.automatedDecisionMaking === void 0) {
941
+ report(
942
+ "purpose/adm-not-stated",
943
+ path,
944
+ `Purpose "${purpose.id}" does not say whether automated decision-making, including profiling, takes place (Art. 13(2)(f) GDPR). Add "automatedDecisionMaking: false", or "automatedDecisionMaking: { logic: {\u2026}, consequences: {\u2026} }" with one text per locale.`
945
+ );
946
+ } else if (purpose.automatedDecisionMaking !== false) {
947
+ checkText(purpose.automatedDecisionMaking.logic, `${path}/automatedDecisionMaking/logic`);
948
+ checkText(purpose.automatedDecisionMaking.consequences, `${path}/automatedDecisionMaking/consequences`);
949
+ }
950
+ if (purpose.dataSubjects === void 0) {
951
+ report(
952
+ "purpose/missing-data-subjects",
953
+ path,
954
+ `Purpose "${purpose.id}" names no category of data subjects (Art. 30(1)(c) GDPR). Add "dataSubjects" with at least one id, e.g. "dataSubjects: [visitors]".`
955
+ );
956
+ }
957
+ (purpose.dataSubjects ?? []).forEach((subject, subjectIndex) => {
958
+ if (dataSubjectIds !== void 0 && !dataSubjectIds.has(subject)) {
959
+ report(
960
+ "purpose/unknown-data-subject",
961
+ `${path}/dataSubjects/${subjectIndex}`,
962
+ `Purpose "${purpose.id}" uses the data subject category "${subject}", which dataSubjectCategories does not declare. ${declared("dataSubjectCategories", dataSubjectIds)}`
963
+ );
964
+ }
965
+ });
966
+ purpose.dataCategories.forEach((category, categoryIndex) => {
967
+ if (dataCategoryIds !== void 0 && !dataCategoryIds.has(category)) {
968
+ report(
969
+ "purpose/unknown-data-category",
970
+ `${path}/dataCategories/${categoryIndex}`,
971
+ `Purpose "${purpose.id}" uses the data category "${category}", which the top-level dataCategories map does not declare. ${declared("dataCategories", dataCategoryIds)}`
972
+ );
973
+ }
974
+ });
975
+ const retentionEvent = durationEvent(parseDuration(purpose.retention));
976
+ if (retentionEvent !== void 0 && retentionEventIds !== void 0 && !retentionEventIds.has(retentionEvent)) {
977
+ report(
978
+ "purpose/unknown-retention-event",
979
+ `${path}/retention`,
980
+ `The retention of purpose "${purpose.id}" refers to the event "${retentionEvent}", which retentionEvents does not declare. ${declared("retentionEvents", retentionEventIds)}`
981
+ );
982
+ }
983
+ (purpose.processors ?? []).forEach((processorId, processorIndex) => {
984
+ referencedProcessors.add(processorId);
985
+ if (!processorIds.has(processorId)) {
986
+ report(
987
+ "purpose/unknown-processor",
988
+ `${path}/processors/${processorIndex}`,
989
+ `Purpose "${purpose.id}" lists processor "${processorId}", which is not declared. ${declared("processors", processorIds)}`
990
+ );
991
+ }
992
+ });
993
+ });
994
+ registry.processors.forEach((processor, index) => {
995
+ if (!EEA_COUNTRIES.has(processor.country) && processor.transferMechanism === void 0) {
996
+ report(
997
+ "processor/missing-transfer-mechanism",
998
+ `/processors/${index}`,
999
+ `Processor "${processor.id}" is in ${processor.country}, outside the EU/EEA, and has no transferMechanism. Set transferMechanism to one of adequacy, scc, dpf, bcr.`
1000
+ );
1001
+ }
1002
+ });
1003
+ registry.artefacts.forEach((artefact2, index) => {
1004
+ const path = `/artefacts/${index}`;
1005
+ checkText(artefact2.description, `${path}/description`);
1006
+ artefact2.purposes.forEach((purposeId, purposeIndex) => {
1007
+ if (!purposeIds.has(purposeId)) {
1008
+ report(
1009
+ "artefact/unknown-purpose",
1010
+ `${path}/purposes/${purposeIndex}`,
1011
+ `Artefact "${artefact2.id}" references purpose "${purposeId}", which is not declared. ${declared("purposes", purposeIds)}`
1012
+ );
1013
+ }
1014
+ });
1015
+ const target = networkUrl(artefact2);
1016
+ const location = target === void 0 ? void 0 : locateUrl(target);
1017
+ const targetPath = `${path}/${artefact2.kind === "pixel" || artefact2.kind === "endpoint" ? "url" : "src"}`;
1018
+ if (location?.where === "invalid") {
1019
+ report(
1020
+ "artefact/unsupported-url",
1021
+ targetPath,
1022
+ `The URL ${JSON.stringify(target)} of artefact "${artefact2.id}" cannot be used: ${location.problem}. Write an http(s) URL such as "https://cdn.example/tag.js", or a site-relative path such as "/js/app.js".`
1023
+ );
1024
+ } else if (location?.where === "remote" && !/^https?:$/.test(location.url.protocol)) {
1025
+ report(
1026
+ "artefact/unsupported-url",
1027
+ targetPath,
1028
+ `Artefact "${artefact2.id}" points at ${target}. Only http(s) URLs and site-relative paths can be gated and listed in the Content-Security-Policy; use one of those.`
1029
+ );
1030
+ }
1031
+ if (artefact2.kind === "script") {
1032
+ const consentPurposes = artefact2.purposes.filter((id2) => consentPurposeIds.has(id2));
1033
+ if (consentPurposes.length > 1) {
1034
+ report(
1035
+ "script/multiple-consent-purposes",
1036
+ `${path}/purposes`,
1037
+ `Script "${artefact2.id}" is bound to ${consentPurposes.length} consent purposes (${consentPurposes.join(", ")}), but the banner can only gate a script on one. Bind it to a single consent purpose, or split it into one script per purpose.`
1038
+ );
1039
+ }
1040
+ }
1041
+ if (artefact2.kind === "stylesheet" || artefact2.kind === "font" || artefact2.kind === "media") {
1042
+ const consentPurposes = artefact2.purposes.filter((id2) => consentPurposeIds.has(id2));
1043
+ if (consentPurposes.length > 0) {
1044
+ report(
1045
+ "artefact/consent-not-enforceable",
1046
+ `${path}/purposes`,
1047
+ `The ${artefact2.kind} "${artefact2.id}" is bound to the consent purpose${consentPurposes.length === 1 ? "" : "s"} ${consentPurposes.join(", ")}, but nothing can hold it back until consent: the banner only manages <script> tags, the guard does not see <link>, CSS url() or <video> loads, and the Content-Security-Policy is the same before and after a decision. Host the file yourself (then it needs no declaration), bind it to a purpose with another lawful basis that you can defend, or load it from a consent-gated script.`
1048
+ );
1049
+ }
1050
+ }
1051
+ if (artefact2.processor === void 0) {
1052
+ const url = networkUrl(artefact2);
1053
+ if (url !== void 0 && isAbsoluteUrl(url)) {
1054
+ report(
1055
+ "artefact/third-party-without-processor",
1056
+ path,
1057
+ `Artefact "${artefact2.id}" loads from or sends to ${url}, a third party, but has no processor. Declare the vendor under processors and set processor to its id.`
1058
+ );
1059
+ }
1060
+ } else if (!processorIds.has(artefact2.processor)) {
1061
+ report(
1062
+ "artefact/unknown-processor",
1063
+ `${path}/processor`,
1064
+ `Artefact "${artefact2.id}" references processor "${artefact2.processor}", which is not declared. ${declared("processors", processorIds)}`
1065
+ );
1066
+ }
1067
+ if ((artefact2.kind === "cookie" || artefact2.kind === "storage") && artefact2.pattern !== void 0) {
1068
+ const problem = regExpProblem(artefact2.pattern);
1069
+ if (problem !== void 0) {
1070
+ report(
1071
+ "artefact/invalid-pattern",
1072
+ `${path}/pattern`,
1073
+ `Pattern "${artefact2.pattern}" of artefact "${artefact2.id}" is not a valid regular expression (${problem}). Fix the expression, or use ${artefact2.kind === "cookie" ? "name" : "key"} for an exact match.`
1074
+ );
1075
+ }
1076
+ }
1077
+ });
1078
+ registry.collectionPoints.forEach((point, pointIndex) => {
1079
+ const seen = /* @__PURE__ */ new Set();
1080
+ checkText(point.title, `/collectionPoints/${pointIndex}/title`);
1081
+ point.fields.forEach((field2, fieldIndex) => {
1082
+ const path = `/collectionPoints/${pointIndex}/fields/${fieldIndex}`;
1083
+ checkText(field2.notice, `${path}/notice`);
1084
+ checkText(field2.consequence, `${path}/consequence`);
1085
+ if (field2.provision === void 0) {
1086
+ report(
1087
+ "collection-field/missing-provision",
1088
+ path,
1089
+ `Field "${field2.name}" of collection point "${point.id}" does not say whether providing it is required (Art. 13(2)(e) GDPR). Add "provision: statutory" (the law requires it), "provision: contractual" (a contract requires it, or it is needed to enter into one) or "provision: voluntary".`
1090
+ );
1091
+ } else if (field2.provision !== "voluntary" && field2.consequence === void 0) {
1092
+ report(
1093
+ "collection-field/missing-consequence",
1094
+ path,
1095
+ `Field "${field2.name}" of collection point "${point.id}" is ${field2.provision} but does not say what happens when it is not provided (Art. 13(2)(e) GDPR). Add "consequence" with one text per locale [${registry.locales.join(", ")}], e.g. "en: Without it we cannot reply."`
1096
+ );
1097
+ }
1098
+ if (seen.has(field2.name)) {
1099
+ report(
1100
+ "collection-point/duplicate-field",
1101
+ `${path}/name`,
1102
+ `Collection point "${point.id}" declares field "${field2.name}" more than once. Keep one entry per field.`
1103
+ );
1104
+ }
1105
+ seen.add(field2.name);
1106
+ if (!purposeIds.has(field2.purpose)) {
1107
+ report(
1108
+ "collection-field/unknown-purpose",
1109
+ `${path}/purpose`,
1110
+ `Field "${field2.name}" of collection point "${point.id}" references purpose "${field2.purpose}", which is not declared. ${declared("purposes", purposeIds)}`
1111
+ );
1112
+ }
1113
+ });
1114
+ });
1115
+ const csp = registry.csp;
1116
+ const allowed = /* @__PURE__ */ new Set();
1117
+ (csp?.allow ?? []).forEach((entry, index) => {
1118
+ const path = `/csp/allow/${index}`;
1119
+ if (!CSP_DIRECTIVES.includes(entry.directive)) {
1120
+ report(
1121
+ "csp/unknown-directive",
1122
+ `${path}/directive`,
1123
+ `"${entry.directive}" is not a directive of the generated Content-Security-Policy. Use one of: ${CSP_DIRECTIVES.join(", ")}.`
1124
+ );
1125
+ }
1126
+ entry.sources.forEach((source, sourceIndex) => {
1127
+ const sourcePath = `${path}/sources/${sourceIndex}`;
1128
+ if (source === "'none'") {
1129
+ report("csp/redundant-source", sourcePath, `'none' allows nothing, so it cannot loosen ${entry.directive}. Remove it; csp.allow only ever adds sources.`);
1130
+ } else if (!isCspSource(source)) {
1131
+ report(
1132
+ "csp/invalid-source",
1133
+ sourcePath,
1134
+ `${JSON.stringify(source)} is not a CSP source expression. Write one source per list item, exactly as it appears in the header: a quoted keyword such as "'unsafe-inline'", a scheme such as "data:", or a host such as "https://cdn.example" or "*.example.org".`
1135
+ );
1136
+ } else if (allowed.has(`${entry.directive} ${source}`)) {
1137
+ report("csp/redundant-source", sourcePath, `${source} is already allowed for ${entry.directive} by an earlier csp.allow entry. Keep one, with one reason.`);
1138
+ }
1139
+ allowed.add(`${entry.directive} ${source}`);
1140
+ });
1141
+ });
1142
+ if (csp?.reportUri !== void 0) {
1143
+ const uri = csp.reportUri;
1144
+ const location = locateUrl(uri);
1145
+ const problem = location.where === "invalid" ? location.problem : /[;,"]/.test(uri) ? 'it contains ";", "," or a double quote, which would end the directive in the header' : location.where === "remote" && !/^https?:$/.test(location.url.protocol) ? "it is not an http(s) URL" : void 0;
1146
+ if (problem !== void 0) {
1147
+ report("csp/invalid-report-uri", "/csp/reportUri", `csp.reportUri ${JSON.stringify(uri)} cannot be used: ${problem}. Write an http(s) URL, or a site-relative path such as "/csp-reports".`);
1148
+ } else if (location.where === "remote" && !registry.artefacts.some((artefact2) => artefact2.kind === "endpoint" && covers(artefact2.url, location.url))) {
1149
+ report(
1150
+ "csp/undeclared-report-endpoint",
1151
+ "/csp/reportUri",
1152
+ `csp.reportUri sends every violation report, with the visitor's IP address and the page URL, to ${uri}, which no endpoint artefact declares. Add an artefact with "kind: endpoint", "url: ${uri}", its processor and a purpose.`
1153
+ );
1154
+ }
1155
+ }
1156
+ const receipts = registry.receipts;
1157
+ if (receipts === void 0) {
1158
+ if (consentPurposeIds.size > 0) {
1159
+ report(
1160
+ "receipts/not-stated",
1161
+ "",
1162
+ `The registry asks for consent (${[...consentPurposeIds].join(", ")}) but does not say where the proof of each decision goes. Add "receipts: { endpoint: /consent-receipts }" (a path or https URL your site answers with a POST handler), or, if this site keeps no receipts, "receipts: { optOut: { reason: <why> } }", which is reported on every check and audit.`
1163
+ );
1164
+ }
1165
+ } else if ("optOut" in receipts) {
1166
+ const phrase = matchVagueReason(receipts.optOut.reason);
1167
+ if (phrase !== void 0) {
1168
+ report(
1169
+ "receipts/vague-reason",
1170
+ "/receipts/optOut/reason",
1171
+ `${phrase === "" ? "The reason for keeping no consent receipts says nothing" : `The reason for keeping no consent receipts is just "${phrase}"`}. Say why this site can do without proof of its visitors' decisions, e.g. where else they are recorded, or the ticket that tracks adding an endpoint.`
1172
+ );
1173
+ }
1174
+ } else {
1175
+ const { endpoint } = receipts;
1176
+ const location = locateUrl(endpoint);
1177
+ const problem = location.where === "invalid" ? location.problem : location.where === "remote" && location.url.protocol !== "https:" ? "it is not an https URL" : void 0;
1178
+ if (problem !== void 0) {
1179
+ report(
1180
+ "receipts/invalid-endpoint",
1181
+ "/receipts/endpoint",
1182
+ `receipts.endpoint ${JSON.stringify(endpoint)} cannot be used: ${problem}. Write a site-relative path such as "/consent-receipts", or an https URL.`
1183
+ );
1184
+ } else if (location.where === "remote") {
1185
+ let best;
1186
+ for (const artefact2 of registry.artefacts) {
1187
+ if (artefact2.kind !== "endpoint" || !covers(artefact2.url, location.url)) continue;
1188
+ const length = locateUrl(artefact2.url).url.pathname.length;
1189
+ if (best === void 0 || length > best.length) best = { artefact: artefact2, length };
1190
+ }
1191
+ if (best === void 0) {
1192
+ report(
1193
+ "receipts/undeclared-endpoint",
1194
+ "/receipts/endpoint",
1195
+ `receipts.endpoint sends every consent receipt, with the visitor's IP address, to ${endpoint}, which no endpoint artefact declares. Add an artefact with "kind: endpoint", "url: ${endpoint}", its processor and a purpose that is not based on consent.`
1196
+ );
1197
+ } else {
1198
+ const consentPurposes = best.artefact.purposes.filter((id2) => consentPurposeIds.has(id2));
1199
+ if (consentPurposes.length > 0) {
1200
+ report(
1201
+ "receipts/endpoint-needs-consent",
1202
+ "/receipts/endpoint",
1203
+ `receipts.endpoint is declared by endpoint artefact "${best.artefact.id}", which is bound to the consent purpose${consentPurposes.length === 1 ? "" : "s"} ${consentPurposes.join(", ")}. A receipt is sent for a rejection too, so its endpoint cannot wait for consent. Bind "${best.artefact.id}" to a purpose with another lawful basis (e.g. the one that keeps your visitors' privacy choices), or declare a separate endpoint artefact for the receipts.`
1204
+ );
1205
+ }
1206
+ }
1207
+ }
1208
+ }
1209
+ const requests = registry.subjectRequests;
1210
+ if (requests !== void 0) {
1211
+ const location = locateUrl(requests.endpoint);
1212
+ if (location.where !== "site" || /[?#]/.test(requests.endpoint)) {
1213
+ const problem = location.where === "invalid" ? location.problem : location.where === "remote" ? "it points at another origin, so the browser would not send the consent cookie (cc_cookie) with the request and it could not be tied to that browser's consent receipts" : "it carries a query or a fragment, which the handler does not match on";
1214
+ report(
1215
+ "subject-requests/endpoint-not-same-origin",
1216
+ "/subjectRequests/endpoint",
1217
+ `subjectRequests.endpoint ${JSON.stringify(requests.endpoint)} cannot be used: ${problem}. Write a site-relative path such as "/privacy/requests" and route it to the handler on the site's own domain.`
1218
+ );
1219
+ }
1220
+ if (requests.notify.length > MAX_EMAIL_LENGTH || !EMAIL_PATTERN.test(requests.notify)) {
1221
+ report(
1222
+ "subject-requests/invalid-notify",
1223
+ "/subjectRequests/notify",
1224
+ `subjectRequests.notify ${JSON.stringify(requests.notify)} is not an email address. Write the mailbox every request is sent to, e.g. "privacy@example.com".`
1225
+ );
1226
+ }
1227
+ requests.types.forEach((type, index) => {
1228
+ if (SUBJECT_REQUEST_TYPES.includes(type)) return;
1229
+ report(
1230
+ "subject-requests/unknown-type",
1231
+ `/subjectRequests/types/${index}`,
1232
+ `"${type}" is not a request type consent-kit handles. Use ${SUBJECT_REQUEST_TYPES.map((known) => `"${known}"`).join(" or ")}; other requests (rectification, objection, portability) still reach the controller's contact.`
1233
+ );
1234
+ });
1235
+ if (!SUBJECT_REQUEST_RETENTION_PATTERN.test(requests.retention)) {
1236
+ report(
1237
+ "subject-requests/retention-format",
1238
+ "/subjectRequests/retention",
1239
+ `subjectRequests.retention ${JSON.stringify(requests.retention)} is not a number of days or years. Write how long a closed request is kept, e.g. "3y" or "400d"; it counts from the day the request is closed.`
1240
+ );
1241
+ }
1242
+ const processor = requests.requesterEmail?.processor;
1243
+ if (processor !== void 0) {
1244
+ referencedProcessors.add(processor);
1245
+ if (!processorIds.has(processor)) {
1246
+ report(
1247
+ "subject-requests/unknown-processor",
1248
+ "/subjectRequests/requesterEmail/processor",
1249
+ `subjectRequests.requesterEmail sends the requester's address to processor "${processor}", which is not declared. ${declared("processors", processorIds)}`
1250
+ );
1251
+ }
1252
+ }
1253
+ registry.purposes.forEach((purpose, index) => {
1254
+ if (purpose.id !== SUBJECT_REQUESTS_PURPOSE_ID) return;
1255
+ report(
1256
+ "subject-requests/purpose-id-taken",
1257
+ `/purposes/${index}/id`,
1258
+ `Purpose id "${SUBJECT_REQUESTS_PURPOSE_ID}" is the built-in purpose that subjectRequests adds to the documents. Rename this purpose, or remove it and let the built-in one describe the handling of requests.`
1259
+ );
1260
+ });
1261
+ }
1262
+ for (const artefact2 of registry.artefacts) if (artefact2.processor !== void 0) referencedProcessors.add(artefact2.processor);
1263
+ if ([...referencedProcessors].every((id2) => processorIds.has(id2))) {
1264
+ registry.processors.forEach((processor, index) => {
1265
+ if (referencedProcessors.has(processor.id)) return;
1266
+ report(
1267
+ "processor/unreferenced",
1268
+ `/processors/${index}`,
1269
+ `Processor "${processor.id}" is used by no artefact and listed by no purpose, so no document can say what it receives data for. Set "processor: ${processor.id}" on its artefacts, add it to "processors" of the purposes whose data it receives, or remove it.`
1270
+ );
1271
+ });
1272
+ }
1273
+ return errors;
1274
+ }
1275
+ function declared(section, ids) {
1276
+ return ids.size === 0 ? `Nothing is declared under ${section} yet; add it there.` : `Add it under ${section}, or use one of: ${[...ids].join(", ")}.`;
1277
+ }
1278
+ function networkUrl(artefact2) {
1279
+ switch (artefact2.kind) {
1280
+ case "script":
1281
+ case "iframe":
1282
+ case "stylesheet":
1283
+ case "font":
1284
+ case "media":
1285
+ return artefact2.src;
1286
+ case "pixel":
1287
+ case "endpoint":
1288
+ return artefact2.url;
1289
+ default:
1290
+ return void 0;
1291
+ }
1292
+ }
1293
+ function covers(declaredUrl, target) {
1294
+ const declared2 = locateUrl(declaredUrl);
1295
+ return declared2.where === "remote" && declared2.url.origin === target.origin && pathCovers(declared2.url.pathname, target.pathname);
1296
+ }
1297
+ function regExpProblem(source) {
1298
+ try {
1299
+ new RegExp(source);
1300
+ return void 0;
1301
+ } catch (error) {
1302
+ return error instanceof Error ? error.message : String(error);
1303
+ }
1304
+ }
1305
+
1306
+ // src/presets/resolve.ts
1307
+ var SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
1308
+ var HOST = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
1309
+ var PLACEHOLDER = /\$\{([A-Za-z0-9_]+)\}/g;
1310
+ var definitions = registrySchema.definitions;
1311
+ var PROCESSOR_FIELDS = Object.keys(definitions.processor.properties).filter((field2) => field2 !== "id");
1312
+ var artefactFields = (kind) => Object.keys(definitions[`${kind}Artefact`].properties).filter((field2) => field2 !== "id" && field2 !== "kind");
1313
+ function parseSemver(version) {
1314
+ const match = SEMVER.exec(version);
1315
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
1316
+ }
1317
+ function compareSemver(a, b) {
1318
+ const [x, y] = [parseSemver(a) ?? [-1, -1, -1], parseSemver(b) ?? [-1, -1, -1]];
1319
+ return x[0] - y[0] || x[1] - y[1] || x[2] - y[2];
1320
+ }
1321
+ function selectPreset(catalogue, id2, version) {
1322
+ const versions = catalogue.filter((preset) => preset.id === id2).sort((a, b) => compareSemver(b.version, a.version));
1323
+ if (typeof version === "number") return versions.find((preset) => parseSemver(preset.version)?.[0] === version);
1324
+ return versions.find((preset) => preset.version === version);
1325
+ }
1326
+ function substitute(value, parameters, missing) {
1327
+ if (typeof value === "string") {
1328
+ return value.replace(PLACEHOLDER, (whole, name) => {
1329
+ if (Object.hasOwn(parameters, name)) return parameters[name];
1330
+ missing.add(name);
1331
+ return whole;
1332
+ });
1333
+ }
1334
+ if (Array.isArray(value)) return value.map((item) => substitute(item, parameters, missing));
1335
+ if (typeof value === "object" && value !== null) {
1336
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, substitute(item, parameters, missing)]));
1337
+ }
1338
+ return value;
1339
+ }
1340
+ function fillPlaceholders(text, parameters) {
1341
+ return substitute(text, parameters, /* @__PURE__ */ new Set());
1342
+ }
1343
+ function parameterProblem(spec, value) {
1344
+ if (spec.type === "origin") {
1345
+ let url;
1346
+ try {
1347
+ url = new URL(value);
1348
+ } catch {
1349
+ }
1350
+ if (!url || !/^https?:$/.test(url.protocol) || url.origin !== value) {
1351
+ return 'must be an origin: scheme, host and optional port, without a path or trailing slash (e.g. "https://stats.example.org")';
1352
+ }
1353
+ }
1354
+ if (spec.type === "host" && !HOST.test(value)) return 'must be a host name such as "example.org", without scheme or path';
1355
+ if (spec.pattern !== void 0) {
1356
+ let matches = false;
1357
+ try {
1358
+ matches = new RegExp(spec.pattern).test(value);
1359
+ } catch {
1360
+ }
1361
+ if (!matches) return `must match /${spec.pattern}/ (e.g. "${spec.example}")`;
1362
+ }
1363
+ return void 0;
1364
+ }
1365
+ var same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
1366
+ var list = (values) => [...values].map((value) => `"${value}"`).join(", ") || "(none)";
1367
+ function resolvePresets(source, catalogue) {
1368
+ const { presets: uses = [], ...rest } = source;
1369
+ const registry = { ...rest, processors: [...source.processors], artefacts: [...source.artefacts] };
1370
+ const errors = [];
1371
+ const warnings = [];
1372
+ const applied = [];
1373
+ const overrides = [];
1374
+ const purposes = new Map(source.purposes.map((purpose) => [purpose.id, purpose]));
1375
+ const owner = { processors: /* @__PURE__ */ new Map(), artefacts: /* @__PURE__ */ new Map() };
1376
+ source.processors.forEach((entry, index) => owner.processors.set(entry.id, `/processors/${index}`));
1377
+ source.artefacts.forEach((entry, index) => owner.artefacts.set(entry.id, `/artefacts/${index}`));
1378
+ uses.forEach((use, index) => {
1379
+ const path = `/presets/${index}`;
1380
+ const before = errors.length;
1381
+ const report = (rule, at, message) => errors.push({ rule, path: at, message });
1382
+ const known = [...new Set(catalogue.map((preset2) => preset2.id))].sort();
1383
+ const versions = catalogue.filter((preset2) => preset2.id === use.use).map((preset2) => preset2.version).sort(compareSemver);
1384
+ if (versions.length === 0) {
1385
+ report("preset/unknown", `${path}/use`, `There is no preset "${use.use}". Known presets: ${list(known)}. Check the spelling, or declare the tool by hand under processors and artefacts.`);
1386
+ return;
1387
+ }
1388
+ const versionOk = typeof use.version === "number" ? Number.isInteger(use.version) && use.version >= 0 : parseSemver(use.version) !== null;
1389
+ const preset = versionOk ? selectPreset(catalogue, use.use, use.version) : void 0;
1390
+ if (!preset) {
1391
+ const what = versionOk ? `Preset "${use.use}" has no version ${JSON.stringify(use.version)}.` : `${JSON.stringify(use.version)} is not a preset version.`;
1392
+ report("preset/unknown", `${path}/version`, `${what} Use a major version (e.g. ${parseSemver(versions[versions.length - 1])?.[0] ?? 1}) or an exact one; available: ${versions.join(", ")}.`);
1393
+ return;
1394
+ }
1395
+ const label = `Preset "${preset.id}@${preset.version}"`;
1396
+ const slots = Object.keys(preset.purposes);
1397
+ const mapping = {};
1398
+ if (use.purpose !== void 0 && use.purposes !== void 0) {
1399
+ report("preset/purpose", `${path}/purpose`, `${label}: set either "purpose" or "purposes", not both.`);
1400
+ } else if (use.purpose !== void 0) {
1401
+ if (slots.length === 1) mapping[slots[0]] = use.purpose;
1402
+ else report("preset/purpose", `${path}/purpose`, `${label} has ${slots.length} purpose slots (${list(slots)}), so "purpose" is ambiguous. Map each one under "purposes", e.g. purposes: { ${slots[0]}: <your purpose id> }.`);
1403
+ } else {
1404
+ for (const [slot, purposeId] of Object.entries(use.purposes ?? {})) {
1405
+ if (slots.includes(slot)) mapping[slot] = purposeId;
1406
+ else report("preset/purpose", `${path}/purposes/${slot}`, `${label} has no purpose slot "${slot}". Its slots are: ${list(slots)}.`);
1407
+ }
1408
+ }
1409
+ if (errors.length === before) {
1410
+ for (const slot of slots) {
1411
+ const purposeId = mapping[slot];
1412
+ const slotPath = use.purpose !== void 0 ? `${path}/purpose` : `${path}/purposes/${slot}`;
1413
+ if (purposeId === void 0) {
1414
+ report("preset/purpose", path, `${label} needs a purpose for "${slot}" (${preset.purposes[slot].description}). ${slots.length === 1 ? 'Set "purpose"' : `Add ${slot} under "purposes"`} to the id of one of your purposes: ${list(purposes.keys())}.`);
1415
+ continue;
1416
+ }
1417
+ const purpose = purposes.get(purposeId);
1418
+ if (!purpose) {
1419
+ report("preset/purpose", slotPath, `${label} is bound to purpose "${purposeId}", which is not declared. Declare it under purposes, or use one of: ${list(purposes.keys())}.`);
1420
+ continue;
1421
+ }
1422
+ const expected = preset.purposes[slot].expectedBasis;
1423
+ if (expected !== void 0 && purpose.basis !== expected) {
1424
+ warnings.push({
1425
+ code: "preset/basis-mismatch",
1426
+ path: slotPath,
1427
+ message: `${label}: slot "${slot}" is bound to purpose "${purposeId}", whose basis is "${purpose.basis}"; the preset expects "${expected}"${preset.purposes[slot].basisReason ? ` (${preset.purposes[slot].basisReason})` : ""}. The lawful basis is your decision; confirm it is the right one.`
1428
+ });
1429
+ }
1430
+ }
1431
+ }
1432
+ const parameters = {};
1433
+ for (const name of Object.keys(use.with ?? {})) {
1434
+ if (!Object.hasOwn(preset.parameters, name)) {
1435
+ report("preset/parameter", `${path}/with/${name}`, `${label} has no parameter "${name}". Its parameters are: ${list(Object.keys(preset.parameters))}.`);
1436
+ }
1437
+ }
1438
+ for (const [name, spec] of Object.entries(preset.parameters)) {
1439
+ const given = use.with?.[name];
1440
+ const value = given === void 0 ? spec.default : String(given);
1441
+ if (value === void 0) {
1442
+ report("preset/parameter", use.with ? `${path}/with` : path, `${label} needs the parameter "${name}" (${spec.description}). Add it under "with", e.g. with: { ${name}: ${spec.example} }.`);
1443
+ continue;
1444
+ }
1445
+ const problem = parameterProblem(spec, value);
1446
+ if (problem !== void 0) report("preset/parameter", `${path}/with/${name}`, `${label}: parameter "${name}" is ${JSON.stringify(value)} but ${problem}.`);
1447
+ parameters[name] = value;
1448
+ }
1449
+ const defaultProcessorId = preset.processor.declares.id;
1450
+ const artefactIds = preset.artefacts.map((entry) => entry.declares.id);
1451
+ const renamed = (defaultId) => use.ids?.[defaultId] ?? defaultId;
1452
+ const artefactHint = `Its artefacts are: ${list(artefactIds)}.`;
1453
+ for (const defaultId of Object.keys(use.ids ?? {})) {
1454
+ if (defaultId !== defaultProcessorId && !artefactIds.includes(defaultId)) {
1455
+ report("preset/override", `${path}/ids/${defaultId}`, `${label} declares nothing with the id "${defaultId}", so it cannot be renamed. Its processor is "${defaultProcessorId}". ${artefactHint}`);
1456
+ }
1457
+ }
1458
+ (use.exclude ?? []).forEach((defaultId, position) => {
1459
+ if (!artefactIds.includes(defaultId)) report("preset/override", `${path}/exclude/${position}`, `${label} has no artefact "${defaultId}" to exclude. ${artefactHint}`);
1460
+ });
1461
+ for (const defaultId of Object.keys(use.overrides?.artefacts ?? {})) {
1462
+ if (!artefactIds.includes(defaultId)) {
1463
+ report("preset/override", `${path}/overrides/artefacts/${defaultId}`, `${label} has no artefact "${defaultId}" to override. Overrides are keyed by the preset's default ids. ${artefactHint}`);
1464
+ } else if (use.exclude?.includes(defaultId)) {
1465
+ report("preset/override", `${path}/overrides/artefacts/${defaultId}`, `${label}: artefact "${defaultId}" is both excluded and overridden. Remove one of the two.`);
1466
+ }
1467
+ }
1468
+ const override = (target, documented, defaultId, changes, fields, at, sourceOf) => {
1469
+ const result = { ...documented };
1470
+ for (const [field2, local] of Object.entries(changes ?? {})) {
1471
+ if (field2 === "id" || field2 === "kind") {
1472
+ report("preset/override", `${at}/${field2}`, `${label}: "${field2}" of "${defaultId}" cannot be overridden. ${field2 === "id" ? `Rename it under "ids" instead: ids: { ${defaultId}: <your id> }.` : "An artefact of another kind is another artefact; declare it by hand."}`);
1473
+ continue;
1474
+ }
1475
+ if (!fields.includes(field2)) {
1476
+ report("preset/override", `${at}/${field2}`, `${label}: "${field2}" is not a field of ${target} "${defaultId}". Its fields are: ${fields.join(", ")}.`);
1477
+ continue;
1478
+ }
1479
+ const was = result[field2];
1480
+ const now = local === null ? void 0 : local;
1481
+ if (same(was, now)) {
1482
+ warnings.push({ code: "preset/redundant-override", path: `${at}/${field2}`, message: `${label}: the override of "${field2}" on "${defaultId}" equals the preset's own value. Remove it.` });
1483
+ continue;
1484
+ }
1485
+ if (now === void 0) delete result[field2];
1486
+ else result[field2] = now;
1487
+ overrides.push({ index, preset: preset.id, version: preset.version, target, id: documented.id, defaultId, change: "field", field: field2, documented: was, local: now, source: sourceOf(field2) });
1488
+ }
1489
+ return result;
1490
+ };
1491
+ const missing = /* @__PURE__ */ new Set();
1492
+ const processorId = renamed(defaultProcessorId);
1493
+ const documentedProcessor = { ...substitute(preset.processor.declares, parameters, missing), id: processorId };
1494
+ const processor = override(
1495
+ "processor",
1496
+ documentedProcessor,
1497
+ defaultProcessorId,
1498
+ use.overrides?.processor,
1499
+ PROCESSOR_FIELDS,
1500
+ `${path}/overrides/processor`,
1501
+ (field2) => preset.processor.facts[field2]?.source
1502
+ );
1503
+ const artefacts = [];
1504
+ const trace = [];
1505
+ for (const entry of preset.artefacts) {
1506
+ const defaultId = entry.declares.id;
1507
+ const id2 = renamed(defaultId);
1508
+ if (use.exclude?.includes(defaultId)) {
1509
+ overrides.push({ index, preset: preset.id, version: preset.version, target: "artefact", id: id2, defaultId, change: "excluded", source: entry.source });
1510
+ continue;
1511
+ }
1512
+ const documented = substitute(entry.declares, parameters, missing);
1513
+ const bound = [...new Set(documented.purposes.map((slot) => mapping[slot]).filter((purposeId) => purposeId !== void 0))];
1514
+ const artefact2 = { ...documented, id: id2, purposes: bound, processor: processorId };
1515
+ const description = localize(documented.description, source.locales);
1516
+ if (description) artefact2.description = description;
1517
+ else {
1518
+ delete artefact2.description;
1519
+ if (documented.description !== void 0) {
1520
+ const absent = source.locales.filter((locale2) => !(locale2 in documented.description));
1521
+ warnings.push({ code: "preset/missing-locale", path, message: `${label} has no ${list(absent)} description for artefact "${defaultId}", so the artefact has none. Supply one: overrides: { artefacts: { ${defaultId}: { description: { ... } } } }.` });
1522
+ }
1523
+ }
1524
+ artefacts.push(override("artefact", artefact2, defaultId, use.overrides?.artefacts?.[defaultId], artefactFields(artefact2.kind), `${path}/overrides/artefacts/${defaultId}`, () => entry.source));
1525
+ trace.push({ id: id2, defaultId });
1526
+ }
1527
+ for (const name of missing) {
1528
+ if (Object.hasOwn(preset.parameters, name)) continue;
1529
+ report("preset/parameter", path, `${label} refers to a parameter "${name}" that it does not define. This is a fault in the preset, not in your registry; please report it.`);
1530
+ }
1531
+ const where = `${path} (preset "${preset.id}")`;
1532
+ const claim = (section, id2, defaultId) => {
1533
+ const taken = owner[section].get(id2);
1534
+ if (taken === void 0) {
1535
+ owner[section].set(id2, where);
1536
+ return;
1537
+ }
1538
+ const noun = section === "processors" ? "processor" : "artefact";
1539
+ report("preset/id-collision", path, `${label} declares the ${noun} "${id2}", but ${taken} already uses that id. A preset declares its tool completely: remove the hand-written entry, or keep both by renaming the preset's: ids: { ${defaultId}: <another id> }.`);
1540
+ };
1541
+ claim("processors", processorId, defaultProcessorId);
1542
+ trace.forEach((entry) => claim("artefacts", entry.id, entry.defaultId));
1543
+ if (errors.length > before) return;
1544
+ registry.processors.push(processor);
1545
+ registry.artefacts.push(...artefacts);
1546
+ applied.push({
1547
+ index,
1548
+ preset: preset.id,
1549
+ version: preset.version,
1550
+ status: preset.status,
1551
+ synthetic: preset.synthetic === true,
1552
+ parameters,
1553
+ purposes: mapping,
1554
+ processor: { id: processorId, defaultId: defaultProcessorId },
1555
+ artefacts: trace,
1556
+ unverified: [
1557
+ ...Object.entries(preset.processor.facts).filter(([, fact]) => !fact.verified).map(([field2]) => `processor.${field2}`),
1558
+ ...preset.artefacts.filter((entry) => !entry.verified).map((entry) => entry.declares.id)
1559
+ ]
1560
+ });
1561
+ });
1562
+ return errors.length > 0 ? { ok: false, errors } : { ok: true, registry, applied, overrides, warnings };
1563
+ }
1564
+ function localize(text, locales) {
1565
+ if (text === void 0 || locales.some((locale2) => !(locale2 in text))) return void 0;
1566
+ return Object.fromEntries(locales.map((locale2) => [locale2, text[locale2]]));
1567
+ }
1568
+ function presetOrigin(applied, section, id2) {
1569
+ return applied.find((entry) => section === "processors" ? entry.processor.id === id2 : entry.artefacts.some((artefact2) => artefact2.id === id2));
1570
+ }
1571
+
1572
+ // src/validate.ts
1573
+ var ajv = new Ajv({ allErrors: true, strict: true, strictTypes: false, strictRequired: false });
1574
+ var validateSchema = ajv.compile(registrySchema);
1575
+ function validateRegistry(input, options = {}) {
1576
+ if (!validateSchema(input)) {
1577
+ return { ok: false, errors: schemaErrors(validateSchema.errors ?? [], input) };
1578
+ }
1579
+ if (input.presets === void 0) return checked(input);
1580
+ const { presets: uses, ...plain } = input;
1581
+ if (uses.length === 0) return checked(plain);
1582
+ if (options.presets === void 0) {
1583
+ return {
1584
+ ok: false,
1585
+ errors: [
1586
+ {
1587
+ rule: "preset/unresolved",
1588
+ path: "/presets",
1589
+ message: "This registry adopts presets, but the validator was given no preset catalogue. Use parseRegistry / validateRegistry from @consent-kit/presets (the consent-kit CLI does), or pass { presets: catalogue }."
1590
+ }
1591
+ ]
1592
+ };
1593
+ }
1594
+ const resolved = resolvePresets(input, options.presets);
1595
+ if (!resolved.ok) return { ok: false, errors: resolved.errors };
1596
+ const { registry, applied, overrides, warnings } = resolved;
1597
+ const relocate = relocator(input, registry, applied);
1598
+ if (!validateSchema(registry)) {
1599
+ return { ok: false, errors: schemaErrors(validateSchema.errors ?? [], registry).map(relocate) };
1600
+ }
1601
+ const result = checked(registry);
1602
+ if (!result.ok) return { ok: false, errors: result.errors.map(relocate) };
1603
+ return { ok: true, registry, presets: { applied, overrides, warnings } };
1604
+ }
1605
+ function checked(registry) {
1606
+ const errors = checkSemanticRules(registry);
1607
+ return errors.length === 0 ? { ok: true, registry } : { ok: false, errors };
1608
+ }
1609
+ function relocator(source, expanded, applied) {
1610
+ return (error) => {
1611
+ const match = /^\/(processors|artefacts)\/(\d+)/.exec(error.path);
1612
+ if (!match) return error;
1613
+ const section = match[1];
1614
+ const index = Number(match[2]);
1615
+ if (index < source[section].length) return error;
1616
+ const id2 = expanded[section][index]?.id;
1617
+ const origin = applied.find((entry) => section === "processors" ? entry.processor.id === id2 : entry.artefacts.some((artefact2) => artefact2.id === id2));
1618
+ if (!origin) return error;
1619
+ return {
1620
+ ...error,
1621
+ path: `/presets/${origin.index}`,
1622
+ message: `${error.message} (This entry is written by preset "${origin.preset}@${origin.version}"; correct it under "overrides", "ids" or "with" of that presets entry.)`
1623
+ };
1624
+ };
1625
+ }
1626
+ function parseRegistry(yamlText, options = {}) {
1627
+ const lineCounter = new LineCounter();
1628
+ const document = parseDocument(yamlText, { lineCounter, prettyErrors: false });
1629
+ if (document.errors.length > 0) {
1630
+ return {
1631
+ ok: false,
1632
+ errors: document.errors.map((error) => {
1633
+ const { line, col } = lineCounter.linePos(error.pos[0]);
1634
+ return {
1635
+ rule: "yaml/syntax",
1636
+ path: "",
1637
+ message: `Invalid YAML at line ${line}, column ${col}: ${error.message}. Fix the syntax; nothing else is checked until the file parses.`,
1638
+ line,
1639
+ column: col
1640
+ };
1641
+ })
1642
+ };
1643
+ }
1644
+ let data;
1645
+ try {
1646
+ data = document.toJS();
1647
+ } catch (error) {
1648
+ const reason = error instanceof Error ? error.message : String(error);
1649
+ return {
1650
+ ok: false,
1651
+ errors: [{ rule: "yaml/syntax", path: "", message: `The YAML could not be read: ${reason}.` }]
1652
+ };
1653
+ }
1654
+ const result = validateRegistry(data, options);
1655
+ if (result.ok) return result;
1656
+ return {
1657
+ ok: false,
1658
+ errors: result.errors.map((error) => {
1659
+ const position = locate(error.path);
1660
+ return position === void 0 ? error : { ...error, ...position };
1661
+ })
1662
+ };
1663
+ function locate(path) {
1664
+ const segments = path === "" ? [] : path.slice(1).split("/").map(unescapePointer);
1665
+ for (let length = segments.length; length >= 0; length--) {
1666
+ const node = document.getIn(segments.slice(0, length), true);
1667
+ if (isNode(node) && node.range) {
1668
+ const { line, col } = lineCounter.linePos(node.range[0]);
1669
+ return { line, column: col };
1670
+ }
1671
+ }
1672
+ return void 0;
1673
+ }
1674
+ }
1675
+ function schemaErrors(ajvErrors, input) {
1676
+ const errors = [];
1677
+ const seen = /* @__PURE__ */ new Set();
1678
+ for (const ajvError of ajvErrors) {
1679
+ const error = translate(ajvError, input);
1680
+ if (error === void 0) continue;
1681
+ const key = `${error.rule} ${error.path}`;
1682
+ if (seen.has(key)) continue;
1683
+ seen.add(key);
1684
+ errors.push(error);
1685
+ }
1686
+ return errors;
1687
+ }
1688
+ function translate(error, input) {
1689
+ const path = error.instancePath;
1690
+ const field2 = lastSegment(path);
1691
+ const where = path === "" ? "The registry" : path;
1692
+ if (error.keyword === "if" || error.schemaPath.includes("/oneOf/")) return void 0;
1693
+ switch (error.keyword) {
1694
+ case "required": {
1695
+ const missing = String(error.params.missingProperty);
1696
+ const missingPath = `${path}/${escapePointer(missing)}`;
1697
+ if (missing === "purposes" && /^\/artefacts\/\d+$/.test(path)) {
1698
+ return { rule: "artefact/no-purpose", path: missingPath, message: noPurposeMessage(artefactId(input, path)) };
1699
+ }
1700
+ if (missing === "purpose" && /^\/collectionPoints\/\d+\/fields\/\d+$/.test(path)) {
1701
+ return {
1702
+ rule: "collection-field/no-purpose",
1703
+ path: missingPath,
1704
+ message: "This field has no purpose. Every collected field needs one: set purpose to the id of a declared purpose."
1705
+ };
1706
+ }
1707
+ return make("schema/required", missingPath, `${where} is missing the required field "${missing}". Add it.`);
1708
+ }
1709
+ case "additionalProperties": {
1710
+ const extra = String(error.params.additionalProperty);
1711
+ return make(
1712
+ "schema/unknown-property",
1713
+ `${path}/${escapePointer(extra)}`,
1714
+ `"${extra}" is not a known field here. Remove it or check the spelling.`
1715
+ );
1716
+ }
1717
+ case "propertyNames":
1718
+ if (/^\/(dataCategories|dataSubjectCategories|retentionEvents)$/.test(path)) {
1719
+ return patternError(`${path}/${escapePointer(String(error.params.propertyName))}`, "", `The key "${error.params.propertyName}" of ${path}`);
1720
+ }
1721
+ return make(
1722
+ "schema/format",
1723
+ `${path}/${escapePointer(String(error.params.propertyName))}`,
1724
+ `"${error.params.propertyName}" is not a valid locale. Use a language tag such as "en" or "de" as the key.`
1725
+ );
1726
+ case "type":
1727
+ return make("schema/type", path, `${where} must be of type ${error.params.type}.`);
1728
+ case "enum":
1729
+ return make(
1730
+ "schema/enum",
1731
+ path,
1732
+ `${where} must be one of: ${error.params.allowedValues.join(", ")}.`
1733
+ );
1734
+ case "const":
1735
+ return make("schema/enum", path, `${where} must be ${JSON.stringify(error.params.allowedValue)}; no other value is supported.`);
1736
+ case "oneOf": {
1737
+ if (field2 === "dpo") {
1738
+ return make("schema/format", path, `${where} must be false (no data protection officer is designated) or an object with "contact" and, optionally, "name".`);
1739
+ }
1740
+ if (field2 === "automatedDecisionMaking") {
1741
+ return make(
1742
+ "schema/format",
1743
+ path,
1744
+ `${where} must be false (no automated decision-making or profiling) or an object with "logic" and "consequences", each a text per locale. "true" alone is not enough: Art. 13(2)(f) GDPR asks for both.`
1745
+ );
1746
+ }
1747
+ if (path === "/receipts") {
1748
+ return make(
1749
+ "schema/exactly-one-of",
1750
+ path,
1751
+ `${where} must set exactly one of "endpoint" (where receipts are sent) or "optOut" (no receipts, with a reason), not both and not neither.`
1752
+ );
1753
+ }
1754
+ const [a, b] = /^\/artefacts\/\d+$/.test(path) && kindAt(input, path) === "storage" ? ["key", "pattern"] : ["name", "pattern"];
1755
+ return make(
1756
+ "schema/exactly-one-of",
1757
+ path,
1758
+ `${where} must set exactly one of "${a}" (exact match) or "${b}" (regular expression), not both and not neither.`
1759
+ );
1760
+ }
1761
+ case "minItems":
1762
+ if (/^\/artefacts\/\d+\/purposes$/.test(path)) {
1763
+ return make("artefact/no-purpose", path, noPurposeMessage(artefactId(input, parentPath(path))));
1764
+ }
1765
+ return make("schema/format", path, `${where} must have at least ${error.params.limit} item(s).`);
1766
+ case "uniqueItems":
1767
+ return make("schema/format", path, `${where} lists the same value twice. Remove the duplicate.`);
1768
+ case "minLength":
1769
+ case "minProperties":
1770
+ return make("schema/format", path, `${where} must not be empty.`);
1771
+ case "minimum":
1772
+ return make("schema/format", path, `${where} must be at least ${error.params.limit}.`);
1773
+ case "pattern":
1774
+ return patternError(path, field2, where, input);
1775
+ default:
1776
+ return make("schema/format", path, `${where} ${error.message ?? "is invalid"}.`);
1777
+ }
1778
+ }
1779
+ function patternError(path, field2, where, input) {
1780
+ if (field2 === "retention") {
1781
+ return make(
1782
+ "purpose/invalid-retention",
1783
+ path,
1784
+ `${where} is not a valid retention. Use "session", "until-withdrawn", a number of days or years such as "30d" or "3y", or days or years after a project event such as "30d-after-closed".`
1785
+ );
1786
+ }
1787
+ if (field2 === "duration" && kindAt(input, parentPath(path)) === "storage") {
1788
+ return make(
1789
+ "storage/invalid-duration",
1790
+ path,
1791
+ `${where} is not a valid storage duration. Use "persistent" (kept until deleted) or a number of days such as "30d".`
1792
+ );
1793
+ }
1794
+ if (field2 === "duration") {
1795
+ return make(
1796
+ "cookie/invalid-duration",
1797
+ path,
1798
+ `${where} is not a valid cookie duration. Use "session" or a number of days such as "365d".`
1799
+ );
1800
+ }
1801
+ if (field2 === "reportTo") {
1802
+ return make("schema/format", path, `${where} must be a reporting group name of letters, digits, "-" and "_", such as "csp".`);
1803
+ }
1804
+ if (field2 === "country") {
1805
+ return make("schema/format", path, `${where} must be an upper-case ISO 3166-1 alpha-2 country code such as "DE" or "US".`);
1806
+ }
1807
+ if (field2 === "defaultLocale" || /^\/locales\/\d+$/.test(path)) {
1808
+ return make("schema/format", path, `${where} must be a language tag such as "en", "de" or "pt-BR".`);
1809
+ }
1810
+ return make(
1811
+ "schema/id-format",
1812
+ path,
1813
+ `${where} is not a valid id. Ids start with a lowercase letter and contain only lowercase letters, digits, "-" and "_" (e.g. "analytics", "correction_reply").`
1814
+ );
1815
+ }
1816
+ function noPurposeMessage(artefactId2) {
1817
+ const subject = artefactId2 === void 0 ? "This artefact" : `Artefact "${artefactId2}"`;
1818
+ return `${subject} is not bound to any purpose, so it would always be blocked. List at least one purpose id under purposes.`;
1819
+ }
1820
+ function make(rule, path, message) {
1821
+ return { rule, path, message };
1822
+ }
1823
+ function escapePointer(segment) {
1824
+ return segment.replace(/~/g, "~0").replace(/\//g, "~1");
1825
+ }
1826
+ function unescapePointer(segment) {
1827
+ return segment.replace(/~1/g, "/").replace(/~0/g, "~");
1828
+ }
1829
+ function lastSegment(path) {
1830
+ return unescapePointer(path.slice(path.lastIndexOf("/") + 1));
1831
+ }
1832
+ function parentPath(path) {
1833
+ return path.slice(0, path.lastIndexOf("/"));
1834
+ }
1835
+ function valueAt(input, path) {
1836
+ let value = input;
1837
+ for (const segment of path === "" ? [] : path.slice(1).split("/").map(unescapePointer)) {
1838
+ if (typeof value !== "object" || value === null) return void 0;
1839
+ value = value[segment];
1840
+ }
1841
+ return value;
1842
+ }
1843
+ function stringProperty(input, path, key) {
1844
+ const value = valueAt(input, `${path}/${key}`);
1845
+ return typeof value === "string" ? value : void 0;
1846
+ }
1847
+ var artefactId = (input, path) => stringProperty(input, path, "id");
1848
+ var kindAt = (input, path) => stringProperty(input, path, "kind");
1849
+
1850
+ // src/diff/model.ts
1851
+ var CLASSIFICATIONS = [
1852
+ "not_material",
1853
+ "needs_confirmation",
1854
+ "material",
1855
+ "needs_review"
1856
+ ];
1857
+ function severity(classification) {
1858
+ return CLASSIFICATIONS.indexOf(classification);
1859
+ }
1860
+ function isClassification(value) {
1861
+ return CLASSIFICATIONS.includes(value);
1862
+ }
1863
+ function strictest(a, b) {
1864
+ return severity(b) > severity(a) ? b : a;
1865
+ }
1866
+ function isMaterial(classification) {
1867
+ return severity(classification) >= severity("material");
1868
+ }
1869
+ var MATERIAL = { consent: "material", nonConsent: "material" };
1870
+ var NOT_MATERIAL = { consent: "not_material", nonConsent: "not_material" };
1871
+ var REVIEW = { consent: "needs_review", nonConsent: "needs_review" };
1872
+ var NEUTRAL = { consent: "needs_confirmation", nonConsent: "not_material" };
1873
+ var CONFIRM = { consent: "needs_confirmation", nonConsent: "needs_confirmation" };
1874
+ var NOTICE = { consent: "needs_confirmation", nonConsent: "material" };
1875
+ var localizedText = {
1876
+ changed: MATERIAL,
1877
+ formatting_changed: NEUTRAL,
1878
+ locale_added: CONFIRM,
1879
+ locale_removed: NOT_MATERIAL
1880
+ };
1881
+ var CHANGE_KINDS = {
1882
+ // Registry-wide. Attributed to every purpose.
1883
+ "registry.format_version_changed": MATERIAL,
1884
+ "registry.locale_added": NOT_MATERIAL,
1885
+ "registry.locale_removed": NOT_MATERIAL,
1886
+ "registry.default_locale_changed": NOT_MATERIAL,
1887
+ "registry.unclassified_changed": MATERIAL,
1888
+ /** Name, contact, address. */
1889
+ "controller.changed": MATERIAL,
1890
+ "controller.dpo_changed": NOTICE,
1891
+ "controller.supervisory_authority_changed": NOTICE,
1892
+ "controller.eu_representative_changed": NOTICE,
1893
+ /** Internal (Art. 30 record only), but a weaker measure is not provably harmless. */
1894
+ "registry.security_measures_changed": CONFIRM,
1895
+ /** Glossary entries name ids; using an id is a `purpose.*` change of its own. */
1896
+ "data_category.added": NOT_MATERIAL,
1897
+ "data_category.removed": NOT_MATERIAL,
1898
+ "data_category.title_changed": localizedText.changed,
1899
+ "data_category.title_formatting_changed": localizedText.formatting_changed,
1900
+ "data_category.title_locale_added": localizedText.locale_added,
1901
+ "data_category.title_locale_removed": localizedText.locale_removed,
1902
+ /** The data is now declared an Art. 9 special category: the lawful basis has to be re-examined. */
1903
+ "data_category.special_flagged": REVIEW,
1904
+ /** No longer declared special: nothing proves the data itself changed. */
1905
+ "data_category.special_unflagged": REVIEW,
1906
+ "data_subject_category.added": NOT_MATERIAL,
1907
+ "data_subject_category.removed": NOT_MATERIAL,
1908
+ "data_subject_category.title_changed": localizedText.changed,
1909
+ "data_subject_category.title_formatting_changed": localizedText.formatting_changed,
1910
+ "data_subject_category.title_locale_added": localizedText.locale_added,
1911
+ "data_subject_category.title_locale_removed": localizedText.locale_removed,
1912
+ "retention_event.added": NOT_MATERIAL,
1913
+ "retention_event.removed": NOT_MATERIAL,
1914
+ "retention_event.description_changed": localizedText.changed,
1915
+ "retention_event.description_formatting_changed": localizedText.formatting_changed,
1916
+ "retention_event.description_locale_added": localizedText.locale_added,
1917
+ "retention_event.description_locale_removed": localizedText.locale_removed,
1918
+ /**
1919
+ * The Content-Security-Policy got weaker: a source was allowed, enforcement was switched to
1920
+ * report-only, or `upgrade-insecure-requests` was dropped. Says nothing new to the visitor,
1921
+ * so nobody is asked again, but a person confirms that the loosening is wanted.
1922
+ */
1923
+ "csp.loosened": CONFIRM,
1924
+ "csp.tightened": NOT_MATERIAL,
1925
+ /** `reportUri` or `reportTo`. A third-party endpoint is a declared artefact with a diff of its own. */
1926
+ "csp.reporting_changed": NOT_MATERIAL,
1927
+ "csp.reason_changed": NOT_MATERIAL,
1928
+ // Consent receipts. Attributed to the consent purposes, whose decisions they prove. Where
1929
+ // receipts go says nothing new to the visitor; keeping none, or no longer saying whether any
1930
+ // are kept, gives up the proof of every decision, so a person confirms it.
1931
+ /** An endpoint where there was none, or an opt-out. */
1932
+ "receipts.endpoint_declared": NOT_MATERIAL,
1933
+ "receipts.endpoint_changed": NOT_MATERIAL,
1934
+ /** The opt-out, where there was an endpoint or no statement. */
1935
+ "receipts.opted_out": CONFIRM,
1936
+ /** The whole section is gone (only valid without consent purposes). */
1937
+ "receipts.removed": CONFIRM,
1938
+ "receipts.opt_out_reason_changed": NOT_MATERIAL,
1939
+ // Data subject requests. Attributed to the built-in purpose `subject-requests`. Offering a way
1940
+ // to exercise a right, or more of them, takes nothing from anyone; offering less of it, keeping
1941
+ // the record longer, or sending the requester's address to another provider is presumed fine
1942
+ // but a person confirms it.
1943
+ /** The section where there was none: requests can now be sent through the form. */
1944
+ "subject_requests.added": NOT_MATERIAL,
1945
+ /** The section is gone: the form and the request records with it. */
1946
+ "subject_requests.removed": CONFIRM,
1947
+ "subject_requests.type_added": NOT_MATERIAL,
1948
+ "subject_requests.type_removed": CONFIRM,
1949
+ "subject_requests.retention_shorter": NOT_MATERIAL,
1950
+ "subject_requests.retention_longer": CONFIRM,
1951
+ /** Not provably shorter or longer, e.g. "365d" against "1y". */
1952
+ "subject_requests.retention_changed": CONFIRM,
1953
+ "subject_requests.retention_reformatted": NOT_MATERIAL,
1954
+ "subject_requests.endpoint_changed": NOT_MATERIAL,
1955
+ /** Where requests are emailed: a wrong mailbox loses them, so a person confirms. */
1956
+ "subject_requests.notify_changed": CONFIRM,
1957
+ /** A provider now receives the requester's address (it did not before). */
1958
+ "subject_requests.requester_email_added": CONFIRM,
1959
+ "subject_requests.requester_email_removed": NOT_MATERIAL,
1960
+ "subject_requests.requester_email_processor_changed": CONFIRM,
1961
+ "subject_requests.unclassified_changed": MATERIAL,
1962
+ "purpose.added": MATERIAL,
1963
+ "purpose.removed": NOT_MATERIAL,
1964
+ "purpose.basis_changed": REVIEW,
1965
+ "purpose.title_changed": localizedText.changed,
1966
+ "purpose.title_formatting_changed": localizedText.formatting_changed,
1967
+ "purpose.title_locale_added": localizedText.locale_added,
1968
+ "purpose.title_locale_removed": localizedText.locale_removed,
1969
+ "purpose.description_changed": localizedText.changed,
1970
+ "purpose.description_formatting_changed": localizedText.formatting_changed,
1971
+ "purpose.description_locale_added": localizedText.locale_added,
1972
+ "purpose.description_locale_removed": localizedText.locale_removed,
1973
+ "purpose.data_category_added": MATERIAL,
1974
+ "purpose.data_category_removed": NOT_MATERIAL,
1975
+ "purpose.retention_longer": MATERIAL,
1976
+ "purpose.retention_shorter": NOT_MATERIAL,
1977
+ /** Not comparable (e.g. fixed vs until-withdrawn, different events). */
1978
+ "purpose.retention_changed": MATERIAL,
1979
+ /** Different spelling of the same duration. */
1980
+ "purpose.retention_reformatted": NOT_MATERIAL,
1981
+ "purpose.default_granted": MATERIAL,
1982
+ "purpose.default_denied": NOT_MATERIAL,
1983
+ /** The interest is stated where none was (only possible against a registry from before the field). */
1984
+ "purpose.legitimate_interest_added": MATERIAL,
1985
+ "purpose.legitimate_interest_removed": NOT_MATERIAL,
1986
+ "purpose.legitimate_interest_changed": localizedText.changed,
1987
+ "purpose.legitimate_interest_formatting_changed": localizedText.formatting_changed,
1988
+ "purpose.legitimate_interest_locale_added": localizedText.locale_added,
1989
+ "purpose.legitimate_interest_locale_removed": localizedText.locale_removed,
1990
+ /** `false` where nothing was stated: the notice gains a sentence, the processing is the same. */
1991
+ "purpose.adm_declared_none": CONFIRM,
1992
+ /** Automated decision-making where there was none (or none stated). */
1993
+ "purpose.adm_introduced": REVIEW,
1994
+ /** Its logic or consequences are described differently. */
1995
+ "purpose.adm_changed": MATERIAL,
1996
+ "purpose.adm_removed": NOT_MATERIAL,
1997
+ "purpose.data_subject_added": MATERIAL,
1998
+ "purpose.data_subject_removed": NOT_MATERIAL,
1999
+ /** A recipient listed under the purpose's `processors`. */
2000
+ "purpose.processor_added": MATERIAL,
2001
+ "purpose.processor_removed": NOT_MATERIAL,
2002
+ /** `processors` appears or disappears as an empty list: a statement, not a recipient. */
2003
+ "purpose.processors_stated": NOT_MATERIAL,
2004
+ "purpose.unclassified_changed": MATERIAL,
2005
+ "processor.added": MATERIAL,
2006
+ "processor.removed": NOT_MATERIAL,
2007
+ "processor.name_changed": MATERIAL,
2008
+ "processor.name_formatting_changed": NEUTRAL,
2009
+ "processor.legal_entity_changed": MATERIAL,
2010
+ "processor.legal_entity_formatting_changed": NEUTRAL,
2011
+ "processor.country_changed": MATERIAL,
2012
+ "processor.transfer_changed": MATERIAL,
2013
+ "processor.first_party_changed": MATERIAL,
2014
+ /** Processor, independent controller or joint controller: who decides what happens to the data. */
2015
+ "processor.role_changed": MATERIAL,
2016
+ /** dpaUrl, privacyUrl, subjectRequestProcess. */
2017
+ "processor.metadata_changed": CONFIRM,
2018
+ "processor.unclassified_changed": MATERIAL,
2019
+ "artefact.added": MATERIAL,
2020
+ "artefact.removed": NOT_MATERIAL,
2021
+ "artefact.kind_changed": MATERIAL,
2022
+ "artefact.purpose_added": MATERIAL,
2023
+ "artefact.purpose_removed": NOT_MATERIAL,
2024
+ "artefact.processor_added": MATERIAL,
2025
+ "artefact.processor_changed": MATERIAL,
2026
+ "artefact.processor_removed": NOT_MATERIAL,
2027
+ "artefact.description_changed": localizedText.changed,
2028
+ "artefact.description_formatting_changed": localizedText.formatting_changed,
2029
+ "artefact.description_locale_added": localizedText.locale_added,
2030
+ "artefact.description_locale_removed": localizedText.locale_removed,
2031
+ /** `src` of a script, iframe, stylesheet, font or media file; `url` of a pixel or endpoint. */
2032
+ "artefact.target_changed": MATERIAL,
2033
+ "artefact.unclassified_changed": MATERIAL,
2034
+ /** A different name, or a different pattern. */
2035
+ "cookie.matcher_changed": MATERIAL,
2036
+ /** `name` replaced by a `pattern`. */
2037
+ "cookie.matcher_broadened": MATERIAL,
2038
+ /** `pattern` replaced by a `name` the old pattern matched. */
2039
+ "cookie.matcher_narrowed": NOT_MATERIAL,
2040
+ "cookie.duration_longer": MATERIAL,
2041
+ "cookie.duration_shorter": NOT_MATERIAL,
2042
+ "cookie.duration_changed": MATERIAL,
2043
+ "cookie.duration_reformatted": NOT_MATERIAL,
2044
+ "cookie.domain_changed": MATERIAL,
2045
+ /** sameSite relaxed or unset, `secure` or `httpOnly` dropped. */
2046
+ "cookie.security_loosened": MATERIAL,
2047
+ "cookie.security_tightened": NOT_MATERIAL,
2048
+ "storage.matcher_changed": MATERIAL,
2049
+ "storage.matcher_broadened": MATERIAL,
2050
+ "storage.matcher_narrowed": NOT_MATERIAL,
2051
+ "storage.area_changed": MATERIAL,
2052
+ "storage.duration_longer": MATERIAL,
2053
+ "storage.duration_shorter": NOT_MATERIAL,
2054
+ "storage.duration_changed": MATERIAL,
2055
+ "storage.duration_reformatted": NOT_MATERIAL,
2056
+ /** A lifetime where the browser default applied before: a bound, never an extension. */
2057
+ "storage.duration_declared": NOT_MATERIAL,
2058
+ /** Back to the browser default, which for local storage and IndexedDB is "never expires". */
2059
+ "storage.duration_removed": MATERIAL,
2060
+ "collection_point.added": MATERIAL,
2061
+ "collection_point.removed": NOT_MATERIAL,
2062
+ "collection_point.description_changed": CONFIRM,
2063
+ "collection_point.title_changed": localizedText.changed,
2064
+ "collection_point.title_formatting_changed": localizedText.formatting_changed,
2065
+ "collection_point.title_locale_added": localizedText.locale_added,
2066
+ "collection_point.title_locale_removed": localizedText.locale_removed,
2067
+ "collection_point.unclassified_changed": MATERIAL,
2068
+ "collection_field.added": MATERIAL,
2069
+ "collection_field.removed": NOT_MATERIAL,
2070
+ /** Attributed to the field's new purpose. */
2071
+ "collection_field.purpose_changed": MATERIAL,
2072
+ /** Same edit, attributed to the purpose the field no longer serves. */
2073
+ "collection_field.purpose_dropped": NOT_MATERIAL,
2074
+ "collection_field.made_required": MATERIAL,
2075
+ "collection_field.made_optional": NOT_MATERIAL,
2076
+ "collection_field.notice_changed": localizedText.changed,
2077
+ "collection_field.notice_formatting_changed": localizedText.formatting_changed,
2078
+ "collection_field.notice_locale_added": localizedText.locale_added,
2079
+ "collection_field.notice_locale_removed": localizedText.locale_removed,
2080
+ /** Stated where nothing was (a registry from before the field). */
2081
+ "collection_field.provision_stated": CONFIRM,
2082
+ /** statutory, contractual or voluntary changed: the visitor was told something else. */
2083
+ "collection_field.provision_changed": MATERIAL,
2084
+ "collection_field.consequence_changed": localizedText.changed,
2085
+ "collection_field.consequence_formatting_changed": localizedText.formatting_changed,
2086
+ "collection_field.consequence_locale_added": localizedText.locale_added,
2087
+ "collection_field.consequence_locale_removed": localizedText.locale_removed,
2088
+ "collection_field.unclassified_changed": MATERIAL
2089
+ };
2090
+
2091
+ // src/diff/text.ts
2092
+ var FREE_PUNCTUATION = /(?<!\p{Nd})\p{P}(?!\p{Nd})/gu;
2093
+ function normalizeText(text) {
2094
+ return text.normalize("NFC").toLowerCase().replace(FREE_PUNCTUATION, " ").replace(/\s+/gu, " ").trim();
2095
+ }
2096
+ function isMeaningNeutral(before, after) {
2097
+ return normalizeText(before) === normalizeText(after);
2098
+ }
2099
+
2100
+ // src/diff/diff.ts
2101
+ function changeKey(kind, path) {
2102
+ return `${kind}@${path}`;
2103
+ }
2104
+ function diffRegistry(previous, next, overrides = {}) {
2105
+ const raw = [];
2106
+ const ctx = {
2107
+ previous,
2108
+ next,
2109
+ allPurposes: next.purposes.map((purpose) => purpose.id),
2110
+ emit: (kind, path, purposes, before, after, note) => {
2111
+ raw.push({ kind, path, purposes, before, after, note });
2112
+ }
2113
+ };
2114
+ diffTopLevel(ctx);
2115
+ diffPurposes(ctx);
2116
+ diffProcessors(ctx);
2117
+ diffArtefacts(ctx);
2118
+ diffCollectionPoints(ctx);
2119
+ const previousPurposes = byId(withBuiltIn(previous));
2120
+ const nextPurposes = byId(withBuiltIn(next));
2121
+ const rejectedOverrides = [];
2122
+ const seenKeys = /* @__PURE__ */ new Set();
2123
+ const changes = raw.map((change) => {
2124
+ const key = changeKey(change.kind, change.path);
2125
+ seenKeys.add(key);
2126
+ return classify(change, key, previousPurposes, nextPurposes, overrides, rejectedOverrides);
2127
+ });
2128
+ for (const key of Object.keys(overrides)) {
2129
+ if (seenKeys.has(key)) continue;
2130
+ const requested = overrides[key];
2131
+ rejectedOverrides.push({
2132
+ key,
2133
+ requested,
2134
+ reason: isClassification(requested) ? "unknown_change" : "invalid_classification"
2135
+ });
2136
+ }
2137
+ return {
2138
+ changes,
2139
+ // The built-in purpose has no version of its own to bump: it is checked as the section.
2140
+ ...summarise(changes, byId(previous.purposes), byId(next.purposes)),
2141
+ rejectedOverrides
2142
+ };
2143
+ }
2144
+ function nextRevision(previousRevision, diff) {
2145
+ if (!Number.isSafeInteger(previousRevision) || previousRevision < 0) {
2146
+ throw new RangeError(`revision must be a non-negative integer, got ${previousRevision}`);
2147
+ }
2148
+ return diff.reconsentRequired ? previousRevision + 1 : previousRevision;
2149
+ }
2150
+ var REGISTRY_KEYS = /* @__PURE__ */ new Set([
2151
+ "version",
2152
+ "controller",
2153
+ "locales",
2154
+ "defaultLocale",
2155
+ "purposes",
2156
+ "processors",
2157
+ "artefacts",
2158
+ "collectionPoints",
2159
+ "dataCategories",
2160
+ "dataSubjectCategories",
2161
+ "retentionEvents",
2162
+ "securityMeasures",
2163
+ "csp",
2164
+ "receipts",
2165
+ "subjectRequests"
2166
+ ]);
2167
+ var CONTROLLER_KINDS = {
2168
+ dpo: "controller.dpo_changed",
2169
+ supervisoryAuthority: "controller.supervisory_authority_changed",
2170
+ euRepresentative: "controller.eu_representative_changed"
2171
+ };
2172
+ function diffTopLevel(ctx) {
2173
+ const { previous, next, allPurposes, emit } = ctx;
2174
+ if (previous.version !== next.version) {
2175
+ emit("registry.format_version_changed", "version", allPurposes, previous.version, next.version);
2176
+ }
2177
+ for (const key of unionKeys(previous.controller, next.controller)) {
2178
+ const before = field(previous.controller, key);
2179
+ const after = field(next.controller, key);
2180
+ if (!deepEqual(before, after)) {
2181
+ emit(CONTROLLER_KINDS[key] ?? "controller.changed", `controller.${key}`, allPurposes, before, after);
2182
+ }
2183
+ }
2184
+ const { added, removed } = setDiff(previous.locales, next.locales);
2185
+ for (const locale2 of added) {
2186
+ emit("registry.locale_added", `locales.${locale2}`, allPurposes, void 0, locale2);
2187
+ }
2188
+ for (const locale2 of removed) {
2189
+ emit("registry.locale_removed", `locales.${locale2}`, allPurposes, locale2, void 0);
2190
+ }
2191
+ if (previous.defaultLocale !== next.defaultLocale) {
2192
+ emit(
2193
+ "registry.default_locale_changed",
2194
+ "defaultLocale",
2195
+ allPurposes,
2196
+ previous.defaultLocale,
2197
+ next.defaultLocale
2198
+ );
2199
+ }
2200
+ if (!deepEqual(previous.securityMeasures, next.securityMeasures)) {
2201
+ emit("registry.security_measures_changed", "securityMeasures", allPurposes, previous.securityMeasures, next.securityMeasures);
2202
+ }
2203
+ diffGlossaries(ctx);
2204
+ diffCsp(ctx);
2205
+ diffReceipts(ctx);
2206
+ diffSubjectRequests(ctx);
2207
+ diffUnknownKeys(ctx, "registry.unclassified_changed", "", allPurposes, previous, next, REGISTRY_KEYS);
2208
+ }
2209
+ function diffCsp(ctx) {
2210
+ const { previous, next, allPurposes, emit } = ctx;
2211
+ const loosenings = (registry) => {
2212
+ const out = /* @__PURE__ */ new Map();
2213
+ for (const entry of registry.csp?.allow ?? []) {
2214
+ for (const source of entry.sources) out.set(`allow.${entry.directive}.${source}`, entry.reason);
2215
+ }
2216
+ if (registry.csp?.reportOnly === true) out.set("reportOnly", void 0);
2217
+ if (registry.csp?.upgradeInsecureRequests === false) out.set("upgradeInsecureRequests", void 0);
2218
+ return out;
2219
+ };
2220
+ const before = loosenings(previous);
2221
+ const after = loosenings(next);
2222
+ const value = (key, registry) => key === "reportOnly" ? registry.csp?.reportOnly : key === "upgradeInsecureRequests" ? registry.csp?.upgradeInsecureRequests : void 0;
2223
+ for (const [key, reason] of after) {
2224
+ if (!before.has(key)) {
2225
+ emit("csp.loosened", `csp.${key}`, allPurposes, key.startsWith("allow.") ? void 0 : value(key, previous), key.startsWith("allow.") ? reason : value(key, next));
2226
+ } else if (before.get(key) !== reason) {
2227
+ emit("csp.reason_changed", `csp.${key}.reason`, allPurposes, before.get(key), reason);
2228
+ }
2229
+ }
2230
+ for (const [key, reason] of before) {
2231
+ if (!after.has(key)) {
2232
+ emit("csp.tightened", `csp.${key}`, allPurposes, key.startsWith("allow.") ? reason : value(key, previous), key.startsWith("allow.") ? void 0 : value(key, next));
2233
+ }
2234
+ }
2235
+ for (const key of ["reportUri", "reportTo"]) {
2236
+ if (previous.csp?.[key] !== next.csp?.[key]) {
2237
+ emit("csp.reporting_changed", `csp.${key}`, allPurposes, previous.csp?.[key], next.csp?.[key]);
2238
+ }
2239
+ }
2240
+ }
2241
+ function diffReceipts(ctx) {
2242
+ const { previous, next, emit } = ctx;
2243
+ const before = previous.receipts;
2244
+ const after = next.receipts;
2245
+ if (deepEqual(before, after)) return;
2246
+ const consent = unique([...previous.purposes, ...next.purposes].filter((purpose) => purpose.basis === "consent").map((purpose) => purpose.id));
2247
+ if (after === void 0) {
2248
+ emit("receipts.removed", "receipts", consent, before, void 0);
2249
+ } else if ("endpoint" in after) {
2250
+ if (before !== void 0 && "endpoint" in before) emit("receipts.endpoint_changed", "receipts.endpoint", consent, before.endpoint, after.endpoint);
2251
+ else emit("receipts.endpoint_declared", "receipts.endpoint", consent, before, after.endpoint);
2252
+ } else if (before !== void 0 && "optOut" in before) {
2253
+ emit("receipts.opt_out_reason_changed", "receipts.optOut.reason", consent, before.optOut.reason, after.optOut.reason);
2254
+ } else {
2255
+ emit("receipts.opted_out", "receipts.optOut", consent, before, after);
2256
+ }
2257
+ }
2258
+ var SUBJECT_REQUEST_KEYS = /* @__PURE__ */ new Set(["endpoint", "notify", "types", "retention", "requesterEmail"]);
2259
+ function diffSubjectRequests(ctx) {
2260
+ const { emit } = ctx;
2261
+ const before = ctx.previous.subjectRequests;
2262
+ const after = ctx.next.subjectRequests;
2263
+ if (deepEqual(before, after)) return;
2264
+ const self = [SUBJECT_REQUESTS_PURPOSE_ID];
2265
+ const path = "subjectRequests";
2266
+ if (before === void 0) return emit("subject_requests.added", path, self, void 0, after);
2267
+ if (after === void 0) return emit("subject_requests.removed", path, self, before, void 0);
2268
+ if (before.endpoint !== after.endpoint) emit("subject_requests.endpoint_changed", `${path}.endpoint`, self, before.endpoint, after.endpoint);
2269
+ if (before.notify !== after.notify) emit("subject_requests.notify_changed", `${path}.notify`, self, before.notify, after.notify);
2270
+ const types = setDiff(before.types, after.types);
2271
+ for (const type of types.added) emit("subject_requests.type_added", `${path}.types.${type}`, self, void 0, type);
2272
+ for (const type of types.removed) emit("subject_requests.type_removed", `${path}.types.${type}`, self, type, void 0);
2273
+ if (before.retention !== after.retention) {
2274
+ const suffix = { equal: "reformatted", longer: "longer", shorter: "shorter", incomparable: "changed" }[compareDurations(before.retention, after.retention)];
2275
+ emit(`subject_requests.retention_${suffix}`, `${path}.retention`, self, before.retention, after.retention);
2276
+ }
2277
+ const was = before.requesterEmail?.processor;
2278
+ const is = after.requesterEmail?.processor;
2279
+ if (was === void 0 && is !== void 0) emit("subject_requests.requester_email_added", `${path}.requesterEmail`, self, before.requesterEmail, after.requesterEmail);
2280
+ else if (was !== void 0 && is === void 0) emit("subject_requests.requester_email_removed", `${path}.requesterEmail`, self, before.requesterEmail, after.requesterEmail);
2281
+ else if (was !== is) emit("subject_requests.requester_email_processor_changed", `${path}.requesterEmail.processor`, self, was, is);
2282
+ if (before.requesterEmail !== void 0 && after.requesterEmail !== void 0) {
2283
+ diffUnknownKeys(ctx, "subject_requests.unclassified_changed", `${path}.requesterEmail`, self, before.requesterEmail, after.requesterEmail, /* @__PURE__ */ new Set(["processor"]));
2284
+ }
2285
+ diffUnknownKeys(ctx, "subject_requests.unclassified_changed", path, self, before, after, SUBJECT_REQUEST_KEYS);
2286
+ }
2287
+ function withBuiltIn(registry) {
2288
+ const builtIn = subjectRequestPurpose(registry);
2289
+ return builtIn === void 0 ? registry.purposes : [...registry.purposes, { ...builtIn, title: {}, description: {} }];
2290
+ }
2291
+ function diffGlossaries(ctx) {
2292
+ const { previous, next, emit } = ctx;
2293
+ const using = (uses) => next.purposes.filter(uses).map((purpose) => purpose.id);
2294
+ const entries = (map) => Object.entries(map ?? {});
2295
+ const each = (before, after, visit) => {
2296
+ const was = new Map(entries(before));
2297
+ const is = new Map(entries(after));
2298
+ for (const id2 of unique([...is.keys(), ...was.keys()])) visit(id2, was.get(id2), is.get(id2));
2299
+ };
2300
+ each(previous.dataCategories, next.dataCategories, (id2, was, is) => {
2301
+ const path = `dataCategories.${id2}`;
2302
+ const purposes = using((purpose) => purpose.dataCategories.includes(id2));
2303
+ if (!was) emit("data_category.added", path, purposes, void 0, is);
2304
+ if (!is) return emit("data_category.removed", path, purposes, was, void 0);
2305
+ if (was) diffText(ctx, "data_category.title", `${path}.title`, purposes, was.title, is.title);
2306
+ if (Boolean(was?.special) !== Boolean(is.special)) {
2307
+ emit(is.special ? "data_category.special_flagged" : "data_category.special_unflagged", `${path}.special`, purposes, was?.special, is.special);
2308
+ }
2309
+ });
2310
+ each(previous.dataSubjectCategories, next.dataSubjectCategories, (id2, was, is) => {
2311
+ const path = `dataSubjectCategories.${id2}`;
2312
+ const purposes = using((purpose) => (purpose.dataSubjects ?? []).includes(id2));
2313
+ if (!was) return emit("data_subject_category.added", path, purposes, void 0, is);
2314
+ if (!is) return emit("data_subject_category.removed", path, purposes, was, void 0);
2315
+ diffText(ctx, "data_subject_category.title", `${path}.title`, purposes, was.title, is.title);
2316
+ });
2317
+ each(previous.retentionEvents, next.retentionEvents, (id2, was, is) => {
2318
+ const path = `retentionEvents.${id2}`;
2319
+ const purposes = using((purpose) => durationEvent(parseDuration(purpose.retention)) === id2);
2320
+ if (!was) return emit("retention_event.added", path, purposes, void 0, is);
2321
+ if (!is) return emit("retention_event.removed", path, purposes, was, void 0);
2322
+ diffText(ctx, "retention_event.description", path, purposes, was, is);
2323
+ });
2324
+ }
2325
+ var PURPOSE_KEYS = /* @__PURE__ */ new Set([
2326
+ "id",
2327
+ "version",
2328
+ "basis",
2329
+ "title",
2330
+ "description",
2331
+ "dataCategories",
2332
+ "retention",
2333
+ "default",
2334
+ "legitimateInterest",
2335
+ "automatedDecisionMaking",
2336
+ "dataSubjects",
2337
+ "processors"
2338
+ ]);
2339
+ function diffPurposes(ctx) {
2340
+ const { emit } = ctx;
2341
+ pair(ctx.previous.purposes, ctx.next.purposes, (before, after, id2) => {
2342
+ const path = `purposes.${id2}`;
2343
+ const self = [id2];
2344
+ if (!before) return emit("purpose.added", path, self, void 0, after);
2345
+ if (!after) return emit("purpose.removed", path, self, before, void 0);
2346
+ if (before.basis !== after.basis) {
2347
+ emit("purpose.basis_changed", `${path}.basis`, self, before.basis, after.basis);
2348
+ }
2349
+ diffText(ctx, "purpose.title", `${path}.title`, self, before.title, after.title);
2350
+ diffText(ctx, "purpose.description", `${path}.description`, self, before.description, after.description);
2351
+ const categories = setDiff(before.dataCategories, after.dataCategories);
2352
+ for (const category of categories.added) {
2353
+ emit("purpose.data_category_added", `${path}.dataCategories.${category}`, self, void 0, category);
2354
+ }
2355
+ for (const category of categories.removed) {
2356
+ emit("purpose.data_category_removed", `${path}.dataCategories.${category}`, self, category, void 0);
2357
+ }
2358
+ diffDuration(ctx, "purpose.retention", `${path}.retention`, self, before.retention, after.retention);
2359
+ const defaultBefore = before.default ?? "denied";
2360
+ const defaultAfter = after.default ?? "denied";
2361
+ if (defaultBefore !== defaultAfter) {
2362
+ emit(
2363
+ defaultAfter === "denied" ? "purpose.default_denied" : "purpose.default_granted",
2364
+ `${path}.default`,
2365
+ self,
2366
+ before.default,
2367
+ after.default
2368
+ );
2369
+ }
2370
+ if (before.legitimateInterest === void 0 && after.legitimateInterest !== void 0) {
2371
+ emit("purpose.legitimate_interest_added", `${path}.legitimateInterest`, self, void 0, after.legitimateInterest);
2372
+ } else if (before.legitimateInterest !== void 0 && after.legitimateInterest === void 0) {
2373
+ emit("purpose.legitimate_interest_removed", `${path}.legitimateInterest`, self, before.legitimateInterest, void 0);
2374
+ } else {
2375
+ diffText(ctx, "purpose.legitimate_interest", `${path}.legitimateInterest`, self, before.legitimateInterest, after.legitimateInterest);
2376
+ }
2377
+ const admBefore = before.automatedDecisionMaking;
2378
+ const admAfter = after.automatedDecisionMaking;
2379
+ if (!deepEqual(admBefore, admAfter)) {
2380
+ const had = admBefore !== void 0 && admBefore !== false;
2381
+ const has = admAfter !== void 0 && admAfter !== false;
2382
+ const kind = has ? had ? "purpose.adm_changed" : "purpose.adm_introduced" : had ? "purpose.adm_removed" : "purpose.adm_declared_none";
2383
+ emit(kind, `${path}.automatedDecisionMaking`, self, admBefore, admAfter);
2384
+ }
2385
+ const subjects = setDiff(before.dataSubjects ?? [], after.dataSubjects ?? []);
2386
+ for (const subject of subjects.added) {
2387
+ emit("purpose.data_subject_added", `${path}.dataSubjects.${subject}`, self, void 0, subject);
2388
+ }
2389
+ for (const subject of subjects.removed) {
2390
+ emit("purpose.data_subject_removed", `${path}.dataSubjects.${subject}`, self, subject, void 0);
2391
+ }
2392
+ const recipients = setDiff(before.processors ?? [], after.processors ?? []);
2393
+ for (const processor of recipients.added) {
2394
+ emit("purpose.processor_added", `${path}.processors.${processor}`, self, void 0, processor);
2395
+ }
2396
+ for (const processor of recipients.removed) {
2397
+ emit("purpose.processor_removed", `${path}.processors.${processor}`, self, processor, void 0);
2398
+ }
2399
+ if (before.processors === void 0 !== (after.processors === void 0) && recipients.added.length + recipients.removed.length === 0) {
2400
+ emit("purpose.processors_stated", `${path}.processors`, self, before.processors, after.processors);
2401
+ }
2402
+ diffUnknownKeys(ctx, "purpose.unclassified_changed", path, self, before, after, PURPOSE_KEYS);
2403
+ });
2404
+ }
2405
+ var PROCESSOR_KEYS = /* @__PURE__ */ new Set([
2406
+ "id",
2407
+ "name",
2408
+ "role",
2409
+ "legalEntity",
2410
+ "country",
2411
+ "firstParty",
2412
+ "transferMechanism",
2413
+ "dpaUrl",
2414
+ "privacyUrl",
2415
+ "subjectRequestProcess"
2416
+ ]);
2417
+ var UNATTRIBUTED_PROCESSOR = "No artefact uses this processor and no purpose lists it, so the change cannot be attributed and is charged to every purpose.";
2418
+ function diffProcessors(ctx) {
2419
+ const { emit } = ctx;
2420
+ const usedBy = (registry, processorId) => unique([
2421
+ ...registry.artefacts.filter((artefact2) => artefact2.processor === processorId).flatMap((artefact2) => artefact2.purposes),
2422
+ ...withBuiltIn(registry).filter((purpose) => (purpose.processors ?? []).includes(processorId)).map((purpose) => purpose.id)
2423
+ ]);
2424
+ pair(ctx.previous.processors, ctx.next.processors, (before, after, id2) => {
2425
+ const path = `processors.${id2}`;
2426
+ if (!after) {
2427
+ return emit("processor.removed", path, usedBy(ctx.previous, id2), before, void 0);
2428
+ }
2429
+ const users = usedBy(ctx.next, id2);
2430
+ const purposes = users.length > 0 ? users : ctx.allPurposes;
2431
+ const note = users.length > 0 ? void 0 : UNATTRIBUTED_PROCESSOR;
2432
+ const changed = (kind, key) => {
2433
+ emit(kind, `${path}.${key}`, purposes, before?.[key], after[key], note);
2434
+ };
2435
+ if (!before) return emit("processor.added", path, purposes, void 0, after, note);
2436
+ if (before.name !== after.name) {
2437
+ changed(
2438
+ isMeaningNeutral(before.name, after.name) ? "processor.name_formatting_changed" : "processor.name_changed",
2439
+ "name"
2440
+ );
2441
+ }
2442
+ if (before.legalEntity !== after.legalEntity) {
2443
+ const neutral = before.legalEntity !== void 0 && after.legalEntity !== void 0 && isMeaningNeutral(before.legalEntity, after.legalEntity);
2444
+ changed(
2445
+ neutral ? "processor.legal_entity_formatting_changed" : "processor.legal_entity_changed",
2446
+ "legalEntity"
2447
+ );
2448
+ }
2449
+ if (before.country !== after.country) changed("processor.country_changed", "country");
2450
+ if (before.transferMechanism !== after.transferMechanism) {
2451
+ changed("processor.transfer_changed", "transferMechanism");
2452
+ }
2453
+ if (Boolean(before.firstParty) !== Boolean(after.firstParty)) {
2454
+ changed("processor.first_party_changed", "firstParty");
2455
+ }
2456
+ if ((before.role ?? "processor") !== (after.role ?? "processor")) changed("processor.role_changed", "role");
2457
+ for (const key of ["dpaUrl", "privacyUrl", "subjectRequestProcess"]) {
2458
+ if (before[key] !== after[key]) changed("processor.metadata_changed", key);
2459
+ }
2460
+ diffUnknownKeys(ctx, "processor.unclassified_changed", path, purposes, before, after, PROCESSOR_KEYS, note);
2461
+ });
2462
+ }
2463
+ var ARTEFACT_BASE_KEYS = ["id", "kind", "purposes", "processor", "description"];
2464
+ var ARTEFACT_KEYS = {
2465
+ script: /* @__PURE__ */ new Set([...ARTEFACT_BASE_KEYS, "src"]),
2466
+ cookie: /* @__PURE__ */ new Set([
2467
+ ...ARTEFACT_BASE_KEYS,
2468
+ "name",
2469
+ "pattern",
2470
+ "duration",
2471
+ "domain",
2472
+ "sameSite",
2473
+ "secure",
2474
+ "httpOnly"
2475
+ ]),
2476
+ storage: /* @__PURE__ */ new Set([...ARTEFACT_BASE_KEYS, "area", "key", "pattern", "duration"]),
2477
+ iframe: /* @__PURE__ */ new Set([...ARTEFACT_BASE_KEYS, "src"]),
2478
+ pixel: /* @__PURE__ */ new Set([...ARTEFACT_BASE_KEYS, "url"]),
2479
+ endpoint: /* @__PURE__ */ new Set([...ARTEFACT_BASE_KEYS, "url"]),
2480
+ stylesheet: /* @__PURE__ */ new Set([...ARTEFACT_BASE_KEYS, "src"]),
2481
+ font: /* @__PURE__ */ new Set([...ARTEFACT_BASE_KEYS, "src"]),
2482
+ media: /* @__PURE__ */ new Set([...ARTEFACT_BASE_KEYS, "src"])
2483
+ };
2484
+ function diffArtefacts(ctx) {
2485
+ const { emit } = ctx;
2486
+ pair(ctx.previous.artefacts, ctx.next.artefacts, (before, after, id2) => {
2487
+ const path = `artefacts.${id2}`;
2488
+ if (!before) return emit("artefact.added", path, after.purposes, void 0, after);
2489
+ if (!after) return emit("artefact.removed", path, before.purposes, before, void 0);
2490
+ const purposes = after.purposes;
2491
+ const bound = setDiff(before.purposes, after.purposes);
2492
+ for (const purpose of bound.added) {
2493
+ emit("artefact.purpose_added", `${path}.purposes.${purpose}`, [purpose], void 0, purpose);
2494
+ }
2495
+ for (const purpose of bound.removed) {
2496
+ emit("artefact.purpose_removed", `${path}.purposes.${purpose}`, [purpose], purpose, void 0);
2497
+ }
2498
+ if (before.processor !== after.processor) {
2499
+ const kind = before.processor === void 0 ? "artefact.processor_added" : after.processor === void 0 ? "artefact.processor_removed" : "artefact.processor_changed";
2500
+ emit(kind, `${path}.processor`, purposes, before.processor, after.processor);
2501
+ }
2502
+ diffText(ctx, "artefact.description", `${path}.description`, purposes, before.description, after.description);
2503
+ if (before.kind !== after.kind) {
2504
+ emit("artefact.kind_changed", `${path}.kind`, unique([...before.purposes, ...purposes]), before, after);
2505
+ return;
2506
+ }
2507
+ diffArtefactDetails(ctx, path, purposes, before, after);
2508
+ diffUnknownKeys(ctx, "artefact.unclassified_changed", path, purposes, before, after, ARTEFACT_KEYS[after.kind]);
2509
+ });
2510
+ }
2511
+ function diffArtefactDetails(ctx, path, purposes, before, after) {
2512
+ const { emit } = ctx;
2513
+ if ("src" in before && "src" in after) {
2514
+ if (before.src !== after.src) {
2515
+ emit("artefact.target_changed", `${path}.src`, purposes, before.src, after.src);
2516
+ }
2517
+ } else if (before.kind === "pixel" && after.kind === "pixel" || before.kind === "endpoint" && after.kind === "endpoint") {
2518
+ if (before.url !== after.url) {
2519
+ emit("artefact.target_changed", `${path}.url`, purposes, before.url, after.url);
2520
+ }
2521
+ } else if (before.kind === "storage" && after.kind === "storage") {
2522
+ if (before.area !== after.area) {
2523
+ emit("storage.area_changed", `${path}.area`, purposes, before.area, after.area);
2524
+ }
2525
+ diffMatcher(ctx, "storage", "key", path, purposes, before.key, before.pattern, after.key, after.pattern);
2526
+ if (before.duration === void 0 && after.duration !== void 0) {
2527
+ emit("storage.duration_declared", `${path}.duration`, purposes, void 0, after.duration);
2528
+ } else if (before.duration !== void 0 && after.duration === void 0) {
2529
+ emit("storage.duration_removed", `${path}.duration`, purposes, before.duration, void 0);
2530
+ } else if (before.duration !== void 0 && after.duration !== void 0) {
2531
+ diffDuration(ctx, "storage.duration", `${path}.duration`, purposes, before.duration, after.duration);
2532
+ }
2533
+ } else if (before.kind === "cookie" && after.kind === "cookie") {
2534
+ diffMatcher(ctx, "cookie", "name", path, purposes, before.name, before.pattern, after.name, after.pattern);
2535
+ diffDuration(ctx, "cookie.duration", `${path}.duration`, purposes, before.duration, after.duration);
2536
+ if (before.domain !== after.domain) {
2537
+ emit("cookie.domain_changed", `${path}.domain`, purposes, before.domain, after.domain);
2538
+ }
2539
+ if (before.sameSite !== after.sameSite) {
2540
+ emit(
2541
+ sameSiteTightened(before.sameSite, after.sameSite) ? "cookie.security_tightened" : "cookie.security_loosened",
2542
+ `${path}.sameSite`,
2543
+ purposes,
2544
+ before.sameSite,
2545
+ after.sameSite
2546
+ );
2547
+ }
2548
+ for (const flag of ["secure", "httpOnly"]) {
2549
+ if (Boolean(before[flag]) !== Boolean(after[flag])) {
2550
+ emit(
2551
+ after[flag] ? "cookie.security_tightened" : "cookie.security_loosened",
2552
+ `${path}.${flag}`,
2553
+ purposes,
2554
+ before[flag],
2555
+ after[flag]
2556
+ );
2557
+ }
2558
+ }
2559
+ }
2560
+ }
2561
+ var SAME_SITE_RANK = { Strict: 0, Lax: 1, None: 2 };
2562
+ function sameSiteTightened(before, after) {
2563
+ const afterRank = after === void 0 ? void 0 : SAME_SITE_RANK[after];
2564
+ if (afterRank === void 0) return false;
2565
+ if (afterRank === 0) return true;
2566
+ const beforeRank = before === void 0 ? void 0 : SAME_SITE_RANK[before];
2567
+ return beforeRank !== void 0 && afterRank < beforeRank;
2568
+ }
2569
+ function diffMatcher(ctx, prefix, exactKey, path, purposes, exactBefore, patternBefore, exactAfter, patternAfter) {
2570
+ if (exactBefore === exactAfter && patternBefore === patternAfter) return;
2571
+ const wasExact = exactBefore !== void 0 && patternBefore === void 0;
2572
+ const wasPattern = patternBefore !== void 0 && exactBefore === void 0;
2573
+ const isExact = exactAfter !== void 0 && patternAfter === void 0;
2574
+ const isPattern = patternAfter !== void 0 && exactAfter === void 0;
2575
+ let kind = "matcher_changed";
2576
+ if (wasExact && isPattern) kind = "matcher_broadened";
2577
+ else if (wasPattern && isExact && patternMatches(patternBefore, exactAfter)) kind = "matcher_narrowed";
2578
+ ctx.emit(
2579
+ `${prefix}.${kind}`,
2580
+ `${path}.matcher`,
2581
+ purposes,
2582
+ { [exactKey]: exactBefore, pattern: patternBefore },
2583
+ { [exactKey]: exactAfter, pattern: patternAfter }
2584
+ );
2585
+ }
2586
+ function patternMatches(pattern, value) {
2587
+ try {
2588
+ return new RegExp(pattern).test(value);
2589
+ } catch {
2590
+ return false;
2591
+ }
2592
+ }
2593
+ var COLLECTION_POINT_KEYS = /* @__PURE__ */ new Set(["id", "title", "description", "fields"]);
2594
+ var COLLECTION_FIELD_KEYS = /* @__PURE__ */ new Set(["name", "purpose", "required", "notice", "provision", "consequence"]);
2595
+ function diffCollectionPoints(ctx) {
2596
+ const { emit } = ctx;
2597
+ const purposesOf = (point) => unique(point.fields.map((entry) => entry.purpose));
2598
+ pair(ctx.previous.collectionPoints, ctx.next.collectionPoints, (before, after, id2) => {
2599
+ const path = `collectionPoints.${id2}`;
2600
+ if (!before) return emit("collection_point.added", path, purposesOf(after), void 0, after);
2601
+ if (!after) return emit("collection_point.removed", path, purposesOf(before), before, void 0);
2602
+ const pointPurposes = purposesOf(after);
2603
+ if (before.description !== after.description) {
2604
+ emit(
2605
+ "collection_point.description_changed",
2606
+ `${path}.description`,
2607
+ pointPurposes,
2608
+ before.description,
2609
+ after.description
2610
+ );
2611
+ }
2612
+ diffText(ctx, "collection_point.title", `${path}.title`, pointPurposes, before.title, after.title);
2613
+ pair(
2614
+ before.fields.map(keyedByName),
2615
+ after.fields.map(keyedByName),
2616
+ (fieldBefore, fieldAfter, name) => {
2617
+ const fieldPath = `${path}.fields.${name}`;
2618
+ if (!fieldBefore) {
2619
+ return emit("collection_field.added", fieldPath, [fieldAfter.purpose], void 0, fieldAfter);
2620
+ }
2621
+ if (!fieldAfter) {
2622
+ return emit("collection_field.removed", fieldPath, [fieldBefore.purpose], fieldBefore, void 0);
2623
+ }
2624
+ const purposes = [fieldAfter.purpose];
2625
+ if (fieldBefore.purpose !== fieldAfter.purpose) {
2626
+ const args = [`${fieldPath}.purpose`, fieldBefore.purpose, fieldAfter.purpose];
2627
+ emit("collection_field.purpose_changed", args[0], purposes, args[1], args[2]);
2628
+ emit("collection_field.purpose_dropped", args[0], [fieldBefore.purpose], args[1], args[2]);
2629
+ }
2630
+ if (Boolean(fieldBefore.required) !== Boolean(fieldAfter.required)) {
2631
+ emit(
2632
+ fieldAfter.required ? "collection_field.made_required" : "collection_field.made_optional",
2633
+ `${fieldPath}.required`,
2634
+ purposes,
2635
+ fieldBefore.required,
2636
+ fieldAfter.required
2637
+ );
2638
+ }
2639
+ diffText(ctx, "collection_field.notice", `${fieldPath}.notice`, purposes, fieldBefore.notice, fieldAfter.notice);
2640
+ if (fieldBefore.provision !== fieldAfter.provision) {
2641
+ emit(
2642
+ fieldBefore.provision === void 0 ? "collection_field.provision_stated" : "collection_field.provision_changed",
2643
+ `${fieldPath}.provision`,
2644
+ purposes,
2645
+ fieldBefore.provision,
2646
+ fieldAfter.provision
2647
+ );
2648
+ }
2649
+ diffText(ctx, "collection_field.consequence", `${fieldPath}.consequence`, purposes, fieldBefore.consequence, fieldAfter.consequence);
2650
+ diffUnknownKeys(
2651
+ ctx,
2652
+ "collection_field.unclassified_changed",
2653
+ fieldPath,
2654
+ purposes,
2655
+ fieldBefore,
2656
+ fieldAfter,
2657
+ COLLECTION_FIELD_KEYS
2658
+ );
2659
+ }
2660
+ );
2661
+ diffUnknownKeys(
2662
+ ctx,
2663
+ "collection_point.unclassified_changed",
2664
+ path,
2665
+ pointPurposes,
2666
+ before,
2667
+ after,
2668
+ COLLECTION_POINT_KEYS
2669
+ );
2670
+ });
2671
+ }
2672
+ function keyedByName(entry) {
2673
+ return { ...entry, id: entry.name };
2674
+ }
2675
+ function diffText(ctx, textField, path, purposes, before, after) {
2676
+ for (const locale2 of unionKeys(before ?? {}, after ?? {})) {
2677
+ const textBefore = before?.[locale2];
2678
+ const textAfter = after?.[locale2];
2679
+ if (textBefore === textAfter) continue;
2680
+ const suffix = textBefore === void 0 ? "locale_added" : textAfter === void 0 ? "locale_removed" : isMeaningNeutral(textBefore, textAfter) ? "formatting_changed" : "changed";
2681
+ ctx.emit(`${textField}_${suffix}`, `${path}.${locale2}`, purposes, textBefore, textAfter);
2682
+ }
2683
+ }
2684
+ function diffDuration(ctx, durationField, path, purposes, before, after) {
2685
+ if (before === after) return;
2686
+ const suffix = { equal: "reformatted", longer: "longer", shorter: "shorter", incomparable: "changed" }[compareDurations(before, after)];
2687
+ ctx.emit(`${durationField}_${suffix}`, path, purposes, before, after);
2688
+ }
2689
+ function diffUnknownKeys(ctx, kind, path, purposes, before, after, known, note) {
2690
+ for (const key of unionKeys(before, after)) {
2691
+ if (known.has(key)) continue;
2692
+ const valueBefore = field(before, key);
2693
+ const valueAfter = field(after, key);
2694
+ if (!deepEqual(valueBefore, valueAfter)) {
2695
+ ctx.emit(kind, path === "" ? key : `${path}.${key}`, purposes, valueBefore, valueAfter, note);
2696
+ }
2697
+ }
2698
+ }
2699
+ function classify(raw, key, previousPurposes, nextPurposes, overrides, rejected) {
2700
+ const rule = CHANGE_KINDS[raw.kind];
2701
+ const defaults = unique(raw.purposes).flatMap((id2) => {
2702
+ const before = previousPurposes.get(id2);
2703
+ const after = nextPurposes.get(id2);
2704
+ const purpose = after ?? before;
2705
+ if (!purpose) return [];
2706
+ const consent = before?.basis === "consent" || after?.basis === "consent";
2707
+ const classification = consent ? rule.consent : rule.nonConsent;
2708
+ return [{ id: id2, basis: purpose.basis, consent, classification }];
2709
+ });
2710
+ const defaultClassification = defaults.length ? defaults.map((entry) => entry.classification).reduce(strictest) : strictest(rule.consent, rule.nonConsent);
2711
+ let escalation;
2712
+ if (Object.hasOwn(overrides, key)) {
2713
+ const requested = overrides[key];
2714
+ if (!isClassification(requested)) {
2715
+ rejected.push({ key, requested, current: defaultClassification, reason: "invalid_classification" });
2716
+ } else if (severity(requested) < severity(defaultClassification)) {
2717
+ rejected.push({ key, requested, current: defaultClassification, reason: "downgrade" });
2718
+ } else if (severity(requested) > severity(defaultClassification)) {
2719
+ escalation = requested;
2720
+ }
2721
+ }
2722
+ const affectedPurposes = defaults.map((entry) => {
2723
+ const classification = escalation ?? entry.classification;
2724
+ return { ...entry, classification, consequence: consequenceOf(classification, entry.consent) };
2725
+ });
2726
+ const change = {
2727
+ key,
2728
+ kind: raw.kind,
2729
+ path: raw.path,
2730
+ classification: escalation ?? defaultClassification,
2731
+ defaultClassification,
2732
+ escalated: escalation !== void 0,
2733
+ affectedPurposes,
2734
+ before: raw.before,
2735
+ after: raw.after
2736
+ };
2737
+ if (raw.note !== void 0) change.note = raw.note;
2738
+ return change;
2739
+ }
2740
+ function consequenceOf(classification, consent) {
2741
+ switch (classification) {
2742
+ case "needs_review":
2743
+ return "human_review";
2744
+ case "material":
2745
+ return consent ? "reconsent" : "notice_update";
2746
+ case "needs_confirmation":
2747
+ return "confirmation";
2748
+ case "not_material":
2749
+ return "changelog";
2750
+ }
2751
+ }
2752
+ function summarise(changes, previousPurposes, nextPurposes) {
2753
+ const materiallyChanged = /* @__PURE__ */ new Set();
2754
+ let reconsentRequired = false;
2755
+ for (const change of changes) {
2756
+ for (const affected of change.affectedPurposes) {
2757
+ if (!isMaterial(affected.classification)) continue;
2758
+ materiallyChanged.add(affected.id);
2759
+ if (affected.consent) reconsentRequired = true;
2760
+ }
2761
+ }
2762
+ const purposesNeedingBump = [];
2763
+ const missingVersionBumps = [];
2764
+ const unnecessaryBumps = [];
2765
+ const versionIssues = [];
2766
+ for (const [id2, after] of [...nextPurposes].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) {
2767
+ const before = previousPurposes.get(id2);
2768
+ const nextVersion = after.version;
2769
+ if (!before) {
2770
+ if (nextVersion !== 1) {
2771
+ versionIssues.push({
2772
+ purposeId: id2,
2773
+ code: "initial_version_not_one",
2774
+ severity: "warning",
2775
+ nextVersion,
2776
+ message: `New purpose "${id2}" starts at version ${nextVersion}; purposes start at 1.`
2777
+ });
2778
+ }
2779
+ continue;
2780
+ }
2781
+ const previousVersion = before.version;
2782
+ const versions = { purposeId: id2, previousVersion, nextVersion };
2783
+ const needsBump = materiallyChanged.has(id2);
2784
+ if (needsBump) purposesNeedingBump.push(id2);
2785
+ if (needsBump && !(nextVersion > previousVersion)) missingVersionBumps.push(id2);
2786
+ if (!needsBump && nextVersion > previousVersion) unnecessaryBumps.push(id2);
2787
+ if (nextVersion < previousVersion) {
2788
+ versionIssues.push({
2789
+ ...versions,
2790
+ code: "version_decreased",
2791
+ severity: "error",
2792
+ message: `Purpose "${id2}" went from version ${previousVersion} down to ${nextVersion}; versions never decrease.`
2793
+ });
2794
+ } else if (nextVersion > previousVersion + 1) {
2795
+ versionIssues.push({
2796
+ ...versions,
2797
+ code: "version_skipped",
2798
+ severity: "error",
2799
+ message: `Purpose "${id2}" jumped from version ${previousVersion} to ${nextVersion}; a release bumps by exactly 1.`
2800
+ });
2801
+ } else if (needsBump && nextVersion === previousVersion) {
2802
+ versionIssues.push({
2803
+ ...versions,
2804
+ code: "missing_bump",
2805
+ severity: "error",
2806
+ message: `Purpose "${id2}" changed materially but is still at version ${previousVersion}; bump it to ${previousVersion + 1}.`
2807
+ });
2808
+ } else if (!needsBump && nextVersion === previousVersion + 1) {
2809
+ versionIssues.push({
2810
+ ...versions,
2811
+ code: "unnecessary_bump",
2812
+ severity: "warning",
2813
+ message: `Purpose "${id2}" was bumped to version ${nextVersion} without a material change; the bump asks users to consent again for no reason.`
2814
+ });
2815
+ }
2816
+ }
2817
+ return {
2818
+ purposesNeedingBump,
2819
+ missingVersionBumps,
2820
+ unnecessaryBumps,
2821
+ versionIssues,
2822
+ reconsentRequired,
2823
+ blocked: changes.some((change) => change.classification === "needs_review")
2824
+ };
2825
+ }
2826
+ function byId(items) {
2827
+ return new Map(items.map((item) => [item.id, item]));
2828
+ }
2829
+ function pair(previous, next, visit) {
2830
+ const before = byId(previous);
2831
+ const after = byId(next);
2832
+ for (const [id2, item] of after) visit(before.get(id2), item, id2);
2833
+ for (const [id2, item] of before) if (!after.has(id2)) visit(item, void 0, id2);
2834
+ }
2835
+ function unique(items) {
2836
+ return [...new Set(items)];
2837
+ }
2838
+ function setDiff(before, after) {
2839
+ const was = new Set(before);
2840
+ const is = new Set(after);
2841
+ return {
2842
+ added: [...is].filter((item) => !was.has(item)),
2843
+ removed: [...was].filter((item) => !is.has(item))
2844
+ };
2845
+ }
2846
+ function unionKeys(before, after) {
2847
+ return unique([...Object.keys(after), ...Object.keys(before)]);
2848
+ }
2849
+ function field(holder, key) {
2850
+ return Object.hasOwn(holder, key) ? holder[key] : void 0;
2851
+ }
2852
+ function deepEqual(a, b) {
2853
+ if (a === b) return true;
2854
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
2855
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
2856
+ if (Array.isArray(a) && Array.isArray(b)) {
2857
+ return a.length === b.length && a.every((item, index) => deepEqual(item, b[index]));
2858
+ }
2859
+ return unionKeys(a, b).every((key) => deepEqual(field(a, key), field(b, key)));
2860
+ }
2861
+
2862
+ export { CHANGE_KINDS, CLASSIFICATIONS, COOKIE_DURATION_PATTERN, CSP_DIRECTIVES, EEA_COUNTRIES, EMAIL_PATTERN, ID_PATTERN, MAX_EMAIL_LENGTH, RETENTION_PATTERN, RULES, SUBJECT_REQUESTS_PURPOSE_ID, SUBJECT_REQUEST_CLOSED_EVENT, SUBJECT_REQUEST_DATA_CATEGORIES, SUBJECT_REQUEST_DATA_SUBJECT, SUBJECT_REQUEST_RETENTION_PATTERN, SUBJECT_REQUEST_TYPES, VAGUE_PURPOSE_PHRASES, VAGUE_REASON_PHRASES, changeKey, compareDurations, compareSemver, diffRegistry, durationEvent, fillPlaceholders, isAbsoluteUrl, isClassification, isCspSource, isMaterial, isMeaningNeutral, locateUrl, matchVaguePhrase, matchVagueReason, nextRevision, normalizeText, parseDuration, parseRegistry, parseSemver, pathCovers, presetOrigin, registrySchema, resolvePresets, selectPreset, severity, strictest, subjectRequestPurpose, validateRegistry };