@hermeticacomms/sdk-cordova 0.0.0-stage → 0.4.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/LICENSE +9 -0
- package/README.md +27 -2
- package/dist/index.d.ts +34 -0
- package/dist/index.js +48 -0
- package/package.json +47 -4
- package/plugin.xml +11 -0
- package/www/hermetica-cordova.js +1 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Hermetica
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,28 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @hermeticacomms/sdk-cordova
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Hermeticor for Cordova apps. The browser SDK runs unchanged in the WebView (consent gate, batching, retries with one
|
|
4
|
+
`Idempotency-Key` per batch); this package adds the FCM token from
|
|
5
|
+
[cordova-plugin-firebasex](https://github.com/dpa99c/cordova-plugin-firebasex), push open tracking, and in-app messages for the
|
|
6
|
+
app's platform. Device details come from cordova-plugin-device.
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
cordova plugin add cordova-plugin-firebasex cordova-plugin-device @hermeticacomms/sdk-cordova
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
```js
|
|
13
|
+
// after the plugin is installed, also available as window.HermeticaCordova
|
|
14
|
+
const hm = await HermeticaCordova.createCordovaClient({
|
|
15
|
+
siteKey: 'hm_pk_...', endpoint: 'https://api.example.com',
|
|
16
|
+
onDeepLink: (link) => router.navigate(link),
|
|
17
|
+
});
|
|
18
|
+
hm.consent.update({ analytics: true, marketing: true });
|
|
19
|
+
hm.identify('user-42', { email: 'ada@example.com' });
|
|
20
|
+
hm.screen('Cart');
|
|
21
|
+
hm.track('add_to_cart', { sku: 'A1' }, { value: 1999, currency: 'USD' });
|
|
22
|
+
await hm.enablePush(); // asks for permission if needed, registers the FCM token
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
- Resolves after `deviceready`. Token refreshes are sent again; the token follows `identify`, `setProfile` and `reset`.
|
|
26
|
+
- Tapped notifications track `$opened_push` and go to `onDeepLink`; others track `$received_push`.
|
|
27
|
+
- In-app messages show on start, `screen` and `track` (`inApp: false` turns them off).
|
|
28
|
+
- Pass `firebase` / `cordovaDevice` to use other plugins with the same shape.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type HybridClient, type HybridOptions } from '@hermeticacomms/sdk-browser';
|
|
2
|
+
export type { AppDevice, HybridClient, ProfileIds } from '@hermeticacomms/sdk-browser';
|
|
3
|
+
type Fail = (e: unknown) => void;
|
|
4
|
+
/** The slice of cordova-plugin-firebasex's `FirebasePlugin` used here. */
|
|
5
|
+
export interface FirebasePlugin {
|
|
6
|
+
hasPermission(ok: (granted: boolean) => void, fail?: Fail): void;
|
|
7
|
+
grantPermission(ok: (granted: boolean) => void, fail?: Fail): void;
|
|
8
|
+
getToken(ok: (token: string | null) => void, fail?: Fail): void;
|
|
9
|
+
onTokenRefresh(ok: (token: string) => void, fail?: Fail): void;
|
|
10
|
+
onMessageReceived(ok: (message: Record<string, unknown>) => void, fail?: Fail): void;
|
|
11
|
+
}
|
|
12
|
+
/** cordova-plugin-device's `window.device`. */
|
|
13
|
+
export interface CordovaDevice {
|
|
14
|
+
platform: string;
|
|
15
|
+
model?: string;
|
|
16
|
+
version?: string;
|
|
17
|
+
}
|
|
18
|
+
export interface CordovaOptions extends Omit<HybridOptions, 'platform'> {
|
|
19
|
+
/** Defaults to `window.FirebasePlugin` (cordova-plugin-firebasex). Without it, push is off (call `setPushToken` yourself). */
|
|
20
|
+
firebase?: FirebasePlugin;
|
|
21
|
+
/** Defaults to `window.device` (cordova-plugin-device), read after `deviceready`. */
|
|
22
|
+
cordovaDevice?: CordovaDevice;
|
|
23
|
+
requestPushPermission?: boolean;
|
|
24
|
+
pushEnvironment?: 'debug' | 'release';
|
|
25
|
+
}
|
|
26
|
+
export type CordovaClient = HybridClient & {
|
|
27
|
+
/** Asks for notification permission if needed and registers the FCM token. Resolves whether notifications are allowed. */
|
|
28
|
+
enablePush(): Promise<boolean>;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Hermeticor for Cordova: the browser SDK in the WebView (consent gate, batching, retries with one Idempotency-Key per batch), plus
|
|
32
|
+
* the FCM token from cordova-plugin-firebasex, push open tracking, and in-app messages for ios / android. Resolves after `deviceready`.
|
|
33
|
+
*/
|
|
34
|
+
export declare function createCordovaClient(o: CordovaOptions): Promise<CordovaClient>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/// <reference lib="dom" />
|
|
2
|
+
import { createHybridClient } from '@hermeticacomms/sdk-browser';
|
|
3
|
+
const whenReady = () => new Promise((r) => {
|
|
4
|
+
if (globalThis.cordova === undefined)
|
|
5
|
+
return r(); // not in Cordova (tests, a browser preview)
|
|
6
|
+
document.addEventListener('deviceready', () => r(), { once: true });
|
|
7
|
+
});
|
|
8
|
+
const ask = (f) => new Promise((r) => f(r, () => r(false)));
|
|
9
|
+
/**
|
|
10
|
+
* Hermeticor for Cordova: the browser SDK in the WebView (consent gate, batching, retries with one Idempotency-Key per batch), plus
|
|
11
|
+
* the FCM token from cordova-plugin-firebasex, push open tracking, and in-app messages for ios / android. Resolves after `deviceready`.
|
|
12
|
+
*/
|
|
13
|
+
export async function createCordovaClient(o) {
|
|
14
|
+
await whenReady();
|
|
15
|
+
const g = globalThis;
|
|
16
|
+
const { firebase = g.FirebasePlugin, cordovaDevice = g.device, requestPushPermission = false, pushEnvironment = 'release', ...rest } = o;
|
|
17
|
+
const platform = cordovaDevice?.platform.toLowerCase() === 'ios' ? 'ios' : 'android';
|
|
18
|
+
const device = { ...(cordovaDevice?.model ? { deviceModel: cordovaDevice.model } : {}), osName: platform, ...(cordovaDevice?.version ? { osVersion: cordovaDevice.version } : {}), ...rest.device };
|
|
19
|
+
const hm = createHybridClient({ ...rest, platform, device, sdkVersion: 'cordova-0.4.0' });
|
|
20
|
+
let allowed = false;
|
|
21
|
+
const send = (token) => {
|
|
22
|
+
if (!token)
|
|
23
|
+
return;
|
|
24
|
+
const t = { token, vendor: 'fcm', environment: pushEnvironment, enablementStatus: allowed ? 'AUTHORIZED' : 'DENIED' };
|
|
25
|
+
void hm.setPushToken(t);
|
|
26
|
+
};
|
|
27
|
+
async function enablePush() {
|
|
28
|
+
if (!firebase)
|
|
29
|
+
return false;
|
|
30
|
+
allowed = (await ask((ok, fail) => firebase.hasPermission(ok, fail))) || (await ask((ok, fail) => firebase.grantPermission(ok, fail)));
|
|
31
|
+
firebase.getToken(send, () => undefined);
|
|
32
|
+
return allowed;
|
|
33
|
+
}
|
|
34
|
+
if (firebase) {
|
|
35
|
+
firebase.onTokenRefresh(send, () => undefined);
|
|
36
|
+
// firebasex flattens the data into the message and sets `tap` when the user opened it.
|
|
37
|
+
firebase.onMessageReceived((m) => { if (m['tap'])
|
|
38
|
+
hm.handlePushOpened(m);
|
|
39
|
+
else
|
|
40
|
+
hm.handlePushReceived(m); }, () => undefined);
|
|
41
|
+
if (requestPushPermission)
|
|
42
|
+
void enablePush();
|
|
43
|
+
else
|
|
44
|
+
void ask((ok, fail) => firebase.hasPermission(ok, fail)).then((yes) => { if (yes)
|
|
45
|
+
void enablePush(); });
|
|
46
|
+
}
|
|
47
|
+
return { ...hm, enablePush };
|
|
48
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hermeticacomms/sdk-cordova",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "Hermetica for Cordova: events, consent, FCM push tokens, in-app messages",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/hermeticacomms/hermetica-cordova.git"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/hermeticacomms/hermetica-cordova#readme",
|
|
12
|
+
"publishConfig": {
|
|
13
|
+
"access": "public",
|
|
14
|
+
"provenance": true
|
|
15
|
+
},
|
|
16
|
+
"exports": {
|
|
17
|
+
".": {
|
|
18
|
+
"types": "./dist/index.d.ts",
|
|
19
|
+
"default": "./dist/index.js"
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"dist",
|
|
24
|
+
"www",
|
|
25
|
+
"plugin.xml"
|
|
26
|
+
],
|
|
27
|
+
"scripts": {
|
|
28
|
+
"prepare": "npm run build",
|
|
29
|
+
"build": "node build.mjs && tsc -p tsconfig.json",
|
|
30
|
+
"test": "vitest run",
|
|
31
|
+
"typecheck": "tsc -p tsconfig.json --noEmit"
|
|
32
|
+
},
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"@hermeticacomms/sdk-browser": "^0.4.0"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"esbuild": "^0.28.2",
|
|
38
|
+
"happy-dom": "^21.0.4",
|
|
39
|
+
"typescript": "^7.0.2",
|
|
40
|
+
"vitest": "^5.0.5"
|
|
41
|
+
},
|
|
42
|
+
"cordova": {
|
|
43
|
+
"id": "hermetica-cordova",
|
|
44
|
+
"platforms": [
|
|
45
|
+
"android",
|
|
46
|
+
"ios"
|
|
47
|
+
]
|
|
48
|
+
}
|
|
49
|
+
}
|
package/plugin.xml
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
<!-- Lets `cordova plugin add @hermeticacomms/sdk-cordova` expose the SDK as window.HermeticaCordova (built into www/ by build.mjs). -->
|
|
3
|
+
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" id="hermetica-cordova" version="0.4.0">
|
|
4
|
+
<name>Hermeticor</name>
|
|
5
|
+
<description>Hermeticor SDK for Cordova: events, identity, consent, push tokens and in-app messages.</description>
|
|
6
|
+
<license>MIT</license>
|
|
7
|
+
<js-module src="www/hermetica-cordova.js" name="Hermetica">
|
|
8
|
+
<clobbers target="HermeticaCordova" />
|
|
9
|
+
</js-module>
|
|
10
|
+
<dependency id="cordova-plugin-device" />
|
|
11
|
+
</plugin>
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var pe=Object.defineProperty;var ze=Object.getOwnPropertyDescriptor;var Re=Object.getOwnPropertyNames;var Ve=Object.prototype.hasOwnProperty;var Ke=(e,t)=>{for(var n in t)pe(e,n,{get:t[n],enumerable:!0})},He=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Re(t))!Ve.call(e,a)&&a!==n&&pe(e,a,{get:()=>t[a],enumerable:!(r=ze(t,a))||r.enumerable});return e};var Be=e=>He(pe({},"__esModule",{value:!0}),e);var Lt={};Ke(Lt,{createCordovaClient:()=>Pt});module.exports=Be(Lt);var Fe="a,button,[role=button],[data-hm-capture]",Je=e=>(e.textContent??"").replace(/\s+/g," ").trim().slice(0,60);function We(e,t=document){let n=[],r=o=>{let c=o.target instanceof Element?o.target.closest(Fe):null;if(!c||c.closest("[data-hm-no-capture]"))return;let u={tag:c.tagName.toLowerCase(),id:c.id||void 0,text:Je(c),href:c instanceof HTMLAnchorElement?c.href:void 0,path:location.pathname};e("element_click",u);let s=Date.now();n=[...n.filter(i=>s-i.at<1e3&&i.el===c),{el:c,at:s}],n.length===3&&e("rage_click",u)},a=()=>e("page_leave",{path:location.pathname});return t.addEventListener("click",r,!0),addEventListener("pagehide",a),()=>{t.removeEventListener("click",r,!0),removeEventListener("pagehide",a)}}var Qe=/^https:\/\/(?:www\.youtube(?:-nocookie)?\.com\/embed|player\.vimeo\.com\/video)\/([\w-]+)/,Ye=["video_ended","video_play","video_pause"],se=["play","pause","ended"];function Ze(e,t=document){let n=(s,i)=>e(s,{path:location.pathname,pageId:t.documentElement.dataset.hmPageId,...i}),r=s=>{let i=s.target;!(i instanceof HTMLVideoElement)||i.closest("[data-hm-no-capture]")||s.type==="pause"&&i.ended||n("video_"+s.type,{provider:"html5",src:(i.currentSrc||i.src).slice(0,300),seconds:Math.round(i.currentTime),duration:Math.round(i.duration)||void 0})},a=new Map,o=()=>t.querySelectorAll("iframe").forEach(s=>{let i=s.contentWindow,l=Qe.exec(s.src);if(!i||!l||a.has(i)||s.closest("[data-hm-no-capture]"))return;let b=s.src.includes("youtu");if(b&&!/[?&]enablejsapi=1/.test(s.src))return;a.set(i,{yt:b,id:l[1]});let h=d=>i.postMessage(JSON.stringify(d),new URL(s.src).origin);b?h({event:"listening",id:l[1],channel:"widget"}):se.forEach(d=>h({method:"addEventListener",value:d}))}),c=s=>{let i=s.source&&a.get(s.source);if(!i||!/youtube|vimeo/.test(s.origin))return;let l;try{l=typeof s.data=="string"?JSON.parse(s.data):s.data}catch{return}let b=i.yt?l.event==="onStateChange"?Ye[l.info]:void 0:se.includes(l.event)?"video_"+l.event:void 0;b&&n(b,{provider:i.yt?"youtube":"vimeo",videoId:i.id,seconds:Math.round(l.data?.seconds??0)||void 0})};se.forEach(s=>t.addEventListener(s,r,!0)),addEventListener("message",c),o();let u=new MutationObserver(o);return u.observe(t.documentElement,{childList:!0,subtree:!0}),()=>{se.forEach(s=>t.removeEventListener(s,r,!0)),removeEventListener("message",c),u.disconnect()}}var me=(e,t)=>new RegExp(`^${e.split("*").map(n=>n.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*")}$`).test(t),ge=e=>!!(e.audience?.listIds?.length||e.audience?.segmentIds?.length||e.hideKnownSubscribers||e.countries?.length||e.countriesExclude?.length);function Ge(e,t){if(e.hideKnownSubscribers&&(!t||t.subscriber))return!1;let n=[...(e.audience?.listIds??[]).map(a=>t?.lists[a]),...(e.audience?.segmentIds??[]).map(a=>t?.segments[a])];if(n.length){let a=n.some(o=>o===!0);if((e.audience?.mode??"show")==="show"?!a:a)return!1}let r=a=>a.some(o=>t?.countries[o]===!0);return!(e.countries?.length&&!r(e.countries)||e.countriesExclude?.length&&r(e.countriesExclude))}function Ue(e,t){if(t.submitted||e.frequencyDays!==void 0&&t.lastClosedAt!==void 0&&t.now-t.lastClosedAt<e.frequencyDays*864e5||e.device==="mobile"&&!t.mobile||e.device==="desktop"&&t.mobile||e.visitor==="new"&&t.returning||e.visitor==="returning"&&!t.returning||e.minPageViews&&t.pageViews<e.minPageViews||e.urlExclude?.some(n=>me(n,t.path))||e.urlInclude?.length&&!e.urlInclude.some(n=>me(n,t.path)))return!1;if(e.utm)for(let n of["source","medium","campaign"]){let r=e.utm[n];if(r&&(t.utm?.[n]??"").toLowerCase()!==r.toLowerCase())return!1}if(e.referrerInclude?.length&&!e.referrerInclude.some(n=>me(n.toLowerCase(),(t.referrer??"").toLowerCase())))return!1;if(e.cart){let n=t.cart??{value:0,items:0};if(e.cart.empty===!0&&n.items>0||e.cart.empty===!1&&n.items===0||e.cart.minValue!==void 0&&n.value<e.cart.minValue||e.cart.minItems!==void 0&&n.items<e.cart.minItems)return!1}return!(e.productPage==="only"&&!t.productPage||e.productPage==="never"&&t.productPage||ge(e)&&!Ge(e,t.flags))}function Ae(e){return e.querySelector('meta[property="og:type"][content="product" i], meta[property="og:type"][content="og:product" i], [itemtype*="schema.org/Product"]')?!0:[...e.querySelectorAll('script[type="application/ld+json"]')].some(t=>/"@type"\s*:\s*"Product"/.test(t.textContent??""))}function Xe(e,t,n){let r=[],a=!1,o=()=>{a=!0,r.forEach(i=>i())},c=()=>{a||(o(),n())},u=(i,l,b)=>{i.addEventListener(l,b,{passive:!0}),r.push(()=>i.removeEventListener(l,b))},s=t&&(e.exitIntent||e.inactivitySeconds!==void 0);if(e.delaySeconds===void 0&&e.scrollPercent===void 0&&!e.exitIntent&&e.inactivitySeconds===void 0)return c(),o;if(e.delaySeconds!==void 0){let i=setTimeout(c,e.delaySeconds*1e3);r.push(()=>clearTimeout(i))}if(e.scrollPercent!==void 0&&u(window,"scroll",()=>{(scrollY+innerHeight)/document.documentElement.scrollHeight*100>=e.scrollPercent&&c()}),e.exitIntent&&!t&&u(document,"mouseout",i=>{let l=i;!l.relatedTarget&&l.clientY<=0&&c()}),s){let i,l=()=>{clearTimeout(i),i=setTimeout(c,(e.inactivitySeconds??30)*1e3)};l();for(let b of["touchstart","scroll","keydown"])u(window,b,l);e.exitIntent&&e.mobileBackExit&&(history.pushState({hm:1},""),u(window,"popstate",c)),r.push(()=>clearTimeout(i))}return o}var et=".tab{position:fixed;z-index:2147483000;margin:0;box-shadow:0 2px 12px #0004}.skip{background:none;border:0;color:inherit;text-decoration:underline}.bar{position:fixed;left:0;right:0;z-index:2147483000}.bar.top{top:0}.bar.bottom{bottom:0}.bar .box{max-width:none;border-radius:0;display:flex;flex-wrap:wrap;align-items:center;gap:8px;padding:10px 48px 10px 16px}.bar .msg{margin:0}.bar form,.bar fieldset{display:flex;flex-wrap:wrap;align-items:center;gap:8px;flex:1}.bar label{margin:0}.bar button{margin:0}@media(max-width:600px){.bar .box,.bar form,.bar fieldset{flex-direction:column;align-items:stretch}}",ke={left:"left:0;top:50%",right:"right:0;top:50%",bottom:"bottom:0;left:50%",top_left:"top:16px;left:16px",top_right:"top:16px;right:16px",bottom_left:"bottom:16px;left:16px",bottom_right:"bottom:16px;right:16px"},tt=e=>ke[e??"right"]??ke.right,Oe=(e,t)=>e==="popup"||e==="flyout"?t:void 0;function nt(e,t){let n=document.body.style,r=t?"paddingTop":"paddingBottom",a=n[r],o=parseFloat(getComputedStyle(document.body)[r])||0;return n[r]=`${o+e.offsetHeight}px`,()=>{n[r]=a}}var rt=/^#[0-9a-f]{3,8}$/i,$e={system:"system-ui,sans-serif",serif:"Georgia,serif",mono:"ui-monospace,monospace"},Se="hm_pv",it={turnstile:["challenges.cloudflare.com/turnstile/v0","turnstile"],hcaptcha:["js.hcaptcha.com/1","hcaptcha"],recaptcha:["www.google.com/recaptcha","grecaptcha"],friendlycaptcha:["cdn.jsdelivr.net/npm/friendly-challenge@0.9.18","friendlyChallenge"]},be,ot=()=>be,qe,_e=e=>{be={value:Math.max(0,Number(e.value)||0),items:Math.max(0,Math.floor(Number(e.items)||0))},qe?.()},oe=globalThis,at=e=>[e].flat().filter(t=>t!==void 0&&t!==!1&&t!=="").map(String),st=(e=[],t)=>e.every(n=>{let r=at(t[n.field]);return n.op==="filled"?!!r.length:n.op==="empty"?!r.length:n.op==="neq"?!r.includes(n.value):n.op==="contains"?r.some(a=>a.toLowerCase().includes(n.value.toLowerCase())):r.includes(n.value)});function lt(e){let t=(a,o)=>a&&rt.test(a)?a:o,n=t(e?.primary,"#1f6feb"),r=e?.buttonStyle!=="outline";return`:host{all:initial}.box{font:15px/1.5 ${$e[e?.font??"system"]??$e.system};background:${t(e?.background,"#fff")};color:${t(e?.text,"#111")};padding:20px;border-radius:${Math.min(32,Number(e?.radius??8))|0}px;box-shadow:0 4px 24px #0004;max-width:min(92vw,400px);box-sizing:border-box}.pop{position:fixed;inset:0;display:grid;place-items:center;background:#0006;z-index:2147483000}.fly{position:fixed;right:16px;bottom:16px;z-index:2147483000}label{display:block;margin:10px 0}input:not([type=checkbox]):not([type=radio]),select{display:block;width:100%;box-sizing:border-box;padding:8px;margin-top:4px}fieldset{border:0;padding:0;margin:0}button{cursor:pointer;padding:9px 16px;border:2px solid ${n};border-radius:inherit;background:${r?n:"transparent"};color:${r?"#fff":n};margin:8px 8px 0 0}button.x{position:absolute;top:6px;right:10px;border:0;background:none;color:inherit;font-size:20px}.box{position:relative}.wheel{width:150px;height:150px;border-radius:50%;margin:8px auto;transition:transform 3s ease-out}.err{color:#b42318}.hp{position:absolute;left:-9999px}img{max-height:40px;display:block;margin-bottom:8px}${et}`}function g(e,t={},...n){let r=Object.assign(document.createElement(e),t);return r.append(...n),r}function dt(e,t){let n=!!e.required;if(e.type==="password")return g("label",{},e.label??"",g("input",{type:"password",name:e.key,required:n,autocomplete:"new-password"}));if(e.type==="company"){let o=`hm-co-${e.key}-${Math.random().toString(36).slice(2,8)}`,c=g("datalist",{id:o}),u=g("input",{type:"text",name:e.key,required:n,autocomplete:"organization"});u.setAttribute("list",o);let s;return u.addEventListener("input",()=>{clearTimeout(s);let i=u.value.trim();i.length<2||(s=setTimeout(()=>{t(i).then(l=>c.replaceChildren(...l.map(b=>g("option",{value:b}))))},250))}),g("label",{},e.label??"",u,c)}if(e.type==="freetext")return g(e.style==="heading"?"strong":"p",{},(e.text??"").replace(/<[^>]*>/g,""));if(e.type==="textarea")return g("label",{},e.label??"",g("textarea",{name:e.key,required:n}));if(e.type==="hidden")return g("input",{type:"hidden",name:e.key,value:e.value??""});if(e.type==="checkbox"||e.type.startsWith("consent_"))return g("label",{},g("input",{type:"checkbox",name:e.key,required:n}),` ${e.disclosureText??e.label??""} `,...e.privacyUrl?[g("a",{href:e.privacyUrl,target:"_blank",rel:"noopener noreferrer"},"Privacy policy")]:[]);if(e.type==="radio"||e.type==="checkbox_group"||e.type==="quiz"){let o=e.type==="checkbox_group"?"checkbox":"radio",c=e.type==="quiz"?(e.choices??[]).map(s=>s.label):e.options??[],u=(s,i)=>e.type==="quiz"?e.choices?.[i]?.display??s:s;return g("fieldset",{className:"grp"},g("legend",{},e.label??""),...c.map((s,i)=>g("label",{},g("input",{type:o,name:e.key,value:s,required:n&&o==="radio"}),` ${u(s,i)}`)))}if(e.type==="select")return g("label",{},e.label??"",g("select",{name:e.key,required:n},g("option",{value:""}),...(e.options??[]).map(o=>g("option",{},o))));let r={email:"email",phone:"tel",number:"number",rating:"number",date:"date",url:"url",datetime:"datetime-local",slider:"range",file:"file"}[e.type]??"text",a=e.type==="slider"?{min:e.min,max:e.max,step:e.step}:e.type==="rating"?{min:1,max:e.max}:{};return g("label",{},e.label??"",g("input",{type:r,name:e.key,required:n,...a}))}function fe(e){var t;let n={};for(let r of e.querySelectorAll("[name]"))if(!(r.name==="website"||r.type==="file"||r.disabled||r.name.endsWith("-response")||r.name.endsWith("-solution"))){if(r.closest(".grp")){r.checked&&(r.type==="radio"?n[r.name]=r.value:(n[t=r.name]??(n[t]=[])).push(r.value));continue}n[r.name]=r.type==="checkbox"?r.checked:r.value}return n}var he=e=>!!e&&/^https?:/.test(e)&&!!(location.href=e);function ct(e,t,n){let r=Object.fromEntries(e.outcomes.map(a=>[a.key,0]));for(let a of t)for(let[o,c]of Object.entries(a.choices?.find(u=>u.label===n[a.key])?.scores??{}))o in r&&(r[o]=r[o]+c*(a.weight??1));return e.outcomes.reduce((a,o)=>!a||r[o.key]>r[a.key]?o:a,void 0)}var ut=e=>e.querySelectorAll("input:not([type=hidden]),select,textarea").forEach(t=>{t.required=!1,t.type==="checkbox"||t.type==="radio"?t.checked=!1:t.value=""});function pt(e,t,n,r,a=!1){let o=e.definition,c=Date.now(),u={authorization:`Bearer ${n.siteKey}`},s=t.attachShadow({mode:"open"}),i=lt(o.theme);if("adoptedStyleSheets"in s&&typeof CSSStyleSheet<"u"){let y=new CSSStyleSheet;y.replaceSync(i),s.adoptedStyleSheets=[y]}else s.append(g("style",{},i));let l=0,b=g("p",{className:"err",role:"alert"}),h=[],d=async y=>{try{let v=await fetch(`${n.endpoint.replace(/\/$/,"")}/ingest/v1/forms/${e.id}/companies?q=${encodeURIComponent(y)}`,{headers:u});return v.ok?(await v.json()).items:[]}catch{return[]}},m=o.steps.map(y=>g("fieldset",{},...y.title?[g("strong",{},y.title)]:[],...y.fields.map(v=>{let k=dt(v,d);return h.push([v,k]),k}))),f=m.length-1,S=!!o.saveEachStep&&f>0,C="",P,N=new Set,L=y=>{f>0&&n.client.track("form_step",{formId:e.id,versionId:e.versionId,step:l,action:y})},J=g("div"),z=g("input",{name:"website",tabIndex:-1,autocomplete:"off"}),U=g("button",{type:"button"}),W=g("button",{type:"button"},"Back"),Q=g("button",{type:"button",className:"skip"},"No thanks"),T=g("form",{noValidate:!1},...m,g("div",{className:"hp",ariaHidden:"true"},z),J,b,W,U,Q),H=e.kind==="bar",O=g("div",{className:"box",role:H?"region":"dialog",ariaLabel:"Sign up"},...o.theme?.logoUrl&&o.theme.logoUrl.startsWith("https:")&&!H?[g("img",{src:o.theme.logoUrl,alt:""})]:[],...H&&o.bar?.text?[g("p",{className:"msg"},o.bar.text)]:[],T);e.kind==="popup"&&O.setAttribute("aria-modal","true");let q=o.captcha&&it[o.captcha.provider],j="";if(q&&o.captcha?.provider==="friendlycaptcha"){let y=()=>new window.friendlyChallenge.WidgetInstance(J,{sitekey:o.captcha.siteKey,doneCallback:v=>j=v});window.friendlyChallenge?y():document.head.append(g("script",{src:`https://${q[0]}/widget.min.js`,async:!0,onload:y}))}else if(q&&o.captcha){let[y,v]=q,k=()=>oe[v].render(J,{sitekey:o.captcha.siteKey,callback:_=>j=_,"expired-callback":()=>j=""});oe[v]?.render?k():document.head.append(g("script",{src:`https://${y}/api.js?render=explicit`,async:!0,onload:()=>oe[v].ready?oe[v].ready(k):k()}))}let ne={},B=()=>{let y=(k,_)=>{k.hidden=!_,k.querySelectorAll("[name]").forEach(V=>V.disabled=!_)};h.forEach(([,k])=>y(k,!0));let v={...ne,...fe(T)};for(let[k,_]of h)st(k.when,v)||(y(_,!1),delete v[k.key])};if(h.some(([y])=>y.when)&&(T.addEventListener("input",B),B()),o.countdown){let y=o.countdown,v=Date.parse(y.to),k=g("p"),_=()=>{let M=Math.max(0,(v-Date.now())/1e3|0);k.textContent=M?`${y.label} ${M/86400|0}d ${M/3600%24|0}h ${M/60%60|0}m ${M%60}s`:y.expiredText},V=setInterval(()=>{_(),t.isConnected||clearInterval(V)},1e3);_(),O.prepend(k)}e.kind!=="embed"&&O.prepend(g("button",{className:"x",type:"button",ariaLabel:"Close",onclick:()=>E(!1)},"\xD7"));let D=o.quiz?.emailCapture==="after"&&f>0?g("p",{className:"msg",role:"status"}):null;D&&m[f].prepend(D);let Y=()=>{if(m.forEach((v,k)=>v.hidden=k!==l),D&&l===f){let v=ct(o.quiz,h.map(([k])=>k),fe(T));D.textContent=v?`${v.title}${v.text?` ${v.text}`:""}`:""}W.hidden=l===0||S,Q.hidden=!o.steps[l]?.optional;let y=o.steps[l]?.submitLabel;U.textContent=y??(l===f?o.submitLabel??"Submit":"Next"),U.type=l===f||S?"submit":"button",N.has(l)||(N.add(l),L("reached"))},Z=()=>(m[l]?.querySelector("input:not([type=hidden]),select,textarea")??U).focus();U.addEventListener("click",()=>{if(l<f&&!S){let y=[...m[l].querySelectorAll("input,select")].find(v=>!v.checkValidity());y?y.reportValidity():(L("completed"),l++,Y(),Z())}}),W.addEventListener("click",()=>{l--,Y(),Z()}),Q.addEventListener("click",()=>{L("skipped"),ut(m[l]),l<f?(l++,Y(),Z()):S&&P?ie(P):T.requestSubmit()});let re=y=>(y.type==="redirect"||y.type==="download")&&he(y.url),ie=y=>{let v=y.success;if(re(v))return;let k=g("p",{role:"status"},`${v.text??"Thanks!"}${v.type==="coupon"&&v.code?` Code: ${v.code}`:""}${y.pendingConfirmation?" Check your email to confirm.":""}`),_=y.spin&&o.spin?g("div",{className:"wheel"}):null;if(_){let I=o.spin.segments.length;_.style.background=`conic-gradient(${Array.from({length:I},(te,K)=>`hsl(${K*360/I} 70% ${K%2?60:45}%) ${K*100/I}% ${(K+1)*100/I}%`)})`,k.hidden=!0,setTimeout(()=>{_.style.transform=`rotate(${1440-(y.spin.index+.5)/I*360}deg)`},50),setTimeout(()=>{k.hidden=!1},3100)}let V=g("button",{type:"button",onclick:()=>E(!0)},"Close"),M=(y.quiz?.products??[]).map(I=>g(I.url&&/^https?:/.test(I.url)?"a":"span",{className:"msg",...I.url&&/^https?:/.test(I.url)?{href:I.url}:{}},...I.imageUrl?.startsWith("https:")?[g("img",{src:I.imageUrl,alt:""})]:[],I.title));T.replaceChildren(...v.title?[g("strong",{},v.title)]:[],..._?[g("div",{},"\u25BC"),_]:[],k,...M,...e.kind==="embed"?[]:[V]),X=!0,e.kind!=="embed"&&V.focus()};T.addEventListener("submit",async y=>{if(y.preventDefault(),q&&!j&&!(S&&l>0)){b.textContent="Please complete the captcha";return}U.disabled=!0;let v=k=>{b.textContent=o.failureText??k,U.disabled=!1,q&&!(S&&l>0)&&(j="",oe[q[1]]?.reset?.())};try{let k=n.client.anonymousId(),_=`${n.endpoint.replace(/\/$/,"")}/ingest/v1/forms/${e.id}`,V=S?m[l]:T,M=fe(V);for(let K of V.querySelectorAll("input[type=file]")){if(!K.files?.[0])continue;let ce=new FormData;ce.append("field",K.name),ce.append("file",K.files[0]);let we=await fetch(`${_}/upload`,{method:"POST",headers:{...u,"idempotency-key":crypto.randomUUID()},body:ce}),ue=await we.json();if(!we.ok||!ue.url)return v(ue.error?.message??"Upload failed");M[K.name]=ue.url}let I=await fetch(`${_}/submit`,{method:"POST",headers:{...u,"content-type":"application/json","idempotency-key":crypto.randomUUID()},body:JSON.stringify({data:M,startedAt:c,website:z.value,...j?{captchaToken:j}:{},pageUrl:location.href,...k?{anonymousId:k}:{},...S?{step:l,...C?{stepToken:C}:{}}:{}})}),te=await I.json();if(!I.ok||!te.success){if(I.status>=500&&he(o.redirects?.error))return;v(te.error?.message??"Something went wrong");return}if(L("completed"),S&&l<f&&te.stepToken){C=te.stepToken,P=te,X=!0,ne={...ne,...M},l++,Y(),U.disabled=!1,Z();return}ie(te)}catch{he(o.redirects?.error)||v("Network error, please try again")}}),Y();let R=e.kind==="popup"?g("div",{className:"pop",onclick:y=>{y.target===R&&E(!1)}},O):e.kind==="flyout"?g("div",{className:"fly"},O):H?g("div",{className:`bar ${o.bar?.position==="top"?"top":"bottom"}`},O):O,G=Oe(e.kind,o.teaser),A=G?g("button",{type:"button",className:"tab",ariaLabel:`${G.text}: open the sign-up form`,onclick:()=>$(!0)},G.text):null;A&&(A.style.cssText=tt(G.side));let X=!1,ee=!1,p=null,x=()=>{},w=y=>{y.key==="Escape"&&R.isConnected&&e.kind!=="embed"&&E(!1)};function $(y=e.kind==="popup"){R.isConnected||!t.isConnected||(p=document.activeElement,A?.remove(),s.append(R),H&&(x=nt(R,o.bar?.position==="top")),e.kind!=="embed"&&document.addEventListener("keydown",w),ee||(ee=!0,n.client.formView(e.id,e.versionId)),y&&Z())}function E(y){document.removeEventListener("keydown",w),x();let v=p;if(r(y||X),A&&!(y||X)){R.remove(),s.append(A),A.focus();return}t.remove(),v?.focus?.()}return A&&a?s.append(A):$(),()=>{ee||$()}}async function mt(e){let t=[];try{let d=await fetch(`${e.endpoint.replace(/\/$/,"")}/ingest/v1/forms?v=${e.client.anonymousId()??crypto.randomUUID()}`,{headers:{authorization:`Bearer ${e.siteKey}`}});if(!d.ok)return;t=(await d.json()).forms}catch{return}let n=e.allowed(),r=n?Number(e.get(Se)??0):0,a=De(e,n),o;if(t.some(d=>ge(d.targeting??{})))try{let d=e.client.anonymousId(),m=await fetch(`${e.endpoint.replace(/\/$/,"")}/ingest/v1/forms/visitor${d?`?aid=${encodeURIComponent(d)}`:""}`,{headers:{authorization:`Bearer ${e.siteKey}`}});m.ok&&(o=await m.json())}catch{}let c=matchMedia("(pointer:coarse)").matches||innerWidth<768,u=new Map,s=[],i=new Set,l="",b=()=>{l!==location.href&&(l=location.href,s.forEach(d=>d()),s=[],i=new Set,r++,n&&e.set(Se,String(r)),t.forEach(h))};qe=()=>t.forEach(d=>{d.targeting?.cart&&!i.has(d.id)&&h(d)});function h(d){let m=d.targeting??{},f=e.get(`hm_c_${d.id}`);if(u.has(d.id)||!Ue(m,{path:location.pathname,mobile:c,returning:r>1,pageViews:r,now:Date.now(),lastClosedAt:f?Number(f):void 0,submitted:e.get(`hm_s_${d.id}`)==="1",...a,cart:be,productPage:Ae(document),flags:o}))return;i.add(d.id);let S=P=>{let N=d.kind==="embed"?document.querySelector(`[data-hm-form="${d.id}"]`):document.body.appendChild(g("div"));!N||u.has(d.id)||u.set(d.id,pt(d,N,e,L=>{n&&(e.set(`hm_c_${d.id}`,String(Date.now())),L&&e.set(`hm_s_${d.id}`,"1")),L||e.client.track("form_dismiss",{formId:d.id,versionId:d.versionId})},P))},C=Oe(d.kind,d.definition.teaser);C?.show==="before_trigger"&&S(!0),s.push(Xe(d.kind==="embed"?{}:m,c,()=>{let P=u.get(d.id);P?P():S(!!C&&C.show!=="after_close")}))}for(let d of["pushState","replaceState"]){let m=history[d].bind(history);history[d]=(...f)=>{m(...f),b()}}addEventListener("popstate",b),b()}function De(e,t){let n=t?e.get("hm_ft"):null;if(n)try{return JSON.parse(n)}catch{}let r=new URLSearchParams(location.search),a={};for(let u of["source","medium","campaign"]){let s=r.get(`utm_${u}`);s&&(a[u]=s.slice(0,100))}let o="";try{let u=document.referrer?new URL(document.referrer).hostname:"";o=u===location.hostname?"":u}catch{}let c={utm:a,referrer:o};return t&&e.set("hm_ft",JSON.stringify(c)),c}function ft(e){let t=e;return!t||typeof t.total_price!="number"||typeof t.item_count!="number"?null:{value:t.total_price/100,items:t.item_count}}async function ht(e,t,n=fetch){if(e==="shopify")try{let r=await n("/cart.js",{credentials:"same-origin",headers:{accept:"application/json"}}),a=r.ok?ft(await r.json()):null;a&&t(a)}catch{}}var yt={banner:"position:fixed;left:0;right:0;top:0;padding:12px 44px 12px 16px",modal:"position:fixed;left:50%;top:50%;transform:translate(-50%,-50%);max-width:min(92vw,440px);padding:24px;border-radius:8px;box-shadow:0 4px 24px #0004",slide_in:"position:fixed;right:16px;bottom:16px;max-width:min(92vw,360px);padding:20px;border-radius:8px;box-shadow:0 4px 24px #0004"};async function gt(e){let t=e.endpoint.replace(/\/$/,""),n={authorization:`Bearer ${e.siteKey}`},r=e.client.anonymousId(),a=[];try{let m=await fetch(`${t}/ingest/v1/site-messages${r?`?aid=${encodeURIComponent(r)}`:""}`,{headers:n});m.ok&&(a=(await m.json()).messages)}catch{return}if(!a.length)return;let o;if(a.some(m=>ge(m.targeting??{})))try{let m=await fetch(`${t}/ingest/v1/forms/visitor${r?`?aid=${encodeURIComponent(r)}`:""}`,{headers:n});m.ok&&(o=await m.json())}catch{}let c=e.allowed(),u=c?Number(e.get("hm_pv")??1):1,s={path:location.pathname,mobile:matchMedia("(pointer:coarse)").matches||innerWidth<768,returning:u>1,pageViews:u,now:Date.now(),...De(e,c),cart:ot(),productPage:Ae(document),flags:o},i=[...a].sort((m,f)=>Number(f.queued)-Number(m.queued)).find(m=>{let f=e.get(`hm_m_${m.id}`);return Ue(m.targeting??{},{...s,lastClosedAt:f?Number(f):void 0,submitted:!1})&&!(f&&m.targeting?.frequencyDays===void 0)});if(!i)return;let l=document.createElement("div"),b=l.attachShadow({mode:"open"}),h=document.createElement("div");if(h.setAttribute("role",i.style==="modal"?"dialog":"status"),h.style.cssText=`${yt[i.style]};background:#fff;color:#111;font:15px/1.5 system-ui,sans-serif;z-index:2147483000;box-sizing:border-box`,h.innerHTML=i.html,i.ctaLabel&&i.ctaUrl&&/^https?:\/\//.test(i.ctaUrl)){let m=Object.assign(document.createElement("a"),{href:i.ctaUrl,textContent:i.ctaLabel,rel:"noopener"});m.style.cssText="display:inline-block;margin-top:10px;padding:8px 14px;background:#1f6feb;color:#fff;border-radius:6px;text-decoration:none",h.append(m)}let d=Object.assign(document.createElement("button"),{type:"button",textContent:"\xD7",ariaLabel:"Close"});d.style.cssText="position:absolute;top:6px;right:10px;border:0;background:none;font-size:20px;cursor:pointer;color:inherit",d.addEventListener("click",()=>{l.remove(),e.allowed()&&e.set(`hm_m_${i.id}`,String(Date.now()))}),h.append(d),b.append(h),document.body.append(l),fetch(`${t}/ingest/v1/site-messages/${i.id}/shown`,{method:"POST",headers:{...n,"content-type":"application/json"},body:JSON.stringify(r?{aid:r}:{})}).catch(()=>{})}function bt(e){let t=new Map,n={get:r=>t.get(r)??null,set:(r,a)=>{t.set(r,a)},del:r=>{t.delete(r)}};try{if(e==="local"){let r=localStorage;return{get:a=>r.getItem(a),set:(a,o)=>r.setItem(a,o),del:a=>r.removeItem(a)}}if(e==="cookie")return{get:r=>document.cookie.split("; ").find(a=>a.startsWith(`${r}=`))?.slice(r.length+1)??null,set:(r,a)=>{document.cookie=`${r}=${a}; max-age=31536000; path=/; SameSite=Lax`},del:r=>{document.cookie=`${r}=; max-age=0; path=/`}}}catch{}return n}function vt(e,t,n){let r=o=>`${e.replace(/\/$/,"")}${o}`,a=o=>new Promise(c=>setTimeout(c,o));return{async send(o,c){for(let u=0,s=crypto.randomUUID();u<5;u++){try{let i=await fetch(r(o),{method:"POST",keepalive:!0,body:JSON.stringify(c),headers:{"content-type":"application/json",authorization:`Bearer ${t}`,"idempotency-key":s}});if(i.status<400)return!0;if(i.status<500&&i.status!==429){let l=await i.json().catch(()=>null);return n(Object.assign(new Error(l?.error?.message??`HTTP ${i.status}`),{status:i.status,code:l?.error?.code})),null}}catch(i){n(i)}await a(500*2**u+Math.random()*500)}return!1},get:o=>fetch(`${r(o)}?k=${encodeURIComponent(t)}`).then(c=>c.ok?c.json():null).catch(()=>null),post:(o,c)=>fetch(r(o),{method:"POST",body:JSON.stringify(c),headers:{"content-type":"application/json",authorization:`Bearer ${t}`}}).then(u=>u.json()),beacon:(o,c)=>navigator.sendBeacon?.(`${r(o)}?k=${encodeURIComponent(t)}`,new Blob([JSON.stringify(c)],{type:"text/plain"}))??!1}}var Ie="0.4.0",Ce=50,Me=50,le="hm_aid",Ee="hm_consent",xt="hm_queue:",wt=3e3,Pe=()=>crypto.randomUUID();function Le(e,t={}){return{mode:e.consentMode??t.consentMode??"require-consent",bufferUntilConsent:e.bufferUntilConsent??t.bufferUntilConsent??!1,stripQuery:e.stripQuery??t.stripQuery??!1,allowParams:e.allowParams??(t.allowParams?.length?t.allowParams:void 0),autoPageViews:e.autoPageViews??t.autoPageViews??!1,pageViewRoutes:e.pageViewRoutes??t.pageViewRoutes??[],identify:{email:!0,phone:!0,externalId:!0,...t.identify,...e.identify},maxSize:Math.min(e.batch?.maxSize??t.batchSize??20,Me),flushMs:e.batch?.flushMs??t.flushMs??2e3,maxQueue:e.maxQueue??t.maxQueue??200,autocapture:e.autocapture??t.autocapture??!1,trackVideo:e.trackVideo??t.trackVideo??!1}}function kt(e,t){return e.length?e.some(n=>{if(n.endsWith("*"))return t.startsWith(n.slice(0,-1));let r=n.replace(/\/$/,"");return t===r||t.startsWith(`${r}/`)}):!0}function $t(e){let t=Le(e),n=bt(e.storage??"local"),r={},a=(p,x)=>(r[p]??[]).forEach(w=>w(x)),o=e.debug??!1,c=(...p)=>o&&console.debug("[hermetica]",...p),u=null,s=p=>{u=p,a("error",p)},i=vt(e.endpoint,e.siteKey,s),l=(()=>{try{return JSON.parse(n.get(Ee)??"null")}catch{return null}})(),b=()=>l??(t.mode==="require-consent"?{analytics:!1,marketing:!1}:{analytics:!0,marketing:!0}),h=b(),d=l!==null||t.mode!=="require-consent",m=!1,f=[],S,C=null,P=Promise.resolve(),N=[],L=(e.storage??"local")==="local"?n:null,J=`${xt}${e.siteKey}`,z=()=>{if(L)try{let p=d&&h.analytics?[...N,...f].slice(-t.maxQueue):[];p.length?L.set(J,JSON.stringify(p)):L.del(J)}catch{}},U=!e.remoteConfig,W=[],Q=p=>{U?p():W.length<Ce&&W.push(p)},T=()=>(C??(C=n.get(le)),C||(C=Pe(),n.set(le,C)),C),H=(()=>{let p={};try{new URL(location.href).searchParams.forEach((x,w)=>{w.startsWith("utm_")&&(p[w.slice(4)]=x.slice(0,256))})}catch{}return p})(),O=p=>{if(!t.stripQuery&&!t.allowParams)return p;try{let x=new URL(p),w=new Set(t.allowParams??[]);for(let $ of Array.from(x.searchParams.keys()))w.has($)||x.searchParams.delete($);return x.hash="",x.href}catch{return p}},q=()=>({url:location.href,referrer:document.referrer,title:document.title,path:location.pathname}),j=p=>({page:{url:O(p.url),referrer:O(p.referrer),title:p.title},...Object.keys(H).length?{utm:H}:{}});function ne(p,x,w,$){if(d&&!h.analytics){c("dropped (analytics denied)",p);return}if(!d&&!t.bufferUntilConsent){c("dropped (consent not decided yet)",p);return}let E={name:p,properties:{...x,hm_sdk:Ie,...globalThis.hmAd?.()},dedupeKey:Pe(),occurredAt:new Date().toISOString(),context:j($),...w};if(e.beforeSend){try{E=e.beforeSend(E)}catch(v){s(v),E=null}if(!E){c("dropped (beforeSend)",p);return}}f.push(E);let y=d?t.maxQueue:Ce;f.length>y&&f.splice(0,f.length-y),c("queued",E),d&&(z(),f.length>=t.maxSize?D():S??(S=setTimeout(()=>{D()},t.flushMs)))}let B=(p,x,w={})=>{let $=q();Q(()=>ne(p,x,w,$))};function D(){if(clearTimeout(S),S=void 0,!d||!h.analytics||f.length===0)return P;let p=T(),x=f.splice(0,t.maxSize);N.push(...x);let w=x.map($=>({...$,anonymousId:p}));return P=P.then(async()=>{let $=await i.send("/ingest/v1/batch",{events:w,consent:h});N=N.filter(E=>!x.includes(E)),$?a("flush",w):$===!1&&(f.unshift(...w),f.splice(0,f.length-t.maxQueue),s(new Error("send failed"))),z(),$!==!1&&f.length&&D()}),P}let Y=()=>{if(!d||!h.analytics||f.length===0)return;let p=T(),x=[];for(;f.length;){let w=f.splice(0,Me);i.beacon("/ingest/v1/batch",{events:w.map($=>({...$,anonymousId:p})),consent:h})||x.push(...w)}f=x,z()};typeof addEventListener=="function"&&addEventListener("pagehide",Y);let Z=(p={})=>B("page_view",p),re=()=>{let p=q();Q(()=>{t.autoPageViews&&kt(t.pageViewRoutes,p.path)&&ne("page_view",{},{},p)})};if(e.autoPageViews||e.remoteConfig&&e.autoPageViews!==!1){re();for(let p of["pushState","replaceState"]){let x=history[p].bind(history);history[p]=(...w)=>{x(...w),re()}}addEventListener("popstate",re)}let ie=()=>{t.autocapture&&typeof document<"u"&&We((p,x)=>B(p,x)),t.trackVideo&&typeof document<"u"&&Ze((p,x)=>B(p,x))},R=()=>({client:A,endpoint:e.endpoint,siteKey:e.siteKey,get:n.get,set:n.set,allowed:()=>d&&h.analytics}),G={start:async()=>{e.cart&&await ht(e.cart,_e),await Promise.all([mt(R()),gt(R())])},setCart:_e},A={forms:G,track:(p,x={},w={})=>B(p,x,{...w.value!==void 0?{value:w.value}:{},...w.currency?{currency:w.currency}:{},...w.dedupeKey?{dedupeKey:w.dedupeKey}:{}}),page:Z,formView:(p,x)=>B("form_view",{formId:p,...x?{versionId:x}:{}}),identify:(p,x={},w={})=>Q(()=>{if(!h.marketing||d&&!h.analytics){c("identify skipped (no marketing consent)");return}let{email:$,phone:E,...y}=x,v={...p&&t.identify.externalId?{externalId:p}:{},...$&&t.identify.email?{email:$}:{},...E&&t.identify.phone?{phone:E}:{}};if(!Object.keys(v).length){c("identify skipped (identifiers not allowed for this site)");return}P.then(()=>i.send("/ingest/v1/identify",{anonymousId:T(),identifiers:v,traits:y,consent:h,...w.signature?{signature:w.signature}:{}}))}),subscribe:p=>i.send("/ingest/v1/subscribe",{...p,pageUrl:O(location.href),anonymousId:A.anonymousId()??void 0}),backInStock:p=>i.send("/ingest/v1/back-in-stock",p),consent:{get:()=>({...h}),update(p){h={...h,...p},d=!0,m=!0,n.set(Ee,JSON.stringify(h)),a("consent",{...h}),h.analytics?D():(f=[],N=[],C=null,n.del(le)),z()}},anonymousId:()=>d&&h.analytics?T():null,reset(){f=[],N=[],C=null,n.del(le),z()},flush:D,on(p,x){(r[p]??(r[p]=[])).push(x)},debug:{events:()=>[...f],lastError:()=>u,enable:()=>{o=!0},disable:()=>{o=!1},test:p=>i.post("/ingest/v1/test",{events:p??(f.length?f:[{name:"test_event",properties:{hm_sdk:Ie},context:j(q())}]),consent:h})}};function X(){if(!L)return;let p=[];try{p=JSON.parse(L.get(J)??"[]")}catch{}if(!Array.isArray(p)||!p.length||!d||!h.analytics){z();return}let x=new Set(f.map($=>$.dedupeKey)),w=p.filter($=>$&&typeof $.name=="string"&&typeof $.dedupeKey=="string"&&!x.has($.dedupeKey)&&x.add($.dedupeKey));f=[...w,...f].slice(-t.maxQueue),c("restored",w.length),S??(S=setTimeout(()=>{D()},t.flushMs))}let ee=p=>{if(!U){p&&(Object.assign(t,Le(e,p)),!m&&l===null&&(h=b(),d=t.mode!=="require-consent"),c("settings",t)),U=!0,X(),ie();for(let x of W.splice(0))x()}};return e.remoteConfig?(setTimeout(()=>ee(null),wt),i.get("/ingest/v1/config").then(p=>ee(p),()=>ee(null))):(X(),ie()),e.forms&&G.start(),A}var ye=e=>!!e&&typeof e=="object"&&!Array.isArray(e),ae=e=>typeof e=="string"&&e?e:null,de=(e,t)=>t?{[e]:t}:{};function Te(e){if(!ye(e))return{};let t=[e];for(let n of[e.data,e.userInfo,e.notification,e.additionalData])ye(n)&&t.push(n,n.data,n.additionalData);return Object.assign({},...t.filter(ye))}function Ne(e,t,n){let r=e.identity(),a=e.device??{};return{data:{type:n,attributes:{token:t.token,platform:e.platform,vendor:t.vendor,enablement_status:t.enablementStatus??"AUTHORIZED",background:t.background??"AVAILABLE",device_metadata:{device_id:r.anonymousId??"",sdk_version:e.sdkVersion??"app-0.4.0",device_model:a.deviceModel??"",os_name:a.osName??e.platform,os_version:a.osVersion??"",app_name:a.appName??"",app_version:a.appVersion??"",app_build:a.appBuild??"",app_id:a.appId??"",environment:t.environment??"release"},profile:{data:{type:"profile",attributes:{...de("email",r.email),...de("phone_number",r.phoneNumber),...de("external_id",r.externalId),...de("anonymous_id",r.anonymousId)}}}}}}}function St(e){let t=o=>`${e.endpoint.replace(/\/$/,"")}${o}?company_id=${encodeURIComponent(e.siteKey)}`,n=e.retryMs??500;async function r(o,c){let u=crypto.randomUUID();for(let s=0;s<5;s++){try{let i=await fetch(t(o),{method:"POST",body:JSON.stringify(c),headers:{"content-type":"application/json",authorization:`Bearer ${e.siteKey}`,"idempotency-key":u}});if(i.status<500&&i.status!==429)return i.ok}catch{}s<4&&await new Promise(i=>setTimeout(i,n*2**s+Math.random()*n))}return!1}let a=o=>typeof o=="string"?o||null:ae(Te(o).hermetica_message_id);return{register:o=>r("/client/push-tokens",Ne(e,o,"push-token")),unregister:o=>r("/client/push-token-unregister",Ne(e,o,"push-token-unregister")),opened(o){let c=Te(o),u=ae(c.hermetica_message_id);return u&&e.track("$opened_push",{hermetica_message_id:u}),ae(c.deep_link)??ae(c.url)??ae(c.hermetica_url)},received(o){let c=a(o);return c&&e.track("$received_push",{hermetica_message_id:c}),!!c}}}var ve=e=>{try{let t=new URL(e,location.href);return t.protocol==="https:"||t.protocol==="http:"?t.href:null}catch{return null}};function _t(e){let t=document.createElement("template");return t.innerHTML=e,t.content.querySelectorAll("script,style,iframe,object,embed,link,meta,base,form").forEach(n=>n.remove()),t.content.querySelectorAll("*").forEach(n=>{for(let r of Array.from(n.attributes))(r.name.startsWith("on")||(r.name==="href"||r.name==="src"||r.name==="action")&&!ve(r.value))&&n.removeAttribute(r.name)}),t.content}var F=(e,t,n)=>{let r=document.createElement(e);return r.style.cssText=t,n!==void 0&&(r.textContent=n),r};function It(e,t){let n=e.style,r=e.layout==="banner_top"||e.layout==="banner_bottom",a=F("div",`position:fixed;z-index:2147483000;display:flex;${r?`left:0;right:0;${e.layout==="banner_top"?"top:0":"bottom:0"};`:`inset:0;background:rgba(0,0,0,.5);align-items:${e.layout==="bottom_sheet"?"flex-end":"center"};justify-content:center;`}`);a.setAttribute("data-hermetica-inapp",e.id);let o=e.layout==="fullscreen",c=e.layout==="bottom_sheet",u=F("div",`background:${n.background};color:${n.textColor};font:16px/1.4 system-ui,sans-serif;box-sizing:border-box;padding:20px;position:relative;${r?"width:100%;":o?"width:100%;height:100%;overflow:auto;":`width:min(92vw,420px);${c?`border-radius:${n.radius}px ${n.radius}px 0 0;width:min(100vw,520px);`:`border-radius:${n.radius}px;`}`}`);if(u.setAttribute("role","dialog"),u.setAttribute("aria-modal",String(!r)),e.content.html)u.append(_t(e.content.html));else for(let s of e.content.blocks)if(s.type==="heading")u.append(F("h2","margin:0 0 8px;font-size:20px",s.text));else if(s.type==="text")u.append(F("p","margin:0 0 12px",s.text));else if(s.type==="image"&&s.url&&ve(s.url)){let i=F("img","max-width:100%;display:block;margin:0 0 12px");i.src=s.url,i.alt=s.alt??"",u.append(i)}else if(s.type==="buttons"){let i=F("div","display:flex;gap:8px;flex-wrap:wrap");for(let l of s.buttons??[]){let b=l.style!=="secondary",h=F("button",`cursor:pointer;padding:10px 16px;border-radius:${Math.min(n.radius,10)}px;font:inherit;border:1px solid ${n.accentColor};background:${b?n.accentColor:"transparent"};color:${b?"#fff":n.accentColor}`,l.label);h.addEventListener("click",()=>t.click(l)),i.append(h)}u.append(i)}if(n.dismissible){let s=F("button","position:absolute;top:8px;right:8px;border:0;background:transparent;color:inherit;font-size:20px;cursor:pointer","\xD7");s.setAttribute("aria-label","Close"),s.addEventListener("click",t.dismiss),u.append(s)}return a.append(u),a}function Ct(e){let t=e.endpoint.replace(/\/$/,""),n={"content-type":"application/json",authorization:`Bearer ${e.siteKey}`},r=(()=>{try{return sessionStorage.getItem("hm_sid")??(sessionStorage.setItem("hm_sid",crypto.randomUUID()),sessionStorage.getItem("hm_sid"))}catch{return crypto.randomUUID()}})(),a=()=>({...e.identity?.(),anonymousId:e.anonymousId()??void 0}),o=new Set,c=(i,l,b)=>{fetch(`${t}/client/in-app-events?company_id=${encodeURIComponent(e.siteKey)}`,{method:"POST",keepalive:!0,headers:{...n,"idempotency-key":crypto.randomUUID()},body:JSON.stringify({events:[{messageId:i.id,variant:i.variant,type:l,platform:e.platform??"web",sessionId:r,...b?{button:b}:{}}],profile:a()})}).catch(()=>{})};function u(i){if(o.has(i.id))return;o.add(i.id);let l=()=>b.remove(),b=It(i,{dismiss:()=>{c(i,"dismiss"),l()},click:h=>{if(c(i,"click",h.label),l(),h.action==="dismiss"||!h.value||e.onAction?.(h.action,h.value,i)===!1||h.action==="event")return;let d=ve(h.value);d&&location.assign(d)}});document.body.append(b),c(i,"impression")}async function s(i={type:"page_url"}){let l=a();if(!l.anonymousId&&!l.externalId&&!l.email&&!l.phoneNumber)return[];let b=new URLSearchParams({company_id:e.siteKey,platform:e.platform??"web",trigger:i.type,session_id:r});"name"in i&&b.set("name",i.name),i.type==="page_url"&&b.set("url",i.url??location.href),i.type==="event"&&i.properties&&b.set("properties",JSON.stringify(i.properties)),l.externalId&&b.set("external_id",l.externalId),l.email&&b.set("email",l.email),l.phoneNumber&&b.set("phone_number",l.phoneNumber),l.anonymousId&&b.set("anonymous_id",l.anonymousId);let h=await fetch(`${t}/client/in-app-messages?${b}`,{headers:{authorization:n.authorization}}).catch(()=>null);if(!h?.ok)return[];let d=(await h.json()).items;return d[0]&&u(d[0]),d}return{trigger:s,display:u}}function je(e){let{platform:t,device:n,sdkVersion:r,inApp:a=!0,onDeepLink:o,...c}=e,u=$t(c),s={},i=null,l=()=>({...s,anonymousId:u.anonymousId()}),b=St({siteKey:e.siteKey,endpoint:e.endpoint,platform:t,identity:l,track:(m,f)=>u.track(m,f),...n?{device:n}:{},...r?{sdkVersion:r}:{}}),h=()=>{i&&b.register(i)},d=a&&typeof document<"u"?Ct({siteKey:e.siteKey,endpoint:e.endpoint,platform:t,anonymousId:u.anonymousId,identity:()=>({...s}),onAction:(m,f,S)=>{if(m==="event")return u.track(f,{hermetica_message_id:S.id}),!1;if(o)return o(f),!1}}):null;return typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&u.flush()}),d&&d.trigger({type:"app_open"}),{...u,track(m,f={},S){u.track(m,f,S),d?.trigger({type:"event",name:m,properties:f})},identify(m,f={}){let S=f;m&&(s.externalId=m),typeof S.email=="string"&&(s.email=S.email),typeof S.phone=="string"&&(s.phoneNumber=S.phone),u.identify(m,f),h()},reset(){for(let m of Object.keys(s))delete s[m];u.reset(),h()},screen(m,f={}){u.page({screen:m,...f}),d?.trigger({type:"screen_view",name:m})},setProfile(m){Object.assign(s,m),h()},async setPushToken(m){return i=m,b.register(m)},async unregisterPushToken(){let m=i;return i=null,m?b.unregister(m):!0},handlePushOpened(m){let f=b.opened(m);return f&&o?.(f),f},handlePushReceived:m=>b.received(m)}}var Et=()=>new Promise(e=>{if(globalThis.cordova===void 0)return e();document.addEventListener("deviceready",()=>e(),{once:!0})}),xe=e=>new Promise(t=>e(t,()=>t(!1)));async function Pt(e){await Et();let t=globalThis,{firebase:n=t.FirebasePlugin,cordovaDevice:r=t.device,requestPushPermission:a=!1,pushEnvironment:o="release",...c}=e,u=r?.platform.toLowerCase()==="ios"?"ios":"android",s={...r?.model?{deviceModel:r.model}:{},osName:u,...r?.version?{osVersion:r.version}:{},...c.device},i=je({...c,platform:u,device:s,sdkVersion:"cordova-0.4.0"}),l=!1,b=d=>{if(!d)return;let m={token:d,vendor:"fcm",environment:o,enablementStatus:l?"AUTHORIZED":"DENIED"};i.setPushToken(m)};async function h(){return n?(l=await xe((d,m)=>n.hasPermission(d,m))||await xe((d,m)=>n.grantPermission(d,m)),n.getToken(b,()=>{}),l):!1}return n&&(n.onTokenRefresh(b,()=>{}),n.onMessageReceived(d=>{d.tap?i.handlePushOpened(d):i.handlePushReceived(d)},()=>{}),a?h():xe((d,m)=>n.hasPermission(d,m)).then(d=>{d&&h()})),{...i,enablePush:h}}
|