hryvinskyi / magento2-cookie-consent
Cookie consent for Magento 2 without a third-party service: banner and preferences, consent categories, a public declaration of cookies, script and embed gates, cookie guards and a server-side record of every choice
Package info
github.com/hryvinskyi/magento2-cookie-consent
Type:magento2-module
pkg:composer/hryvinskyi/magento2-cookie-consent
Requires
- php: ^8.1
- ext-intl: *
- hryvinskyi/magento2-admin-setup-wizard: ^1.0
- hryvinskyi/magento2-admin-ui: ^1.2
- hryvinskyi/magento2-base: ^2.3 || ^3.0
- hryvinskyi/magento2-client-address: ^1.0
- hryvinskyi/magento2-clock: ^1.0
- hryvinskyi/magento2-configuration-fields: ^1.0.11
- hryvinskyi/magento2-document-export: ^1.0
- hryvinskyi/magento2-head-tag-manager: ^4.0
- hryvinskyi/magento2-rate-limit: ^1.0
- hryvinskyi/magento2-theme-assets: ^1.0.1
- laminas/laminas-http: ^2.15
- magento/framework: *
- magento/module-backend: *
- magento/module-cms: *
- magento/module-config: *
- magento/module-cookie: *
- magento/module-cron: *
- magento/module-deploy: *
- magento/module-developer: *
- magento/module-page-cache: *
- magento/module-store: *
- magento/module-theme: *
- magento/module-ui: *
- magento/module-webapi: *
- magento/module-widget: *
- psr/clock: ^1.0
- psr/log: ^1.1 || ^2.0 || ^3.0
- symfony/console: ^5.4 || ^6.0 || ^7.0
Requires (Dev)
- magento/zend-pdf: ^1.16
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Cookie consent for Magento 2 without a third-party service: banner and preferences, consent categories, a public declaration of cookies, script and embed gates, cookie guards and a server-side record of every choice.
What it does for a store
- Asks the visitor. A banner on the first visit (bar, corner box or centred dialog, three looks), a cookie settings dialog with one switch per category, and a way back to it after a choice: a floating button or a footer link. Under the opt-in model Reject all always sits beside Accept all, and no optional category is pre-selected; no setting removes either.
- Holds things back until they are allowed. Scripts and embeds are held behind a category on the server (the page's HTML is rewritten before it is sent) and in the browser (scripts created at run time). Blocking rules name what to hold back: an address of a script or a frame, or a fragment of an inline script.
- Refuses cookies a visitor has not allowed, when the cookie guard is switched on: on the server for cookies written through the platform's cookie manager, and in the browser for cookies and local and session storage keys a script writes.
- Publishes a cookie declaration. Categories and the trackers in them (cookies, local and session storage keys, IndexedDB, pixels), with who sets each, what it is for and how long it is kept, per store view. A CMS widget prints it on the cookie policy page with the visitor's own choice and a way to change or withdraw it. The cookies the store sets itself (the session, the cart, the consent cookie) are listed under the store's own name, not the platform's (see The store as a provider).
- Keeps a record of every choice on the server, as proof: which decision, under which version of the policy, what was allowed, when, in which store view. Records are searched, exported to CSV, printed one at a time as PDF and erased per consent ID from the admin.
- Finds what it does not know yet. Storage names that no declared tracker matches are reported by a sample of visitors' browsers and wait in the Observed inbox, with a suggested category, provider and purpose from the built-in catalogue of known trackers (or from another module that contributes an advisor).
- Checks the result. The setup wizard opens the storefront in test mode in the admin's own browser and reports six checks before the banner is switched on.
Requirements
- Magento Open Source or Adobe Commerce 2.4, PHP 8.1 or higher with
ext-intl. - What it declares in
composer.jsonandetc/module.xml: the platform's Store, Config, Backend, UI, CMS, Widget, Cookie, PageCache, Theme, Webapi, Cron, Developer and Deploy modules,laminas/laminas-http,psr/log,symfony/console, andhryvinskyi/magento2-base,hryvinskyi/magento2-head-tag-manager,hryvinskyi/magento2-theme-assets,hryvinskyi/magento2-admin-ui,hryvinskyi/magento2-configuration-fields,hryvinskyi/magento2-admin-setup-wizard,hryvinskyi/magento2-rate-limit(request limits),hryvinskyi/magento2-document-export(CSV, PDF and file downloads),hryvinskyi/magento2-clock(the time) andhryvinskyi/magento2-client-address(the anonymised address of a record). - Cron must run: the policy snapshots, the statistics, the suggestions, the exports and every cleanup are cron jobs (below).
Installation
Run these from the Magento root:
composer require hryvinskyi/magento2-cookie-consent bin/magento setup:upgrade bin/magento setup:di:compile # production mode only bin/magento setup:static-content:deploy # production mode only bin/magento cache:flush
The installation creates the four categories (necessary, preferences, statistics, marketing; necessary is the essential one), declares the platform's own cookies, stores revision 1 and enables the module's cache type. The banner stays off until it is switched on.
Upgrading to 1.2
Version 1.2 delivers the script as a static file of the theme, built by static content deployment (see The runtime file). The address cookie-consent/runtime/script/… is gone. Run the sequence above, in that order. The cache clean at its end also removes the pages that still name the old address; flush any cache in front of the store (a reverse proxy, a CDN) as well, because a page cached before the upgrade waits for a "not found" answer in its head and runs without consent management until it is gone.
Static content deployment keeps a file that is already published. The platform builds a static file only when its path does not exist in pub/static, and reports no error when it does. This holds for every script and stylesheet of the platform. The sequence above leaves no stale copy: setup:upgrade empties pub/static and var/view_preprocessed before the deployment. A copy survives where pub/static is kept — setup:upgrade --keep-generated, or a build that deploys into an existing pub/static — and a deployment there keeps a theme's published runtime file (Hryvinskyi_CookieConsent/js/runtime.js, or runtime.min.js on a store that minifies JavaScript): the parts of the release that built it, against the settings of the release you installed. Then deploy into an emptied pub/static, or delete the published copies first (The runtime file, below, has the commands).
The release that first holds the file is not affected: there is no earlier copy. Every later release is, where pub/static is kept.
A storefront check that finished before the upgrade shows "Settings changed since this check. Run it again to be sure." in the Check step of the setup wizard (Stores › Cookie Consent › Setup) until the check is run again: the check ties its result to a hash of the store's settings document, and version 2 of the document hashes differently.
Getting started
- Open Stores › Cookie Consent › Setup. The wizard walks through Scope, Rules, Categories, Trackers, Blocking, Banner, Texts and Check, then a review of every change before it saves.
- The Check step runs the storefront check (it needs Test Mode, Stores › Configuration › Hryvinskyi Extensions › Cookie Consent › General). Each check says what it saw and links to the step that fixes it.
- Switch the banner on from the wizard's last step, or with Show the Banner to Visitors on the configuration page. The switch is set per store view: default, website, store view.
A visit with ?consent_test=1 on a store with test mode on gets its own consent cookie and stores its decisions as test records, which the statistics skip and the Records page hides until asked. ?consent_test=0 ends it.
Admin pages
Every page is under Stores › Cookie Consent, on the admin route hryvinskyi_cookieconsent (front name cookieconsent).
| Page | Address | Access rule |
|---|---|---|
| Overview: how visitors chose over 7, 30 or 90 days, what needs attention, the status | hryvinskyi_cookieconsent/overview/index |
Hryvinskyi_CookieConsent::overview |
| Setup (the wizard) | hryvinskyi_setup_wizard/wizard/index/id/cookie_consent |
Hryvinskyi_CookieConsent::setup; running the storefront check also needs ::check |
| Declaration: categories (order, offered or not, texts per store view) and trackers | hryvinskyi_cookieconsent/declaration/index |
Hryvinskyi_CookieConsent::declaration |
| Observed: names waiting in the inbox, declared, ignored | hryvinskyi_cookieconsent/observed/index |
Hryvinskyi_CookieConsent::observed; switching collection on needs ::observation_settings |
| Blocking rules: the merchant's rules, the rules other modules contribute, hosts that set names without a rule | hryvinskyi_cookieconsent/rules/index |
Hryvinskyi_CookieConsent::rules |
| Records: lookup by consent ID, filters, a record's detail and history | hryvinskyi_cookieconsent/records/index |
Hryvinskyi_CookieConsent::records; export needs ::records_export, erasing a consent ID's history ::records_delete |
| Advanced settings | adminhtml/system_config/edit/section/hryvinskyi_cookie_consent |
Hryvinskyi_CookieConsent::config |
Configuration
Stores › Configuration › Hryvinskyi Extensions › Cookie Consent (section hryvinskyi_cookie_consent). Scope: D default, W website, S store view.
| Group | Settings (path below the section) | Scope |
|---|---|---|
| General | general/enabled (show the banner, off by default), general/test_mode, general/revision (raising it asks everyone again) |
DWS, D, D |
| Consent Rules | consent/model (opt_in by default, opt_out, notice), consent/lifetime_days (6, 12 or 13 months; 365 days by default), consent/privacy_signal (on), consent/reload_on_withdraw (on), consent/cookie_name, records/retention_days (13, 24, 36 or 60 months; 36 by default), records/ip_mode (anonymised or nothing), records/client_limit_per_minute (10), records/store_limit_per_minute (300), signals/native_categories |
DWS for the model, the address mode, the limits and the native categories; DW for the lifetime, the signal and the withdrawal; D for the retention and the cookie name |
| Banner | banner/look, layout, position, corner, scheme, corners, buttons, accent, trigger, z_index |
DWS |
| Cookie List | declaration/store_provider: the name given as the provider of the store's own cookies; empty means the store name from General › Store Information, else the store view's name |
DWS |
| Texts | texts/title, message, accept, reject, choose, link, privacy_page, renewal_title, renewal_message, signal_notice, saved (empty means the translated default), texts/keep_default_texts |
DWS; the last S only |
| Observed | observations/enabled, sample (1 in 10 visits by default), keep_days, cap (1 000), the browser report limits, statistics/count_visits (off), suggestions/run_limit (50), run_seconds (50), auto_declare (off), threshold (0.85), min_days (2), run_cap (5), day_cap (20) |
DW for the switch, D for the rest |
| Blocking | gate/enabled (on), gate/skip_paths, gate/script_guard (on), guard/mode (off, declared by default, strict), guard/unknown_category |
DW, DW, DWS, DWS, DWS |
| Developer | developer/console_log, runtime/delivery (Script delivery: external by default, inline; see The runtime file) |
D, DW |
A lifetime is read as at most 400 days and a retention as at least 400 days, wherever the value came from, so the purge never deletes a record younger than any consent can be.
The store as a provider
A tracker the store sets itself has the store as its provider. It is stored as TrackerInterface::PROVIDER_STORE (@store) in place of a name, and wherever a person reads it — the cookie list, the declaration editor, the setup wizard, the Observed page, the policy snapshot — the name the store goes by on that store view stands in:
declaration/store_providerof the store view, when it is set;- else the store name from General › Store Information (
general/store_information/name); - else the name of the store the view belongs to.
So one installation with several brands shows each brand's name, and a renamed store needs no tracker saved again. The built-in catalogues (the platform's trackers and this module's own) declare their trackers this way. A provider typed in the admin as the store's own name, in the scope being edited, is stored as the store too.
Saving either setting cleans the cookie list and records a new snapshot for the stores of the saved scope. Renaming a store view in Stores › All Stores is noticed by the snapshot reconciliation, within five minutes.
Upgrading from 1.0 renames the trackers and catalogue suggestions the built-in catalogues named "Magento" or "Cookie Consent", without a privacy page, to the store. A provider of either name with a privacy page was set on purpose and is kept. Run bin/magento cache:flush after the upgrade, so the cookie list is built again.
The storefront
- The consent runtime is one script in
<head>, ahead of every other script, made of parts; a vendor module adds its signal as a part. Script delivery chooses how a page gets it: as a static file (default) or inline (see The runtime file). - The banner, the dialog, the settings button and an embed's placeholder are templates in
view/base/templates/ui/drawn by single-file ES modules loaded on demand fromview/base/web/js/ui/. A theme overrides the templates as any template; the stylesheet's selectors are wrapped in:where()so a theme rule wins. - The cached page is the same for every visitor: nothing the server prints depends on the visitor's consent, so the full-page cache keeps working. The declaration is served as a cached fragment,
cookie-consent/ui/declaration, fetched once per page view. - The platform's own cookie notice block is removed while the module manages consent on a store.
Gated markup. A script held back is <script type="text/plain" data-consent-category="<code>">; a non-classic type goes into data-consent-type. An embed held back carries its address in data-consent-src instead of src, with data-consent-category. Markup written this way by hand is held back too, whatever the rules say, and opens only for an allowed category.
Buttons in content. data-consent-action on any element: accept-all, reject-all, withdraw, preferences, or allow with data-consent-category="<code>". The Cookie Settings Link widget prints such a link (with an address for visitors without JavaScript), the Cookie Declaration widget the declaration.
Browser API. window.hryvinskyiCookieConsent (frozen, version 1): get(), allows(code), categories(), onChange(listener), acceptAll(), rejectAll(), withdraw(), choose(codes), allow(code), openPreferences(). The document events hryvinskyi-cookie-consent:ready (once) and hryvinskyi-cookie-consent:changed (after every change) carry the consent as a frozen object. The types are in Test/Js/types/published.d.ts.
Every decision and every page load remove the cookies and storage keys that the trackers of the refused categories declare (first-party, best effort): what a page wrote before the visitor's first choice, or while the cookie guard was off, goes too. It also tells every signal, and reloads the page when a withdrawn category already ran and When Consent Is Withdrawn says so.
The browser's privacy signal (Global Privacy Control), when the store respects it, is applied as Reject all and a short notice is shown instead of the banner.
The runtime file
With Script delivery set to the external file, the page's head holds the settings element, then one script element whose address is the static file Hryvinskyi_CookieConsent/js/runtime.js of the store's theme, or runtime.min.js when the store minifies JavaScript (Stores › Configuration › Advanced › Developer › JavaScript Settings › Minify JavaScript Files). The web server or a CDN serves it like any other static file; no request for it reaches PHP.
-
The address carries the static content version as a query string,
…/runtime.min.js?v=<version>, so it changes with every deployment whether or not static file signing (Stores › Configuration › Advanced › Developer › Static Files Settings › Sign Static Files) is on. The addresses of the UI modules and of the stylesheet are plain static addresses: with signing off they do not change on a deployment, so leave signing on, as for every script and stylesheet of the store. -
The file holds every declared part, the composition root last, in one closure, minified whatever the store's minification setting is — unless the minifier fails on it: then the file is published unminified, and an error line naming the file goes to
var/log/exception.log(a minifier that throws) orvar/log/system.log(one that returns nothing). It is the same for every store. Which parts a store starts is the settings document's business, not the file's: itsactivelist names them, and the composition root makes only those. For the core module's parts the file is about 74 KiB (about 21 KiB gzipped). -
A published copy is never replaced. The platform builds a static file only when its path is missing from
pub/static, so after a part file or the composition root changes the copies of the old content stay until they are deleted. That happens on an upgrade that keepspub/static(setup:upgrade --keep-generated, or a build that deploys into an existingpub/static; a plainsetup:upgradeempties it), and after an edit in developer mode. From the Magento root, then clean the page cache:rm -f pub/static/frontend/*/*/*/Hryvinskyi_CookieConsent/js/runtime*.js rm -f var/view_preprocessed/pub/static/frontend/*/*/*/Hryvinskyi_CookieConsent/js/runtime*.js
-
It is built by static content deployment, by an asset preprocessor on the platform's own pipeline, from the part files the pool declares. Outside production mode it is built on its first request and served from
pub/staticafter that. A theme's own copy ofjs/runtime.jsoverrides nothing: the content is always built, and the copy is ignored. To override a part, override the part's file (below). The module's view configuration (etc/view.xml) keeps the runtime file and the module's part files out of the platform's JavaScript bundles, whichsetup:static-content:deploywrites for every theme unless it runs with--no-js-bundleor--no-javascript. -
A part file that cannot be read fails the build of the runtime file, as a stylesheet that does not compile does.
setup:static-content:deployprints the source path of the placeholder file, a line break and the cause, and deploys none of that theme and locale's files after it, nor its map:Compilation from source: <path to view/frontend/web/js/runtime.js> The consent runtime file cannot be built: the file "Hryvinskyi_CookieConsent::js/runtime/clock.js" is missing or empty.The cause is
the file "<file id>" is missing or empty.for an empty or unreadable part file or composition root, andthe required parts <codes> are not declared.when the pool lacks a part the composition root cannot start without (config,consent,logger,clock,id,cookie-jar,page,signals,pending-receipts,kernel).Run in one process (the default), the deployment stops at the first theme and locale that meets the error and the command ends with an error. With
--jobsabove 1 (and PHP'spcntlextension), each theme and locale is deployed by a process of its own: the process that meets the error ends, the others go on, and the command still ends successfully. Either way, read the deployment's output, or the log that kept it, forCompilation from sourcelines, and check that the runtime file was published:pub/static/frontend/<Vendor>/<theme>/<locale>/Hryvinskyi_CookieConsent/js/runtime.js, orruntime.min.json a store that minifies JavaScript. Under the compact strategy a theme that overrides no part has no copy of its own: its pages load the one underpub/static/frontend/Magento/base/default/. -
A part file that does not parse stops the runtime on every store that uses the file, whether or not the store starts that part: the deployment does not notice, because the minifier does not parse. Run
node --checkon the file a deployment wrote, for examplenode --check pub/static/frontend/<Vendor>/<theme>/<locale>/Hryvinskyi_CookieConsent/js/runtime.min.js. -
With Script delivery set to inline, every page prints the store's own script instead: the parts active for the store only, minified always. The core module's parts make about 44 KiB, which every page carries; the file is one request the browser caches.
-
A store whose active parts lack one the composition root requires gets neither the settings element nor the runtime element, whichever delivery is set, and one critical line in the log names the parts.
-
A project that runs script optimizers which merge or move local static scripts gives the runtime element their opt-out attributes through the
criticalScriptAttributesargument ofHryvinskyi\CookieConsent\ViewModel\Head\RuntimeRegistrar, in a globaletc/di.xml; each item is an attribute name and its text value, and the module adds none:<type name="Hryvinskyi\CookieConsent\ViewModel\Head\RuntimeRegistrar"> <arguments> <argument name="criticalScriptAttributes" xsi:type="array"> <item name="data-example" xsi:type="string">true</item> </argument> </arguments> </type>
data-examplestands for whichever attribute the optimizer reads.
Records
POST /V1/cookie-consent/decisions (anonymous REST) records a decision at most once per consent ID; the answer re-issues the consent cookie from the server so that it lives its whole lifetime. A record holds the consent ID and the one it replaces, the store view, the policy revision and hash, the decision method, the allowed categories, the times, the anonymised address (or none), the user agent, where on the page the decision was made, and whether it was a test.
- A record names a policy snapshot the server stored itself. Snapshots are written when an admin changes the policy and by the reconciling cron job every 5 minutes; until a store's current policy has one (right after a deployment that changed it, with cron not run yet), the endpoint answers 503 with
Retry-Afterand the browser keeps the decision to send it again. - Records are kept for the retention setting and purged daily; statistics are counted from them every 15 minutes, test records left out.
- An export runs in the background: a CSV file in
var/hryvinskyi_cookie_consent/exports/, offered for 24 hours to the admin who asked; cells that a spreadsheet would read as a formula are neutralised. - A record's PDF holds what the visitor was shown and what they allowed, without the address or the user agent.
- Erasing removes the whole history of a consent ID (every record of the chain) in one transaction, and says how many records go first. Nothing records who erased it.
Observed names and suggestions
POST /V1/cookie-consent/observationstakes storage names from a sample of sessions. Only names leave the browser, with the page's path and, when the cookie guard saw the write, the host of the script that wrote the name; never a value, a query string or a fragment. The inbox holds at most 1 000 waiting names and forgets one after the days set without a sighting.- An observed name is never allowed because it was seen. Under the guard's
strictmode an undeclared name is treated as the category the settings name. - The advising run (cron every 15 minutes in its own group
hryvinskyi_cookie_consent_advising, run as a separate process; orbin/magento cookie-consent:advise [--limit=N] [--seconds=N]) asks the advisors about waiting names and stores their suggestions. The built-in advisor is the catalogue of known trackers. - Automatic declaration is off by default. Switched on, a suggestion becomes a tracker without a person only when its confidence reaches the threshold, it names a known provider, the name was seen on at least the set number of distinct days, and its category is an active one that is not the essential one; at most the set number a run and a day, and never in a storefront or web API request. A pattern with a wildcard is declared this way only when the catalogue supplied it. Such a tracker stays marked not reviewed until a person confirms it; undoing it returns the name to the inbox, where it is never declared automatically again.
What it can and cannot see
- The server cookie guard stands in front of the platform's cookie manager in the storefront, REST and GraphQL areas. It does not see cookies written as sensitive (
HttpOnly) through the cookie manager, cookies a rawsetcookie()orheader()call writes, nor any other area. A built-in full-page cache hit writes no cookie and never asks the guard. - The browser cookie guard stands in front of
document.cookie, the cookie store'sset, andsetItemof local and session storage; a storage key is judged by what is declared for the storage it is written to. It cannot see cookies the server sets (the server guard's part),HttpOnlycookies, cookies of other domains (third-party cookies), a storage key written by assigning a property of the storage, or IndexedDB. A refused write is silently not made; a write it cannot read passes untouched. The storefront check's own session keys pass without being declared. - The script guard sees
scriptandiframeelements created throughdocument.createElementand given an address afterwards. Inline script text created at run time is not judged. - The observer reads the names of the page's cookies (
document.cookie) and of local and session storage, once the page is idle and again a few seconds later. It does not seeHttpOnlycookies, third-party cookies, IndexedDB, or names set and removed between two looks. - The removal on a decision reaches first-party cookies and storage keys only; it cannot reach
HttpOnlycookies or other domains. - The storefront check visits the store's home page in the admin's browser in test mode, and fetches it from the server as a fresh visitor, which is how
HttpOnlycookies are seen. It reports names and third-party hosts on that page only; a page it does not visit can still set something before a choice. - Behind HTTP authentication (a staging store with a password on the web server), the observer's, visit and rule-hit reports are refused by the web server: they are sent without credentials, so that no report carries the visitor's session, and the web server's password is a credential too. The Observed inbox, the visit statistics and the rule hits then stay empty. The cookie list of the settings dialog and the decision records are sent with the page's credentials and work there.
- The policy hash covers what the module resolves for a store: the policy (model, revision, lifetime, categories and their texts), the declaration and the banner. Wording a theme changes by overriding a template is not part of a record's snapshot.
Operations
- Cache type
hryvinskyi_cookie_consent(Cookie Consent): each store's policy and declaration. A policy change cleans what it touches. Entries are validated with stamps of their own, so an entry is never served after a clean even when the platform's file cache backend loses ids from its tag index. - Cron jobs, group
default:hryvinskyi_cookie_consent_reconcile_snapshots(every 5 minutes),…_aggregate_statistics(every 15 minutes),…_purge_records,…_prune_observations,…_prune_tracker_changes,…_prune_check_runs,…_prune_rule_hits(daily). Grouphryvinskyi_cookie_consent_advising:…_advise_waiting(every 15 minutes). Grouphryvinskyi_cookie_consent_export:…_export_records(every minute) and…_clean_exports(hourly). Both own groups run in a separate process. - REST endpoints, anonymous:
POST /V1/cookie-consent/decisions,/observations,/visitsand/rule-hits. Each has a per-visitor and a per-store-view limit a minute of its own. A visit report is counted only while visit counting is on, and no test-mode visit, observation sighting or rule hit is counted. - The module's own browser names (its consent cookie, the test-mode cookies, the storage keys of its runtime and of the check) are one list, so the declaration lists the ones a visitor's browser may hold and the observer never reports any of them.
- Tables:
hryvinskyi_cookie_consent_*— categories and texts, revisions, snapshots, trackers, texts and their change log, blocking rules and their addresses, records, observations with their days and pages, suggestions, statistics (decisions, grants, visits, reports, rule hits) and their watermark, check runs, exports, and the addresses a rule held back.
Extending
A module adds to these pools in its own global etc/di.xml (an area di.xml that names one of these arguments replaces the whole list in that area). Each item's interface is @api.
| Pool (class › argument) | Item | What it adds |
|---|---|---|
Model\Runtime\PartPool › parts |
{part: Api\RuntimePartInterface, sortOrder} |
a browser part of the runtime, such as a vendor's signal |
Model\Catalog\KnownTrackerSources › sources |
Api\KnownTrackerSourceInterface |
known trackers offered for declaration and to the catalogue advisor |
Model\Rule\RuleCollector › sources |
Api\BlockingRuleSourceInterface (optionally Api\BlockingRuleSourceDescriptionInterface) |
blocking rules, shown read-only on the Blocking rules page |
Model\Rule\TagManagementSources › sources |
Api\TagManagementSourceInterface |
that a module loads tags itself, so the rows covering their hosts are drawn read-only with its label |
Model\Wizard\ContributedRuleSwitches › rows |
Api\Wizard\ContributedRuleSwitchInterface, usually a virtual type of Model\Wizard\ContributedRuleSwitch |
a row of the wizard's Blocking step that edits the module's own settings |
Model\Suggestion\AdvisorPool › advisors |
Api\ObservationAdvisorInterface |
an advisor for observed names |
Model\TextHelp\TextHelp › textHelpProviders |
Api\TextHelpProviderInterface (with sortOrder) |
"suggest a purpose" and "translate" in the admin; the first provider is asked, and with none the buttons are not shown |
Model\Status\StatusFacts › statusFactProviders |
Api\StatusFactProviderInterface |
a line of the Overview's status card |
Model\Attention\AttentionItems › attentionItemProviders |
Api\AttentionItemProviderInterface |
an item of the Overview's attention list |
Model\Category\CategoryRules › usages |
Api\CategoryUsageInterface |
something that keeps a category from being deleted |
Model\Text\TextCoverage › textCoverageSources |
Api\TextCoverageSourceInterface |
texts counted in the store-view text coverage |
Model\Snapshot\SectionPool › sections |
Api\SnapshotSectionInterface |
a section of the policy snapshot (changes every store's hash) |
<type name="Hryvinskyi\CookieConsent\Model\Runtime\PartPool"> <arguments> <argument name="parts" xsi:type="array"> <item name="signal-example" xsi:type="array"> <item name="part" xsi:type="object">Vendor\Module\Model\Runtime\ExampleSignalPart</item> <item name="sortOrder" xsi:type="number">300</item> </item> </argument> </arguments> </type>
A part's file assigns parts['<code>'] = function (deps) { … } and nothing else, so it does nothing when it is parsed, on stores that do not start the part as well: the runtime file holds every declared part. Api\RuntimePartInterface::isActive() decides whether a store's page starts the part, not whether its code is downloaded; the store's script (Api\RuntimeScriptInterface, which inline delivery prints) holds the active parts only. A signal registers with deps and is told the model's default before any vendor tag runs, then the stored consent, then every change. Read ports for other modules include Api\ConsentActivityInterface, Api\ConsentSettingsInterface, Api\DeclarationInterface, Api\BannerSettingsInterface, Api\BannerTextsInterface and Api\ConsentStatusInterface.
Keeping a part's file out of the bundles. The platform's JavaScript bundles take in the scripts of a theme that no view configuration excludes. This module excludes its own part files; a module that adds a part excludes that part's file in its own etc/view.xml, or a store that loads the bundles downloads the part a second time beside the runtime file:
<view xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/view.xsd"> <exclude> <item type="file">Vendor_Module::js/runtime/signal-example.js</item> </exclude> </view>
The settings document is the JSON in <script type="application/json" id="hryvinskyi-cookie-consent-config">, printed ahead of the runtime. It is version 2 (v). active lists the codes of the store's active parts in pool order, parts with no settings of their own included; parts holds the settings of the active parts that have any, by code. The composition root makes the parts active names and no other. The browser refuses a document that is another version, has no active list, or holds a value in it that is not a part code: nothing starts, gated scripts stay gated and the page works. It does not start either when active lacks a part the composition root requires; its error line, The consent runtime did not start, names the required parts that are not active. An active part the script does not carry (a page cached against a file from another release) is skipped with one warning that names it, and the rest starts; a known optional part gets its stand-in.
Overriding a part in a theme. A theme overrides a part's file as it overrides any view file (for a core part, <theme>/Hryvinskyi_CookieConsent/web/js/runtime/<part>.js); the override is in that theme's runtime file after deployment, whichever static deployment strategy runs. The quick and standard strategies build a runtime file for every theme. The compact strategy deploys a module's file once for all themes, so the module adds a step to the deployment (Model\Runtime\File\Deploy\OverriddenPartsProcessor, on Magento\Deploy\Package\Package): a theme that overrides a part file or the composition root, itself or through a theme it inherits from, gets a runtime file of its own, and every other theme keeps sharing the module's.
Developing a part. In developer mode the runtime file is built on the first request and then served from pub/static, so an edit to a part file or to the composition root shows only after the published copy is deleted (the commands are in The runtime file).
Translations
The storefront and admin wording ships in en_US and 25 more locales: the official languages of the European Union, Norwegian Bokmål and Ukrainian. The translations are machine-made; have them read by a native speaker before a store relies on them, and override a phrase in a theme or a language pack.
Tests
- Unit:
vendor/bin/phpunit -c app/code/Hryvinskyi/CookieConsent/phpunit.xml.dist. - Browser parts:
npm testandnpm run checkinTest/Js; the admin pages and the wizard plug-in infrontend/admin-pages/andfrontend/setup-wizard/(npm run check,npm test,npm run build,npm run verify-build). - Integration: the platform's harness in
dev/tests/integration. The suite registers the PHPUnit extensionHryvinskyi\CookieConsent\Test\Integration\Harness\ReleaseDiscardedSessionsindev/tests/integration/phpunit.xml, which frees the sessions isolated tests start, so the whole suite runs in one process. - Browser flows:
Test/E2e/, run with the@hryvinskyi/magento2-e2epackage from the shop'se2e/directory (npm testthere). The admin flows need an admin account for the package.
Out of scope
IAB TCF consent strings (they need a registered consent management platform), an advertising vendor's certification programme for consent platforms, a consent model chosen by the visitor's location (the model is set per store view), consent shared across domains, consent shared across a logged-in customer's devices, and a link from a record to a customer account.
Renaming the consent cookie
The consent cookie's name is a setting (Consent Rules › Consent Cookie Name). Renaming it makes every stored choice unreadable: visitors are asked again, and the cookie under the old name stays in their browsers until it expires on its own. The module's own declared cookie follows the new name, so the declaration lists the cookie visitors now get.