@sentientui/snippet 0.31.1 → 0.32.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/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @sentientui/snippet
2
2
 
3
- Style-rung [SentientUI](https://sentient-ui.com) for sites that are not built with React.
4
- One script tag: visitor-type attributes on `<html>` plus learned `data-*` style tokens on the
3
+ [SentientUI](https://sentient-ui.com) for sites that are not built with React (Shopify, Webflow,
4
+ WordPress, plain HTML). A script tag: visitor-type attributes on `<html>` plus learned `data-*` style tokens on the
5
5
  elements you declare. Plain CSS does the rest. No HTML is ever accepted or injected — text is
6
6
  written as `textContent`, styles come from a bounded validated set, and dashboard-authored
7
7
  Composition Blocks are a typed, enumerated component tree rendered via `createElement` only
@@ -66,8 +66,11 @@ and on a return visit the browser may already have painted your original section
66
66
  baseline styles before it does. The pre-paint script closes that gap: a tiny synchronous inline
67
67
  script that applies the last served decision *before* the page paints. It reads only the
68
68
  snapshot already stored on that visitor's own device, makes no network request, hides nothing
69
- (there is no cloak here, by design), and does nothing at all on a first visit or for a
70
- Do-Not-Track / Global Privacy Control / consent-gated visitor. Anything it gets wrong — a
69
+ (there is no cloak here, by design), and does nothing at all on a first visit, for a
70
+ Do-Not-Track / Global Privacy Control visitor, or unless the config says `consent: true` or
71
+ has no consent gate at all. It can't read a consent platform (it runs before any of them load),
72
+ so with `consentFrom` it steps aside and the loader applies the visitor's decision once the
73
+ platform grants. See [Consent](#consent). Anything it gets wrong — a
71
74
  selector that resolved differently mid-parse, say — the loader reverts within the same page
72
75
  load. It reads `window.sentient` when it runs, which is why it can share a tag with the config
73
76
  (keep the `;` that ends the assignment). Skip it and everything still works; your returning
@@ -99,18 +102,33 @@ and what the Shopify app embed and the dashboard's install page both hand out.
99
102
  when you want Subresource Integrity — an SRI hash is only possible on a pinned URL, since the
100
103
  hash changes with every release. Compute it from the published file
101
104
  (`openssl dgst -sha384 -binary dist/snippet.global.js | openssl base64 -A`) and pass it as
102
- `integrity="sha384-…"`, or self-host the file and skip the CDN entirely. Do **not** ship a
105
+ `integrity="sha384-…"`, or self-host the files and skip the CDN entirely. Do **not** ship a
103
106
  placeholder `integrity` value — a hash that doesn't match makes the browser refuse to run the
104
- script. A pinned tag is yours to update; the SentientUI dashboard flags the project when the
107
+ script. A pinned snippet loads its lazy chunks (below) with integrity too: their hashes are
108
+ built into each release. A pinned tag is yours to update; the SentientUI dashboard flags the project when the
105
109
  version it sees running falls behind.
106
110
 
111
+ **Lazy chunks.** Four parts load on demand from beside the snippet's own URL:
112
+ `engagement.global.js` (section and interaction capture, fetched at boot in parallel with the
113
+ decision, only for a visit that may be tracked), `consent.global.js` (only when a consent
114
+ source is configured, or on Shopify),
115
+ `preview.global.js` (only for `?sentient_preview=` / `?sentient_persona=` links from your
116
+ dashboard) and `editor.global.js` (only when you open the on-site editor). Self-hosting? Put
117
+ all five files in one folder. If the chunk URL can't be derived (an inlined or bundled
118
+ snippet), set `consentSrc` / `editorSrc` in `window.sentient`. A missing consent chunk keeps
119
+ tracking **off** and logs a warning.
120
+
121
+ **Content-Security-Policy nonces.** The snippet's injected `<style>` and chunk `<script>`
122
+ elements carry the nonce of a script already on the page, or `nonce` from `window.sentient`,
123
+ so a nonce-based policy needs no `'unsafe-inline'`.
124
+
107
125
  ```css
108
126
  #hero[data-tone='urgent'] .cta { font-weight: 700; }
109
127
  html[data-sentient-persona='trial_user'] .upgrade-banner { display: block; }
110
128
  ```
111
129
 
112
130
  The first value of each dim is your baseline (what you show today). Decisions are locked per
113
- session and learned per visitor type on the SentientUI API: Visit 1 learns, Visit 2 converts.
131
+ session and learned per visitor type on the SentientUI API: a first visit sees your original, the return visit adapts.
114
132
 
115
133
  `persona` declares the visitor type your site already knows (e.g. a role from your own
116
134
  session state) instead of waiting for it to be inferred. It must be a key in the project's
@@ -130,4 +148,58 @@ signals by default — that's what builds audience profiles with zero tagging. A
130
148
  `sectionCapture: false` to `window.sentient` to turn it off; it never runs for a Do-Not-Track,
131
149
  Global Privacy Control, or consent-gated visitor.
132
150
 
133
- Bundle ≤ 23 KiB gzip, pre-paint tag ≤ 3 KiB raw (both CI-enforced). MIT.
151
+ ## Consent
152
+
153
+ Tracking starts on the first page view unless you gate it. Pick one:
154
+
155
+ ```js
156
+ window.sentient = { apiKey: 'pk_…', consentFrom: 'cookiebot' };
157
+ // or 'onetrust' | 'cookieyes' | 'tcf' | 'google-consent-mode' | 'shopify',
158
+ // { cmp: 'onetrust', group: 'C0004' }, { cmp: 'google-consent-mode', region: 'ES' },
159
+ // { cookie: 'my_consent', value: 'yes', event: 'my-consent-changed' }
160
+ window.sentient = { apiKey: 'pk_…', consent: false }; // then SentientSnippet.grantConsent()
161
+ ```
162
+
163
+ - **Shopify:** set `consentFrom: 'shopify'` (Shopify's Customer Privacy API, which Shopify's
164
+ banner and every Shopify cookie-banner app report into), as the theme embed does. With neither
165
+ `consent` nor `consentFrom` set the snippet picks it too, but the inline pre-paint script
166
+ only steps aside if `window.Shopify` already exists when it runs, so it depends on tag
167
+ placement.
168
+ - **Typos fail closed:** an unknown `consentFrom` or a non-boolean `consent` logs a warning and
169
+ keeps tracking **off** until the config is fixed.
170
+ - **Grant and revoke without a reload:** the snippet starts tracking when the platform grants,
171
+ and stops and forgets the visitor when it revokes. A refusal given on a page without the
172
+ snippet is acted on at the next page that has it. Once the platform has answered, a return
173
+ to "no answer" (a banner reset that deletes its cookie) pauses tracking and keeps the visitor.
174
+ - **A banner that may answer before the snippet loads:** with `consent: false`, call
175
+ through a stub so an early answer is queued and replayed in order once the snippet boots:
176
+
177
+ ```js
178
+ (function () {
179
+ var S = (window.SentientSnippet = window.SentientSnippet || { q: [] });
180
+ // Queued before boot; forwarded to the live API after it, so a CMP that
181
+ // saved a method (onAccept = SentientSnippet.grantConsent) still reaches it.
182
+ ['goal', 'grantConsent', 'revokeConsent'].forEach(function (m) {
183
+ S[m] = S[m] || function () {
184
+ var live = window.SentientSnippet;
185
+ if (live !== S && live && live[m]) return live[m].apply(live, arguments);
186
+ S.q.push([m].concat([].slice.call(arguments)));
187
+ };
188
+ });
189
+ })();
190
+ ```
191
+
192
+ If the visitor already accepted on an earlier page, pass `consent: true` instead.
193
+ - **Your own JS-API banner:** `{ check, event }` sources pause on false; add
194
+ `refused: () => …` so a refusal also deletes the visitor's data.
195
+ - **Reusing the reader:** `SentientSnippet.consentWatcher(source)` gates your other
196
+ consent-bound scripts on the same reader. Its `read()` returns `null` until the presets chunk
197
+ has loaded (usually tens of milliseconds), so subscribe instead of reading once at load:
198
+ `w.subscribe(() => w.read() && loadPixel())`.
199
+
200
+ Everything stored and sent is listed in
201
+ [SDK_COOKIE_DISCLOSURE.md](https://github.com/SentientUI/sdk/blob/main/SDK_COOKIE_DISCLOSURE.md).
202
+
203
+ The always-on bundle is capped at 29 KiB gzip, a ceiling that only ever goes down. The
204
+ engagement, consent and preview chunks are capped at 6.5, 3.5 and 3 KiB gzip, the editor overlay
205
+ at 30 KiB gzip, and the pre-paint tag at 3 KiB raw. All limits are CI-enforced. MIT.
@@ -0,0 +1 @@
1
+ "use strict";var __sentientConsent=(()=>{var x=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var F=Object.getOwnPropertyNames;var W=Object.prototype.hasOwnProperty;var z=(t,r)=>{for(var e in r)x(t,e,{get:r[e],enumerable:!0})},D=(t,r,e,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let u of F(r))!W.call(t,u)&&u!==e&&x(t,u,{get:()=>r[u],enumerable:!(o=G(r,u))||o.enumerable});return t};var V=t=>D(x({},"__esModule",{value:!0}),t);var oe={};z(oe,{consentWatcher:()=>R});var M=Object.defineProperty,Z=Object.defineProperties,B=Object.getOwnPropertyDescriptors,E=Object.getOwnPropertySymbols,q=Object.prototype.hasOwnProperty,H=Object.prototype.propertyIsEnumerable,T=(t,r,e)=>r in t?M(t,r,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[r]=e,j=(t,r)=>{for(var e in r||(r={}))q.call(r,e)&&T(t,e,r[e]);if(E)for(var e of E(r))H.call(r,e)&&T(t,e,r[e]);return t},U=(t,r)=>Z(t,B(r));var J=[1,5,6,8],L=t=>{try{return decodeURIComponent(t)}catch(r){return t}};function y(t,r){if(t)for(let e of t.cookie.split(";")){let o=e.indexOf("=");if(o>0&&e.slice(0,o).trim()===r)return e.slice(o+1).trim()}}function _(t,r,e){let o=[t,...t.document?[t.document]:[]];for(let u of o)for(let n of r)u.addEventListener(n,e);return()=>{for(let u of o)for(let n of r)u.removeEventListener(n,e)}}function N(t,r="statistics"){if(t==null||t==="")return null;let e=L(t).trim();if(e==="-1")return!0;if(e==="0")return!1;let o=new RegExp(`[{,]\\s*${r}\\s*:\\s*(true|false)`).exec(e);return o?o[1]==="true":null}function Y(t,r="C0002"){if(t==null||t==="")return null;let e;for(let o of t.split("&"))o.startsWith("groups=")&&(e=L(o.slice(7)));if(e==null)return null;for(let o of e.split(",")){let[u,n]=o.split(":");if(u===r)return n==="1"}return null}function K(t,r="analytics"){if(t==null||t==="")return null;let e=new RegExp(`(?:^|,)${r}:(yes|no)(?:,|$)`).exec(L(t));return e?e[1]==="yes":null}var Q=new Set([1,3,4,5,6]);function X(t,r,e,o){return t.purposes.every(u=>r(u)||!Q.has(u)&&e(u))?t.vendorId===void 0?!0:o(t.vendorId):!1}function ee(t){var r,e,o,u,n,s,i;let l=typeof t=="string"?{cmp:t}:t;switch(l.cmp){case"cookiebot":return{cmp:"cookiebot",category:(r=l.category)!=null?r:"statistics"};case"onetrust":return{cmp:"onetrust",group:(e=l.group)!=null?e:"C0002"};case"cookieyes":return{cmp:"cookieyes",category:(o=l.category)!=null?o:"analytics"};case"tcf":return{cmp:"tcf",purposes:l.purposes&&l.purposes.length>0?l.purposes:J,vendorId:typeof l.vendorId=="number"&&l.vendorId>0?l.vendorId:void 0};case"google-consent-mode":return{cmp:"google-consent-mode",type:(u=l.type)!=null?u:"analytics_storage",dataLayer:(n=l.dataLayer)!=null?n:"dataLayer",region:typeof l.region=="string"&&l.region.trim()!==""?l.region.trim().toUpperCase():void 0};case"shopify":return{cmp:"shopify",category:(s=l.category)!=null?s:"analytics"};default:return{cmp:"custom",cookie:l.cookie,value:(i=l.value)!=null?i:"accepted",check:l.check,event:l.event,refused:l.refused}}}var $=()=>({update:null,global:null,regions:new Map});function te(t,r,e){let o=r&&typeof r=="object"&&"length"in r?Array.prototype.slice.call(r):null;if(!o||o[0]!=="consent"||o[1]!=="default"&&o[1]!=="update")return;let u=o[2],n=u==null?void 0:u[e],s=n==="granted"?!0:n==="denied"?!1:null;if(s===null)return;if(o[1]==="update"){t.update=s;return}let i=u==null?void 0:u.region,l=(Array.isArray(i)?i:typeof i=="string"?[i]:[]).filter(a=>typeof a=="string"&&a.trim()!=="").map(a=>a.trim().toUpperCase());if(l.length===0)t.global=s;else for(let a of l)t.regions.set(a,s)}function re(t){return t.update===!1}function ne(t,r){if(t.update!==null)return t.update;if(r){let e=t.regions.get(r);if(e!==void 0)return e;let o=r.split("-")[0],u=t.regions.get(o);if(u!==void 0)return u;if(r===o){for(let[n,s]of t.regions)if(s===!1&&n.startsWith(`${o}-`))return!1}return t.global}for(let e of t.regions.values())if(e===!1)return!1;return t.global!==null?t.global:t.regions.size>0?!1:null}function R(t,r=window){let e=ee(t),o=r,u=r.document;switch(e.cmp){case"cookiebot":return{read:()=>{let n=o.Cookiebot,s=N(y(u,"CookieConsent"),e.category);return n!=null&&n.consent&&typeof n.consent[e.category]=="boolean"&&(n.hasResponse===!0||s===null)?n.consent[e.category]===!0:s},subscribe:n=>_(r,["CookiebotOnAccept","CookiebotOnDecline","CookiebotOnConsentReady","CookiebotOnLoad"],n),refused(){let n=o.Cookiebot;return((n==null?void 0:n.hasResponse)===!0||y(u,"CookieConsent")!==void 0)&&this.read()===!1}};case"onetrust":return{read:()=>{let n=o.OnetrustActiveGroups;return typeof n=="string"?`,${n},`.includes(`,${e.group},`):Y(y(u,"OptanonConsent"),e.group)},subscribe:n=>_(r,["OneTrustGroupsUpdated"],n),refused(){return y(u,"OptanonAlertBoxClosed")!==void 0&&this.read()===!1}};case"cookieyes":return{read:()=>{var n;let s=o.getCkyConsent;if(typeof s=="function")try{let i=(n=s())==null?void 0:n.categories;if(i&&typeof i[e.category]=="boolean")return i[e.category]===!0}catch(i){}return K(y(u,"cookieyes-consent"),e.category)},subscribe:n=>_(r,["cookieyes_consent_update","cookieyes_banner_load","cookieyes_banner_loaded"],n),refused(){var n,s;let i=/(?:^|,)action:yes(?:,|$)/.test(L((n=y(u,"cookieyes-consent"))!=null?n:"")),l=o.getCkyConsent;if(!i&&typeof l=="function")try{i=((s=l())==null?void 0:s.isUserActionCompleted)===!0}catch(a){}return i&&this.read()===!1}};case"tcf":{let n=null,s=!1,i=!1;return{read:()=>n,refused:()=>n===!1&&!s&&i,subscribe:l=>{let a,v=!1,f=!1,h=(c,b)=>{var w,p,O,S;if(!b||v)return;typeof c.listenerId=="number"&&(a=c.listenerId),s=c.eventStatus==="cmpuishown",i=(c.eventStatus==="tcloaded"||c.eventStatus==="useractioncomplete")&&c.purposeOneTreatment!==!0&&c.gdprApplies!==!1&&((p=(w=c.purpose)==null?void 0:w.consents)==null?void 0:p[1])!==!0&&((S=(O=c.publisher)==null?void 0:O.consents)==null?void 0:S[1])!==!0;let P=c.eventStatus==="tcloaded"||c.eventStatus==="useractioncomplete";P&&(f=!0),s?n=!1:!P&&c.gdprApplies!==!1?f||(n=null):n=c.gdprApplies===!1||X(c.purposeOneTreatment===!0?U(j({},e),{purposes:e.purposes.filter(d=>d!==1)}):e,d=>{var g,m,A,I;return((m=(g=c.purpose)==null?void 0:g.consents)==null?void 0:m[d])===!0||((I=(A=c.publisher)==null?void 0:A.consents)==null?void 0:I[d])===!0},d=>{var g,m,A,I;return((m=(g=c.purpose)==null?void 0:g.legitimateInterests)==null?void 0:m[d])===!0||((I=(A=c.publisher)==null?void 0:A.legitimateInterests)==null?void 0:I[d])===!0},d=>{var g,m;return((m=(g=c.vendor)==null?void 0:g.consents)==null?void 0:m[d])===!0})===!0,l()},k=0,C=()=>{if(v)return;let c=o.__tcfapi;typeof c=="function"?c("addEventListener",2,h):k++<40&&window.setTimeout(C,250)};return C(),()=>{v=!0;let c=o.__tcfapi;typeof c=="function"&&a!==void 0&&c("removeEventListener",2,()=>{},a)}}}}case"google-consent-mode":{let n=null,s=0,i=$(),l=()=>{let a=o[e.dataLayer];if(!Array.isArray(a))return null;for((a!==n||a.length<s)&&(n=a,s=0,i=$());s<a.length;s++)te(i,a[s],e.type);return ne(i,e.region)};return{read:l,refused:()=>l()===!1&&re(i),subscribe:a=>{let v=new WeakSet,f=!1,h=[],k=-1,C=()=>{var b,w;let p=(w=o[b=e.dataLayer])!=null?w:o[b]=[];if(!v.has(p)){v.add(p);let O=p.push,S=function(...P){let d=O.apply(p,P);return k=p.length,f||a(),d};p.push=S,h.push(()=>{p.push===S&&(p.push=O)})}p.length!==k&&(k=p.length,a())};C();let c=window.setInterval(C,1e3);return()=>{f=!0,window.clearInterval(c);for(let b of h)b()}}}}case"shopify":{let n=e.category==="marketing"?"marketingAllowed":e.category==="preferences"?"preferencesProcessingAllowed":"analyticsProcessingAllowed";return{read:()=>{var s,i;let l=(i=(s=o.Shopify)==null?void 0:s.customerPrivacy)==null?void 0:i[n];if(typeof l!="function")return null;try{let a=l();return typeof a=="boolean"?a:null}catch(a){return null}},refused(){var s,i;let l=(s=o.Shopify)==null?void 0:s.customerPrivacy;if(typeof(l==null?void 0:l.currentVisitorConsent)!="function")return!1;try{return((i=l.currentVisitorConsent())==null?void 0:i[e.category])==="no"}catch(a){return!1}},subscribe:s=>{let i=_(r,["visitorConsentCollected"],s),l=!1,a=0,v=()=>{if(l)return;let f=o.Shopify;if(f!=null&&f.customerPrivacy){s();return}if(typeof(f==null?void 0:f.loadFeatures)=="function"){try{f.loadFeatures([{name:"consent-tracking-api",version:"0.1"}],h=>{!l&&!h&&s()})}catch(h){}return}a++<40&&window.setTimeout(v,250)};return v(),()=>{l=!0,i()}}}}case"custom":return{read:()=>{if(e.check)try{return e.check()===!0}catch(s){return!1}if(!e.cookie)return null;let n=y(u,e.cookie);return n===void 0?null:n===e.value},refused:()=>{var n;if(e.check)try{return((n=e.refused)==null?void 0:n.call(e))===!0}catch(s){return!1}return!!e.cookie&&y(u,e.cookie)!==void 0&&y(u,e.cookie)!==e.value},subscribe:n=>e.event?_(r,[e.event],n):()=>{}}}}return V(oe);})();