bitsnap-react 1.8.0 → 1.10.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 +162 -0
- package/dist/CartProvider-HXLGQ4EX.mjs +2 -0
- package/dist/CartProvider-OHHYOMSG.js +2 -0
- package/dist/CartProvider-OHHYOMSG.js.map +1 -0
- package/dist/analytics.d.mts +45 -0
- package/dist/analytics.d.ts +45 -0
- package/dist/analytics.js +2 -0
- package/dist/analytics.js.map +1 -0
- package/dist/analytics.mjs +2 -0
- package/dist/catalog.d.mts +14 -1
- package/dist/catalog.d.ts +14 -1
- package/dist/catalog.js +1 -1
- package/dist/catalog.js.map +1 -1
- package/dist/catalog.mjs +1 -1
- package/dist/chunk-3Z6VNXBP.js +2 -0
- package/dist/chunk-3Z6VNXBP.js.map +1 -0
- package/dist/chunk-43IIYJ6J.mjs +2 -0
- package/dist/chunk-43IIYJ6J.mjs.map +1 -0
- package/dist/chunk-6D3OORMK.mjs +2 -0
- package/dist/chunk-6D3OORMK.mjs.map +1 -0
- package/dist/chunk-ADYVTMGH.mjs +2 -0
- package/dist/chunk-ADYVTMGH.mjs.map +1 -0
- package/dist/{chunk-WRCXZMKK.js → chunk-AJNULBC3.js} +2 -2
- package/dist/chunk-AJNULBC3.js.map +1 -0
- package/dist/chunk-B32ACCW2.js +2 -0
- package/dist/chunk-B32ACCW2.js.map +1 -0
- package/dist/chunk-DDY7IBMG.mjs +2 -0
- package/dist/chunk-DDY7IBMG.mjs.map +1 -0
- package/dist/chunk-DPKT6ITB.js +4 -0
- package/dist/chunk-DPKT6ITB.js.map +1 -0
- package/dist/{chunk-T2POA6RW.js → chunk-F46RJVWC.js} +2 -2
- package/dist/chunk-F46RJVWC.js.map +1 -0
- package/dist/chunk-F6GQLKA6.js +2 -0
- package/dist/chunk-F6GQLKA6.js.map +1 -0
- package/dist/chunk-JSDGZ4NY.js.map +1 -1
- package/dist/chunk-JXCHRSPW.mjs +4 -0
- package/dist/chunk-JXCHRSPW.mjs.map +1 -0
- package/dist/chunk-KOYBZORL.js.map +1 -1
- package/dist/chunk-RLEC25JI.mjs +2 -0
- package/dist/chunk-RLEC25JI.mjs.map +1 -0
- package/dist/chunk-RVILRUW3.js +2 -0
- package/dist/chunk-RVILRUW3.js.map +1 -0
- package/dist/chunk-T2OUOO4X.mjs +2 -0
- package/dist/chunk-T2OUOO4X.mjs.map +1 -0
- package/dist/chunk-VIII45AC.js +2 -0
- package/dist/chunk-VIII45AC.js.map +1 -0
- package/dist/chunk-XIHGWNTS.js +2 -0
- package/dist/chunk-XIHGWNTS.js.map +1 -0
- package/dist/chunk-YXFJG4MF.mjs +2 -0
- package/dist/chunk-YXFJG4MF.mjs.map +1 -0
- package/dist/chunk-ZPTHK4OX.mjs +2 -0
- package/dist/{chunk-OJT3YO2R.mjs.map → chunk-ZPTHK4OX.mjs.map} +1 -1
- package/dist/consent.d.mts +165 -0
- package/dist/consent.d.ts +165 -0
- package/dist/consent.js +75 -0
- package/dist/consent.js.map +1 -0
- package/dist/consent.mjs +75 -0
- package/dist/consent.mjs.map +1 -0
- package/dist/course.d.mts +13 -3
- package/dist/course.d.ts +13 -3
- package/dist/course.js +1 -1
- package/dist/course.js.map +1 -1
- package/dist/course.mjs +1 -1
- package/dist/course.mjs.map +1 -1
- package/dist/embed/analytics.js +1 -0
- package/dist/embed/consent.js +74 -0
- package/dist/errors.js.map +1 -1
- package/dist/index.css +1 -1
- package/dist/index.css.map +1 -1
- package/dist/index.d.mts +54 -7
- package/dist/index.d.ts +54 -7
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/instrument-CmxK7S4T.d.mts +929 -0
- package/dist/instrument-CmxK7S4T.d.ts +929 -0
- package/dist/internal.js.map +1 -1
- package/dist/methods-A5KGZBAM.js +2 -0
- package/dist/methods-A5KGZBAM.js.map +1 -0
- package/dist/methods-AOHKV7IN.mjs +2 -0
- package/dist/methods-AOHKV7IN.mjs.map +1 -0
- package/dist/models.js.map +1 -1
- package/dist/returns.d.mts +9 -1
- package/dist/returns.d.ts +9 -1
- package/dist/returns.js +1 -1
- package/dist/returns.js.map +1 -1
- package/dist/returns.mjs +1 -1
- package/dist/{types-PSBBDdQm.d.mts → types-BnVWLcoB.d.mts} +13 -0
- package/dist/{types-BTm_ZolC.d.ts → types-i-IuN4Im.d.ts} +13 -0
- package/package.json +46 -45
- package/dist/CartProvider-5KAG5QGA.mjs +0 -2
- package/dist/CartProvider-7GJXW2IP.js +0 -2
- package/dist/CartProvider-7GJXW2IP.js.map +0 -1
- package/dist/chunk-45AP7UZE.mjs +0 -2
- package/dist/chunk-45AP7UZE.mjs.map +0 -1
- package/dist/chunk-7XTDFTQU.js +0 -4
- package/dist/chunk-7XTDFTQU.js.map +0 -1
- package/dist/chunk-C6Z7LOHB.mjs +0 -2
- package/dist/chunk-C6Z7LOHB.mjs.map +0 -1
- package/dist/chunk-HB6KQT26.mjs +0 -4
- package/dist/chunk-HB6KQT26.mjs.map +0 -1
- package/dist/chunk-LWK4E5G5.js +0 -2
- package/dist/chunk-LWK4E5G5.js.map +0 -1
- package/dist/chunk-OJT3YO2R.mjs +0 -2
- package/dist/chunk-OUYRKNZJ.mjs +0 -2
- package/dist/chunk-OUYRKNZJ.mjs.map +0 -1
- package/dist/chunk-P2YB25KZ.js +0 -2
- package/dist/chunk-P2YB25KZ.js.map +0 -1
- package/dist/chunk-T2POA6RW.js.map +0 -1
- package/dist/chunk-VPKE2ZOR.mjs +0 -2
- package/dist/chunk-VPKE2ZOR.mjs.map +0 -1
- package/dist/chunk-WRCXZMKK.js.map +0 -1
- package/dist/chunk-WSM4OM72.mjs +0 -2
- package/dist/chunk-WSM4OM72.mjs.map +0 -1
- package/dist/chunk-XRNTUSBH.js +0 -2
- package/dist/chunk-XRNTUSBH.js.map +0 -1
- package/dist/chunk-Z2BKIX6F.js +0 -2
- package/dist/chunk-Z2BKIX6F.js.map +0 -1
- package/dist/methods-ITD6WFIY.mjs +0 -2
- package/dist/methods-JENIGNF7.js +0 -2
- package/dist/methods-JENIGNF7.js.map +0 -1
- /package/dist/{CartProvider-5KAG5QGA.mjs.map → CartProvider-HXLGQ4EX.mjs.map} +0 -0
- /package/dist/{methods-ITD6WFIY.mjs.map → analytics.mjs.map} +0 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkB32ACCW2js = require('./chunk-B32ACCW2.js');var p="X-Bitsnap-Client",a=`bitsnap-react@${_chunkB32ACCW2js.a}`,T="bs_client",L= exports.a ={[p]:a},E= exports.b =e=>t=>(t.header.set(p,a),e(t));function h(e){let t=e.indexOf("#"),o=t===-1?e:e.slice(0,t),s=t===-1?"":e.slice(t),n=o.includes("?")?/[?&]$/.test(o)?"":"&":"?";return`${o}${n}${T}=${encodeURIComponent(a)}${s}`}var y="https://bitsnap.pl",g= exports.f =y;function v(e){console.log("setCustomHost",e),g= exports.f =e}function d(e,t){return t.toLowerCase().startsWith("en")?e.en:e.pl}function f(e,t){let o={...e};if(t!=null)for(let[s,n]of Object.entries(t))n!=null&&(o[s]=n);return o}function u(e,t,o){return f(d(e,t),o)}function x(e,t){return _nullishCoalesce(e[t], () => (t))}var C={en:{cart:"Cart",emptyCart:"Your cart is empty.",total:"Total:",delivery:"+ delivery",chooseCountry:"Choose a country",nextStep:"Next step",unavailableProducts:"Not all products are available."},pl:{cart:"Koszyk",emptyCart:"Brak produkt\xF3w w koszyku.",total:"Suma:",delivery:"+ dostawa",chooseCountry:"Wybierz kraj",nextStep:"Nast\u0119pny krok",unavailableProducts:"Nie wszystkie produkty s\u0105 dost\u0119pne w magazynie."}};function m(e,t){return u(C,e,t)}function A(e,t,o){return x(m(t,o),e)}var i="pl-PL",l="bitsnap-locale",r;function w(e){let t=_optionalChain([e, 'optionalAccess', _ => _.trim, 'call', _2 => _2()]);r=t?t.toLowerCase()==="en"?"en-US":t.toLowerCase()==="pl"?i:t:void 0,typeof localStorage<"u"&&(r==null?localStorage.removeItem(l):localStorage.setItem(l,r))}function H(){return _nullishCoalesce(r, () => ((typeof localStorage<"u"?_nullishCoalesce(localStorage.getItem(l), () => (i)):i)))}var _clsx = require('clsx');var _tailwindmerge = require('tailwind-merge');function $(...e){return _tailwindmerge.twMerge.call(void 0, _clsx.clsx.call(void 0, e))}exports.a = L; exports.b = E; exports.c = h; exports.d = $; exports.e = y; exports.f = g; exports.g = v; exports.h = d; exports.i = u; exports.j = A; exports.k = i; exports.l = w; exports.m = H;
|
|
2
|
+
//# sourceMappingURL=chunk-VIII45AC.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/visitor-cookie/dist/chunk-VIII45AC.js","../src/lib/client-header.ts"],"names":["CLIENT_HEADER_NAME","CLIENT_HEADER_VALUE","SDK_VERSION"],"mappings":"AAAA,uuBAAuC,ICG1BA,CAAAA,CAAqB,kBAAA,CACrBC,CAAAA,CAAsB,CAAA,cAAA,EAAiBC,kBAAW,CAAA,CAAA","file":"/home/emems/.t3/worktrees/bitsnap-react/visitor-cookie/dist/chunk-VIII45AC.js","sourcesContent":[null,"import type { Interceptor } from \"@connectrpc/connect\";\nimport { SDK_VERSION } from \"../version\";\n\nexport const CLIENT_HEADER_NAME = \"X-Bitsnap-Client\";\nexport const CLIENT_HEADER_VALUE = `bitsnap-react@${SDK_VERSION}`;\n\nexport const CLIENT_QUERY_PARAM = \"bs_client\";\n\n/**\n * Spread into the `headers` of a fetch that already triggers a CORS preflight\n * (JSON POST, Connect RPC). Never use it on a simple cross-origin GET: the\n * custom header would force a preflight that older servers and merchant\n * proxies do not allow. Use `withClientParam` there.\n */\nexport const clientHeaders: Record<string, string> = {\n [CLIENT_HEADER_NAME]: CLIENT_HEADER_VALUE,\n};\n\n/** Connect interceptor adding the client header to every RPC. */\nexport const clientHeaderInterceptor: Interceptor = (next) => (req) => {\n req.header.set(CLIENT_HEADER_NAME, CLIENT_HEADER_VALUE);\n return next(req);\n};\n\n/** Adds `bs_client=<pkg>@<ver>` to a URL, for simple GETs that must stay preflight-free. */\nexport function withClientParam(url: string): string {\n const hash = url.indexOf(\"#\");\n const base = hash === -1 ? url : url.slice(0, hash);\n const fragment = hash === -1 ? \"\" : url.slice(hash);\n const separator = base.includes(\"?\") ? (/[?&]$/.test(base) ? \"\" : \"&\") : \"?\";\n return `${base}${separator}${CLIENT_QUERY_PARAM}=${encodeURIComponent(CLIENT_HEADER_VALUE)}${fragment}`;\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var s={maxBatchEvents:50,maxBodyBytes:65536,maxPropsChars:4096,maxPropString:200,maxPropArray:50,host:253,path:512,referrerHost:253,utm:100,refCode:64,id:64,sdk:64,pageId:32,region:64,osBrowser:32,tsSkewMs:864e5},w=["storefront_events","app_events","business_events"],N=["live","test"],A=["storefront","sdk_react","script","server","dashboard"],P=["hosted","custom_domain","embed","api","panel"],$=["shop","catalog","product","cart","checkout","payment","panel","course","custom_page","order","returns","app","other"];var T={storefront_events:["storefront","sdk_react","script"],app_events:["dashboard"],business_events:["server"]},_={value_minor:"number",currency:"string"},h={page_view:{landing:"boolean"},product_list_viewed:{list_id:"string?",item_count:"number"},product_impression:{list_id:"string?",product_ids:"string[]",positions:"number[]"},product_clicked:{list_id:"string?",position:"number?"},product_view:{price_minor:"number",currency:"string",availability:"enum:in_stock|out_of_stock|preorder"},variant_selected:{},add_to_cart:{qty:"number",..._},remove_from_cart:{qty:"number",..._},cart_opened:{item_count:"number",..._},checkout_started:{item_count:"number",checkout_type:"enum:single|cart|link",..._},checkout_step_completed:{step:"enum:contact|delivery|invoice|consents"},checkout_validation_error:{field:"string",rule:"string"},coupon_applied:{coupon_id:"string"},coupon_rejected:{coupon_id:"string?",reason:"string"},delivery_method_selected:{method:"string"},payment_method_selected:{gateway:"string",method:"string"},payment_submitted:{gateway:"string",method:"string"},apple_pay_clicked:{},apple_pay_result:{outcome:"enum:success|fail|cancel"},payment_returned:{gateway:"string",method:"string?",outcome:"enum:success|fail|cancel|pending",error_code:"string?"},availability_signup:{},panel_login:{},panel_order_viewed:{},panel_download:{},return_started:{},return_submitted:{reason_code:"string",item_count:"number"},course_opened:{course_id:"string"},lesson_started:{course_id:"string",lesson_id:"string",position:"number"},lesson_completed:{course_id:"string",lesson_id:"string",position:"number"},video_progress:{course_id:"string",lesson_id:"string",milestone:"number"},test_submitted:{course_id:"string",lesson_id:"string",score_bucket:"enum:0-24|25-49|50-74|75-99|100"},lesson_rated:{course_id:"string",lesson_id:"string",rating:"number"},consent_updated:{consent_id:"string",action:"enum:accept_all|reject_all|custom|withdraw",analytics:"boolean",marketing:"boolean",preferences:"boolean",banner_version:"number"}},E={app_page_view:{route:"string",previous_route:"string?"},insight_shown:{insight_type:"string",rank:"number",category:"string"},insight_clicked:{insight_type:"string",rank:"number",category:"string"},insight_dismissed:{insight_type:"string",rank:"number",category:"string"},checklist_step_viewed:{step:"string"},checklist_step_completed:{step:"string"},gateway_connect_started:{gateway:"string",step:"string?"},gateway_connect_completed:{gateway:"string",step:"string?"},gateway_connect_failed:{gateway:"string",step:"string?",error_code:"string?"},domain_connect_started:{},domain_connect_verified:{},domain_connect_failed:{error_code:"string?"},product_created:{product_type:"string?"},product_published:{product_type:"string?"},product_editor_section_opened:{section:"string"},feature_enabled:{feature:"string"},stats_viewed:{tab:"string"},stats_filter_changed:{tab:"string",filter:"string"},report_exported:{report:"string",format:"string?"},search_performed:{result_count:"number"},error_shown:{code:"string",route:"string"},help_opened:{topic:"string?"},ai_assistant_used:{topic:"string?"},member_invited:{role:"string"}},d={gateway:"string?",method:"string?",value_minor:"number?",currency:"string?"},u={subscription_id:"string?",value_minor:"number?",currency:"string?"},S={transaction_created:d,transaction_success:d,transaction_failure:{...d,error_code:"string?"},transaction_expired:d,transaction_charge:d,subscription_created:u,subscription_paused:u,subscription_resumed:u,subscription_updated:u,subscription_deleted:u,subscription_charge_paid:u,subscription_charge_failed:{...u,error_code:"string?"},subscription_past_due:u,subscription_canceled:u,access_expires_in_3_days:{},access_expired:{},cart_recovery:{value_minor:"number?",currency:"string?"},testimonial_email_send:{},testimonial_fulfilled:{},partner_commission_earned:{partner_id:"string",commission_minor:"number",currency:"string"},checkout_session_created:{item_count:"number",checkout_type:"enum:single|cart|link",gateway:"string?",..._},order_paid:{gateway:"string",method:"string?",item_count:"number?",visitor_day:"string?",items:"line_items?",..._},refund_issued:{gateway:"string?",reason:"string?",..._},return_requested:{item_count:"number",reason_code:"string?"},automation_run_completed:{automation_id:"string",status:"string",trigger:"string?"},notification_sent:{medium:"string",template:"string?"},notification_failed:{medium:"string",template:"string?",error_code:"string?"},recovery_email_sent:{step:"number?"},recovery_link_clicked:{},api_request:{endpoint:"string",client:"string?",status:"number",latency_bucket:"enum:lt_50|lt_200|lt_1000|gte_1000",sample_rate:"number"}};var O={...h,...E,...S},R={storefront_events:Object.keys(h),app_events:Object.keys(E),business_events:Object.keys(S)},v=Object.fromEntries(w.flatMap(t=>R[t].map(e=>[e,t])));function x(t){return typeof t=="string"&&Object.hasOwn(v,t)}var et=365*24*60*60;function nt(t){let e=t.startsWith("pk_")?t.slice(3):t;return/^[A-Za-z0-9]{1,32}$/.test(e)?e:null}var I=/^([a-z][a-z0-9-]{0,39})@(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]{1,20})?)$/;function k(t){if(!t||t.length>s.sdk)return null;let e=I.exec(t);return e?{package:e[1],version:e[2]}:null}var m=s.utm;function g(t,e){if(t==null)return null;let r=t.trim();return r.length===0||r.includes("@")?null:r.slice(0,e)}function M(t){let r=t.split("/").map(n=>n.includes("@")||n.includes("%40")?":email":/^[A-Za-z0-9_-]{24,}$/.test(n)?":token":n).join("/")||"/";return(r.startsWith("/")?r:`/${r}`).slice(0,s.path)}function rt(t,e){let r;try{r=new URL(t,e)}catch (e2){return null}if(r.protocol!=="https:"&&r.protocol!=="http:")return null;let n=r.searchParams;return{host:r.hostname.toLowerCase().slice(0,s.host),path:M(r.pathname),utm_source:g(n.get("utm_source"),m),utm_medium:g(n.get("utm_medium"),m),utm_campaign:g(n.get("utm_campaign"),m),utm_content:g(n.get("utm_content"),m),utm_term:g(n.get("utm_term"),m),ref_code:g(n.get("ref"),s.refCode)}}var U=/^[A-Za-z0-9_-]{1,64}$/;function st(t){if(!t)return null;try{let e=new URL(t);return e.protocol!=="https:"&&e.protocol!=="http:"?null:e.hostname.toLowerCase().slice(0,s.referrerHost)}catch (e3){return null}}var ot=new TextEncoder;function it(t){return`bs_vid_${t}`}var V=/^[A-Za-z0-9_-]{22}$/;var D=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,L=/^[A-Za-z0-9_-]{8,32}$/,j=/[^\s@]+@[^\s@]+\.[A-Za-z]{2,}\b/;function f(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function z(t,e,r){let n=t[e];return n==null?null:typeof n!="string"?`bad_${e}`:n.length>r?`too_long_${e}`:null}function B(t,e){let n=t.endsWith("?")?t.slice(0,-1):t;if(n.startsWith("enum:"))return typeof e=="string"&&n.slice(5).split("|").includes(e);switch(n){case"string":return typeof e=="string"&&e.length<=s.maxPropString;case"number":return typeof e=="number"&&Number.isFinite(e);case"boolean":return typeof e=="boolean";case"string[]":return Array.isArray(e)&&e.length<=s.maxPropArray&&e.every(o=>typeof o=="string"&&o.length<=s.maxPropString);case"number[]":return Array.isArray(e)&&e.length<=s.maxPropArray&&e.every(o=>typeof o=="number"&&Number.isFinite(o));case"line_items":return Array.isArray(e)&&e.length<=s.maxPropArray&&e.every(o=>f(o)&&typeof o.product_id=="string"&&U.test(o.product_id)&&b(o.qty)&&b(o.value_minor));default:return!1}}function b(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0}function K(t){return k(t)!==null?!1:j.test(t)}function y(t){return typeof t=="string"?K(t):Array.isArray(t)?t.some(y):f(t)?Object.values(t).some(y):!1}function H(t,e){if(!x(t))return{ok:!1,reason:"unknown_event"};let r=O[t];if(!r)return{ok:!1,reason:"unknown_event"};if(!f(e))return{ok:!1,reason:"bad_props"};let n={};for(let[o,c]of Object.entries(r)){let a=e[o];if(a==null){if(!c.endsWith("?"))return{ok:!1,reason:`props_missing_${o}`};continue}if(!B(c,a))return{ok:!1,reason:`props_bad_${o}`};if(y(a))return{ok:!1,reason:`props_pii_${o}`};n[o]=c.startsWith("line_items")&&Array.isArray(a)?a.map(i=>({product_id:i.product_id,qty:i.qty,value_minor:i.value_minor})):a}return JSON.stringify(n).length>s.maxPropsChars?{ok:!1,reason:"props_too_large"}:{ok:!0,props:n}}function at(t,e={}){let r=_nullishCoalesce(e.from, () => ("browser")),n=i=>({ok:!1,reason:i});if(!f(t))return n("not_object");if(typeof t.event_id!="string"||!D.test(t.event_id))return n("bad_event_id");if(!x(t.event))return n("unknown_event");let o=v[t.event];if(r==="browser"){if(o==="business_events")return n("server_only_event");if(t.event==="consent_updated")return n("consent_via_consent_endpoint")}if(typeof t.ts!="number"||!Number.isInteger(t.ts)||t.ts<=0||t.ts>4e12)return n("bad_ts");if(t.schema_version!==1)return n("bad_schema_version");if(!N.includes(t.env))return n("bad_env");if(!A.includes(t.source))return n("bad_source");if(!T[o].includes(t.source))return n("source_not_allowed_for_event");if(!P.includes(t.channel))return n("bad_channel");if(t.sdk!=null&&(typeof t.sdk!="string"||k(t.sdk)===null))return n("bad_sdk");if(t.page_id!=null&&(typeof t.page_id!="string"||!L.test(t.page_id)))return n("bad_page_id");if(t.page_type!=null&&!$.includes(t.page_type))return n("bad_page_type");if(r==="browser"){if(typeof t.host!="string"||t.host.length===0)return n("bad_host");if(typeof t.path!="string"||!t.path.startsWith("/"))return n("bad_path")}if(typeof t.path=="string"&&t.path.includes("?"))return n("path_has_query");if(typeof t.path=="string"&&t.path.includes("#"))return n("path_has_fragment");let c=[["host",s.host],["path",s.path],["referrer_host",s.referrerHost],["utm_source",s.utm],["utm_medium",s.utm],["utm_campaign",s.utm],["utm_content",s.utm],["utm_term",s.utm],["ref_code",s.refCode],["product_id",s.id],["variant_id",s.id],["order_ref",s.id]];for(let[i,p]of c){let l=z(t,i,p);if(l)return n(l)}if(t.visitor_id!=null&&(typeof t.visitor_id!="string"||!/^[A-Za-z0-9_-]{22}$/.test(t.visitor_id)))return n("bad_visitor_id");if(t.client_id!=null&&(typeof t.client_id!="string"||!V.test(t.client_id)))return n("bad_client_id");let a=H(t.event,t.props);return a.ok?{ok:!0}:n(a.reason)}var C="bitsnap_consent";function ut(t,e){return e==="project"&&t?`${C}_${t.replace(/[^A-Za-z0-9_-]/g,"_")}`:C}function q(t){return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Y(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return atob(e+"=".repeat((4-e.length%4)%4))}function W(t){return q(JSON.stringify({v:1,id:t.id,ts:t.ts,bv:t.bv,c:t.c}))}function Z(t){try{let e=JSON.parse(Y(t));return!e||e.v!==1||typeof e.id!="string"||e.id===""||typeof e.ts!="number"||typeof e.bv!="number"||!e.c||typeof e.c.analytics!="boolean"||typeof e.c.marketing!="boolean"||typeof e.c.preferences!="boolean"?null:{id:e.id,ts:e.ts,bv:e.bv,c:{analytics:e.c.analytics,marketing:e.c.marketing,preferences:e.c.preferences}}}catch (e4){return null}}function F(t,e,r){return`${t}=${W(e)}; Max-Age=31536000; Path=/; SameSite=Lax`+(r?"; Secure":"")}function X(t){return t.split(";").map(e=>e.split("=")[0].trim()).filter(Boolean)}function G(t,e){for(let r of t.split(";")){let n=r.indexOf("=");if(n!==-1&&r.slice(0,n).trim()===e)return Z(r.slice(n+1).trim())}return null}function lt(){try{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch (e5){}let t="";for(let e=0;e<32;e++)t+=Math.floor(Math.random()*16).toString(16);return t}function pt(t,e){try{return G(t.cookie,e)}catch (e6){return null}}function _t(t,e,r){try{t.cookie=F(e,r,_optionalChain([t, 'access', _2 => _2.location, 'optionalAccess', _3 => _3.protocol])==="https:")}catch (e7){}}function gt(t,e){try{t.cookie=`${e}=; Max-Age=0; Path=/; SameSite=Lax`}catch (e8){}}function J(t){if(!t||/^[\d.]+$/.test(t)||t.includes(":"))return[];let e=t.split("."),r=[];for(let n=0;n<=e.length-2;n++)r.push(e.slice(n).join("."));return r}function dt(t,e,r){try{let n=e.filter(i=>r.includes(i.category)).flatMap(i=>_nullishCoalesce(i.cookies, () => ([])));if(n.length===0)return;let o=X(t.cookie),c=new Set;for(let i of n)if(i.endsWith("*")){let p=i.slice(0,-1);for(let l of o)l.startsWith(p)&&c.add(l)}else c.add(i);let a=J(_nullishCoalesce(_optionalChain([t, 'access', _4 => _4.location, 'optionalAccess', _5 => _5.hostname]), () => ("")));for(let i of c){let p=`${encodeURIComponent(i)}=; Max-Age=0; Path=/`;t.cookie=p;for(let l of a)t.cookie=`${p}; Domain=${l}`,t.cookie=`${p}; Domain=.${l}`}}catch (e9){}}var _react = require('react');function yt(t,e){(typeof window<"u"?_react.useLayoutEffect:(0, _react.useEffect))(t,e)}exports.a = s; exports.b = nt; exports.c = M; exports.d = rt; exports.e = st; exports.f = it; exports.g = H; exports.h = at; exports.i = ut; exports.j = lt; exports.k = pt; exports.l = _t; exports.m = gt; exports.n = J; exports.o = dt; exports.p = yt;
|
|
2
|
+
//# sourceMappingURL=chunk-XIHGWNTS.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/analytics/contract.ts"],"names":["LIMITS","STREAMS","ENVS","SOURCES","CHANNELS","PAGE_TYPES","SOURCES_FOR_STREAM","MONEY","STOREFRONT_EVENT_SPEC","APP_EVENT_SPEC","TX","SUB","BUSINESS_EVENT_SPEC","EVENT_SPEC","EVENT_NAMES","STREAM_FOR_EVENT","stream","name","isEventName","CONSENT_COOKIE_MAX_AGE_SECONDS","normalizeProjectKey","key","bare","CLIENT_RE","parseClientHeader","value","m","MAX_QUERY_VALUE","cleanValue","v","max","t","sanitizePath","pathname","joined","seg"],"mappings":"AAiBO,qrBAAMA,CAAAA,CAAS,CAEpB,cAAA,CAAgB,EAAA,CAEhB,YAAA,CAAc,KAAA,CAEd,aAAA,CAAe,IAAA,CACf,aAAA,CAAe,GAAA,CACf,YAAA,CAAc,EAAA,CACd,IAAA,CAAM,GAAA,CACN,IAAA,CAAM,GAAA,CACN,YAAA,CAAc,GAAA,CACd,GAAA,CAAK,GAAA,CACL,OAAA,CAAS,EAAA,CACT,EAAA,CAAI,EAAA,CACJ,GAAA,CAAK,EAAA,CACL,MAAA,CAAQ,EAAA,CACR,MAAA,CAAQ,EAAA,CACR,SAAA,CAAW,EAAA,CAEX,QAAA,CAAU,KACZ,CAAA,CAMaC,CAAAA,CAAU,CACrB,mBAAA,CACA,YAAA,CACA,iBACF,CAAA,CA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3/worktrees/bitsnap-react/visitor-cookie/dist/chunk-XIHGWNTS.js","sourcesContent":["/**\n * Bitsnap merchant analytics: the wire contract.\n *\n * SOURCE OF TRUTH: instapay `apps/collector/src/contract.ts` (prose version:\n * `docs/merchant-analytics-contract.md`). This file is a verbatim copy of it\n * (everything below the next comment block). Do not edit it here: change\n * instapay's file and copy it over. `computeVisitorId` and\n * `computeConsentedVisitorId` are pure but need the server secret; they are\n * server-only: the browser never calls them, so bundlers drop them.\n */\n\nexport const SCHEMA_VERSION = 1;\n\n// ---------------------------------------------------------------------------\n// Limits\n// ---------------------------------------------------------------------------\n\nexport const LIMITS = {\n /** Events in one POST /e. */\n maxBatchEvents: 50,\n /** Body of one POST /e or /consent, in bytes. */\n maxBodyBytes: 64 * 1024,\n /** `JSON.stringify(props)` of one event, in UTF-16 code units. */\n maxPropsChars: 4096,\n maxPropString: 200,\n maxPropArray: 50,\n host: 253,\n path: 512,\n referrerHost: 253,\n utm: 100,\n refCode: 64,\n id: 64,\n sdk: 64,\n pageId: 32,\n region: 64,\n osBrowser: 32,\n /** Collector replaces a client `ts` farther than this from `received_at`. */\n tsSkewMs: 24 * 60 * 60 * 1000,\n} as const;\n\n// ---------------------------------------------------------------------------\n// Enumerations\n// ---------------------------------------------------------------------------\n\nexport const STREAMS = [\n \"storefront_events\",\n \"app_events\",\n \"business_events\",\n] as const;\nexport type Stream = (typeof STREAMS)[number];\n\nexport const ENVS = [\"live\", \"test\"] as const;\nexport type Env = (typeof ENVS)[number];\n\nexport const SOURCES = [\n \"storefront\",\n \"sdk_react\",\n \"script\",\n \"server\",\n \"dashboard\",\n] as const;\nexport type Source = (typeof SOURCES)[number];\n\nexport const CHANNELS = [\n \"hosted\",\n \"custom_domain\",\n \"embed\",\n \"api\",\n \"panel\",\n] as const;\nexport type Channel = (typeof CHANNELS)[number];\n\nexport const PAGE_TYPES = [\n \"shop\",\n \"catalog\",\n \"product\",\n \"cart\",\n \"checkout\",\n \"payment\",\n \"panel\",\n \"course\",\n \"custom_page\",\n \"order\",\n \"returns\",\n \"app\",\n \"other\",\n] as const;\nexport type PageType = (typeof PAGE_TYPES)[number];\n\nexport const DEVICE_TYPES = [\"desktop\", \"mobile\", \"tablet\", \"other\"] as const;\nexport type DeviceType = (typeof DEVICE_TYPES)[number];\n\n/** Sources a browser may claim, per stream. `business_events` is server-only. */\nexport const SOURCES_FOR_STREAM: Record<Stream, readonly Source[]> = {\n storefront_events: [\"storefront\", \"sdk_react\", \"script\"],\n app_events: [\"dashboard\"],\n business_events: [\"server\"],\n};\n\n// ---------------------------------------------------------------------------\n// Event catalogue\n//\n// Each prop is `<type>[?]`: type is `string`, `number`, `boolean`, `string[]`,\n// `number[]` or `enum:a|b|c`; a trailing `?` makes the prop optional.\n// Money is always integer minor units (`*_minor`, grosze/cents) + `currency`\n// (ISO 4217, upper case). `product_id`, `variant_id` and `order_ref` live in\n// the envelope, never in props. Strings never hold PII (see the prose doc).\n// ---------------------------------------------------------------------------\n\nconst MONEY = { value_minor: \"number\", currency: \"string\" } as const;\n\n/** Browser events from hosted pages (H), bitsnap-react (R) and the script (S). */\nexport const STOREFRONT_EVENT_SPEC = {\n page_view: { landing: \"boolean\" },\n product_list_viewed: { list_id: \"string?\", item_count: \"number\" },\n product_impression: {\n list_id: \"string?\",\n product_ids: \"string[]\",\n positions: \"number[]\",\n },\n product_clicked: { list_id: \"string?\", position: \"number?\" },\n product_view: {\n price_minor: \"number\",\n currency: \"string\",\n availability: \"enum:in_stock|out_of_stock|preorder\",\n },\n variant_selected: {},\n add_to_cart: { qty: \"number\", ...MONEY },\n remove_from_cart: { qty: \"number\", ...MONEY },\n cart_opened: { item_count: \"number\", ...MONEY },\n checkout_started: {\n item_count: \"number\",\n checkout_type: \"enum:single|cart|link\",\n ...MONEY,\n },\n checkout_step_completed: {\n step: \"enum:contact|delivery|invoice|consents\",\n },\n checkout_validation_error: { field: \"string\", rule: \"string\" },\n coupon_applied: { coupon_id: \"string\" },\n coupon_rejected: { coupon_id: \"string?\", reason: \"string\" },\n delivery_method_selected: { method: \"string\" },\n payment_method_selected: { gateway: \"string\", method: \"string\" },\n payment_submitted: { gateway: \"string\", method: \"string\" },\n apple_pay_clicked: {},\n apple_pay_result: { outcome: \"enum:success|fail|cancel\" },\n payment_returned: {\n gateway: \"string\",\n method: \"string?\",\n outcome: \"enum:success|fail|cancel|pending\",\n error_code: \"string?\",\n },\n availability_signup: {},\n panel_login: {},\n panel_order_viewed: {},\n panel_download: {},\n return_started: {},\n return_submitted: { reason_code: \"string\", item_count: \"number\" },\n course_opened: { course_id: \"string\" },\n lesson_started: {\n course_id: \"string\",\n lesson_id: \"string\",\n position: \"number\",\n },\n lesson_completed: {\n course_id: \"string\",\n lesson_id: \"string\",\n position: \"number\",\n },\n video_progress: {\n course_id: \"string\",\n lesson_id: \"string\",\n /** 25, 50, 75 or 100. */\n milestone: \"number\",\n },\n test_submitted: {\n course_id: \"string\",\n lesson_id: \"string\",\n score_bucket: \"enum:0-24|25-49|50-74|75-99|100\",\n },\n lesson_rated: {\n course_id: \"string\",\n lesson_id: \"string\",\n /** 1..5. */\n rating: \"number\",\n },\n /** Written by the collector's POST /consent, never sent to POST /e. */\n consent_updated: {\n consent_id: \"string\",\n action: \"enum:accept_all|reject_all|custom|withdraw\",\n analytics: \"boolean\",\n marketing: \"boolean\",\n preferences: \"boolean\",\n banner_version: \"number\",\n },\n} as const;\n\n/** Merchant behaviour in /app, sent through the same tracker core. */\nexport const APP_EVENT_SPEC = {\n app_page_view: { route: \"string\", previous_route: \"string?\" },\n insight_shown: { insight_type: \"string\", rank: \"number\", category: \"string\" },\n insight_clicked: {\n insight_type: \"string\",\n rank: \"number\",\n category: \"string\",\n },\n insight_dismissed: {\n insight_type: \"string\",\n rank: \"number\",\n category: \"string\",\n },\n checklist_step_viewed: { step: \"string\" },\n checklist_step_completed: { step: \"string\" },\n gateway_connect_started: { gateway: \"string\", step: \"string?\" },\n gateway_connect_completed: { gateway: \"string\", step: \"string?\" },\n gateway_connect_failed: {\n gateway: \"string\",\n step: \"string?\",\n error_code: \"string?\",\n },\n domain_connect_started: {},\n domain_connect_verified: {},\n domain_connect_failed: { error_code: \"string?\" },\n product_created: { product_type: \"string?\" },\n product_published: { product_type: \"string?\" },\n product_editor_section_opened: { section: \"string\" },\n feature_enabled: { feature: \"string\" },\n stats_viewed: { tab: \"string\" },\n stats_filter_changed: { tab: \"string\", filter: \"string\" },\n report_exported: { report: \"string\", format: \"string?\" },\n search_performed: { result_count: \"number\" },\n error_shown: { code: \"string\", route: \"string\" },\n help_opened: { topic: \"string?\" },\n ai_assistant_used: { topic: \"string?\" },\n member_invited: { role: \"string\" },\n} as const;\n\nconst TX = {\n gateway: \"string?\",\n method: \"string?\",\n value_minor: \"number?\",\n currency: \"string?\",\n} as const;\nconst SUB = {\n subscription_id: \"string?\",\n value_minor: \"number?\",\n currency: \"string?\",\n} as const;\n\n/**\n * Emitted by instapay only. The lower-cased `EventType` of\n * server/event-system/event.list.ts maps 1:1 to the first group.\n */\nexport const BUSINESS_EVENT_SPEC = {\n // Mirror of the event bus (EventType.X -> x.toLowerCase()).\n transaction_created: TX,\n transaction_success: TX,\n transaction_failure: { ...TX, error_code: \"string?\" },\n transaction_expired: TX,\n transaction_charge: TX,\n subscription_created: SUB,\n subscription_paused: SUB,\n subscription_resumed: SUB,\n subscription_updated: SUB,\n subscription_deleted: SUB,\n subscription_charge_paid: SUB,\n subscription_charge_failed: { ...SUB, error_code: \"string?\" },\n subscription_past_due: SUB,\n subscription_canceled: SUB,\n access_expires_in_3_days: {},\n access_expired: {},\n cart_recovery: { value_minor: \"number?\", currency: \"string?\" },\n testimonial_email_send: {},\n testimonial_fulfilled: {},\n partner_commission_earned: {\n partner_id: \"string\",\n commission_minor: \"number\",\n currency: \"string\",\n },\n // Added by the analytics work.\n checkout_session_created: {\n item_count: \"number\",\n checkout_type: \"enum:single|cart|link\",\n gateway: \"string?\",\n ...MONEY,\n },\n order_paid: {\n gateway: \"string\",\n method: \"string?\",\n item_count: \"number?\",\n /** UTC date (`YYYY-MM-DD`) the envelope `visitor_id` was computed for. */\n visitor_day: \"string?\",\n /** Every line of the order (public hashed product ids), at most 50. */\n items: \"line_items?\",\n ...MONEY,\n },\n refund_issued: {\n gateway: \"string?\",\n reason: \"string?\",\n ...MONEY,\n },\n return_requested: { item_count: \"number\", reason_code: \"string?\" },\n automation_run_completed: {\n automation_id: \"string\",\n status: \"string\",\n trigger: \"string?\",\n },\n notification_sent: { medium: \"string\", template: \"string?\" },\n notification_failed: {\n medium: \"string\",\n template: \"string?\",\n error_code: \"string?\",\n },\n recovery_email_sent: { step: \"number?\" },\n recovery_link_clicked: {},\n api_request: {\n /** Route template without ids or query, e.g. `/api/rpc/public.v1.PublicApiService/ListProducts`. */\n endpoint: \"string\",\n /** `X-Bitsnap-Client` value, absent when the caller sent none. */\n client: \"string?\",\n status: \"number\",\n latency_bucket: \"enum:lt_50|lt_200|lt_1000|gte_1000\",\n /** 1 for errors, <1 for sampled successes; rollups divide counts by it. */\n sample_rate: \"number\",\n },\n} as const;\n\nexport const EVENT_SPEC_BY_STREAM = {\n storefront_events: STOREFRONT_EVENT_SPEC,\n app_events: APP_EVENT_SPEC,\n business_events: BUSINESS_EVENT_SPEC,\n} as const;\n\nexport const EVENT_SPEC = {\n ...STOREFRONT_EVENT_SPEC,\n ...APP_EVENT_SPEC,\n ...BUSINESS_EVENT_SPEC,\n} as const;\n\nexport type StorefrontEventName = keyof typeof STOREFRONT_EVENT_SPEC;\nexport type AppEventName = keyof typeof APP_EVENT_SPEC;\nexport type BusinessEventName = keyof typeof BUSINESS_EVENT_SPEC;\nexport type EventName = StorefrontEventName | AppEventName | BusinessEventName;\n\nexport const EVENT_NAMES = {\n storefront_events: Object.keys(STOREFRONT_EVENT_SPEC) as StorefrontEventName[],\n app_events: Object.keys(APP_EVENT_SPEC) as AppEventName[],\n business_events: Object.keys(BUSINESS_EVENT_SPEC) as BusinessEventName[],\n} as const;\n\nexport const STREAM_FOR_EVENT: Record<EventName, Stream> = Object.fromEntries(\n STREAMS.flatMap((stream) =>\n (EVENT_NAMES[stream] as string[]).map((name) => [name, stream] as const),\n ),\n) as Record<EventName, Stream>;\n\n/** True for a catalogue event name; own keys only (`constructor`, `toString` are not events). */\nexport function isEventName(name: unknown): name is EventName {\n return typeof name === \"string\" && Object.hasOwn(STREAM_FOR_EVENT, name);\n}\n\n// -- props types, derived from the spec ------------------------------------\n\ntype PropPrimitives = {\n string: string;\n number: number;\n boolean: boolean;\n \"string[]\": string[];\n \"number[]\": number[];\n line_items: Array<{ product_id: string; qty: number; value_minor: number }>;\n};\ntype SplitEnum<S extends string> = S extends `${infer H}|${infer R}`\n ? H | SplitEnum<R>\n : S;\ntype StripOpt<S extends string> = S extends `${infer B}?` ? B : S;\ntype ResolveProp<S extends string> =\n StripOpt<S> extends `enum:${infer E}`\n ? SplitEnum<E>\n : StripOpt<S> extends keyof PropPrimitives\n ? PropPrimitives[StripOpt<S>]\n : never;\ntype PropsFromSpec<S extends Record<string, string>> = {\n [K in keyof S as S[K] extends `${string}?` ? never : K]: ResolveProp<S[K]>;\n} & {\n [K in keyof S as S[K] extends `${string}?` ? K : never]?: ResolveProp<S[K]>;\n};\n\nexport type EventProps<E extends EventName> = PropsFromSpec<\n (typeof EVENT_SPEC)[E]\n>;\n\n// ---------------------------------------------------------------------------\n// Envelope\n// ---------------------------------------------------------------------------\n\n/** Fields the emitter fills in. Everything else is derived by the collector. */\nexport interface ClientEvent<E extends EventName = EventName> {\n /** UUIDv7, generated by the emitter. Dedupe key. */\n event_id: string;\n event: E;\n /** Client clock, unix ms. */\n ts: number;\n schema_version: typeof SCHEMA_VERSION;\n env: Env;\n source: Source;\n channel: Channel;\n /** `<package>@<version>`, e.g. `bitsnap-react@1.9.0`. */\n sdk?: string | null;\n /** Random per page load, in memory only. */\n page_id?: string | null;\n page_type?: PageType | null;\n host?: string | null;\n /** Path without query string and fragment, already run through `sanitizePath`. */\n path?: string | null;\n referrer_host?: string | null;\n utm_source?: string | null;\n utm_medium?: string | null;\n utm_campaign?: string | null;\n utm_content?: string | null;\n utm_term?: string | null;\n ref_code?: string | null;\n product_id?: string | null;\n variant_id?: string | null;\n order_ref?: string | null;\n /** Object on the wire; the collector stores `JSON.stringify(props)`. */\n props: EventProps<E>;\n /**\n * Only honoured for `source: \"dashboard\"`: the hashed Clerk user id computed\n * by instapay and handed to the dashboard tracker. Ignored for every other\n * source (the collector computes `visitor_id` itself).\n */\n visitor_id?: string | null;\n /**\n * The value of the first-party `bs_vid_<projectKey>` cookie (`CLIENT_ID_RE`), sent only\n * while analytics consent is granted. The collector turns it into a stable\n * `consentedVisitorId` and never stores it.\n */\n client_id?: string | null;\n}\n\n/** One row as stored in Basin (all three streams share this shape). */\nexport interface StoredEvent {\n event_id: string;\n event: EventName;\n /** Unix ms, client clock after `clampTs`. */\n ts: number;\n /** Unix ms, collector clock. */\n received_at: number;\n schema_version: number;\n /** Numeric database id. Resolved by the collector, never taken from the client. */\n project_id: number;\n env: Env;\n source: Source;\n channel: Channel;\n sdk: string | null;\n visitor_id: string | null;\n page_id: string | null;\n page_type: PageType | null;\n host: string | null;\n path: string | null;\n referrer_host: string | null;\n utm_source: string | null;\n utm_medium: string | null;\n utm_campaign: string | null;\n utm_content: string | null;\n utm_term: string | null;\n ref_code: string | null;\n country: string | null;\n region: string | null;\n device_type: DeviceType | null;\n os: string | null;\n browser: string | null;\n product_id: string | null;\n variant_id: string | null;\n order_ref: string | null;\n /** `JSON.stringify` of the props object. */\n props: string;\n}\n\n/** POST /e body. */\nexport interface IngestBody {\n /** Project key, see `normalizeProjectKey`. */\n k: string;\n events: ClientEvent[];\n}\n\n// ---------------------------------------------------------------------------\n// Consent shapes\n// ---------------------------------------------------------------------------\n\nexport const CONSENT_TEXT_KEYS = [\n \"title\",\n \"description\",\n \"acceptAll\",\n \"rejectAll\",\n \"settings\",\n \"save\",\n \"close\",\n \"necessaryTitle\",\n \"necessaryDescription\",\n \"analyticsTitle\",\n \"analyticsDescription\",\n \"marketingTitle\",\n \"marketingDescription\",\n \"preferencesTitle\",\n \"preferencesDescription\",\n \"poweredBy\",\n] as const;\nexport type ConsentTextKey = (typeof CONSENT_TEXT_KEYS)[number];\nexport type ConsentTexts = Record<ConsentTextKey, string>;\n\nexport type ConsentCategory = \"analytics\" | \"marketing\" | \"preferences\";\nexport type ConsentChoice = Record<ConsentCategory, boolean>;\n\nexport type ConsentConfig = {\n version: number;\n theme: \"auto\" | \"light\" | \"dark\";\n accentColor?: string;\n position: \"bottom\" | \"bottom-left\" | \"bottom-right\";\n privacyPolicyUrl?: string;\n categories: { analytics: boolean; marketing: boolean; preferences: boolean };\n services: Array<{\n name: string;\n category: \"analytics\" | \"marketing\" | \"preferences\";\n cookies?: string[];\n }>;\n texts?: Partial<Record<\"pl\" | \"en\", Partial<ConsentTexts>>>;\n poweredBy: true;\n};\n\n/** Value of the consent cookie, JSON then base64url. */\nexport interface ConsentCookie {\n v: 1;\n /** Random consent id (also sent to POST /consent). */\n id: string;\n /** Unix seconds. */\n ts: number;\n /** Banner version (`ConsentConfig.version`) the visitor answered. */\n bv: number;\n c: ConsentChoice;\n}\n\nexport const CONSENT_COOKIE_NAME = \"bitsnap_consent\";\nexport const CONSENT_COOKIE_MAX_AGE_SECONDS = 365 * 24 * 60 * 60;\nexport const CONSENT_ACTIONS = [\n \"accept_all\",\n \"reject_all\",\n \"custom\",\n \"withdraw\",\n] as const;\nexport type ConsentAction = (typeof CONSENT_ACTIONS)[number];\n\n/** POST /consent body. */\nexport interface ConsentLogBody {\n k: string;\n /** Same random id as `ConsentCookie.id`. 16 to 64 chars of `[A-Za-z0-9_-]`. */\n consent_id: string;\n action: ConsentAction;\n c: ConsentChoice;\n /** Banner version. */\n bv: number;\n /** Hostname the banner ran on. Collector overwrites it with the Origin host. */\n host: string;\n /** Unix SECONDS (like the cookie), not ms. */\n ts: number;\n}\n\n/** `bitsnap_consent`, or `bitsnap_consent_<projectKey>` for `data-scope=\"project\"`. */\nexport function consentCookieName(scope: \"site\" | \"project\", projectKey?: string): string {\n if (scope === \"project\") {\n if (!projectKey) throw new Error(\"projectKey required for project scope\");\n return `${CONSENT_COOKIE_NAME}_${normalizeProjectKey(projectKey)}`;\n }\n return CONSENT_COOKIE_NAME;\n}\n\n/**\n * Decodes the value of a consent cookie (§11.3). Null when it is not base64url\n * JSON of the documented shape (`v` 1 and a boolean per category).\n */\nexport function parseConsentCookie(value: string | null | undefined): ConsentCookie | null {\n if (!value || !/^[A-Za-z0-9_-]+$/.test(value)) return null;\n try {\n const padded = value.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const bin = atob(padded + \"=\".repeat((4 - (padded.length % 4)) % 4));\n const json: unknown = JSON.parse(\n new TextDecoder().decode(Uint8Array.from(bin, (ch) => ch.charCodeAt(0))),\n );\n if (!isRecord(json) || json.v !== 1) return null;\n const c = json.c;\n if (!isRecord(c)) return null;\n if (\n typeof c.analytics !== \"boolean\" ||\n typeof c.marketing !== \"boolean\" ||\n typeof c.preferences !== \"boolean\"\n ) {\n return null;\n }\n return json as unknown as ConsentCookie;\n } catch {\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Project key\n// ---------------------------------------------------------------------------\n\n/**\n * The project key is the existing public hashed project id\n * (`hashId(projectId)` in apps/bitsnap/queries/hashids.ts, the `projectID`\n * of bitsnap-react). A leading `pk_` is accepted and dropped so the\n * documented `pk_…` snippets work too. Returns null when it is not a plausible\n * key (hashids default alphabet).\n */\nexport function normalizeProjectKey(key: string): string | null {\n const bare = key.startsWith(\"pk_\") ? key.slice(3) : key;\n return /^[A-Za-z0-9]{1,32}$/.test(bare) ? bare : null;\n}\n\n// ---------------------------------------------------------------------------\n// X-Bitsnap-Client\n// ---------------------------------------------------------------------------\n\nconst CLIENT_RE = /^([a-z][a-z0-9-]{0,39})@(\\d+\\.\\d+\\.\\d+(?:[-+][0-9A-Za-z.+-]{1,20})?)$/;\n\n/** `<package>@<version>`, e.g. `bitsnap-react@1.9.0`. Also the shape of `sdk`. */\nexport function parseClientHeader(\n value: string | null | undefined,\n): { package: string; version: string } | null {\n if (!value || value.length > LIMITS.sdk) return null;\n const m = CLIENT_RE.exec(value);\n return m ? { package: m[1], version: m[2] } : null;\n}\n\n// ---------------------------------------------------------------------------\n// URL stripping\n// ---------------------------------------------------------------------------\n\nconst MAX_QUERY_VALUE = LIMITS.utm;\n\n/**\n * Campaign/ref value: trimmed, capped, null when empty or when it holds an \"@\"\n * (someone put an email in a tag). The collector runs every client-supplied\n * `utm_*` and `ref_code` through it again.\n */\nexport function cleanValue(v: string | null | undefined, max: number): string | null {\n if (v == null) return null;\n const t = v.trim();\n // An \"@\" means someone put an email in a campaign tag: drop the value.\n if (t.length === 0 || t.includes(\"@\")) return null;\n return t.slice(0, max);\n}\n\n/**\n * Path sanitiser: no query, no fragment, capped. Opaque segments (24+ chars of\n * `[A-Za-z0-9_-]`, i.e. tokens in order/panel links) become `:token` and\n * segments containing `@` become `:email`.\n */\nexport function sanitizePath(pathname: string): string {\n const segments = pathname.split(\"/\").map((seg) => {\n if (seg.includes(\"@\") || seg.includes(\"%40\")) return \":email\";\n if (/^[A-Za-z0-9_-]{24,}$/.test(seg)) return \":token\";\n return seg;\n });\n const joined = segments.join(\"/\") || \"/\";\n return (joined.startsWith(\"/\") ? joined : `/${joined}`).slice(0, LIMITS.path);\n}\n\nexport interface UrlParts {\n host: string;\n /** Sanitised path, no query. */\n path: string;\n utm_source: string | null;\n utm_medium: string | null;\n utm_campaign: string | null;\n utm_content: string | null;\n utm_term: string | null;\n /** The `ref` query parameter. */\n ref_code: string | null;\n}\n\n/**\n * Parses a URL and keeps only what may leave the browser: host, sanitised path\n * and the `utm_*` and `ref` query parameters. Returns null for non-http(s) or\n * unparseable input. `base` resolves relative URLs.\n */\nexport function parseUrl(url: string, base?: string): UrlParts | null {\n let u: URL;\n try {\n u = new URL(url, base);\n } catch {\n return null;\n }\n if (u.protocol !== \"https:\" && u.protocol !== \"http:\") return null;\n const q = u.searchParams;\n return {\n host: u.hostname.toLowerCase().slice(0, LIMITS.host),\n path: sanitizePath(u.pathname),\n utm_source: cleanValue(q.get(\"utm_source\"), MAX_QUERY_VALUE),\n utm_medium: cleanValue(q.get(\"utm_medium\"), MAX_QUERY_VALUE),\n utm_campaign: cleanValue(q.get(\"utm_campaign\"), MAX_QUERY_VALUE),\n utm_content: cleanValue(q.get(\"utm_content\"), MAX_QUERY_VALUE),\n utm_term: cleanValue(q.get(\"utm_term\"), MAX_QUERY_VALUE),\n ref_code: cleanValue(q.get(\"ref\"), LIMITS.refCode),\n };\n}\n\n/**\n * Returns the URL with userinfo, fragment and every query parameter removed\n * except `utm_*` and `ref`. Null when `url` is not a usable http(s) URL.\n */\nexport function stripUrl(url: string, base?: string): string | null {\n let u: URL;\n try {\n u = new URL(url, base);\n } catch {\n return null;\n }\n if (u.protocol !== \"https:\" && u.protocol !== \"http:\") return null;\n const keep = new URLSearchParams();\n for (const [key, value] of u.searchParams) {\n if (key !== \"ref\" && !key.startsWith(\"utm_\")) continue;\n const cleaned = cleanValue(value, MAX_QUERY_VALUE);\n if (cleaned != null) keep.append(key, cleaned);\n }\n const qs = keep.toString();\n return `${u.protocol}//${u.host}${sanitizePath(u.pathname)}${qs ? `?${qs}` : \"\"}`;\n}\n\nconst HOSTNAME_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;\n\n/** A plain DNS hostname (lower-cased), or null: no scheme, port, path, userinfo or \"@\". */\nexport function cleanHostname(\n v: string | null | undefined,\n max: number = LIMITS.referrerHost,\n): string | null {\n if (typeof v !== \"string\") return null;\n const h = v.trim().toLowerCase();\n return h.length > 0 && h.length <= max && HOSTNAME_RE.test(h) ? h : null;\n}\n\n/** Public hashed ids (`product_id`, `variant_id`, `order_ref`): URL-safe, at most `LIMITS.id`. */\nexport const ID_RE = /^[A-Za-z0-9_-]{1,64}$/;\n\nexport function cleanId(v: string | null | undefined): string | null {\n return typeof v === \"string\" && ID_RE.test(v) ? v : null;\n}\n\n/** Host of a referrer URL, or null (also null for non-http(s) referrers). */\nexport function referrerHost(referrer: string | null | undefined): string | null {\n if (!referrer) return null;\n try {\n const u = new URL(referrer);\n if (u.protocol !== \"https:\" && u.protocol !== \"http:\") return null;\n return u.hostname.toLowerCase().slice(0, LIMITS.referrerHost);\n } catch {\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Bot rule\n// ---------------------------------------------------------------------------\n\nconst BOT_UA =\n /bot\\b|crawl|spider|slurp|facebookexternalhit|bingpreview|headless|phantomjs|lighthouse|pagespeed|gtmetrix|pingdom|uptime|statuscake|monitor|preview|scrapy|curl\\/|wget|python-|go-http-client|java\\/|okhttp|axios|node-fetch|undici|libwww|httpclient|aiohttp|postman|insomnia/i;\n\n/** True when the User-Agent is empty or looks automated. Such events are dropped. */\nexport function isBotUserAgent(ua: string | null | undefined): boolean {\n if (!ua || ua.trim().length === 0) return true;\n return BOT_UA.test(ua);\n}\n\n// ---------------------------------------------------------------------------\n// visitor_id\n// ---------------------------------------------------------------------------\n\nconst encoder = new TextEncoder();\n\nasync function hmacSha256(\n key: Uint8Array,\n message: string,\n): Promise<Uint8Array> {\n const cryptoKey = await crypto.subtle.importKey(\n \"raw\",\n key,\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n return new Uint8Array(\n await crypto.subtle.sign(\"HMAC\", cryptoKey, encoder.encode(message)),\n );\n}\n\nfunction base64url(bytes: Uint8Array): string {\n let bin = \"\";\n for (const b of bytes) bin += String.fromCharCode(b);\n return btoa(bin).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** `YYYY-MM-DD` of a unix-ms timestamp in UTC. */\nexport function utcDate(ms: number): string {\n return new Date(ms).toISOString().slice(0, 10);\n}\n\n/**\n * IP as hashed: lower-case; IPv4 unchanged; IPv4-mapped IPv6 (`::ffff:1.2.3.4`\n * or `::ffff:102:304`) becomes plain IPv4; any other IPv6, including one with\n * an embedded dotted quad (`64:ff9b::1.2.3.4`), is cut to its /64 (first four\n * hextets, canonical form `a:b:c:d::`). Both the Worker and the instapay\n * server MUST call this on the client IP before `computeVisitorId`.\n */\nexport function normalizeIp(ip: string): string {\n let s = ip.trim().toLowerCase();\n const zone = s.indexOf(\"%\");\n if (zone >= 0) s = s.slice(0, zone);\n if (!s.includes(\":\")) return s; // plain IPv4 (or not an IP at all)\n\n // Embedded dotted quad in the last 32 bits: turn it into two hextets.\n const quad = /^(.*:)(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/.exec(s);\n if (quad) {\n const o = [quad[2], quad[3], quad[4], quad[5]].map(Number);\n if (o.some((n) => n > 255)) return s;\n const hex = (hi: number, lo: number) => (hi * 256 + lo).toString(16);\n s = `${quad[1]}${hex(o[0], o[1])}:${hex(o[2], o[3])}`;\n }\n\n const [head, tail] = s.split(\"::\");\n const headParts = head ? head.split(\":\") : [];\n const tailParts = tail !== undefined && tail !== \"\" ? tail.split(\":\") : [];\n const fill =\n tail === undefined ? 0 : Math.max(0, 8 - headParts.length - tailParts.length);\n const groups = [...headParts, ...Array<string>(fill).fill(\"0\"), ...tailParts];\n if (groups.length !== 8) return s;\n const h = groups.map((g) => Number.parseInt(g, 16) || 0);\n\n // ::ffff:a.b.c.d in hex form.\n if (h.slice(0, 5).every((x) => x === 0) && h[5] === 0xffff) {\n return `${h[6] >> 8}.${h[6] & 255}.${h[7] >> 8}.${h[7] & 255}`;\n }\n return `${h\n .slice(0, 4)\n .map((g) => g.toString(16))\n .join(\":\")}::`;\n}\n\n/**\n * Cookieless visitor id, identical in the Worker and the instapay server.\n *\n * day_secret = HMAC-SHA256(key = utf8(masterSecret), msg = utf8(\"YYYY-MM-DD\")) // 32 raw bytes\n * visitor_id = base64url(HMAC-SHA256(key = day_secret, msg = utf8(ip + \"\\n\" + ua + \"\\n\" + projectId))).slice(0, 22)\n *\n * `dateUtc` is the UTC date of the request; `ip` is `normalizeIp(<client IP>)`;\n * `ua` is the raw `User-Agent` request header; `projectId` is the decimal\n * numeric project id.\n */\nexport async function computeVisitorId(\n masterSecret: string,\n dateUtc: string,\n ip: string,\n ua: string,\n projectId: number | string,\n): Promise<string> {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(dateUtc)) {\n throw new Error(`dateUtc must be YYYY-MM-DD, got ${dateUtc}`);\n }\n const daySecret = await hmacSha256(encoder.encode(masterSecret), dateUtc);\n const mac = await hmacSha256(daySecret, `${ip}\\n${ua}\\n${projectId}`);\n return base64url(mac).slice(0, 22);\n}\n\n/**\n * The `bs_vid_<projectKey>` cookie name. `projectKey` is the bare public key\n * (like `consentCookieName`): consent is per project, so is the client id.\n */\nexport function clientIdCookieName(projectKey: string): string {\n return `bs_vid_${projectKey}`;\n}\n\n/** Value of the `bs_vid_<projectKey>` cookie: 16 random bytes, base64url without padding. */\nexport const CLIENT_ID_RE = /^[A-Za-z0-9_-]{22}$/;\n\n/**\n * Stable visitor id of a browser that granted analytics consent (contract §6).\n *\n * consented_visitor_id = \"p_\" + base64url(HMAC-SHA256(key = utf8(masterSecret),\n * msg = utf8(\"client\\n\" + clientId + \"\\n\" + projectId))).slice(0, 22)\n *\n * 24 characters; daily ids are 22, so `isConsentedVisitorId` tells them apart.\n * `clientId` is the `bs_vid_<projectKey>` cookie value and is never stored.\n */\nexport async function computeConsentedVisitorId(\n masterSecret: string,\n clientId: string,\n projectId: number | string,\n): Promise<string> {\n if (!CLIENT_ID_RE.test(clientId)) {\n throw new Error(\"clientId must be 22 base64url characters\");\n }\n const mac = await hmacSha256(\n encoder.encode(masterSecret),\n `client\\n${clientId}\\n${projectId}`,\n );\n return `p_${base64url(mac).slice(0, 22)}`;\n}\n\n/** Whether `visitorId` came from `computeConsentedVisitorId` (not a daily id). */\nexport function isConsentedVisitorId(visitorId: string): boolean {\n return visitorId.length === 24 && visitorId.startsWith(\"p_\");\n}\n\n// ---------------------------------------------------------------------------\n// Validation\n// ---------------------------------------------------------------------------\n\nexport type ValidationResult = { ok: true } | { ok: false; reason: string };\n\nconst UUID_V7 =\n /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\nconst PAGE_ID_RE = /^[A-Za-z0-9_-]{8,32}$/;\n/** A letter TLD is required: `bitsnap-react@1.9.0` and `v@1.2` are not addresses. */\nconst EMAIL_LIKE = /[^\\s@]+@[^\\s@]+\\.[A-Za-z]{2,}\\b/;\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\nfunction nullableString(\n e: Record<string, unknown>,\n key: string,\n max: number,\n): string | null {\n const v = e[key];\n if (v === undefined || v === null) return null;\n if (typeof v !== \"string\") return `bad_${key}`;\n return v.length > max ? `too_long_${key}` : null;\n}\n\nfunction checkPropValue(spec: string, value: unknown): boolean {\n const optional = spec.endsWith(\"?\");\n const type = optional ? spec.slice(0, -1) : spec;\n if (type.startsWith(\"enum:\")) {\n return typeof value === \"string\" && type.slice(5).split(\"|\").includes(value);\n }\n switch (type) {\n case \"string\":\n return typeof value === \"string\" && value.length <= LIMITS.maxPropString;\n case \"number\":\n return typeof value === \"number\" && Number.isFinite(value);\n case \"boolean\":\n return typeof value === \"boolean\";\n case \"string[]\":\n return (\n Array.isArray(value) &&\n value.length <= LIMITS.maxPropArray &&\n value.every((x) => typeof x === \"string\" && x.length <= LIMITS.maxPropString)\n );\n case \"number[]\":\n return (\n Array.isArray(value) &&\n value.length <= LIMITS.maxPropArray &&\n value.every((x) => typeof x === \"number\" && Number.isFinite(x))\n );\n case \"line_items\":\n return (\n Array.isArray(value) &&\n value.length <= LIMITS.maxPropArray &&\n value.every(\n (x) =>\n isRecord(x) &&\n typeof x.product_id === \"string\" &&\n ID_RE.test(x.product_id) &&\n isNonNegativeSafeInteger(x.qty) &&\n isNonNegativeSafeInteger(x.value_minor),\n )\n );\n default:\n return false;\n }\n}\n\nfunction isNonNegativeSafeInteger(value: unknown): boolean {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n}\n\n/** True when `value` looks like an email address (also exported for the collector's re-checks). */\nexport function looksLikeEmail(value: string): boolean {\n // A well-formed `<package>@<version>` client id is never an address.\n if (parseClientHeader(value) !== null) return false;\n return EMAIL_LIKE.test(value);\n}\n\nfunction hasEmailLike(value: unknown): boolean {\n if (typeof value === \"string\") return looksLikeEmail(value);\n if (Array.isArray(value)) return value.some(hasEmailLike);\n if (isRecord(value)) return Object.values(value).some(hasEmailLike);\n return false;\n}\n\n/**\n * Validates `props` against the catalogue and returns a copy without keys the\n * catalogue does not know (forward compatibility: a newer SDK adding an\n * optional prop must not get its events dropped by an older collector).\n * Fails on missing required props, wrong types, bad enum values, oversize\n * props and string values that look like an email address.\n */\nexport function sanitizeProps(\n event: string,\n props: unknown,\n): { ok: true; props: Record<string, unknown> } | { ok: false; reason: string } {\n if (!isEventName(event)) return { ok: false, reason: \"unknown_event\" };\n const spec = (EVENT_SPEC as Record<string, Record<string, string>>)[event];\n if (!spec) return { ok: false, reason: \"unknown_event\" };\n if (!isRecord(props)) return { ok: false, reason: \"bad_props\" };\n const out: Record<string, unknown> = {};\n for (const [key, type] of Object.entries(spec)) {\n const value = props[key];\n if (value === undefined || value === null) {\n if (!type.endsWith(\"?\")) return { ok: false, reason: `props_missing_${key}` };\n continue;\n }\n if (!checkPropValue(type, value)) return { ok: false, reason: `props_bad_${key}` };\n if (hasEmailLike(value)) return { ok: false, reason: `props_pii_${key}` };\n out[key] =\n type.startsWith(\"line_items\") && Array.isArray(value)\n ? value.map((x) => ({ product_id: x.product_id, qty: x.qty, value_minor: x.value_minor }))\n : value;\n }\n if (JSON.stringify(out).length > LIMITS.maxPropsChars) {\n return { ok: false, reason: \"props_too_large\" };\n }\n return { ok: true, props: out };\n}\n\nexport interface ValidateOptions {\n /**\n * Who sent it. `browser` (default) is POST /e: the event must belong to\n * `storefront_events` or `app_events`, `consent_updated` is refused (only\n * POST /consent writes it) and `source` must fit the stream. `server` is the\n * instapay emitter: any stream, `source` must fit the stream.\n */\n from?: \"browser\" | \"server\";\n}\n\n/**\n * Validates the emitter-controlled part of an event: names, types, enums,\n * lengths, the event/source/stream pairing and `props`. It does not check\n * that `ts` is plausible (use `clampTs`), origins or project keys.\n */\nexport function validateEnvelope(\n e: unknown,\n options: ValidateOptions = {},\n): ValidationResult {\n const from = options.from ?? \"browser\";\n const fail = (reason: string): ValidationResult => ({ ok: false, reason });\n if (!isRecord(e)) return fail(\"not_object\");\n\n if (typeof e.event_id !== \"string\" || !UUID_V7.test(e.event_id)) {\n return fail(\"bad_event_id\");\n }\n if (!isEventName(e.event)) return fail(\"unknown_event\");\n const stream = STREAM_FOR_EVENT[e.event as EventName];\n if (from === \"browser\") {\n if (stream === \"business_events\") return fail(\"server_only_event\");\n if (e.event === \"consent_updated\") return fail(\"consent_via_consent_endpoint\");\n }\n if (\n typeof e.ts !== \"number\" ||\n !Number.isInteger(e.ts) ||\n e.ts <= 0 ||\n e.ts > 4e12\n ) {\n return fail(\"bad_ts\");\n }\n if (e.schema_version !== SCHEMA_VERSION) return fail(\"bad_schema_version\");\n if (!ENVS.includes(e.env as Env)) return fail(\"bad_env\");\n if (!SOURCES.includes(e.source as Source)) return fail(\"bad_source\");\n if (!SOURCES_FOR_STREAM[stream].includes(e.source as Source)) {\n return fail(\"source_not_allowed_for_event\");\n }\n if (!CHANNELS.includes(e.channel as Channel)) return fail(\"bad_channel\");\n\n if (e.sdk != null) {\n if (typeof e.sdk !== \"string\" || parseClientHeader(e.sdk) === null) {\n return fail(\"bad_sdk\");\n }\n }\n if (e.page_id != null) {\n if (typeof e.page_id !== \"string\" || !PAGE_ID_RE.test(e.page_id)) {\n return fail(\"bad_page_id\");\n }\n }\n if (e.page_type != null && !PAGE_TYPES.includes(e.page_type as PageType)) {\n return fail(\"bad_page_type\");\n }\n if (from === \"browser\") {\n if (typeof e.host !== \"string\" || e.host.length === 0) return fail(\"bad_host\");\n if (typeof e.path !== \"string\" || !e.path.startsWith(\"/\")) return fail(\"bad_path\");\n }\n if (typeof e.path === \"string\" && e.path.includes(\"?\")) return fail(\"path_has_query\");\n if (typeof e.path === \"string\" && e.path.includes(\"#\")) return fail(\"path_has_fragment\");\n\n const lengths: Array<[string, number]> = [\n [\"host\", LIMITS.host],\n [\"path\", LIMITS.path],\n [\"referrer_host\", LIMITS.referrerHost],\n [\"utm_source\", LIMITS.utm],\n [\"utm_medium\", LIMITS.utm],\n [\"utm_campaign\", LIMITS.utm],\n [\"utm_content\", LIMITS.utm],\n [\"utm_term\", LIMITS.utm],\n [\"ref_code\", LIMITS.refCode],\n [\"product_id\", LIMITS.id],\n [\"variant_id\", LIMITS.id],\n [\"order_ref\", LIMITS.id],\n ];\n for (const [key, max] of lengths) {\n const problem = nullableString(e, key, max);\n if (problem) return fail(problem);\n }\n if (e.visitor_id != null) {\n if (typeof e.visitor_id !== \"string\" || !/^[A-Za-z0-9_-]{22}$/.test(e.visitor_id)) {\n return fail(\"bad_visitor_id\");\n }\n }\n if (e.client_id != null) {\n if (typeof e.client_id !== \"string\" || !CLIENT_ID_RE.test(e.client_id)) {\n return fail(\"bad_client_id\");\n }\n }\n\n const props = sanitizeProps(e.event, e.props);\n if (!props.ok) return fail(props.reason);\n return { ok: true };\n}\n\n/** Client `ts` as stored: replaced by `receivedAt` when more than 24 h away from it. */\nexport function clampTs(ts: number, receivedAt: number): number {\n return Math.abs(ts - receivedAt) > LIMITS.tsSkewMs ? receivedAt : ts;\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{o as p}from"./chunk-T2OUOO4X.mjs";import{l as g,n as d}from"./chunk-RLEC25JI.mjs";var t={projectID:void 0,loginURL:"/panel/login",theme:void 0,host:void 0,allowedReturnOrigins:[]},u=[];function w(e){t={...t,...e}}function s(){return t}function P(e){t.projectID=e}function v(e){t.theme=e}function C(e){t.loginURL=e}function R(e){t.host=e}function x(e){u=e,t={...t,allowedReturnOrigins:e}}function y(){return u}import{createContext as c,useContext as m}from"react";import{jsx as r}from"react/jsx-runtime";var f=c(s()),b=({children:e,analytics:n})=>{let o=s(),i=d(o.projectID,n,"panel");return r(p,{children:r(f.Provider,{value:{...o},children:r(g,{value:i,children:r("div",{className:"bitsnap-react",children:e})})})})},L=()=>m(f);var l=(e,n)=>`bitsnap-panel-session:${encodeURIComponent(n??"https://bitsnap.pl")}:${encodeURIComponent(e)}`,a=(e,n)=>`bitsnap-panel-email:${encodeURIComponent(n??"https://bitsnap.pl")}:${encodeURIComponent(e)}`;function $(e,n){return typeof window>"u"||!e?void 0:window.localStorage.getItem(l(e,n))??void 0}function G(e,n,o,i){typeof window>"u"||!e||(window.localStorage.setItem(l(e,i),n),window.localStorage.setItem(a(e,i),o))}function k(e,n){return typeof window>"u"||!e?null:window.localStorage.getItem(a(e,n))}function E(e,n){typeof window>"u"||!e||(window.localStorage.removeItem(l(e,n)),window.localStorage.removeItem(a(e,n)))}export{w as a,s as b,P as c,v as d,C as e,R as f,x as g,y as h,b as i,L as j,$ as k,G as l,k as m,E as n};
|
|
2
|
+
//# sourceMappingURL=chunk-YXFJG4MF.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/panel/config.ts","../src/panel/PanelProvider.tsx","../src/panel/session-storage.ts"],"sourcesContent":["import type { GetThemeOutput } from \"./types\";\n\nlet config: PanelConfig = {\n projectID: undefined,\n loginURL: \"/panel/login\",\n theme: undefined,\n host: undefined,\n allowedReturnOrigins: [],\n};\n\nlet allowedReturnOrigins: string[] = [];\n\nexport interface PanelConfig {\n projectID?: string;\n loginURL?: string;\n theme?: GetThemeOutput;\n host?: string;\n allowedReturnOrigins: string[];\n}\n\nexport function setPanelConfig(newConfig: Partial<PanelConfig>): void {\n config = { ...config, ...newConfig };\n}\n\nexport function getPanelConfig(): PanelConfig {\n return config;\n}\n\nexport function setProjectID(projectID: string): void {\n config.projectID = projectID;\n}\n\nexport function setTheme(theme: GetThemeOutput): void {\n config.theme = theme;\n}\n\nexport function setLoginURL(loginURL: string): void {\n config.loginURL = loginURL;\n}\n\nexport function setHost(host: string): void {\n config.host = host;\n}\n\nexport function setAllowedReturnOrigins(origins: string[]): void {\n allowedReturnOrigins = origins;\n config = { ...config, allowedReturnOrigins: origins };\n}\n\nexport function getAllowedReturnOrigins(): string[] {\n return allowedReturnOrigins;\n}\n","import { createContext, useContext } from \"react\";\nimport {\n InstrumentProvider,\n useInstrument,\n type AnalyticsOption,\n} from \"../analytics/instrument\";\nimport { RpcProvider } from \"../rpc-provider\";\nimport { getPanelConfig, type PanelConfig } from \"./config\";\n\nconst PanelContext = createContext<PanelConfig>(getPanelConfig());\n\nexport const PanelProvider: React.FC<{\n children: React.ReactNode;\n /**\n * Usage statistics for your Bitsnap dashboard (panel logins, orders viewed,\n * downloads, course progress). On by default; `false` turns it off. An\n * object lets you forward every event: `{ onEvent }`. Nothing is stored on\n * the visitor's device.\n */\n analytics?: AnalyticsOption;\n}> = ({ children, analytics }) => {\n const config = getPanelConfig();\n const instrument = useInstrument(config.projectID, analytics, \"panel\");\n return (\n <RpcProvider>\n <PanelContext.Provider value={{ ...config }}>\n <InstrumentProvider value={instrument}>\n <div className=\"bitsnap-react\">{children}</div>\n </InstrumentProvider>\n </PanelContext.Provider>\n </RpcProvider>\n );\n};\n\nexport const usePanelConfig = () => useContext(PanelContext);\n","const panelSessionKey = (projectID: string, host?: string) =>\n `bitsnap-panel-session:${encodeURIComponent(host ?? \"https://bitsnap.pl\")}:${encodeURIComponent(projectID)}`;\n\nconst panelEmailKey = (projectID: string, host?: string) =>\n `bitsnap-panel-email:${encodeURIComponent(host ?? \"https://bitsnap.pl\")}:${encodeURIComponent(projectID)}`;\n\nexport function getPanelSession(projectID?: string, host?: string) {\n if (typeof window === \"undefined\" || !projectID) return undefined;\n const token = window.localStorage.getItem(panelSessionKey(projectID, host));\n return token ?? undefined;\n}\n\nexport function savePanelSession(projectID: string | undefined, token: string, email: string, host?: string) {\n if (typeof window === \"undefined\" || !projectID) return;\n window.localStorage.setItem(panelSessionKey(projectID, host), token);\n window.localStorage.setItem(panelEmailKey(projectID, host), email);\n}\n\nexport function getPanelEmail(projectID?: string, host?: string) {\n if (typeof window === \"undefined\" || !projectID) return null;\n return window.localStorage.getItem(panelEmailKey(projectID, host));\n}\n\nexport function clearPanelSession(projectID?: string, host?: string) {\n if (typeof window === \"undefined\" || !projectID) return;\n window.localStorage.removeItem(panelSessionKey(projectID, host));\n window.localStorage.removeItem(panelEmailKey(projectID, host));\n}\n"],"mappings":"yFAEA,IAAIA,EAAsB,CACxB,UAAW,OACX,SAAU,eACV,MAAO,OACP,KAAM,OACN,qBAAsB,CAAC,CACzB,EAEIC,EAAiC,CAAC,EAU/B,SAASC,EAAeC,EAAuC,CACpEH,EAAS,CAAE,GAAGA,EAAQ,GAAGG,CAAU,CACrC,CAEO,SAASC,GAA8B,CAC5C,OAAOJ,CACT,CAEO,SAASK,EAAaC,EAAyB,CACpDN,EAAO,UAAYM,CACrB,CAEO,SAASC,EAASC,EAA6B,CACpDR,EAAO,MAAQQ,CACjB,CAEO,SAASC,EAAYC,EAAwB,CAClDV,EAAO,SAAWU,CACpB,CAEO,SAASC,EAAQC,EAAoB,CAC1CZ,EAAO,KAAOY,CAChB,CAEO,SAASC,EAAwBC,EAAyB,CAC/Db,EAAuBa,EACvBd,EAAS,CAAE,GAAGA,EAAQ,qBAAsBc,CAAQ,CACtD,CAEO,SAASC,GAAoC,CAClD,OAAOd,CACT,CCnDA,OAAS,iBAAAe,EAAe,cAAAC,MAAkB,QA2BhC,cAAAC,MAAA,oBAlBV,IAAMC,EAAeC,EAA2BC,EAAe,CAAC,EAEnDC,EASR,CAAC,CAAE,SAAAC,EAAU,UAAAC,CAAU,IAAM,CAChC,IAAMC,EAASJ,EAAe,EACxBK,EAAaC,EAAcF,EAAO,UAAWD,EAAW,OAAO,EACrE,OACEN,EAACU,EAAA,CACC,SAAAV,EAACC,EAAa,SAAb,CAAsB,MAAO,CAAE,GAAGM,CAAO,EACxC,SAAAP,EAACW,EAAA,CAAmB,MAAOH,EACzB,SAAAR,EAAC,OAAI,UAAU,gBAAiB,SAAAK,EAAS,EAC3C,EACF,EACF,CAEJ,EAEaO,EAAiB,IAAMC,EAAWZ,CAAY,EClC3D,IAAMa,EAAkB,CAACC,EAAmBC,IAC1C,yBAAyB,mBAAmBA,GAAQ,oBAAoB,CAAC,IAAI,mBAAmBD,CAAS,CAAC,GAEtGE,EAAgB,CAACF,EAAmBC,IACxC,uBAAuB,mBAAmBA,GAAQ,oBAAoB,CAAC,IAAI,mBAAmBD,CAAS,CAAC,GAEnG,SAASG,EAAgBH,EAAoBC,EAAe,CACjE,OAAI,OAAO,OAAW,KAAe,CAACD,EAAW,OACnC,OAAO,aAAa,QAAQD,EAAgBC,EAAWC,CAAI,CAAC,GAC1D,MAClB,CAEO,SAASG,EAAiBJ,EAA+BK,EAAeC,EAAeL,EAAe,CACvG,OAAO,OAAW,KAAe,CAACD,IACtC,OAAO,aAAa,QAAQD,EAAgBC,EAAWC,CAAI,EAAGI,CAAK,EACnE,OAAO,aAAa,QAAQH,EAAcF,EAAWC,CAAI,EAAGK,CAAK,EACnE,CAEO,SAASC,EAAcP,EAAoBC,EAAe,CAC/D,OAAI,OAAO,OAAW,KAAe,CAACD,EAAkB,KACjD,OAAO,aAAa,QAAQE,EAAcF,EAAWC,CAAI,CAAC,CACnE,CAEO,SAASO,EAAkBR,EAAoBC,EAAe,CAC/D,OAAO,OAAW,KAAe,CAACD,IACtC,OAAO,aAAa,WAAWD,EAAgBC,EAAWC,CAAI,CAAC,EAC/D,OAAO,aAAa,WAAWC,EAAcF,EAAWC,CAAI,CAAC,EAC/D","names":["config","allowedReturnOrigins","setPanelConfig","newConfig","getPanelConfig","setProjectID","projectID","setTheme","theme","setLoginURL","loginURL","setHost","host","setAllowedReturnOrigins","origins","getAllowedReturnOrigins","createContext","useContext","jsx","PanelContext","createContext","getPanelConfig","PanelProvider","children","analytics","config","instrument","useInstrument","RpcProvider","InstrumentProvider","usePanelConfig","useContext","panelSessionKey","projectID","host","panelEmailKey","getPanelSession","savePanelSession","token","email","getPanelEmail","clearPanelSession"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{A as N,f as m,i,j as d,k as R,s as c,t as E,u as p,v as S,w as l,x as y,y as I,z as T}from"./chunk-DDY7IBMG.mjs";import{d as a}from"./chunk-43IIYJ6J.mjs";var B=["orders","order","confirmation","result","myReturns","myReturn"];function P(e){return B.includes(e)}function f(e){return e?{name:"orders"}:{name:"email"}}function C(e,n){switch(n.type){case"SESSION_EXPIRED":return P(e.name)?{name:"email"}:e;case"CODE_SENT":return e.name==="email"?{name:"code"}:e;case"AUTHENTICATED":return e.name==="email"||e.name==="code"?{name:"orders"}:e;case"SELECT_ORDER":return e.name==="orders"?{name:"order",orderId:n.orderId}:e;case"REVIEW":return e.name==="order"?{name:"confirmation",orderId:e.orderId,items:n.items,note:n.note}:e;case"SUBMITTED":return e.name==="confirmation"?{name:"result",returnId:n.returnId}:e;case"OPEN_MY_RETURNS":return e.name==="orders"||e.name==="result"?{name:"myReturns"}:e;case"SELECT_RETURN":return e.name==="myReturns"?{name:"myReturn",returnId:n.returnId}:e;case"CONTINUE":return e.name==="result"?{name:"orders"}:e;case"BACK":switch(e.name){case"code":return{name:"email"};case"order":case"myReturns":return{name:"orders"};case"confirmation":return{name:"order",orderId:e.orderId,items:e.items,note:e.note};case"myReturn":return{name:"myReturns"};default:return e}}}var x={email:1,code:2,orders:3,order:4,confirmation:5,result:6},_=6;function O(e){return x[e]}import{useEffect as D,useReducer as A}from"react";import{jsx as o,jsxs as L}from"react/jsx-runtime";function g({current:e}){let n=i(),r=m("stepIndicator");return o("p",{"data-bitsnap-returns-slot":"stepIndicator",className:a("text-xs",r.className),style:r.style,children:n("stepIndicator",{current:e,total:_})})}function b({panelToken:e}){let{status:n}=d("BitsnapReturns"),[r,t]=A(C,f(!1));if(D(()=>{n==="authenticated"?t({type:"AUTHENTICATED"}):n==="anonymous"&&t({type:"SESSION_EXPIRED"})},[n]),n==="exchanging"||n==="hydrating"&&e)return o(c,{});let s=O(r.name);return L("div",{className:"flex flex-col gap-4",children:[s!=null&&o(g,{current:s}),r.name==="email"&&o(E,{onSubmitted:()=>t({type:"CODE_SENT"})}),r.name==="code"&&o(p,{onVerified:()=>t({type:"AUTHENTICATED"}),onBack:()=>t({type:"BACK"})}),r.name==="orders"&&o(S,{showLogout:!e,onSelectOrder:u=>t({type:"SELECT_ORDER",orderId:u}),onOpenMyReturns:()=>t({type:"OPEN_MY_RETURNS"})}),r.name==="order"&&o(l,{orderId:r.orderId,initialItems:r.items,initialNote:r.note,onBack:()=>t({type:"BACK"}),onContinue:({items:u,note:U})=>t({type:"REVIEW",items:u,note:U})}),r.name==="confirmation"&&o(y,{orderId:r.orderId,items:r.items,note:r.note,onBack:()=>t({type:"BACK"}),onSubmitted:u=>t({type:"SUBMITTED",returnId:u})}),r.name==="result"&&o(I,{returnId:r.returnId,onContinue:()=>t({type:"CONTINUE"}),onOpenMyReturns:()=>t({type:"OPEN_MY_RETURNS"})}),r.name==="myReturns"&&o(T,{onSelectReturn:u=>t({type:"SELECT_RETURN",returnId:u}),onBack:()=>t({type:"BACK"})}),r.name==="myReturn"&&o(N,{returnId:r.returnId,onBack:()=>t({type:"BACK"})})]})}function q(e){return o(R,{...e,children:o(b,{panelToken:e.panelAccessToken!=null&&e.panelAccessToken!==""})})}export{q as a};
|
|
2
|
+
//# sourceMappingURL=chunk-ZPTHK4OX.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/components/returns/state-machine.ts","../src/components/returns/BitsnapReturns.tsx"],"sourcesContent":["/** One line chosen for return. */\nexport type SelectedReturnLine = {\n lineId: string;\n quantity: number;\n};\n\n/** Where the default flow of `BitsnapReturns` currently is. */\nexport type ReturnsStep =\n | { name: \"email\" }\n | { name: \"code\" }\n | { name: \"orders\" }\n | {\n name: \"order\";\n orderId: string;\n /** Selection to restore when coming back from the confirmation. */\n items?: SelectedReturnLine[];\n note?: string;\n }\n | {\n name: \"confirmation\";\n orderId: string;\n items: SelectedReturnLine[];\n note: string;\n }\n | { name: \"result\"; returnId: string }\n | { name: \"myReturns\" }\n | { name: \"myReturn\"; returnId: string };\n\nexport type ReturnsStepName = ReturnsStep[\"name\"];\n\nexport type ReturnsStepEvent =\n /** A verification code was requested. */\n | { type: \"CODE_SENT\" }\n /** The session became valid: code verified, stored session or panel token. */\n | { type: \"AUTHENTICATED\" }\n /** The session was dropped by the backend, expiry or logout. */\n | { type: \"SESSION_EXPIRED\" }\n | { type: \"SELECT_ORDER\"; orderId: string }\n | { type: \"REVIEW\"; items: SelectedReturnLine[]; note: string }\n | { type: \"SUBMITTED\"; returnId: string }\n | { type: \"OPEN_MY_RETURNS\" }\n | { type: \"SELECT_RETURN\"; returnId: string }\n | { type: \"BACK\" }\n /** Leave the result screen for the order list. */\n | { type: \"CONTINUE\" };\n\nconst STEPS_WITH_SESSION: readonly ReturnsStepName[] = [\n \"orders\",\n \"order\",\n \"confirmation\",\n \"result\",\n \"myReturns\",\n \"myReturn\",\n];\n\n/** Steps that cannot be shown without a returns session. */\nexport function stepRequiresSession(step: ReturnsStepName): boolean {\n return STEPS_WITH_SESSION.includes(step);\n}\n\n/** Starts at the orders when a session exists, otherwise at the email. */\nexport function initialReturnsStep(hasSession: boolean): ReturnsStep {\n return hasSession ? { name: \"orders\" } : { name: \"email\" };\n}\n\n/**\n * Pure transition function of the default flow. Events that do not apply to\n * the current step leave it unchanged.\n */\nexport function reduceReturnsStep(\n step: ReturnsStep,\n event: ReturnsStepEvent,\n): ReturnsStep {\n switch (event.type) {\n case \"SESSION_EXPIRED\":\n // Email and code do not need a session; keep a pending verification.\n return stepRequiresSession(step.name) ? { name: \"email\" } : step;\n case \"CODE_SENT\":\n return step.name === \"email\" ? { name: \"code\" } : step;\n case \"AUTHENTICATED\":\n return step.name === \"email\" || step.name === \"code\"\n ? { name: \"orders\" }\n : step;\n case \"SELECT_ORDER\":\n return step.name === \"orders\"\n ? { name: \"order\", orderId: event.orderId }\n : step;\n case \"REVIEW\":\n return step.name === \"order\"\n ? {\n name: \"confirmation\",\n orderId: step.orderId,\n items: event.items,\n note: event.note,\n }\n : step;\n case \"SUBMITTED\":\n return step.name === \"confirmation\"\n ? { name: \"result\", returnId: event.returnId }\n : step;\n case \"OPEN_MY_RETURNS\":\n return step.name === \"orders\" || step.name === \"result\"\n ? { name: \"myReturns\" }\n : step;\n case \"SELECT_RETURN\":\n return step.name === \"myReturns\"\n ? { name: \"myReturn\", returnId: event.returnId }\n : step;\n case \"CONTINUE\":\n return step.name === \"result\" ? { name: \"orders\" } : step;\n case \"BACK\":\n switch (step.name) {\n case \"code\":\n return { name: \"email\" };\n case \"order\":\n case \"myReturns\":\n return { name: \"orders\" };\n case \"confirmation\":\n return {\n name: \"order\",\n orderId: step.orderId,\n items: step.items,\n note: step.note,\n };\n case \"myReturn\":\n return { name: \"myReturns\" };\n default:\n return step;\n }\n }\n}\n\nconst STEP_NUMBERS: Partial<Record<ReturnsStepName, number>> = {\n email: 1,\n code: 2,\n orders: 3,\n order: 4,\n confirmation: 5,\n result: 6,\n};\n\nexport const RETURNS_STEP_COUNT = 6;\n\n/** Position of a step in the return flow, `undefined` for the \"my returns\" views. */\nexport function returnsStepNumber(step: ReturnsStepName): number | undefined {\n return STEP_NUMBERS[step];\n}\n","import { useEffect, useReducer } from \"react\";\nimport { cn } from \"@/src/lib/utils\";\nimport { useReturnsSlot } from \"./appearance.context\";\nimport { ReturnsCodeStep, ReturnsEmailStep } from \"./AuthSteps\";\nimport { SkeletonRows } from \"./internal\";\nimport { ReturnsMyReturnDetail, ReturnsMyReturnsList } from \"./MyReturns\";\nimport {\n ReturnsConfirmation,\n ReturnsOrderDetail,\n ReturnsOrderList,\n ReturnsResult,\n} from \"./OrderSteps\";\nimport {\n ReturnsProvider,\n useReturnsContext,\n type ReturnsProviderProps,\n} from \"./ReturnsProvider\";\nimport {\n initialReturnsStep,\n reduceReturnsStep,\n RETURNS_STEP_COUNT,\n returnsStepNumber,\n} from \"./state-machine\";\nimport { useReturnsText } from \"./texts.context\";\n\nexport type BitsnapReturnsProps = Omit<ReturnsProviderProps, \"children\">;\n\nfunction StepIndicator({ current }: { current: number }) {\n const text = useReturnsText();\n const slot = useReturnsSlot(\"stepIndicator\");\n\n return (\n <p\n data-bitsnap-returns-slot=\"stepIndicator\"\n className={cn(\"text-xs\", slot.className)}\n style={slot.style}\n >\n {text(\"stepIndicator\", { current, total: RETURNS_STEP_COUNT })}\n </p>\n );\n}\n\n/** Default step router. All transitions come from the pure state machine. */\nfunction ReturnsRouter({ panelToken }: { panelToken: boolean }) {\n const { status } = useReturnsContext(\"BitsnapReturns\");\n const [step, dispatch] = useReducer(\n reduceReturnsStep,\n initialReturnsStep(false),\n );\n\n // A valid session (verified code, stored session, exchanged panel token)\n // moves on to the orders; a dropped one returns to the start.\n useEffect(() => {\n if (status === \"authenticated\") {\n dispatch({ type: \"AUTHENTICATED\" });\n } else if (status === \"anonymous\") {\n dispatch({ type: \"SESSION_EXPIRED\" });\n }\n }, [status]);\n\n // Without a panel token the server render and the first client render show\n // the email step; a stored session switches to the orders after hydration.\n if (status === \"exchanging\" || (status === \"hydrating\" && panelToken)) {\n return <SkeletonRows />;\n }\n\n const stepNumber = returnsStepNumber(step.name);\n\n return (\n <div className=\"flex flex-col gap-4\">\n {stepNumber != null && <StepIndicator current={stepNumber} />}\n {step.name === \"email\" && (\n <ReturnsEmailStep onSubmitted={() => dispatch({ type: \"CODE_SENT\" })} />\n )}\n {step.name === \"code\" && (\n <ReturnsCodeStep\n onVerified={() => dispatch({ type: \"AUTHENTICATED\" })}\n onBack={() => dispatch({ type: \"BACK\" })}\n />\n )}\n {step.name === \"orders\" && (\n <ReturnsOrderList\n showLogout={!panelToken}\n onSelectOrder={(orderId) =>\n dispatch({ type: \"SELECT_ORDER\", orderId })\n }\n onOpenMyReturns={() => dispatch({ type: \"OPEN_MY_RETURNS\" })}\n />\n )}\n {step.name === \"order\" && (\n <ReturnsOrderDetail\n orderId={step.orderId}\n initialItems={step.items}\n initialNote={step.note}\n onBack={() => dispatch({ type: \"BACK\" })}\n onContinue={({ items, note }) =>\n dispatch({ type: \"REVIEW\", items, note })\n }\n />\n )}\n {step.name === \"confirmation\" && (\n <ReturnsConfirmation\n orderId={step.orderId}\n items={step.items}\n note={step.note}\n onBack={() => dispatch({ type: \"BACK\" })}\n onSubmitted={(returnId) =>\n dispatch({ type: \"SUBMITTED\", returnId })\n }\n />\n )}\n {step.name === \"result\" && (\n <ReturnsResult\n returnId={step.returnId}\n onContinue={() => dispatch({ type: \"CONTINUE\" })}\n onOpenMyReturns={() => dispatch({ type: \"OPEN_MY_RETURNS\" })}\n />\n )}\n {step.name === \"myReturns\" && (\n <ReturnsMyReturnsList\n onSelectReturn={(returnId) =>\n dispatch({ type: \"SELECT_RETURN\", returnId })\n }\n onBack={() => dispatch({ type: \"BACK\" })}\n />\n )}\n {step.name === \"myReturn\" && (\n <ReturnsMyReturnDetail\n returnId={step.returnId}\n onBack={() => dispatch({ type: \"BACK\" })}\n />\n )}\n </div>\n );\n}\n\n/**\n * Customer return flow: email, code, orders, line selection, confirmation and\n * result, plus the list of earlier returns. It is `ReturnsProvider` with the\n * default step router; compose your own page from the step components to\n * change the layout.\n *\n * ```tsx\n * <BitsnapReturns projectID=\"…\" appearance={brand} texts={{ emailStepTitle: \"Return a product\" }} />\n * ```\n */\nexport function BitsnapReturns(props: BitsnapReturnsProps) {\n return (\n <ReturnsProvider {...props}>\n <ReturnsRouter panelToken={props.panelAccessToken != null && props.panelAccessToken !== \"\"} />\n </ReturnsProvider>\n );\n}\n"],"mappings":"4JA8CA,IAAMA,EAAiD,CACrD,SACA,QACA,eACA,SACA,YACA,UACF,EAGO,SAASC,EAAoBC,EAAgC,CAClE,OAAOF,EAAmB,SAASE,CAAI,CACzC,CAGO,SAASC,EAA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,EACnB,SAAApC,EAACU,EAAA,CAAc,WAAY0B,EAAM,kBAAoB,MAAQA,EAAM,mBAAqB,GAAI,EAC9F,CAEJ","names":["STEPS_WITH_SESSION","stepRequiresSession","step","initialReturnsStep","hasSession","reduceReturnsStep","event","STEP_NUMBERS","RETURNS_STEP_COUNT","returnsStepNumber","useEffect","useReducer","jsx","jsxs","StepIndicator","current","text","useReturnsText","slot","useReturnsSlot","cn","RETURNS_STEP_COUNT","ReturnsRouter","panelToken","status","useReturnsContext","step","dispatch","useReducer","reduceReturnsStep","initialReturnsStep","useEffect","SkeletonRows","stepNumber","returnsStepNumber","ReturnsEmailStep","ReturnsCodeStep","ReturnsOrderList","orderId","ReturnsOrderDetail","items","note","ReturnsConfirmation","returnId","ReturnsResult","ReturnsMyReturnsList","ReturnsMyReturnDetail","BitsnapReturns","props","ReturnsProvider"]}
|
|
1
|
+
{"version":3,"sources":["../src/components/returns/state-machine.ts","../src/components/returns/BitsnapReturns.tsx"],"sourcesContent":["/** One line chosen for return. */\nexport type SelectedReturnLine = {\n lineId: string;\n quantity: number;\n};\n\n/** Where the default flow of `BitsnapReturns` currently is. */\nexport type ReturnsStep =\n | { name: \"email\" }\n | { name: \"code\" }\n | { name: \"orders\" }\n | {\n name: \"order\";\n orderId: string;\n /** Selection to restore when coming back from the confirmation. */\n items?: SelectedReturnLine[];\n note?: string;\n }\n | {\n name: \"confirmation\";\n orderId: string;\n items: SelectedReturnLine[];\n note: string;\n }\n | { name: \"result\"; returnId: string }\n | { name: \"myReturns\" }\n | { name: \"myReturn\"; returnId: string };\n\nexport type ReturnsStepName = ReturnsStep[\"name\"];\n\nexport type ReturnsStepEvent =\n /** A verification code was requested. */\n | { type: \"CODE_SENT\" }\n /** The session became valid: code verified, stored session or panel token. */\n | { type: \"AUTHENTICATED\" }\n /** The session was dropped by the backend, expiry or logout. */\n | { type: \"SESSION_EXPIRED\" }\n | { type: \"SELECT_ORDER\"; orderId: string }\n | { type: \"REVIEW\"; items: SelectedReturnLine[]; note: string }\n | { type: \"SUBMITTED\"; returnId: string }\n | { type: \"OPEN_MY_RETURNS\" }\n | { type: \"SELECT_RETURN\"; returnId: string }\n | { type: \"BACK\" }\n /** Leave the result screen for the order list. */\n | { type: \"CONTINUE\" };\n\nconst STEPS_WITH_SESSION: readonly ReturnsStepName[] = [\n \"orders\",\n \"order\",\n \"confirmation\",\n \"result\",\n \"myReturns\",\n \"myReturn\",\n];\n\n/** Steps that cannot be shown without a returns session. */\nexport function stepRequiresSession(step: ReturnsStepName): boolean {\n return STEPS_WITH_SESSION.includes(step);\n}\n\n/** Starts at the orders when a session exists, otherwise at the email. */\nexport function initialReturnsStep(hasSession: boolean): ReturnsStep {\n return hasSession ? { name: \"orders\" } : { name: \"email\" };\n}\n\n/**\n * Pure transition function of the default flow. Events that do not apply to\n * the current step leave it unchanged.\n */\nexport function reduceReturnsStep(\n step: ReturnsStep,\n event: ReturnsStepEvent,\n): ReturnsStep {\n switch (event.type) {\n case \"SESSION_EXPIRED\":\n // Email and code do not need a session; keep a pending verification.\n return stepRequiresSession(step.name) ? { name: \"email\" } : step;\n case \"CODE_SENT\":\n return step.name === \"email\" ? { name: \"code\" } : step;\n case \"AUTHENTICATED\":\n return step.name === \"email\" || step.name === \"code\"\n ? { name: \"orders\" }\n : step;\n case \"SELECT_ORDER\":\n return step.name === \"orders\"\n ? { name: \"order\", orderId: event.orderId }\n : step;\n case \"REVIEW\":\n return step.name === \"order\"\n ? {\n name: \"confirmation\",\n orderId: step.orderId,\n items: event.items,\n note: event.note,\n }\n : step;\n case \"SUBMITTED\":\n return step.name === \"confirmation\"\n ? { name: \"result\", returnId: event.returnId }\n : step;\n case \"OPEN_MY_RETURNS\":\n return step.name === \"orders\" || step.name === \"result\"\n ? { name: \"myReturns\" }\n : step;\n case \"SELECT_RETURN\":\n return step.name === \"myReturns\"\n ? { name: \"myReturn\", returnId: event.returnId }\n : step;\n case \"CONTINUE\":\n return step.name === \"result\" ? { name: \"orders\" } : step;\n case \"BACK\":\n switch (step.name) {\n case \"code\":\n return { name: \"email\" };\n case \"order\":\n case \"myReturns\":\n return { name: \"orders\" };\n case \"confirmation\":\n return {\n name: \"order\",\n orderId: step.orderId,\n items: step.items,\n note: step.note,\n };\n case \"myReturn\":\n return { name: \"myReturns\" };\n default:\n return step;\n }\n }\n}\n\nconst STEP_NUMBERS: Partial<Record<ReturnsStepName, number>> = {\n email: 1,\n code: 2,\n orders: 3,\n order: 4,\n confirmation: 5,\n result: 6,\n};\n\nexport const RETURNS_STEP_COUNT = 6;\n\n/** Position of a step in the return flow, `undefined` for the \"my returns\" views. */\nexport function returnsStepNumber(step: ReturnsStepName): number | undefined {\n return STEP_NUMBERS[step];\n}\n","import { useEffect, useReducer } from \"react\";\nimport { cn } from \"@/src/lib/utils\";\nimport { useReturnsSlot } from \"./appearance.context\";\nimport { ReturnsCodeStep, ReturnsEmailStep } from \"./AuthSteps\";\nimport { SkeletonRows } from \"./internal\";\nimport { ReturnsMyReturnDetail, ReturnsMyReturnsList } from \"./MyReturns\";\nimport {\n ReturnsConfirmation,\n ReturnsOrderDetail,\n ReturnsOrderList,\n ReturnsResult,\n} from \"./OrderSteps\";\nimport {\n ReturnsProvider,\n useReturnsContext,\n type ReturnsProviderProps,\n} from \"./ReturnsProvider\";\nimport {\n initialReturnsStep,\n reduceReturnsStep,\n RETURNS_STEP_COUNT,\n returnsStepNumber,\n} from \"./state-machine\";\nimport { useReturnsText } from \"./texts.context\";\n\nexport type BitsnapReturnsProps = Omit<ReturnsProviderProps, \"children\">;\n\nfunction StepIndicator({ current }: { current: number }) {\n const text = useReturnsText();\n const slot = useReturnsSlot(\"stepIndicator\");\n\n return (\n <p\n data-bitsnap-returns-slot=\"stepIndicator\"\n className={cn(\"text-xs\", slot.className)}\n style={slot.style}\n >\n {text(\"stepIndicator\", { current, total: RETURNS_STEP_COUNT })}\n </p>\n );\n}\n\n/** Default step router. All transitions come from the pure state machine. */\nfunction ReturnsRouter({ panelToken }: { panelToken: boolean }) {\n const { status } = useReturnsContext(\"BitsnapReturns\");\n const [step, dispatch] = useReducer(\n reduceReturnsStep,\n initialReturnsStep(false),\n );\n\n // A valid session (verified code, stored session, exchanged panel token)\n // moves on to the orders; a dropped one returns to the start.\n useEffect(() => {\n if (status === \"authenticated\") {\n dispatch({ type: \"AUTHENTICATED\" });\n } else if (status === \"anonymous\") {\n dispatch({ type: \"SESSION_EXPIRED\" });\n }\n }, [status]);\n\n // Without a panel token the server render and the first client render show\n // the email step; a stored session switches to the orders after hydration.\n if (status === \"exchanging\" || (status === \"hydrating\" && panelToken)) {\n return <SkeletonRows />;\n }\n\n const stepNumber = returnsStepNumber(step.name);\n\n return (\n <div className=\"flex flex-col gap-4\">\n {stepNumber != null && <StepIndicator current={stepNumber} />}\n {step.name === \"email\" && (\n <ReturnsEmailStep onSubmitted={() => dispatch({ type: \"CODE_SENT\" })} />\n )}\n {step.name === \"code\" && (\n <ReturnsCodeStep\n onVerified={() => dispatch({ type: \"AUTHENTICATED\" })}\n onBack={() => dispatch({ type: \"BACK\" })}\n />\n )}\n {step.name === \"orders\" && (\n <ReturnsOrderList\n showLogout={!panelToken}\n onSelectOrder={(orderId) =>\n dispatch({ type: \"SELECT_ORDER\", orderId })\n }\n onOpenMyReturns={() => dispatch({ type: \"OPEN_MY_RETURNS\" })}\n />\n )}\n {step.name === \"order\" && (\n <ReturnsOrderDetail\n orderId={step.orderId}\n initialItems={step.items}\n initialNote={step.note}\n onBack={() => dispatch({ type: \"BACK\" })}\n onContinue={({ items, note }) =>\n dispatch({ type: \"REVIEW\", items, note })\n }\n />\n )}\n {step.name === \"confirmation\" && (\n <ReturnsConfirmation\n orderId={step.orderId}\n items={step.items}\n note={step.note}\n onBack={() => dispatch({ type: \"BACK\" })}\n onSubmitted={(returnId) =>\n dispatch({ type: \"SUBMITTED\", returnId })\n }\n />\n )}\n {step.name === \"result\" && (\n <ReturnsResult\n returnId={step.returnId}\n onContinue={() => dispatch({ type: \"CONTINUE\" })}\n onOpenMyReturns={() => dispatch({ type: \"OPEN_MY_RETURNS\" })}\n />\n )}\n {step.name === \"myReturns\" && (\n <ReturnsMyReturnsList\n onSelectReturn={(returnId) =>\n dispatch({ type: \"SELECT_RETURN\", returnId })\n }\n onBack={() => dispatch({ type: \"BACK\" })}\n />\n )}\n {step.name === \"myReturn\" && (\n <ReturnsMyReturnDetail\n returnId={step.returnId}\n onBack={() => dispatch({ type: \"BACK\" })}\n />\n )}\n </div>\n );\n}\n\n/**\n * Customer return flow: email, code, orders, line selection, confirmation and\n * result, plus the list of earlier returns. It is `ReturnsProvider` with the\n * default step router; compose your own page from the step components to\n * change the layout.\n *\n * ```tsx\n * <BitsnapReturns projectID=\"…\" appearance={brand} texts={{ emailStepTitle: \"Return a product\" }} />\n * ```\n */\nexport function BitsnapReturns(props: BitsnapReturnsProps) {\n return (\n <ReturnsProvider {...props}>\n <ReturnsRouter panelToken={props.panelAccessToken != null && props.panelAccessToken !== \"\"} />\n </ReturnsProvider>\n );\n}\n"],"mappings":"iKA8CA,IAAMA,EAAiD,CACrD,SACA,QACA,eACA,SACA,YACA,UACF,EAGO,SAASC,EAAoBC,EAAgC,CAClE,OAAOF,EAAmB,SAASE,CAAI,CACzC,CAGO,SAASC,EAAmBC,EAAkC,CACnE,OAAOA,EAAa,CAAE,KAAM,QAAS,EAAI,CAAE,KAAM,OAAQ,CAC3D,CAMO,SAASC,EACdH,EACAI,EACa,CACb,OAAQA,EAAM,KAAM,CAClB,IAAK,kBAEH,OAAOL,EAAoBC,EAAK,IAAI,EAAI,CAAE,KAAM,OAAQ,EAAIA,EAC9D,IAAK,YACH,OAAOA,EAAK,OAAS,QAAU,CAAE,KAAM,MAAO,EAAIA,EACpD,IAAK,gBACH,OAAOA,EAAK,OAAS,SAAWA,EAAK,OAAS,OAC1C,CAAE,KAAM,QAAS,EACjBA,EACN,IAAK,eACH,OAAOA,EAAK,OAAS,SACjB,CAAE,KAAM,QAAS,QAASI,EAAM,OAAQ,EACxCJ,EACN,I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CAAK,CAAC,EAE5C,EAEDf,EAAK,OAAS,gBACbd,EAAC8B,EAAA,CACC,QAAShB,EAAK,QACd,MAAOA,EAAK,MACZ,KAAMA,EAAK,KACX,OAAQ,IAAMC,EAAS,CAAE,KAAM,MAAO,CAAC,EACvC,YAAcgB,GACZhB,EAAS,CAAE,KAAM,YAAa,SAAAgB,CAAS,CAAC,EAE5C,EAEDjB,EAAK,OAAS,UACbd,EAACgC,EAAA,CACC,SAAUlB,EAAK,SACf,WAAY,IAAMC,EAAS,CAAE,KAAM,UAAW,CAAC,EAC/C,gBAAiB,IAAMA,EAAS,CAAE,KAAM,iBAAkB,CAAC,EAC7D,EAEDD,EAAK,OAAS,aACbd,EAACiC,EAAA,CACC,eAAiBF,GACfhB,EAAS,CAAE,KAAM,gBAAiB,SAAAgB,CAAS,CAAC,EAE9C,OAAQ,IAAMhB,EAAS,CAAE,KAAM,MAAO,CAAC,EACzC,EAEDD,EAAK,OAAS,YACbd,EAACkC,EAAA,CACC,SAAUpB,EAAK,SACf,OAAQ,IAAMC,EAAS,CAAE,KAAM,MAAO,CAAC,EACzC,GAEJ,CAEJ,CAYO,SAASoB,EAAeC,EAA4B,CACzD,OACEpC,EAACqC,EAAA,CAAiB,GAAGD,EACnB,SAAApC,EAACU,EAAA,CAAc,WAAY0B,EAAM,kBAAoB,MAAQA,EAAM,mBAAqB,GAAI,EAC9F,CAEJ","names":["STEPS_WITH_SESSION","stepRequiresSession","step","initialReturnsStep","hasSession","reduceReturnsStep","event","STEP_NUMBERS","RETURNS_STEP_COUNT","returnsStepNumber","useEffect","useReducer","jsx","jsxs","StepIndicator","current","text","useReturnsText","slot","useReturnsSlot","cn","RETURNS_STEP_COUNT","ReturnsRouter","panelToken","status","useReturnsContext","step","dispatch","useReducer","reduceReturnsStep","initialReturnsStep","useEffect","SkeletonRows","stepNumber","returnsStepNumber","ReturnsEmailStep","ReturnsCodeStep","ReturnsOrderList","orderId","ReturnsOrderDetail","items","note","ReturnsConfirmation","returnId","ReturnsResult","ReturnsMyReturnsList","ReturnsMyReturnDetail","BitsnapReturns","props","ReturnsProvider"]}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
type ConsentCategory = "analytics" | "marketing" | "preferences";
|
|
2
|
+
type ConsentChoices = Record<ConsentCategory, boolean>;
|
|
3
|
+
type ConsentTheme = "auto" | "light" | "dark";
|
|
4
|
+
type ConsentPosition = "bottom" | "bottom-left" | "bottom-right";
|
|
5
|
+
type ConsentLocale = "pl" | "en";
|
|
6
|
+
declare const CONSENT_CATEGORIES: readonly ConsentCategory[];
|
|
7
|
+
declare const CONSENT_TEXT_KEYS: readonly ["title", "description", "acceptAll", "rejectAll", "settings", "save", "close", "necessaryTitle", "necessaryDescription", "analyticsTitle", "analyticsDescription", "marketingTitle", "marketingDescription", "preferencesTitle", "preferencesDescription", "poweredBy"];
|
|
8
|
+
type ConsentTexts = Record<(typeof CONSENT_TEXT_KEYS)[number], string>;
|
|
9
|
+
type ConsentService = {
|
|
10
|
+
name: string;
|
|
11
|
+
category: ConsentCategory;
|
|
12
|
+
/** Cookies to delete (best effort) when the category is withdrawn. A trailing `*` matches a prefix. */
|
|
13
|
+
cookies?: string[];
|
|
14
|
+
};
|
|
15
|
+
type ConsentConfig = {
|
|
16
|
+
/** Banner version. A stored choice with a lower `bv` makes the banner ask again. */
|
|
17
|
+
version: number;
|
|
18
|
+
theme: ConsentTheme;
|
|
19
|
+
accentColor?: string;
|
|
20
|
+
position: ConsentPosition;
|
|
21
|
+
privacyPolicyUrl?: string;
|
|
22
|
+
categories: ConsentChoices;
|
|
23
|
+
services: ConsentService[];
|
|
24
|
+
texts?: Partial<Record<ConsentLocale, Partial<ConsentTexts>>>;
|
|
25
|
+
poweredBy: true;
|
|
26
|
+
};
|
|
27
|
+
/** What the consent cookie holds, and what `get()` returns. */
|
|
28
|
+
type ConsentState = {
|
|
29
|
+
id: string;
|
|
30
|
+
/** Unix seconds. */
|
|
31
|
+
ts: number;
|
|
32
|
+
/** Version of the banner the choice was made on. */
|
|
33
|
+
bv: number;
|
|
34
|
+
c: ConsentChoices;
|
|
35
|
+
};
|
|
36
|
+
type ConsentAction = "accept_all" | "reject_all" | "custom" | "withdraw";
|
|
37
|
+
/** `detail` of `bitsnap:consent` and the argument of `on('change')`. */
|
|
38
|
+
type ConsentChangeDetail = ConsentState & {
|
|
39
|
+
/** `reset` when the visitor's stored choice was cleared (`get()` is `null` then). */
|
|
40
|
+
action: ConsentAction | "reset";
|
|
41
|
+
};
|
|
42
|
+
type ConsentOptions = {
|
|
43
|
+
/** Public project key. Enables the remote config and the consent log. */
|
|
44
|
+
projectKey?: string;
|
|
45
|
+
theme?: ConsentTheme;
|
|
46
|
+
locale?: "auto" | ConsentLocale;
|
|
47
|
+
position?: ConsentPosition;
|
|
48
|
+
privacyPolicyUrl?: string;
|
|
49
|
+
/** `project` keeps one cookie per project key (`bitsnap_consent_<key>`). */
|
|
50
|
+
scope?: "global" | "project";
|
|
51
|
+
apiHost?: string;
|
|
52
|
+
collectHost?: string;
|
|
53
|
+
/** Google Consent Mode v2. `auto` is on when `gtag` or `dataLayer` already exist. */
|
|
54
|
+
gcm?: "auto" | "on" | "off";
|
|
55
|
+
/** Local overrides, merged over the defaults and the remote config. */
|
|
56
|
+
config?: Partial<ConsentConfig>;
|
|
57
|
+
/** Categories used when no remote config is loaded. */
|
|
58
|
+
categories?: Partial<ConsentChoices>;
|
|
59
|
+
reloadOnWithdraw?: boolean;
|
|
60
|
+
/**
|
|
61
|
+
* Dashboard preview: shows the banner at once from the local options, never
|
|
62
|
+
* reads or writes the cookie, loads no remote config, sends no consent log,
|
|
63
|
+
* and the buttons only close the banner.
|
|
64
|
+
*/
|
|
65
|
+
preview?: boolean;
|
|
66
|
+
/** Replaces the banner title (current locale, non-empty values only). */
|
|
67
|
+
title?: string;
|
|
68
|
+
/** Replaces the banner description (current locale, non-empty values only). */
|
|
69
|
+
description?: string;
|
|
70
|
+
};
|
|
71
|
+
type BitsnapConsentApi = {
|
|
72
|
+
/**
|
|
73
|
+
* Whose choice this banner holds: `project` keeps one cookie per project key
|
|
74
|
+
* (`bitsnap_consent_<key>`), `global` the site-wide `bitsnap_consent`.
|
|
75
|
+
*/
|
|
76
|
+
readonly scope: "global" | "project";
|
|
77
|
+
/** The bare public project key the banner was started with, if any (`pk_` stripped). */
|
|
78
|
+
readonly projectKey: string | null;
|
|
79
|
+
get(): ConsentState | null;
|
|
80
|
+
/**
|
|
81
|
+
* `true` when the visitor refused `category`, also in a choice made on an older banner
|
|
82
|
+
* version (which `get()` no longer returns) that they have not answered again yet.
|
|
83
|
+
*/
|
|
84
|
+
denied(category: ConsentCategory): boolean;
|
|
85
|
+
on(event: "change", fn: (detail: ConsentChangeDetail) => void): () => void;
|
|
86
|
+
open(): void;
|
|
87
|
+
close(): void;
|
|
88
|
+
accept(categories?: Partial<ConsentChoices>): void;
|
|
89
|
+
acceptAll(): void;
|
|
90
|
+
rejectAll(): void;
|
|
91
|
+
reset(): void;
|
|
92
|
+
/** Resolves with the stored choice (or `null`) once config and stored choice are applied. */
|
|
93
|
+
ready: Promise<ConsentState | null>;
|
|
94
|
+
destroy(): void;
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
declare global {
|
|
98
|
+
interface Window {
|
|
99
|
+
BitsnapConsent?: BitsnapConsentApi;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
type BitsnapConsentProps = {
|
|
103
|
+
/** Public project key: loads the project's banner config and logs choices. */
|
|
104
|
+
projectKey?: string;
|
|
105
|
+
theme?: ConsentOptions["theme"];
|
|
106
|
+
locale?: ConsentOptions["locale"];
|
|
107
|
+
position?: ConsentOptions["position"];
|
|
108
|
+
privacyPolicyUrl?: string;
|
|
109
|
+
/** `project` keeps the consent cookie per project key. */
|
|
110
|
+
scope?: ConsentOptions["scope"];
|
|
111
|
+
apiHost?: string;
|
|
112
|
+
collectHost?: string;
|
|
113
|
+
/** Local config, merged over the project config. */
|
|
114
|
+
config?: Partial<ConsentConfig>;
|
|
115
|
+
reloadOnWithdraw?: boolean;
|
|
116
|
+
/** Google Consent Mode v2: `auto` (default) is on when `gtag` or `dataLayer` already exist. */
|
|
117
|
+
gcm?: ConsentOptions["gcm"];
|
|
118
|
+
/** Categories offered when no remote config is loaded. */
|
|
119
|
+
categories?: ConsentOptions["categories"];
|
|
120
|
+
/** Dashboard preview: shows the banner from the local options only; touches no cookie. */
|
|
121
|
+
preview?: boolean;
|
|
122
|
+
/** Replaces the banner title. */
|
|
123
|
+
title?: string;
|
|
124
|
+
/** Replaces the banner description. */
|
|
125
|
+
description?: string;
|
|
126
|
+
};
|
|
127
|
+
/** Mounts Bitsnap Consent on the page. Renders nothing itself (the banner lives in a Shadow DOM). */
|
|
128
|
+
declare function BitsnapConsent(props: BitsnapConsentProps): null;
|
|
129
|
+
type UseConsent = {
|
|
130
|
+
/** The stored choice, or `null` while there is none (or on the server). */
|
|
131
|
+
consent: ConsentState | null;
|
|
132
|
+
/** `true` once the visitor has made a choice that is still valid. */
|
|
133
|
+
decided: boolean;
|
|
134
|
+
open: () => void;
|
|
135
|
+
accept: (categories?: Partial<ConsentChoices>) => void;
|
|
136
|
+
acceptAll: () => void;
|
|
137
|
+
rejectAll: () => void;
|
|
138
|
+
reset: () => void;
|
|
139
|
+
};
|
|
140
|
+
/** Current consent state of the page, kept up to date as the visitor chooses. */
|
|
141
|
+
declare function useConsent(): UseConsent;
|
|
142
|
+
|
|
143
|
+
/** Sync `get()`-style API with no DOM until a layer is shown. Never throws into the page. */
|
|
144
|
+
declare function createConsent(options?: ConsentOptions): BitsnapConsentApi;
|
|
145
|
+
|
|
146
|
+
declare function defaultConfig(): ConsentConfig;
|
|
147
|
+
/** Layers partial configs (later wins) over the defaults, dropping invalid values. */
|
|
148
|
+
declare function mergeConfig(...layers: (Partial<ConsentConfig> | null | undefined)[]): ConsentConfig;
|
|
149
|
+
|
|
150
|
+
declare const DEFAULT_TEXTS: Record<ConsentLocale, ConsentTexts>;
|
|
151
|
+
declare function resolveLocale(preference: "auto" | ConsentLocale | undefined, navigatorLanguage?: string): ConsentLocale;
|
|
152
|
+
/** Built-in texts for the locale, with the (non-empty) overrides of the config on top. */
|
|
153
|
+
declare function mergeTexts(locale: ConsentLocale, overrides?: Partial<Record<ConsentLocale, Partial<ConsentTexts>>>): ConsentTexts;
|
|
154
|
+
|
|
155
|
+
/** analytics -> analytics_storage; marketing -> ad_*; preferences -> functionality/personalization. */
|
|
156
|
+
declare function toConsentModeUpdate(c: ConsentChoices): {
|
|
157
|
+
analytics_storage: string;
|
|
158
|
+
ad_storage: string;
|
|
159
|
+
ad_user_data: string;
|
|
160
|
+
ad_personalization: string;
|
|
161
|
+
functionality_storage: string;
|
|
162
|
+
personalization_storage: string;
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
export { BitsnapConsent, type BitsnapConsentApi, type BitsnapConsentProps, CONSENT_CATEGORIES, CONSENT_TEXT_KEYS, type ConsentAction, type ConsentCategory, type ConsentChangeDetail, type ConsentChoices, type ConsentConfig, type ConsentLocale, type ConsentOptions, type ConsentPosition, type ConsentService, type ConsentState, type ConsentTexts, type ConsentTheme, DEFAULT_TEXTS, type UseConsent, createConsent, defaultConfig, mergeConfig, mergeTexts, resolveLocale, toConsentModeUpdate, useConsent };
|