@buildbase/sdk 0.0.65 → 0.0.67
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/CHANGELOG.md +8 -0
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/react/chunks/{SettingsDialog-D4FCwpN7.cjs → SettingsDialog-CcpkqG7N.cjs} +1 -1
- package/dist/react/chunks/{SettingsDialog-CKwldz7y.mjs → SettingsDialog-D2lDYNYo.mjs} +1 -1
- package/dist/react/chunks/{SubscriptionDialog-DJmrU0r1.cjs → SubscriptionDialog-DQaPB1F_.cjs} +1 -1
- package/dist/react/chunks/{SubscriptionDialog-DoWnS_JD.mjs → SubscriptionDialog-DeWq470C.mjs} +1 -1
- package/dist/react/chunks/react-CHhQFy94.mjs +2 -0
- package/dist/react/chunks/react-DP8VKZUU.cjs +2 -0
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.mjs +1 -1
- package/dist/tracking/index.cjs +1 -1
- package/dist/tracking/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/react/chunks/react-Be1VMiVO.mjs +0 -2
- package/dist/react/chunks/react-ClieHJPH.cjs +0 -2
package/dist/react/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";var e=require("./chunks/react-
|
|
2
|
+
"use strict";var e=require("./chunks/react-DP8VKZUU.cjs");require("react/jsx-runtime"),require("react"),require("clsx"),require("tailwind-merge"),require("intl-messageformat"),require("@hookform/resolvers/zod"),require("react-hook-form"),require("@radix-ui/react-slot"),require("class-variance-authority"),require("lucide-react"),require("@radix-ui/react-label"),require("zod"),require("@radix-ui/react-avatar"),require("@radix-ui/react-dialog"),require("@radix-ui/react-icons"),require("@radix-ui/react-radio-group"),require("@radix-ui/react-scroll-area"),require("@radix-ui/react-separator"),require("@radix-ui/react-accordion"),require("@radix-ui/react-alert-dialog"),Object.defineProperty(exports,"ApiVersion",{enumerable:!0,get:function(){return e.ApiVersion}}),exports.AuthApi=e.AuthApi,Object.defineProperty(exports,"AuthStatus",{enumerable:!0,get:function(){return e.AuthStatus}}),exports.BBAction=e.BBAction,exports.BBScreen=e.BBScreen,exports.BBStatus=e.BBStatus,exports.BB_PARAM=e.BB_PARAM,exports.BaseApi=e.BaseApi,exports.BetaForm=e.BetaForm,exports.BillingIntervals=e.BillingIntervals,exports.BuildBaseBadge=e.BuildBaseBadge,exports.BuildBaseProvider=e.SaaSOSProvider,exports.CURRENCY_DISPLAY=e.CURRENCY_DISPLAY,exports.CURRENCY_FLAG=e.CURRENCY_FLAG,exports.ConnectMcpGuide=e.ConnectMcpGuide,exports.ConnectedAgents=e.ConnectedAgents,exports.ConnectedAgentsApi=e.ConnectedAgentsApi,exports.CreditActionsProvider=e.CreditActionsProvider,exports.CreditBalance=e.CreditBalance,exports.CreditBalanceContextProvider=e.CreditBalanceContextProvider,exports.CreditBucketSource=e.CreditBucketSource,exports.CreditBucketStatus=e.CreditBucketStatus,exports.CreditStorePage=e.CreditStorePage,exports.CreditTransactionType=e.CreditTransactionType,exports.DEFAULT_ROLE_PERMISSIONS=e.DEFAULT_ROLE_PERMISSIONS,exports.Devices=e.Devices,exports.DevicesApi=e.DevicesApi,exports.DunningState=e.DunningState,exports.EmptyState=e.EmptyState,exports.EventEmitter=e.EventEmitter,exports.FullScreenLoader=e.FullScreenLoader,exports.InvoiceStatuses=e.InvoiceStatuses,exports.LoadingState=e.LoadingState,exports.PLAN_CURRENCY_CODES=e.PLAN_CURRENCY_CODES,exports.PLAN_CURRENCY_OPTIONS=e.PLAN_CURRENCY_OPTIONS,exports.PUSH_SERVICE_WORKER_SCRIPT=e.PUSH_SERVICE_WORKER_SCRIPT,exports.Permission=e.Permission,exports.PricingPage=e.PricingPage,exports.PushApi=e.PushApi,exports.PushNotificationProvider=e.PushNotificationProvider,exports.QuotaUsageContextProvider=e.QuotaUsageContextProvider,exports.SDKEvent=e.SDKEvent,exports.SETTINGS_SCREENS=e.SETTINGS_SCREENS,exports.SUPPORTED_LOCALES=e.SUPPORTED_LOCALES,exports.SaaSOSProvider=e.SaaSOSProvider,exports.SectionHeader=e.SectionHeader,exports.Sessions=e.Sessions,exports.SessionsApi=e.SessionsApi,exports.SettingsApi=e.SettingsApi,exports.SettingsScreen=e.SettingsScreen,exports.SidebarNavItem=e.SidebarNavItem,exports.SidebarNavSection=e.SidebarNavSection,exports.StatusBanner=e.StatusBanner,exports.SubscriptionContextProvider=e.SubscriptionContextProvider,exports.SubscriptionItemType=e.SubscriptionItemType,exports.SubscriptionStatus=e.SubscriptionStatus,exports.UserApi=e.UserApi,exports.WhenAuthenticated=e.WhenAuthenticated,exports.WhenCreditsAvailable=e.WhenCreditsAvailable,exports.WhenCreditsExhausted=e.WhenCreditsExhausted,exports.WhenCreditsLow=e.WhenCreditsLow,exports.WhenNoSubscription=e.WhenNoSubscription,exports.WhenNotTrialing=e.WhenNotTrialing,exports.WhenPermission=e.WhenPermission,exports.WhenQuotaAvailable=e.WhenQuotaAvailable,exports.WhenQuotaExhausted=e.WhenQuotaExhausted,exports.WhenQuotaOverage=e.WhenQuotaOverage,exports.WhenQuotaThreshold=e.WhenQuotaThreshold,exports.WhenRoles=e.WhenRoles,exports.WhenSubscription=e.WhenSubscription,exports.WhenSubscriptionToPlans=e.WhenSubscriptionToPlans,exports.WhenTrialEnding=e.WhenTrialEnding,exports.WhenTrialing=e.WhenTrialing,exports.WhenUnauthenticated=e.WhenUnauthenticated,exports.WhenUserFeatureDisabled=e.WhenUserFeatureDisabled,exports.WhenUserFeatureEnabled=e.WhenUserFeatureEnabled,exports.WhenWorkspaceFeatureDisabled=e.WhenWorkspaceFeatureDisabled,exports.WhenWorkspaceFeatureEnabled=e.WhenWorkspaceFeatureEnabled,exports.WhenWorkspaceRoles=e.WhenWorkspaceRoles,exports.WorkspaceApi=e.WorkspaceApi,exports.WorkspaceSwitcher=e.WorkspaceSwitcher,exports.calculateBillableSeats=e.calculateBillableSeats,exports.calculateSeatOverageCents=e.calculateSeatOverageCents,exports.calculateTotalSubscriptionCents=e.calculateTotalSubscriptionCents,exports.cleanBBParams=e.cleanBBParams,exports.clearAuthIntent=e.clearAuthIntent,exports.coerceBadgeRef=e.coerceBadgeRef,exports.consumeAuthIntent=e.consumeAuthIntent,exports.createBBUrl=e.createBBUrl,exports.createCheckoutRedirectUrls=e.createCheckoutRedirectUrls,exports.createCreditPurchaseRedirectUrls=e.createCreditPurchaseRedirectUrls,exports.eventEmitter=e.eventEmitter,exports.fillMcpTemplate=e.fillMcpTemplate,exports.formatCents=e.formatCents,exports.formatMinorAmountIntl=e.formatMinorAmountIntl,exports.formatOverageRate=e.formatOverageRate,exports.formatOverageRateWithLabel=e.formatOverageRateWithLabel,exports.formatQuotaIncludedOverage=e.formatQuotaIncludedOverage,exports.formatQuotaWithPrice=e.formatQuotaWithPrice,exports.getAvailableCurrenciesFromPlans=e.getAvailableCurrenciesFromPlans,exports.getBasePriceCents=e.getBasePriceCents,exports.getBillingIntervalAndCurrencyFromPriceId=e.getBillingIntervalAndCurrencyFromPriceId,exports.getCurrencyDecimals=e.getCurrencyDecimals,exports.getCurrencyFlag=e.getCurrencyFlag,exports.getCurrencySymbol=e.getCurrencySymbol,exports.getDisplayCurrency=e.getDisplayCurrency,exports.getPerSeatPriceCents=e.getPerSeatPriceCents,exports.getPricingVariant=e.getPricingVariant,exports.getQuotaDisplayValue=e.getQuotaDisplayValue,exports.getQuotaDisplayWithVariant=e.getQuotaDisplayWithVariant,exports.getQuotaOverageCents=e.getQuotaOverageCents,exports.getQuotaUnitLabelFromName=e.getQuotaUnitLabelFromName,exports.getSeatPricing=e.getSeatPricing,exports.getStripePriceIdForInterval=e.getStripePriceIdForInterval,exports.hasPermission=e.hasPermission,exports.invalidateCreditBalance=e.invalidateCreditBalance,exports.invalidateQuotaUsage=e.invalidateQuotaUsage,exports.invalidateSubscription=e.invalidateSubscription,exports.isZeroDecimalCurrency=e.isZeroDecimalCurrency,exports.mcpServerKey=e.mcpServerKey,exports.mergeUIConfig=e.mergeUIConfig,exports.minorAmountToDisplay=e.minorAmountToDisplay,exports.readBBParams=e.readBBParams,exports.resolveMaxUsers=e.resolveMaxUsers,exports.resolvePermissions=e.resolvePermissions,exports.safeRedirect=e.safeRedirect,exports.saveAuthIntent=e.saveAuthIntent,exports.useAllQuotaUsage=e.useAllQuotaUsage,exports.useBillingPortal=e.useBillingPortal,exports.useCancelSubscription=e.useCancelSubscription,exports.useConnectedAgents=e.useConnectedAgents,exports.useConnectedAgentsApi=e.useConnectedAgentsApi,exports.useConsumeCredits=e.useConsumeCredits,exports.useCreateCheckoutSession=e.useCreateCheckoutSession,exports.useCreditBalance=e.useCreditBalance,exports.useCreditBalanceContext=e.useCreditBalanceContext,exports.useCreditPackages=e.useCreditPackages,exports.useCreditTransactions=e.useCreditTransactions,exports.useDevices=e.useDevices,exports.useDevicesApi=e.useDevicesApi,exports.useExpiringCredits=e.useExpiringCredits,exports.useFullScreenLoader=e.useFullScreenLoader,exports.useInvoice=e.useInvoice,exports.useInvoices=e.useInvoices,exports.useMcpConnection=e.useMcpConnection,exports.usePermissions=e.usePermissions,exports.usePlanGroup=e.usePlanGroup,exports.usePlanGroupVersions=e.usePlanGroupVersions,exports.usePublicCreditPackages=e.usePublicCreditPackages,exports.usePublicPlanGroupVersion=e.usePublicPlanGroupVersion,exports.usePublicPlans=e.usePublicPlans,exports.usePurchaseCredits=e.usePurchaseCredits,exports.usePushNotifications=e.usePushNotifications,exports.useQuotaUsageContext=e.useQuotaUsageContext,exports.useQuotaUsageStatus=e.useQuotaUsageStatus,exports.useRecordUsage=e.useRecordUsage,exports.useResumeSubscription=e.useResumeSubscription,exports.useSaaSAuth=e.useSaaSAuth,exports.useSaaSOs=e.useSaaSOs,exports.useSaaSSettings=e.useSaaSSettings,exports.useSaaSWorkspaces=e.useSaaSWorkspaces,exports.useSeatStatus=e.useSeatStatus,exports.useSessions=e.useSessions,exports.useSessionsApi=e.useSessionsApi,exports.useSubscription=e.useSubscription,exports.useSubscriptionContext=e.useSubscriptionContext,exports.useSubscriptionManagement=e.useSubscriptionManagement,exports.useTranslation=e.useTranslation,exports.useTrialStatus=e.useTrialStatus,exports.useUIConfig=e.useUIConfig,exports.useUIVisibility=e.useUIVisibility,exports.useUpdateSubscription=e.useUpdateSubscription,exports.useUsageLogs=e.useUsageLogs,exports.useUserAttributes=e.useUserAttributes,exports.useUserFeatures=e.useUserFeatures,exports.validateInvite=e.validateInvite,exports.validateRedirectUrl=e.validateRedirectUrl,exports.workspaceSettingsManager=e.workspaceSettingsManager;
|
package/dist/react/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
export{aS as ApiVersion,aT as AuthApi,aU as AuthStatus,o as BBAction,aV as BBScreen,p as BBStatus,aW as BB_PARAM,aX as BaseApi,aY as BetaForm,ag as BillingIntervals,aZ as BuildBaseBadge,a_ as BuildBaseProvider,a$ as CURRENCY_DISPLAY,b0 as CURRENCY_FLAG,b1 as ConnectMcpGuide,C as ConnectedAgents,b2 as ConnectedAgentsApi,b3 as CreditActionsProvider,b4 as CreditBalance,b5 as CreditBalanceContextProvider,b6 as CreditBucketSource,b7 as CreditBucketStatus,b8 as CreditStorePage,y as CreditTransactionType,b9 as DEFAULT_ROLE_PERMISSIONS,R as Devices,ba as DevicesApi,ax as DunningState,E as EmptyState,bb as EventEmitter,bc as FullScreenLoader,ae as InvoiceStatuses,L as LoadingState,bd as PLAN_CURRENCY_CODES,be as PLAN_CURRENCY_OPTIONS,bf as PUSH_SERVICE_WORKER_SCRIPT,P as Permission,bg as PricingPage,bh as PushApi,bi as PushNotificationProvider,bj as QuotaUsageContextProvider,bk as SDKEvent,aO as SETTINGS_SCREENS,bl as SUPPORTED_LOCALES,a_ as SaaSOSProvider,s as SectionHeader,T as Sessions,bm as SessionsApi,bn as SettingsApi,aH as SettingsScreen,aJ as SidebarNavItem,aI as SidebarNavSection,r as StatusBanner,bo as SubscriptionContextProvider,ah as SubscriptionItemType,ak as SubscriptionStatus,bp as UserApi,bq as WhenAuthenticated,br as WhenCreditsAvailable,bs as WhenCreditsExhausted,bt as WhenCreditsLow,bu as WhenNoSubscription,bv as WhenNotTrialing,bw as WhenPermission,bx as WhenQuotaAvailable,by as WhenQuotaExhausted,bz as WhenQuotaOverage,bA as WhenQuotaThreshold,bB as WhenRoles,bC as WhenSubscription,bD as WhenSubscriptionToPlans,bE as WhenTrialEnding,bF as WhenTrialing,bG as WhenUnauthenticated,bH as WhenUserFeatureDisabled,bI as WhenUserFeatureEnabled,bJ as WhenWorkspaceFeatureDisabled,bK as WhenWorkspaceFeatureEnabled,bL as WhenWorkspaceRoles,bM as WorkspaceApi,bN as WorkspaceSwitcher,bO as calculateBillableSeats,bP as calculateSeatOverageCents,bQ as calculateTotalSubscriptionCents,bR as cleanBBParams,bS as clearAuthIntent,bT as coerceBadgeRef,bU as consumeAuthIntent,bV as createBBUrl,az as createCheckoutRedirectUrls,v as createCreditPurchaseRedirectUrls,bW as eventEmitter,bX as fillMcpTemplate,bY as formatCents,f as formatMinorAmountIntl,bZ as formatOverageRate,b_ as formatOverageRateWithLabel,b$ as formatQuotaIncludedOverage,c0 as formatQuotaWithPrice,aQ as getAvailableCurrenciesFromPlans,au as getBasePriceCents,at as getBillingIntervalAndCurrencyFromPriceId,e as getCurrencyDecimals,a0 as getCurrencyFlag,g as getCurrencySymbol,c1 as getDisplayCurrency,aw as getPerSeatPriceCents,aP as getPricingVariant,aj as getQuotaDisplayValue,ai as getQuotaDisplayWithVariant,aD as getQuotaOverageCents,c2 as getQuotaUnitLabelFromName,av as getSeatPricing,ay as getStripePriceIdForInterval,c3 as hasPermission,q as invalidateCreditBalance,c4 as invalidateQuotaUsage,aA as invalidateSubscription,c5 as isZeroDecimalCurrency,c6 as mcpServerKey,aL as mergeUIConfig,c7 as minorAmountToDisplay,c8 as readBBParams,c9 as resolveMaxUsers,ca as resolvePermissions,x as safeRedirect,cb as saveAuthIntent,cc as useAllQuotaUsage,aq as useBillingPortal,ao as useCancelSubscription,cd as useConnectedAgents,ce as useConnectedAgentsApi,cf as useConsumeCredits,an as useCreateCheckoutSession,cg as useCreditBalance,j as useCreditBalanceContext,k as useCreditPackages,m as useCreditTransactions,ch as useDevices,ci as useDevicesApi,l as useExpiringCredits,cj as useFullScreenLoader,ck as useInvoice,ac as useInvoices,cl as useMcpConnection,h as usePermissions,cm as usePlanGroup,ar as usePlanGroupVersions,cn as usePublicCreditPackages,co as usePublicPlanGroupVersion,cp as usePublicPlans,n as usePurchaseCredits,a7 as usePushNotifications,aB as useQuotaUsageContext,cq as useQuotaUsageStatus,cr as useRecordUsage,ap as useResumeSubscription,aE as useSaaSAuth,cs as useSaaSOs,A as useSaaSSettings,z as useSaaSWorkspaces,aF as useSeatStatus,ct as useSessions,cu as useSessionsApi,cv as useSubscription,aC as useSubscriptionContext,am as useSubscriptionManagement,u as useTranslation,cw as useTrialStatus,aK as useUIConfig,i as useUIVisibility,cx as useUpdateSubscription,cy as useUsageLogs,cz as useUserAttributes,cA as useUserFeatures,cB as validateInvite,cC as validateRedirectUrl,w as workspaceSettingsManager}from"./chunks/react-
|
|
2
|
+
export{aS as ApiVersion,aT as AuthApi,aU as AuthStatus,o as BBAction,aV as BBScreen,p as BBStatus,aW as BB_PARAM,aX as BaseApi,aY as BetaForm,ag as BillingIntervals,aZ as BuildBaseBadge,a_ as BuildBaseProvider,a$ as CURRENCY_DISPLAY,b0 as CURRENCY_FLAG,b1 as ConnectMcpGuide,C as ConnectedAgents,b2 as ConnectedAgentsApi,b3 as CreditActionsProvider,b4 as CreditBalance,b5 as CreditBalanceContextProvider,b6 as CreditBucketSource,b7 as CreditBucketStatus,b8 as CreditStorePage,y as CreditTransactionType,b9 as DEFAULT_ROLE_PERMISSIONS,R as Devices,ba as DevicesApi,ax as DunningState,E as EmptyState,bb as EventEmitter,bc as FullScreenLoader,ae as InvoiceStatuses,L as LoadingState,bd as PLAN_CURRENCY_CODES,be as PLAN_CURRENCY_OPTIONS,bf as PUSH_SERVICE_WORKER_SCRIPT,P as Permission,bg as PricingPage,bh as PushApi,bi as PushNotificationProvider,bj as QuotaUsageContextProvider,bk as SDKEvent,aO as SETTINGS_SCREENS,bl as SUPPORTED_LOCALES,a_ as SaaSOSProvider,s as SectionHeader,T as Sessions,bm as SessionsApi,bn as SettingsApi,aH as SettingsScreen,aJ as SidebarNavItem,aI as SidebarNavSection,r as StatusBanner,bo as SubscriptionContextProvider,ah as SubscriptionItemType,ak as SubscriptionStatus,bp as UserApi,bq as WhenAuthenticated,br as WhenCreditsAvailable,bs as WhenCreditsExhausted,bt as WhenCreditsLow,bu as WhenNoSubscription,bv as WhenNotTrialing,bw as WhenPermission,bx as WhenQuotaAvailable,by as WhenQuotaExhausted,bz as WhenQuotaOverage,bA as WhenQuotaThreshold,bB as WhenRoles,bC as WhenSubscription,bD as WhenSubscriptionToPlans,bE as WhenTrialEnding,bF as WhenTrialing,bG as WhenUnauthenticated,bH as WhenUserFeatureDisabled,bI as WhenUserFeatureEnabled,bJ as WhenWorkspaceFeatureDisabled,bK as WhenWorkspaceFeatureEnabled,bL as WhenWorkspaceRoles,bM as WorkspaceApi,bN as WorkspaceSwitcher,bO as calculateBillableSeats,bP as calculateSeatOverageCents,bQ as calculateTotalSubscriptionCents,bR as cleanBBParams,bS as clearAuthIntent,bT as coerceBadgeRef,bU as consumeAuthIntent,bV as createBBUrl,az as createCheckoutRedirectUrls,v as createCreditPurchaseRedirectUrls,bW as eventEmitter,bX as fillMcpTemplate,bY as formatCents,f as formatMinorAmountIntl,bZ as formatOverageRate,b_ as formatOverageRateWithLabel,b$ as formatQuotaIncludedOverage,c0 as formatQuotaWithPrice,aQ as getAvailableCurrenciesFromPlans,au as getBasePriceCents,at as getBillingIntervalAndCurrencyFromPriceId,e as getCurrencyDecimals,a0 as getCurrencyFlag,g as getCurrencySymbol,c1 as getDisplayCurrency,aw as getPerSeatPriceCents,aP as getPricingVariant,aj as getQuotaDisplayValue,ai as getQuotaDisplayWithVariant,aD as getQuotaOverageCents,c2 as getQuotaUnitLabelFromName,av as getSeatPricing,ay as getStripePriceIdForInterval,c3 as hasPermission,q as invalidateCreditBalance,c4 as invalidateQuotaUsage,aA as invalidateSubscription,c5 as isZeroDecimalCurrency,c6 as mcpServerKey,aL as mergeUIConfig,c7 as minorAmountToDisplay,c8 as readBBParams,c9 as resolveMaxUsers,ca as resolvePermissions,x as safeRedirect,cb as saveAuthIntent,cc as useAllQuotaUsage,aq as useBillingPortal,ao as useCancelSubscription,cd as useConnectedAgents,ce as useConnectedAgentsApi,cf as useConsumeCredits,an as useCreateCheckoutSession,cg as useCreditBalance,j as useCreditBalanceContext,k as useCreditPackages,m as useCreditTransactions,ch as useDevices,ci as useDevicesApi,l as useExpiringCredits,cj as useFullScreenLoader,ck as useInvoice,ac as useInvoices,cl as useMcpConnection,h as usePermissions,cm as usePlanGroup,ar as usePlanGroupVersions,cn as usePublicCreditPackages,co as usePublicPlanGroupVersion,cp as usePublicPlans,n as usePurchaseCredits,a7 as usePushNotifications,aB as useQuotaUsageContext,cq as useQuotaUsageStatus,cr as useRecordUsage,ap as useResumeSubscription,aE as useSaaSAuth,cs as useSaaSOs,A as useSaaSSettings,z as useSaaSWorkspaces,aF as useSeatStatus,ct as useSessions,cu as useSessionsApi,cv as useSubscription,aC as useSubscriptionContext,am as useSubscriptionManagement,u as useTranslation,cw as useTrialStatus,aK as useUIConfig,i as useUIVisibility,cx as useUpdateSubscription,cy as useUsageLogs,cz as useUserAttributes,cA as useUserFeatures,cB as validateInvite,cC as validateRedirectUrl,w as workspaceSettingsManager}from"./chunks/react-CHhQFy94.mjs";import"react/jsx-runtime";import"react";import"clsx";import"tailwind-merge";import"intl-messageformat";import"@hookform/resolvers/zod";import"react-hook-form";import"@radix-ui/react-slot";import"class-variance-authority";import"lucide-react";import"@radix-ui/react-label";import"zod";import"@radix-ui/react-avatar";import"@radix-ui/react-dialog";import"@radix-ui/react-icons";import"@radix-ui/react-radio-group";import"@radix-ui/react-scroll-area";import"@radix-ui/react-separator";import"@radix-ui/react-accordion";import"@radix-ui/react-alert-dialog";
|
package/dist/tracking/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";var e=require("react/jsx-runtime"),t=require("react");const n="bb_attr",r=["gclid","gbraid","wbraid","dclid","fbclid","msclkid","li_fat_id","twclid","ttclid","rdt_cid","epik","irclickid","utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_id"],i=/^[\w.~-]{1,200}$/;function o(){return"undefined"==typeof window?null:window}function a(e,t){if(!e||!e.includes("."))return"";if(/^\d{1,3}(\.\d{1,3}){3}$/.test(e))return"";const n=t??o()?.document;if(!n)return"";const r=e.split(".");for(let e=r.length-2;e>=0;e--){const t="."+r.slice(e).join("."),i=`__bb_probe_${Date.now()}`;n.cookie=`${i}=1; domain=${t}; path=/; SameSite=Lax`;const o=n.cookie.includes(`${i}=1`);if(n.cookie=`${i}=; domain=${t}; path=/; max-age=0; SameSite=Lax`,o)return t}return""}function s(e){const t=e.cookie.split("; ").find(e=>e.startsWith(`${n}=`));if(!t)return{};try{const e=JSON.parse(decodeURIComponent(t.slice(8)));return"object"==typeof e&&e?e:{}}catch{return{}}}function c(){const e=o();if(!e)return{};const t=e.document,c=s(t),d={...function(e){const t=new URLSearchParams(e),n={};for(const e of r){const r=t.get(e);r&&(r.length>200||i.test(r)&&(n[e]=r))}return n}(e.location.search),...c};if(0===Object.keys(d).length)return{};return Object.keys(d).some(e=>void 0===c[e])&&function(e,t,r){const i=encodeURIComponent(JSON.stringify(t));e.cookie=`${n}=${i}; path=/; max-age=7776000; SameSite=Lax`+(r?`; domain=${r}`:"")}(t,d,a(e.location.hostname,t)),d}function d(e){try{const t=new URLSearchParams(e);return t.has("code")&&t.has("state")}catch{return!1}}const l="bb_pending_checkout";function u(){try{return"undefined"==typeof window?null:window.sessionStorage}catch{return null}}const p="bb_co";function g(){try{return"undefined"==typeof window?null:window.document??null}catch{return null}}function f(){const e=g();if(e)try{const t=a(window.location?.hostname??"",e);e.cookie=`${p}=; path=/; max-age=0; SameSite=Lax`+(t?`; domain=${t}`:"")}catch{}}function m(e,t){if(!e)return null;try{const n=JSON.parse(e);return n&&"string"==typeof n.eventId&&n.eventId?"number"!=typeof n.startedAt||t-n.startedAt>216e5?null:n:null}catch{return null}}function h(e=Date.now()){const t=u();if(!t)return null;let n=null;try{n=t.getItem(l),t.removeItem(l)}catch{return null}const r=m(n,e);return r&&f(),r}function y(e){try{return m(u()?.getItem(l)??null,e)}catch{return null}}function w(e,t=Date.now()){let n=null;try{n=new URLSearchParams(e).get("session_id")}catch{return null}if(!n)return null;const r=y(t);if(r?.sessionId===n)return h(t);const i=function(e){const t=g();if(!t||"string"!=typeof t.cookie)return null;const n=t.cookie.split("; ").find(e=>e.startsWith(`${p}=`));return n?m(decodeURIComponent(n.slice(6)),e):null}(t);return i?.sessionId!==n?null:(f(),i)}function v(e,t=Date.now()){return function(e){let t=null;try{t=new URLSearchParams(e).get("bb")}catch{return!1}if(!t)return!1;const n={};for(const e of t.split(",")){const t=e.indexOf(":");if(-1!==t)try{n[decodeURIComponent(e.slice(0,t))]=decodeURIComponent(e.slice(t+1))}catch{}}return"checkout"===n.action&&"cancel"===n.status}(e)&&y(t)?h(t):null}const _=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"]),k=new Set(["bhd","jod","kwd","omr","tnd"]);function b(e,t){if("number"!=typeof e||!Number.isFinite(e))return;const n=(t??"").toLowerCase();return _.has(n)?e:e/(k.has(n)?1e3:100)}function I(){return"undefined"==typeof window?null:window}function C(e){const t=I();if(!t)return;t.gtag?.("consent","update",{ad_storage:e.marketing?"granted":"denied",ad_user_data:e.marketing?"granted":"denied",ad_personalization:e.marketing?"granted":"denied",analytics_storage:e.analytics?"granted":"denied"});const n=t.fbq;n?.("consent",e.marketing?"grant":"revoke")}const x={gtm:{title:"Google Tag Manager",vendor:"Google LLC",privacyUrl:"https://policies.google.com/privacy",idLabel:"Container ID",idPattern:"^GTM-[A-Z0-9]{4,10}$",idExample:"GTM-ABC1234",scriptOrigin:"https://www.googletagmanager.com",defaultConsentCategory:"analytics",supportsConsentMode:!0,needsConversionIds:!1},ga4:{title:"Google Analytics 4",vendor:"Google LLC",privacyUrl:"https://policies.google.com/privacy",idLabel:"Measurement ID",idPattern:"^G-[A-Z0-9]{8,12}$",idExample:"G-ABCD123456",scriptOrigin:"https://www.googletagmanager.com",defaultConsentCategory:"analytics",supportsConsentMode:!0,needsConversionIds:!1},google_ads:{title:"Google Ads",vendor:"Google LLC",privacyUrl:"https://policies.google.com/privacy",idLabel:"Conversion ID",idPattern:"^AW-[0-9]{9,12}$",idExample:"AW-123456789",scriptOrigin:"https://www.googletagmanager.com",defaultConsentCategory:"marketing",supportsConsentMode:!0,needsConversionIds:!0},meta_pixel:{title:"Meta Pixel",vendor:"Meta Platforms Ireland Limited",privacyUrl:"https://www.facebook.com/privacy/policy",idLabel:"Pixel ID",idPattern:"^[0-9]{15,16}$",idExample:"123456789012345",scriptOrigin:"https://connect.facebook.net",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},x_pixel:{title:"X (Twitter) Pixel",vendor:"X Corp.",privacyUrl:"https://x.com/en/privacy",idLabel:"Pixel ID",idPattern:"^o[a-z0-9]{4,6}$",idExample:"o1a2b3",scriptOrigin:"https://static.ads-twitter.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!0,multiInstance:!0},linkedin:{title:"LinkedIn Insight Tag",vendor:"LinkedIn Ireland Unlimited Company",privacyUrl:"https://www.linkedin.com/legal/privacy-policy",idLabel:"Partner ID",idPattern:"^[0-9]{6,9}$",idExample:"1234567",scriptOrigin:"https://snap.licdn.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!0,multiInstance:!0},tiktok:{title:"TikTok Pixel",vendor:"TikTok Information Technologies UK Limited",privacyUrl:"https://www.tiktok.com/legal/privacy-policy",idLabel:"Pixel ID",idPattern:"^[A-Z0-9]{20}$",idExample:"C4A1B2C3D4E5F6G7H8I9",scriptOrigin:"https://analytics.tiktok.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},reddit:{title:"Reddit Pixel",vendor:"Reddit, Inc.",privacyUrl:"https://www.reddit.com/policies/privacy-policy",idLabel:"Advertiser ID",idPattern:"^t2_[a-z0-9]{4,12}$",idExample:"t2_abc123",scriptOrigin:"https://www.redditstatic.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},bing_uet:{title:"Microsoft Advertising (UET)",vendor:"Microsoft Corporation",privacyUrl:"https://privacy.microsoft.com/en-us/privacystatement",idLabel:"Tag ID",idPattern:"^[0-9]{7,9}$",idExample:"12345678",scriptOrigin:"https://bat.bing.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},clarity:{title:"Microsoft Clarity",vendor:"Microsoft Corporation",privacyUrl:"https://privacy.microsoft.com/en-us/privacystatement",idLabel:"Project ID",idPattern:"^[a-z0-9]{10}$",idExample:"ab12cd34ef",scriptOrigin:"https://www.clarity.ms",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1},hotjar:{title:"Hotjar",vendor:"Hotjar Limited",privacyUrl:"https://www.hotjar.com/legal/policies/privacy/",idLabel:"Site ID",idPattern:"^[0-9]{6,9}$",idExample:"1234567",scriptOrigin:"https://static.hotjar.com",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1},posthog:{title:"PostHog",vendor:"PostHog, Inc.",privacyUrl:"https://posthog.com/privacy",idLabel:"Project API key",idPattern:"^phc_[A-Za-z0-9]{32,48}$",idExample:"phc_abcdefghijklmnopqrstuvwxyz012345",scriptOrigin:"https://us-assets.i.posthog.com",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1,hosts:["us.i.posthog.com","eu.i.posthog.com"]},plausible:{title:"Plausible Analytics",vendor:"Plausible Insights OÜ",privacyUrl:"https://plausible.io/privacy",idLabel:"Domain",idPattern:"^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$",idExample:"example.com",scriptOrigin:"https://plausible.io",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1},ahrefs:{title:"Ahrefs Analytics",vendor:"Ahrefs Pte. Ltd.",privacyUrl:"https://ahrefs.com/privacy",idLabel:"Analytics key",idPattern:"^[A-Za-z0-9+/=]{20,64}$",idExample:"AbCdEfGhIjKlMnOpQrStUv==",scriptOrigin:"https://analytics.ahrefs.com",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1}},$=Object.keys(x);function j(e){return"string"==typeof e&&Object.prototype.hasOwnProperty.call(x,e)}function A(e,t){return!!j(e)&&("string"==typeof t&&0!==t.length&&new RegExp(x[e].idPattern).test(t))}const q=/^[a-z][a-z0-9-]{0,40}$/,S=/^[\w.:/@+=-]{1,200}$/;function P(e){return function(e){if("string"!=typeof e)return!1;if(0===e.length||e.length>300)return!1;let t;try{t=new URL(e)}catch{return!1}return!("https:"!==t.protocol||!t.hostname||!t.hostname.includes(".")||e.includes("?")||e.includes("#")||t.username||t.password)}(e.src)&&function(e){if(null==e)return!0;if("object"!=typeof e||Array.isArray(e))return!1;const t=Object.entries(e);return!(t.length>12)&&t.every(([e,t])=>q.test(e)&&"string"==typeof t&&S.test(t))}(e.dataAttributes)}const E=Array.from(new Set($.map(e=>x[e].scriptOrigin))).sort(),O={sign_up:{ga4:"sign_up",meta:"CompleteRegistration",tiktok:"CompleteRegistration",reddit:"SignUp"},login:{ga4:"login",meta:null,tiktok:null,reddit:null},trial_started:{ga4:"begin_checkout",meta:"StartTrial",tiktok:"StartTrial",reddit:"Lead"},checkout_started:{ga4:"begin_checkout",meta:"InitiateCheckout",tiktok:"InitiateCheckout",reddit:"AddToCart"},purchase:{ga4:"purchase",meta:"Purchase",tiktok:"CompletePayment",reddit:"Purchase"},subscription_created:{ga4:"purchase",meta:"Subscribe",tiktok:"Subscribe",reddit:"Purchase"},subscription_upgraded:{ga4:"subscription_upgraded",meta:null,tiktok:null,reddit:null},lead:{ga4:"generate_lead",meta:"Lead",tiktok:"SubmitForm",reddit:"Lead"},workspace_created:{ga4:"workspace_created",meta:null,tiktok:null,reddit:null}},T=Object.keys(O);function U(e){return T.includes(e)}function L(){return"undefined"==typeof window?null:window}const R={gtm:"dataLayer",ga4:"gtag",google_ads:"gtag",meta_pixel:"fbq",x_pixel:"twq",linkedin:"lintrk",tiktok:"ttq",reddit:"rdt",bing_uet:"uetq",clarity:"clarity",hotjar:"hj",posthog:"posthog",plausible:"plausible",ahrefs:"__ahrefs_loaded"};function M(){return"undefined"==typeof window?null:window}function D(e,t={}){const n=M();if(!n)return null;const r=n.document.createElement("script");r.async=!0,r.src=e;for(const[e,n]of Object.entries(t))r.setAttribute(e,n);return n.document.head.appendChild(r),r}function N(e){const t=M();if(!t)return;const n=t.document.createElement("script");n.text=e,t.document.head.appendChild(n)}function B(e){const t=M();t&&(Array.isArray(t[e])||(t[e]=[]),"function"!=typeof t.gtag&&(t.gtag=function(){t[e].push(arguments)}))}const G=new Set;function V(e){for(const t of G)if(t.slice(0,t.indexOf(":"))===e)return!0;return!1}function z(e,t){const n=M();if(!n)return!1;if("gtm"===e||"ga4"===e||"google_ads"===e){const e=n.google_tag_manager;return!(!e||"object"!=typeof e)&&Object.prototype.hasOwnProperty.call(e,t)}const r=R[e];if(!r)return!1;if(void 0===n[r])return!1;if(G.has(`${e}:${t}`))return!0;return!x[e].multiInstance||!V(e)}const F={meta_pixel:e=>`fbq('init','${e}');fbq('track','PageView');`,x_pixel:e=>`twq('config','${e}');`,tiktok:e=>`ttq.load('${e}');ttq.page();`,reddit:e=>`rdt('init','${e}');rdt('track','PageVisit');`,bing_uet:e=>`window.uetq=window.uetq||[];window.uetq.push({ti:'${e}',enableAutoSpaTracking:false});`,linkedin:e=>`window._linkedin_data_partner_ids=window._linkedin_data_partner_ids||[];window._linkedin_data_partner_ids.push('${e}');`};function H(e,t,n){const r=function(e,t,n){const r=M();if(!r)return!1;if("external"===e.provider){if(!e.src)return!1;const t={};for(const[n,r]of Object.entries(e.dataAttributes??{}))t[`data-${n}`]=r;return D(e.src,t),!0}const i=e.provider,o=x[i];if(!o)return!1;const a=e.providerId;if(!a)return!1;const s=F[i];if(s&&V(i))return N(s(a)),!0;switch(i){case"gtm":{B(t),r[t].push({"gtm.start":Date.now(),event:"gtm.js"});const e="dataLayer"===t?"":`&l=${t}`;return D(`${o.scriptOrigin}/gtm.js?id=${a}${e}`),!0}case"ga4":case"google_ads":{B(t),D(`${o.scriptOrigin}/gtag/js?id=${a}`);const e=r.gtag;e("js",new Date);const s="ga4"===i&&n?.gaClientId?{client_id:n.gaClientId}:void 0;return s?e("config",a,s):e("config",a),!0}case"meta_pixel":return N(`!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','${o.scriptOrigin}/en_US/fbevents.js');fbq('init','${a}');fbq('track','PageView');`),!0;case"x_pixel":return N(`!function(e,t,n,s,u,a){e.twq||(s=e.twq=function(){s.exe?s.exe.apply(s,arguments):s.queue.push(arguments)},s.version='1.1',s.queue=[],u=t.createElement(n),u.async=!0,u.src='${o.scriptOrigin}/uwt.js',a=t.getElementsByTagName(n)[0],a.parentNode.insertBefore(u,a))}(window,document,'script');twq('config','${a}');`),!0;case"linkedin":return N(`window._linkedin_partner_id='${a}';window._linkedin_data_partner_ids=window._linkedin_data_partner_ids||[];window._linkedin_data_partner_ids.push('${a}');window.lintrk=window.lintrk||function(a,b){(window.lintrk.q=window.lintrk.q||[]).push([a,b])};window.lintrk.q=window.lintrk.q||[];`),D(`${o.scriptOrigin}/li.lms-analytics/insight.min.js`),!0;case"tiktok":return N(`!function(w,d,t){w.TiktokAnalyticsObject=t;var ttq=w[t]=w[t]||[];ttq.methods=['page','track','identify','instances','debug','on','off','once','ready','alias','group','enableCookie','disableCookie'];ttq.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var i=0;i<ttq.methods.length;i++)ttq.setAndDefer(ttq,ttq.methods[i]);ttq.load=function(e,n){var r='${o.scriptOrigin}/i18n/pixel/events.js';ttq._i=ttq._i||{};ttq._i[e]=[];ttq._i[e]._u=r;ttq._t=ttq._t||{};ttq._t[e]=+new Date;ttq._o=ttq._o||{};ttq._o[e]=n||{};var o=d.createElement('script');o.type='text/javascript';o.async=!0;o.src=r+'?sdkid='+e+'&lib='+t;var a=d.getElementsByTagName('script')[0];a.parentNode.insertBefore(o,a)};ttq.load('${a}');ttq.page()}(window,document,'ttq');`),!0;case"reddit":return N(`!function(w,d){if(!w.rdt){var p=w.rdt=function(){p.sendEvent?p.sendEvent.apply(p,arguments):p.callQueue.push(arguments)};p.callQueue=[];var t=d.createElement('script');t.src='${o.scriptOrigin}/ads/pixel.js';t.async=!0;var s=d.getElementsByTagName('script')[0];s.parentNode.insertBefore(t,s)}}(window,document);rdt('init','${a}');rdt('track','PageVisit');`),!0;case"bing_uet":return N(`(function(w,d,t,r,u){w[u]=w[u]||[];w[u].push({ti:'${a}',enableAutoSpaTracking:false});var o=d.createElement(t);o.src='${o.scriptOrigin}/bat.js';o.async=1;var i=d.getElementsByTagName(t)[0];i.parentNode.insertBefore(o,i)})(window,document,'script',0,'uetq');`),!0;case"clarity":return N(`(function(c,l,a,r,i,t,y){c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};t=l.createElement(r);t.async=1;t.src='${o.scriptOrigin}/tag/'+i;y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y)})(window,document,'clarity','script','${a}');`),!0;case"hotjar":return N(`(function(h,o,t,j,a,r){h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};h._hjSettings={hjid:${a},hjsv:6};a=o.getElementsByTagName('head')[0];r=o.createElement('script');r.async=1;r.src='${o.scriptOrigin}/hotjar-'+h._hjSettings.hjid+'.js?sv='+h._hjSettings.hjsv;a.appendChild(r)})(window,document);`),!0;case"posthog":{const t=o.hosts,n=t?.includes(e.host??"")?e.host:t?.[0]??"us.i.posthog.com";return N(`!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split('.');2==o.length&&(t=t[o[0]],e=o[1]);t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement('script')).type='text/javascript',p.async=!0,p.src='${o.scriptOrigin}/static/array.js',(r=t.getElementsByTagName('script')[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a='posthog',u.people=u.people||[],u.toString=function(t){var e='posthog';return'posthog'!==a&&(e+='.'+a),t||(e+=' (stub)'),e},u.people.toString=function(){return u.toString(1)+'.people (stub)'},o='init capture register register_once identify alias people.set people.set_once set_config get_distinct_id getFeatureFlag isFeatureEnabled onFeatureFlags reloadFeatureFlags group reset'.split(' '),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);posthog.init('${a}',{api_host:'https://${n}'});`),!0}case"plausible":return N("window.plausible=window.plausible||function(){(window.plausible.q=window.plausible.q||[]).push(arguments)};"),D(`${o.scriptOrigin}/js/script.js`,{"data-domain":a,defer:"true"}),!0;case"ahrefs":return D(`${o.scriptOrigin}/analytics.js`,{"data-key":a}),r.__ahrefs_loaded=!0,!0;default:return!1}}(e,t,n);return r&&"external"!==e.provider&&e.providerId&&G.add(`${e.provider}:${e.providerId}`),r}const Z=Symbol.for("@buildbase/sdk.tracking.context"),J=globalThis,K=J[Z]??(J[Z]=t.createContext(null)),W={consent:{manifest:[],state:null,set:()=>{}},track:()=>{},setUser:()=>{},setProperties:()=>{},getProperties:()=>({}),completeCheckout:async()=>{},installed:{},ready:!0,attribution:{}};function Q(){return t.useContext(K)??W}const X=({serverUrl:n,orgId:r,clientId:i,enabled:o=!0,consent:a="auto",autoPageview:s=!0,events:l,onEvent:u,properties:p,enrich:g,identity:f,debug:m=!1,children:h})=>{const y=t.useRef(f);y.current=f;const[_,k]=t.useState(null),[$,q]=t.useState(!1),[S,E]=t.useState(!1),T="granted"===a?{analytics:!0,marketing:!0}:"denied"===a?{analytics:!1,marketing:!1}:null,[R,M]=t.useState(T),D=t.useRef(null),N=t.useRef(u);N.current=u;const G=t.useRef(g);G.current=g;const V=t.useRef({});V.current=p??{};const F=t.useRef({}),Z=t.useCallback(()=>({...V.current,...F.current}),[]),J=t.useCallback(e=>{const t={...F.current,...e};for(const[e,n]of Object.entries(t))void 0===n&&delete t[e];F.current=t},[]),[W,Q]=t.useState({}),X=t.useRef({}),[Y,ee]=t.useState(0),te=_?.dataLayerName??"dataLayer",ne=t.useCallback((...e)=>{m&&console.info("[buildbase:tracking]",...e)},[m]);t.useEffect(()=>{if(!(o&&n&&r&&i))return void q(!0);let e=!1;const t=`${n.replace(/\/$/,"")}/api/v1/public/${r}/tracking?clientId=${encodeURIComponent(i)}`;return fetch(t).then(e=>e.ok?e.json():null).then(t=>{if(e||!t)return;const n=t.data??t;n&&Array.isArray(n.scripts)&&k(n)}).catch(()=>{ne("config fetch failed; nothing installed")}).finally(()=>{e||q(!0)}),()=>{e=!0}},[o,n,r,i,ne]),t.useEffect(()=>{o&&Q(c())},[o]),t.useEffect(()=>{o&&_?.enabled&&(B(te),function(e,t){const n=I();if(!n)return;Array.isArray(n[e])||(n[e]=[]),"function"!=typeof n.gtag&&(n.gtag=function(){n[e].push(arguments)});const r="granted"===t?"granted":"denied";n.gtag("consent","default",{ad_storage:r,ad_user_data:r,ad_personalization:r,analytics_storage:r,wait_for_update:500})}(te,a),D.current&&C(D.current))},[o,_?.enabled,te,a]);const re=t.useMemo(()=>_?.enabled?_.scripts.filter(e=>{const t=j(e.provider)&&x[e.provider].supportsConsentMode;return function(e,t,n,r){return"denied"!==r&&("granted"===r||(n?"marketing"===e?n.marketing:n.analytics:t&&"analytics"===e))}(e.consentCategory,t,R,a)}):[],[_,R,a]),[ie,oe]=t.useState(()=>"undefined"==typeof window||!d(window.location.search));t.useEffect(()=>{if(ie)return;const e=setInterval(()=>{d(window.location.search)||oe(!0)},50),t=setTimeout(()=>oe(!0),5e3);return()=>{clearInterval(e),clearTimeout(t)}},[ie]),t.useEffect(()=>{if(!ie)return;if(!o||!_?.enabled)return void($&&E(!0));let e=0;for(const t of re)if(!X.current[t.key]){if("external"===t.provider){if(!P({src:t.src,dataAttributes:t.dataAttributes})){ne("rejected external script",t.key);continue}}else{if(!j(t.provider)){ne("rejected unknown provider",t.provider);continue}if(!A(t.provider,t.providerId)){ne("rejected id for",t.provider);continue}if(z(t.provider,t.providerId??"")){ne(`${t.provider} ${t.providerId} is already on the page; skipping. Configure each tag in exactly one place.`);continue}}H(t,te,y.current)&&(X.current[t.key]=t.providerId??t.src??"",e+=1,ne("installed",t.key))}e&&ee(e=>e+1);const t=window;t.__buildbase=t.__buildbase??{},t.__buildbase.tracking={installed:{...X.current},dataLayerName:te,clientId:i};const n=Object.keys(X.current).length>0,r=null!==R||0===_.scripts.length;(n||r)&&E(!0)},[o,_,re,$,R,te,ne,ie,i]),t.useEffect(()=>{if(!o||!s||!_?.enabled)return;if("undefined"==typeof window)return;if(!ie)return;let e=null;const t=()=>{e&&clearTimeout(e),e=setTimeout(()=>function(e,t){const n=L();if(!n)return;const r=n[t];Array.isArray(r)&&r.push({event:"page_view",page_path:n.location.pathname,page_location:n.location.href,page_title:n.document.title});for(const t of e)switch(t.provider){case"ga4":n.gtag?.("event","page_view",{send_to:t.providerId,page_path:n.location.pathname,page_location:n.location.href,page_title:n.document.title});break;case"meta_pixel":n.fbq?.("track","PageView");break;case"tiktok":{const e=n.ttq;e?.page?.();break}case"reddit":n.rdt?.("track","PageVisit")}}(re,te),50)},n=window.history,r=n.pushState,i=n.replaceState;return n.pushState=function(...e){const n=r.apply(this,e);return t(),n},n.replaceState=function(...e){const n=i.apply(this,e);return t(),n},window.addEventListener("popstate",t),()=>{n.pushState=r,n.replaceState=i,window.removeEventListener("popstate",t),e&&clearTimeout(e)}},[o,s,_?.enabled,re,te,ie]),t.useEffect(()=>{if(!o)return;const e=function(e,t){const n=e?.mode??"auto",r=e?.overrides??{};if(("manual"===n||Object.values(r).some(e=>"manual"===e))&&!t)return'[buildbase:tracking] events are set to "manual" but no onEvent handler was provided, so those events would never fire anywhere. Pass onEvent, or use mode "auto".';for(const e of Object.keys(r))if(!U(e))return`[buildbase:tracking] unknown event "${e}" in events.overrides. Overrides only apply to the events the SDK fires itself.`;return null}(l,!!u);if(e)throw new Error(e)},[o,l,u]);const ae=t.useCallback((e,t={},n)=>{if(!o)return;const r=n?.eventId||function(){const e=globalThis.crypto;return e?.randomUUID?e.randomUUID():`${Date.now().toString(16)}-${Math.random().toString(16).slice(2,10)}`}(),i=l?.mode??"auto",a=(U(e)?l?.overrides?.[e]:void 0)??i,s={...V.current,...F.current,...W,...t},c=G.current?.({name:e,params:s})??{},d={...s,...c},u=N.current?.({name:e,params:d,eventId:r,handledBy:a});"manual"!==a&&!0!==u?(!function(e,t,n,r,i){const o=L();if(!o)return;const a=o[i];Array.isArray(a)&&a.push({event:e,...t,event_id:n});const s=U(e)?O[e]:{ga4:e,meta:null,tiktok:null,reddit:null};for(const i of r){const r=i.provider,a=x[r];if(a){if(a.needsConversionIds){const a=i.conversionIds?.[e];if(!a)continue;"google_ads"===r?o.gtag?.("event","conversion",{send_to:`${i.providerId}/${a}`,transaction_id:n,...t}):"x_pixel"===r?o.twq?.("event",a,{...t,conversion_id:n}):"linkedin"===r&&o.lintrk?.("track",{conversion_id:a});continue}switch(r){case"ga4":s.ga4&&o.gtag?.("event",s.ga4,{...t,send_to:i.providerId,event_id:n});break;case"meta_pixel":s.meta&&o.fbq?.("track",s.meta,t,{eventID:n});break;case"tiktok":if(s.tiktok){const e=o.ttq;e?.track?.(s.tiktok,{...t,event_id:n})}break;case"reddit":s.reddit&&o.rdt?.("track",s.reddit,{...t,conversionId:n});break;case"bing_uet":{const r=o.uetq;r?.push?.("event",s.ga4??e,{...t,event_id:n});break}case"clarity":o.clarity?.("event",e);break;case"hotjar":{const t=o.hj;t?.("event",e);break}case"posthog":{const r=o.posthog;r?.capture?.(e,{...t,event_id:n});break}case"plausible":o.plausible?.(e,{props:t})}}}}(e,d,r,re,te),ne("event fired:",e,r)):ne("event handled by app:",e)},[o,l,re,te,W,ne]),se=t.useCallback(async(e,t={})=>{const i=function(e){return{name:"trial_started"===e.kind?"trial_started":"purchase",params:{...e.workspaceId?{workspace_id:e.workspaceId}:{},...e.planVersionId?{plan_version_id:e.planVersionId}:{},...e.creditPackageId?{credit_package_id:e.creditPackageId}:{},...e.billingInterval?{billing_interval:e.billingInterval}:{},...e.currency?{currency:e.currency.toUpperCase()}:{},..."number"==typeof e.value?{value:e.value}:{},...e.sessionId?{transaction_id:e.sessionId}:{}}}}(e);let o=i.params;if(e.sessionId&&n&&r){const t=await async function(e,t){try{const n=e.serverUrl.replace(/\/$/,""),r=await fetch(`${n}/api/v1/public/${encodeURIComponent(e.orgId)}/checkout/${encodeURIComponent(t)}`,{credentials:"omit",..."undefined"!=typeof AbortSignal&&AbortSignal.timeout?{signal:AbortSignal.timeout(2e3)}:{}});if(!r.ok)return null;const i=await r.json(),o=i?.data??i;return"number"!=typeof o?.amount?null:{value:b(o.amount,o.currency),currency:"string"==typeof o.currency?o.currency:void 0,...Array.isArray(o.items)&&o.items.length?{items:o.items}:{}}}catch{return null}}({serverUrl:n,orgId:r},e.sessionId);t&&"number"==typeof t.value&&(o={...o,value:t.value,...t.currency?{currency:t.currency.toUpperCase()}:{},...t.items?.length?{items:t.items}:{}})}if(ae(i.name,{...o,...t},{eventId:e.eventId}),"purchase"===i.name&&e.sessionId&&n&&r){const t=(_?.scripts??[]).find(e=>"ga4"===e.provider&&e.providerId);t&&z("ga4",t.providerId??"")&&function(e,t,n){try{const r=e.serverUrl.replace(/\/$/,"");fetch(`${r}/api/v1/public/${encodeURIComponent(e.orgId)}/checkout/${encodeURIComponent(t)}/reported`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:n}),keepalive:!0,credentials:"omit"}).catch(()=>{})}catch{}}({serverUrl:n,orgId:r},e.sessionId,"ga4")}},[n,r,ae,_]),[ce]=t.useState(()=>"undefined"==typeof window?"":window.location.search);t.useEffect(()=>{if(!o||!S)return;if("undefined"==typeof window)return;const e=w(window.location.search);if(e)return void se(e);const t=v(ce);t&&ae("checkout_abandoned",{...t.workspaceId?{workspace_id:t.workspaceId}:{},...t.planVersionId?{plan_version_id:t.planVersionId}:{},...t.creditPackageId?{credit_package_id:t.creditPackageId}:{},...t.billingInterval?{billing_interval:t.billingInterval}:{},...t.currency?{currency:t.currency.toUpperCase()}:{},..."number"==typeof t.value?{value:t.value}:{},seconds_at_checkout:Math.max(0,Math.round((Date.now()-t.startedAt)/1e3))})},[o,S,se,ce,ae]);const de=t.useCallback(e=>{D.current=e,M(e),C(e)},[]),le=t.useCallback((e,t)=>function(e,t,n){const r=L();if(!r)return;const i=!!n&&Object.keys(n).length>0;for(const o of t)switch(o.provider){case"ga4":case"google_ads":r.gtag?.("set",{user_id:e}),i&&r.gtag?.("set",{user_properties:n});break;case"meta_pixel":o.providerId&&r.fbq?.("init",o.providerId,{external_id:e});break;case"posthog":r.posthog?.identify?.(e,i?n:void 0);break;case"clarity":if(r.clarity?.("identify",e),i)for(const[e,t]of Object.entries(n))r.clarity?.("set",e,String(t));break;case"hotjar":r.hj?.("identify",e,{});break;case"tiktok":{const t=r.ttq;t?.identify?.({external_id:e});break}}}(e,re,t),[re]),ue=t.useMemo(()=>({consent:{manifest:_?.consent?.manifest??[],state:R,set:de},track:ae,setUser:le,setProperties:J,getProperties:Z,completeCheckout:se,installed:{...X.current},ready:S,attribution:W}),[_,R,de,ae,le,J,Z,se,S,Y,W]);return e.jsx(K.Provider,{value:ue,children:h})};X.displayName="BuildBaseTracking";exports.ATTRIBUTION_PARAMS=r,exports.BuildBaseTracking=X,exports.EVENT_MAPPINGS=O,exports.FUNNEL_EVENTS={sign_in_started:"The sign-in / sign-up button was pressed.",pricing_viewed:"A <PricingPage> finished loading its plans.",pricing_plan_selected:"A plan was chosen on a <PricingPage>.",workspace_switcher_opened:"The workspace switcher was opened.",workspace_settings_opened:"The workspace settings modal was opened.",workspace_settings_section_viewed:"A different section of the settings modal was opened.",plan_picker_opened:"The plan picker was shown.",billing_interval_changed:"Monthly / quarterly / yearly was switched in the plan picker.",plan_selected:"A plan was chosen in the plan picker.",plan_picker_dismissed:"The plan picker was closed without choosing a plan.",checkout_abandoned:"The customer came back from Stripe without paying.",billing_portal_opened:"Stripe’s billing portal was opened.",subscription_cancel_started:"The cancel-subscription confirmation was opened.",subscription_cancelled:"A subscription was cancelled.",subscription_resumed:"A cancelled subscription was resumed.",feature_gate_shown:'A feature gate rendered its "not on your plan" side.',quota_limit_reached:"A quota gate rendered because a quota is used up.",quota_threshold_reached:"A usage-threshold gate rendered.",plan_gate_shown:'A plan gate rendered its "needs another plan" side.',subscription_notice_shown:"A billing notice (trial ending, payment failed…) was shown.",sdk_error:"An SDK operation failed (component, action and code only)."},exports.TAG_PROVIDERS=x,exports.TAG_PROVIDER_IDS=$,exports.TAG_SCRIPT_ORIGINS=E,exports.captureAttribution=c,exports.getAttribution=function(){const e=o();return e?s(e.document):{}},exports.isCanonicalEvent=U,exports.isTagProviderId=j,exports.isValidProviderId=A,exports.useCheckoutCompleted=function(e={}){const{completeCheckout:n,ready:r}=Q(),i=t.useRef(e);i.current=e;const o=t.useRef(!1);t.useEffect(()=>{if(!r)return;if(o.current)return;const e=w(window.location.search)??h();e&&(o.current=!0,n(e,i.current))},[r,n])},exports.useTracking=Q;
|
|
2
|
+
"use strict";var e=require("react/jsx-runtime"),t=require("react");const n="__buildbaseBeforeLeave",r=globalThis,i=r[n]??(r[n]=new Set);const o="bb_attr",a=["gclid","gbraid","wbraid","dclid","fbclid","msclkid","li_fat_id","twclid","ttclid","rdt_cid","epik","irclickid","utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_id"],s=/^[\w.~-]{1,200}$/;function c(){return"undefined"==typeof window?null:window}function d(e,t){if(!e||!e.includes("."))return"";if(/^\d{1,3}(\.\d{1,3}){3}$/.test(e))return"";const n=t??c()?.document;if(!n)return"";const r=e.split(".");for(let e=r.length-2;e>=0;e--){const t="."+r.slice(e).join("."),i=`__bb_probe_${Date.now()}`;n.cookie=`${i}=1; domain=${t}; path=/; SameSite=Lax`;const o=n.cookie.includes(`${i}=1`);if(n.cookie=`${i}=; domain=${t}; path=/; max-age=0; SameSite=Lax`,o)return t}return""}function l(e){const t=e.cookie.split("; ").find(e=>e.startsWith(`${o}=`));if(!t)return{};try{const e=JSON.parse(decodeURIComponent(t.slice(8)));return"object"==typeof e&&e?e:{}}catch{return{}}}function u(){const e=c();if(!e)return{};const t=e.document,n=l(t),r={...function(e){const t=new URLSearchParams(e),n={};for(const e of a){const r=t.get(e);r&&(r.length>200||s.test(r)&&(n[e]=r))}return n}(e.location.search),...n};if(0===Object.keys(r).length)return{};return Object.keys(r).some(e=>void 0===n[e])&&function(e,t,n){const r=encodeURIComponent(JSON.stringify(t));e.cookie=`${o}=${r}; path=/; max-age=7776000; SameSite=Lax`+(n?`; domain=${n}`:"")}(t,r,d(e.location.hostname,t)),r}function p(e){try{const t=new URLSearchParams(e);return t.has("code")&&t.has("state")}catch{return!1}}const g="bb_pending_checkout";function f(){try{return"undefined"==typeof window?null:window.sessionStorage}catch{return null}}const m="bb_co";function h(){try{return"undefined"==typeof window?null:window.document??null}catch{return null}}function y(){const e=h();if(e)try{const t=d(window.location?.hostname??"",e);e.cookie=`${m}=; path=/; max-age=0; SameSite=Lax`+(t?`; domain=${t}`:"")}catch{}}function w(e,t){if(!e)return null;try{const n=JSON.parse(e);return n&&"string"==typeof n.eventId&&n.eventId?"number"!=typeof n.startedAt||t-n.startedAt>216e5?null:n:null}catch{return null}}function v(e=Date.now()){const t=f();if(!t)return null;let n=null;try{n=t.getItem(g),t.removeItem(g)}catch{return null}const r=w(n,e);return r&&y(),r}function _(e){try{return w(f()?.getItem(g)??null,e)}catch{return null}}function k(e,t=Date.now()){let n=null;try{n=new URLSearchParams(e).get("session_id")}catch{return null}if(!n)return null;const r=_(t);if(r?.sessionId===n)return v(t);const i=function(e){const t=h();if(!t||"string"!=typeof t.cookie)return null;const n=t.cookie.split("; ").find(e=>e.startsWith(`${m}=`));return n?w(decodeURIComponent(n.slice(6)),e):null}(t);return i?.sessionId!==n?null:(y(),i)}function b(e,t=Date.now()){return function(e){let t=null;try{t=new URLSearchParams(e).get("bb")}catch{return!1}if(!t)return!1;const n={};for(const e of t.split(",")){const t=e.indexOf(":");if(-1!==t)try{n[decodeURIComponent(e.slice(0,t))]=decodeURIComponent(e.slice(t+1))}catch{}}return"checkout"===n.action&&"cancel"===n.status}(e)&&_(t)?v(t):null}const I=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"]),C=new Set(["bhd","jod","kwd","omr","tnd"]);function x(e,t){if("number"!=typeof e||!Number.isFinite(e))return;const n=(t??"").toLowerCase();return I.has(n)?e:e/(C.has(n)?1e3:100)}function $(){return"undefined"==typeof window?null:window}function j(e){const t=$();if(!t)return;t.gtag?.("consent","update",{ad_storage:e.marketing?"granted":"denied",ad_user_data:e.marketing?"granted":"denied",ad_personalization:e.marketing?"granted":"denied",analytics_storage:e.analytics?"granted":"denied"});const n=t.fbq;n?.("consent",e.marketing?"grant":"revoke")}const A={gtm:{title:"Google Tag Manager",vendor:"Google LLC",privacyUrl:"https://policies.google.com/privacy",idLabel:"Container ID",idPattern:"^GTM-[A-Z0-9]{4,10}$",idExample:"GTM-ABC1234",scriptOrigin:"https://www.googletagmanager.com",defaultConsentCategory:"analytics",supportsConsentMode:!0,needsConversionIds:!1},ga4:{title:"Google Analytics 4",vendor:"Google LLC",privacyUrl:"https://policies.google.com/privacy",idLabel:"Measurement ID",idPattern:"^G-[A-Z0-9]{8,12}$",idExample:"G-ABCD123456",scriptOrigin:"https://www.googletagmanager.com",defaultConsentCategory:"analytics",supportsConsentMode:!0,needsConversionIds:!1},google_ads:{title:"Google Ads",vendor:"Google LLC",privacyUrl:"https://policies.google.com/privacy",idLabel:"Conversion ID",idPattern:"^AW-[0-9]{9,12}$",idExample:"AW-123456789",scriptOrigin:"https://www.googletagmanager.com",defaultConsentCategory:"marketing",supportsConsentMode:!0,needsConversionIds:!0},meta_pixel:{title:"Meta Pixel",vendor:"Meta Platforms Ireland Limited",privacyUrl:"https://www.facebook.com/privacy/policy",idLabel:"Pixel ID",idPattern:"^[0-9]{15,16}$",idExample:"123456789012345",scriptOrigin:"https://connect.facebook.net",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},x_pixel:{title:"X (Twitter) Pixel",vendor:"X Corp.",privacyUrl:"https://x.com/en/privacy",idLabel:"Pixel ID",idPattern:"^o[a-z0-9]{4,6}$",idExample:"o1a2b3",scriptOrigin:"https://static.ads-twitter.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!0,multiInstance:!0},linkedin:{title:"LinkedIn Insight Tag",vendor:"LinkedIn Ireland Unlimited Company",privacyUrl:"https://www.linkedin.com/legal/privacy-policy",idLabel:"Partner ID",idPattern:"^[0-9]{6,9}$",idExample:"1234567",scriptOrigin:"https://snap.licdn.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!0,multiInstance:!0},tiktok:{title:"TikTok Pixel",vendor:"TikTok Information Technologies UK Limited",privacyUrl:"https://www.tiktok.com/legal/privacy-policy",idLabel:"Pixel ID",idPattern:"^[A-Z0-9]{20}$",idExample:"C4A1B2C3D4E5F6G7H8I9",scriptOrigin:"https://analytics.tiktok.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},reddit:{title:"Reddit Pixel",vendor:"Reddit, Inc.",privacyUrl:"https://www.reddit.com/policies/privacy-policy",idLabel:"Advertiser ID",idPattern:"^t2_[a-z0-9]{4,12}$",idExample:"t2_abc123",scriptOrigin:"https://www.redditstatic.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},bing_uet:{title:"Microsoft Advertising (UET)",vendor:"Microsoft Corporation",privacyUrl:"https://privacy.microsoft.com/en-us/privacystatement",idLabel:"Tag ID",idPattern:"^[0-9]{7,9}$",idExample:"12345678",scriptOrigin:"https://bat.bing.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},clarity:{title:"Microsoft Clarity",vendor:"Microsoft Corporation",privacyUrl:"https://privacy.microsoft.com/en-us/privacystatement",idLabel:"Project ID",idPattern:"^[a-z0-9]{10}$",idExample:"ab12cd34ef",scriptOrigin:"https://www.clarity.ms",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1},hotjar:{title:"Hotjar",vendor:"Hotjar Limited",privacyUrl:"https://www.hotjar.com/legal/policies/privacy/",idLabel:"Site ID",idPattern:"^[0-9]{6,9}$",idExample:"1234567",scriptOrigin:"https://static.hotjar.com",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1},posthog:{title:"PostHog",vendor:"PostHog, Inc.",privacyUrl:"https://posthog.com/privacy",idLabel:"Project API key",idPattern:"^phc_[A-Za-z0-9]{32,48}$",idExample:"phc_abcdefghijklmnopqrstuvwxyz012345",scriptOrigin:"https://us-assets.i.posthog.com",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1,hosts:["us.i.posthog.com","eu.i.posthog.com"]},plausible:{title:"Plausible Analytics",vendor:"Plausible Insights OÜ",privacyUrl:"https://plausible.io/privacy",idLabel:"Domain",idPattern:"^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$",idExample:"example.com",scriptOrigin:"https://plausible.io",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1},ahrefs:{title:"Ahrefs Analytics",vendor:"Ahrefs Pte. Ltd.",privacyUrl:"https://ahrefs.com/privacy",idLabel:"Analytics key",idPattern:"^[A-Za-z0-9+/=]{20,64}$",idExample:"AbCdEfGhIjKlMnOpQrStUv==",scriptOrigin:"https://analytics.ahrefs.com",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1}},q=Object.keys(A);function P(e){return"string"==typeof e&&Object.prototype.hasOwnProperty.call(A,e)}function S(e,t){return!!P(e)&&("string"==typeof t&&0!==t.length&&new RegExp(A[e].idPattern).test(t))}const E=/^[a-z][a-z0-9-]{0,40}$/,O=/^[\w.:/@+=-]{1,200}$/;function T(e){return function(e){if("string"!=typeof e)return!1;if(0===e.length||e.length>300)return!1;let t;try{t=new URL(e)}catch{return!1}return!("https:"!==t.protocol||!t.hostname||!t.hostname.includes(".")||e.includes("?")||e.includes("#")||t.username||t.password)}(e.src)&&function(e){if(null==e)return!0;if("object"!=typeof e||Array.isArray(e))return!1;const t=Object.entries(e);return!(t.length>12)&&t.every(([e,t])=>E.test(e)&&"string"==typeof t&&O.test(t))}(e.dataAttributes)}const U=Array.from(new Set(q.map(e=>A[e].scriptOrigin))).sort(),L={sign_up:{ga4:"sign_up",meta:"CompleteRegistration",tiktok:"CompleteRegistration",reddit:"SignUp"},login:{ga4:"login",meta:null,tiktok:null,reddit:null},trial_started:{ga4:"begin_checkout",meta:"StartTrial",tiktok:"StartTrial",reddit:"Lead"},checkout_started:{ga4:"begin_checkout",meta:"InitiateCheckout",tiktok:"InitiateCheckout",reddit:"AddToCart"},purchase:{ga4:"purchase",meta:"Purchase",tiktok:"CompletePayment",reddit:"Purchase"},subscription_created:{ga4:"purchase",meta:"Subscribe",tiktok:"Subscribe",reddit:"Purchase"},subscription_upgraded:{ga4:"subscription_upgraded",meta:null,tiktok:null,reddit:null},lead:{ga4:"generate_lead",meta:"Lead",tiktok:"SubmitForm",reddit:"Lead"},workspace_created:{ga4:"workspace_created",meta:null,tiktok:null,reddit:null}},R=Object.keys(L);function M(e){return R.includes(e)}function D(){return"undefined"==typeof window?null:window}const N={gtm:"dataLayer",ga4:"gtag",google_ads:"gtag",meta_pixel:"fbq",x_pixel:"twq",linkedin:"lintrk",tiktok:"ttq",reddit:"rdt",bing_uet:"uetq",clarity:"clarity",hotjar:"hj",posthog:"posthog",plausible:"plausible",ahrefs:"__ahrefs_loaded"};function B(){return"undefined"==typeof window?null:window}function G(e,t={}){const n=B();if(!n)return null;const r=n.document.createElement("script");r.async=!0,r.src=e;for(const[e,n]of Object.entries(t))r.setAttribute(e,n);return n.document.head.appendChild(r),r}function V(e){const t=B();if(!t)return;const n=t.document.createElement("script");n.text=e,t.document.head.appendChild(n)}function z(e){const t=B();t&&(Array.isArray(t[e])||(t[e]=[]),"function"!=typeof t.gtag&&(t.gtag=function(){t[e].push(arguments)}))}const F=new Set;function H(e){for(const t of F)if(t.slice(0,t.indexOf(":"))===e)return!0;return!1}function Z(e,t){const n=B();if(!n)return!1;if("gtm"===e||"ga4"===e||"google_ads"===e){const e=n.google_tag_manager;return!(!e||"object"!=typeof e)&&Object.prototype.hasOwnProperty.call(e,t)}const r=N[e];if(!r)return!1;if(void 0===n[r])return!1;if(F.has(`${e}:${t}`))return!0;return!A[e].multiInstance||!H(e)}const J={meta_pixel:e=>`fbq('init','${e}');fbq('track','PageView');`,x_pixel:e=>`twq('config','${e}');`,tiktok:e=>`ttq.load('${e}');ttq.page();`,reddit:e=>`rdt('init','${e}');rdt('track','PageVisit');`,bing_uet:e=>`window.uetq=window.uetq||[];window.uetq.push({ti:'${e}',enableAutoSpaTracking:false});`,linkedin:e=>`window._linkedin_data_partner_ids=window._linkedin_data_partner_ids||[];window._linkedin_data_partner_ids.push('${e}');`};function K(e,t,n){const r=function(e,t,n){const r=B();if(!r)return!1;if("external"===e.provider){if(!e.src)return!1;const t={};for(const[n,r]of Object.entries(e.dataAttributes??{}))t[`data-${n}`]=r;return G(e.src,t),!0}const i=e.provider,o=A[i];if(!o)return!1;const a=e.providerId;if(!a)return!1;const s=J[i];if(s&&H(i))return V(s(a)),!0;switch(i){case"gtm":{z(t),r[t].push({"gtm.start":Date.now(),event:"gtm.js"});const e="dataLayer"===t?"":`&l=${t}`;return G(`${o.scriptOrigin}/gtm.js?id=${a}${e}`),!0}case"ga4":case"google_ads":{z(t),G(`${o.scriptOrigin}/gtag/js?id=${a}`);const e=r.gtag;e("js",new Date);const s="ga4"===i&&n?.gaClientId?{client_id:n.gaClientId}:void 0;return s?e("config",a,s):e("config",a),!0}case"meta_pixel":return V(`!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','${o.scriptOrigin}/en_US/fbevents.js');fbq('init','${a}');fbq('track','PageView');`),!0;case"x_pixel":return V(`!function(e,t,n,s,u,a){e.twq||(s=e.twq=function(){s.exe?s.exe.apply(s,arguments):s.queue.push(arguments)},s.version='1.1',s.queue=[],u=t.createElement(n),u.async=!0,u.src='${o.scriptOrigin}/uwt.js',a=t.getElementsByTagName(n)[0],a.parentNode.insertBefore(u,a))}(window,document,'script');twq('config','${a}');`),!0;case"linkedin":return V(`window._linkedin_partner_id='${a}';window._linkedin_data_partner_ids=window._linkedin_data_partner_ids||[];window._linkedin_data_partner_ids.push('${a}');window.lintrk=window.lintrk||function(a,b){(window.lintrk.q=window.lintrk.q||[]).push([a,b])};window.lintrk.q=window.lintrk.q||[];`),G(`${o.scriptOrigin}/li.lms-analytics/insight.min.js`),!0;case"tiktok":return V(`!function(w,d,t){w.TiktokAnalyticsObject=t;var ttq=w[t]=w[t]||[];ttq.methods=['page','track','identify','instances','debug','on','off','once','ready','alias','group','enableCookie','disableCookie'];ttq.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var i=0;i<ttq.methods.length;i++)ttq.setAndDefer(ttq,ttq.methods[i]);ttq.load=function(e,n){var r='${o.scriptOrigin}/i18n/pixel/events.js';ttq._i=ttq._i||{};ttq._i[e]=[];ttq._i[e]._u=r;ttq._t=ttq._t||{};ttq._t[e]=+new Date;ttq._o=ttq._o||{};ttq._o[e]=n||{};var o=d.createElement('script');o.type='text/javascript';o.async=!0;o.src=r+'?sdkid='+e+'&lib='+t;var a=d.getElementsByTagName('script')[0];a.parentNode.insertBefore(o,a)};ttq.load('${a}');ttq.page()}(window,document,'ttq');`),!0;case"reddit":return V(`!function(w,d){if(!w.rdt){var p=w.rdt=function(){p.sendEvent?p.sendEvent.apply(p,arguments):p.callQueue.push(arguments)};p.callQueue=[];var t=d.createElement('script');t.src='${o.scriptOrigin}/ads/pixel.js';t.async=!0;var s=d.getElementsByTagName('script')[0];s.parentNode.insertBefore(t,s)}}(window,document);rdt('init','${a}');rdt('track','PageVisit');`),!0;case"bing_uet":return V(`(function(w,d,t,r,u){w[u]=w[u]||[];w[u].push({ti:'${a}',enableAutoSpaTracking:false});var o=d.createElement(t);o.src='${o.scriptOrigin}/bat.js';o.async=1;var i=d.getElementsByTagName(t)[0];i.parentNode.insertBefore(o,i)})(window,document,'script',0,'uetq');`),!0;case"clarity":return V(`(function(c,l,a,r,i,t,y){c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};t=l.createElement(r);t.async=1;t.src='${o.scriptOrigin}/tag/'+i;y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y)})(window,document,'clarity','script','${a}');`),!0;case"hotjar":return V(`(function(h,o,t,j,a,r){h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};h._hjSettings={hjid:${a},hjsv:6};a=o.getElementsByTagName('head')[0];r=o.createElement('script');r.async=1;r.src='${o.scriptOrigin}/hotjar-'+h._hjSettings.hjid+'.js?sv='+h._hjSettings.hjsv;a.appendChild(r)})(window,document);`),!0;case"posthog":{const t=o.hosts,n=t?.includes(e.host??"")?e.host:t?.[0]??"us.i.posthog.com";return V(`!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split('.');2==o.length&&(t=t[o[0]],e=o[1]);t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement('script')).type='text/javascript',p.async=!0,p.src='${o.scriptOrigin}/static/array.js',(r=t.getElementsByTagName('script')[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a='posthog',u.people=u.people||[],u.toString=function(t){var e='posthog';return'posthog'!==a&&(e+='.'+a),t||(e+=' (stub)'),e},u.people.toString=function(){return u.toString(1)+'.people (stub)'},o='init capture register register_once identify alias people.set people.set_once set_config get_distinct_id getFeatureFlag isFeatureEnabled onFeatureFlags reloadFeatureFlags group reset'.split(' '),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);posthog.init('${a}',{api_host:'https://${n}'});`),!0}case"plausible":return V("window.plausible=window.plausible||function(){(window.plausible.q=window.plausible.q||[]).push(arguments)};"),G(`${o.scriptOrigin}/js/script.js`,{"data-domain":a,defer:"true"}),!0;case"ahrefs":return G(`${o.scriptOrigin}/analytics.js`,{"data-key":a}),r.__ahrefs_loaded=!0,!0;default:return!1}}(e,t,n);return r&&"external"!==e.provider&&e.providerId&&F.add(`${e.provider}:${e.providerId}`),r}const W=Symbol.for("@buildbase/sdk.tracking.context"),Q=globalThis,X=Q[W]??(Q[W]=t.createContext(null)),Y={consent:{manifest:[],state:null,set:()=>{}},track:()=>{},setUser:()=>{},setProperties:()=>{},getProperties:()=>({}),completeCheckout:async()=>{},installed:{},ready:!0,attribution:{}};function ee(){return t.useContext(X)??Y}const te=({serverUrl:n,orgId:r,clientId:o,enabled:a=!0,consent:s="auto",autoPageview:c=!0,events:d,onEvent:l,properties:g,enrich:f,identity:m,debug:h=!1,children:y})=>{const w=t.useRef(m);w.current=m;const[v,_]=t.useState(null),[I,C]=t.useState(!1),[q,E]=t.useState(!1),O="granted"===s?{analytics:!0,marketing:!0}:"denied"===s?{analytics:!1,marketing:!1}:null,[U,R]=t.useState(O),N=t.useRef(null),B=t.useRef(l);B.current=l;const G=t.useRef(f);G.current=f;const V=t.useRef({});V.current=g??{};const F=t.useRef({}),H=t.useCallback(()=>({...V.current,...F.current}),[]),J=t.useCallback(e=>{const t={...F.current,...e};for(const[e,n]of Object.entries(t))void 0===n&&delete t[e];F.current=t},[]),[W,Q]=t.useState({}),Y=t.useRef({}),[ee,te]=t.useState(0),ne=v?.dataLayerName??"dataLayer",re=t.useCallback((...e)=>{h&&console.info("[buildbase:tracking]",...e)},[h]);t.useEffect(()=>{return e=()=>{0!==Object.keys(Y.current).length&&window.dispatchEvent("function"==typeof PageTransitionEvent?new PageTransitionEvent("pagehide",{persisted:!1}):new Event("pagehide"))},i.add(e),()=>{i.delete(e)};var e},[]),t.useEffect(()=>{if(!(a&&n&&r&&o))return void C(!0);let e=!1;const t=`${n.replace(/\/$/,"")}/api/v1/public/${r}/tracking?clientId=${encodeURIComponent(o)}`;return fetch(t).then(e=>e.ok?e.json():null).then(t=>{if(e||!t)return;const n=t.data??t;n&&Array.isArray(n.scripts)&&_(n)}).catch(()=>{re("config fetch failed; nothing installed")}).finally(()=>{e||C(!0)}),()=>{e=!0}},[a,n,r,o,re]),t.useEffect(()=>{a&&Q(u())},[a]),t.useEffect(()=>{a&&v?.enabled&&(z(ne),function(e,t){const n=$();if(!n)return;Array.isArray(n[e])||(n[e]=[]),"function"!=typeof n.gtag&&(n.gtag=function(){n[e].push(arguments)});const r="granted"===t?"granted":"denied";n.gtag("consent","default",{ad_storage:r,ad_user_data:r,ad_personalization:r,analytics_storage:r,wait_for_update:500})}(ne,s),N.current&&j(N.current))},[a,v?.enabled,ne,s]);const ie=t.useMemo(()=>v?.enabled?v.scripts.filter(e=>{const t=P(e.provider)&&A[e.provider].supportsConsentMode;return function(e,t,n,r){return"denied"!==r&&("granted"===r||(n?"marketing"===e?n.marketing:n.analytics:t&&"analytics"===e))}(e.consentCategory,t,U,s)}):[],[v,U,s]),[oe,ae]=t.useState(()=>"undefined"==typeof window||!p(window.location.search));t.useEffect(()=>{if(oe)return;const e=setInterval(()=>{p(window.location.search)||ae(!0)},50),t=setTimeout(()=>ae(!0),5e3);return()=>{clearInterval(e),clearTimeout(t)}},[oe]),t.useEffect(()=>{if(!oe)return;if(!a||!v?.enabled)return void(I&&E(!0));let e=0;for(const t of ie)if(!Y.current[t.key]){if("external"===t.provider){if(!T({src:t.src,dataAttributes:t.dataAttributes})){re("rejected external script",t.key);continue}}else{if(!P(t.provider)){re("rejected unknown provider",t.provider);continue}if(!S(t.provider,t.providerId)){re("rejected id for",t.provider);continue}if(Z(t.provider,t.providerId??"")){re(`${t.provider} ${t.providerId} is already on the page; skipping. Configure each tag in exactly one place.`);continue}}K(t,ne,w.current)&&(Y.current[t.key]=t.providerId??t.src??"",e+=1,re("installed",t.key))}e&&te(e=>e+1);const t=window;t.__buildbase=t.__buildbase??{},t.__buildbase.tracking={installed:{...Y.current},dataLayerName:ne,clientId:o};const n=Object.keys(Y.current).length>0,r=null!==U||0===v.scripts.length;(n||r)&&E(!0)},[a,v,ie,I,U,ne,re,oe,o]),t.useEffect(()=>{if(!a||!c||!v?.enabled)return;if("undefined"==typeof window)return;if(!oe)return;let e=null;const t=()=>{e&&clearTimeout(e),e=setTimeout(()=>function(e,t){const n=D();if(!n)return;const r=n[t];Array.isArray(r)&&r.push({event:"page_view",page_path:n.location.pathname,page_location:n.location.href,page_title:n.document.title});for(const t of e)switch(t.provider){case"ga4":n.gtag?.("event","page_view",{send_to:t.providerId,page_path:n.location.pathname,page_location:n.location.href,page_title:n.document.title});break;case"meta_pixel":n.fbq?.("track","PageView");break;case"tiktok":{const e=n.ttq;e?.page?.();break}case"reddit":n.rdt?.("track","PageVisit")}}(ie,ne),50)},n=window.history,r=n.pushState,i=n.replaceState;return n.pushState=function(...e){const n=r.apply(this,e);return t(),n},n.replaceState=function(...e){const n=i.apply(this,e);return t(),n},window.addEventListener("popstate",t),()=>{n.pushState=r,n.replaceState=i,window.removeEventListener("popstate",t),e&&clearTimeout(e)}},[a,c,v?.enabled,ie,ne,oe]),t.useEffect(()=>{if(!a)return;const e=function(e,t){const n=e?.mode??"auto",r=e?.overrides??{};if(("manual"===n||Object.values(r).some(e=>"manual"===e))&&!t)return'[buildbase:tracking] events are set to "manual" but no onEvent handler was provided, so those events would never fire anywhere. Pass onEvent, or use mode "auto".';for(const e of Object.keys(r))if(!M(e))return`[buildbase:tracking] unknown event "${e}" in events.overrides. Overrides only apply to the events the SDK fires itself.`;return null}(d,!!l);if(e)throw new Error(e)},[a,d,l]);const se=t.useCallback((e,t={},n)=>{if(!a)return;const r=n?.eventId||function(){const e=globalThis.crypto;return e?.randomUUID?e.randomUUID():`${Date.now().toString(16)}-${Math.random().toString(16).slice(2,10)}`}(),i=d?.mode??"auto",o=(M(e)?d?.overrides?.[e]:void 0)??i,s={...V.current,...F.current,...W,...t},c=G.current?.({name:e,params:s})??{},l={...s,...c},u=B.current?.({name:e,params:l,eventId:r,handledBy:o});"manual"!==o&&!0!==u?(!function(e,t,n,r,i){const o=D();if(!o)return;const a=o[i];Array.isArray(a)&&a.push({event:e,...t,event_id:n});const s=M(e)?L[e]:{ga4:e,meta:null,tiktok:null,reddit:null};for(const i of r){const r=i.provider,a=A[r];if(a){if(a.needsConversionIds){const a=i.conversionIds?.[e];if(!a)continue;"google_ads"===r?o.gtag?.("event","conversion",{send_to:`${i.providerId}/${a}`,transaction_id:n,...t}):"x_pixel"===r?o.twq?.("event",a,{...t,conversion_id:n}):"linkedin"===r&&o.lintrk?.("track",{conversion_id:a});continue}switch(r){case"ga4":s.ga4&&o.gtag?.("event",s.ga4,{...t,send_to:i.providerId,event_id:n});break;case"meta_pixel":s.meta&&o.fbq?.("track",s.meta,t,{eventID:n});break;case"tiktok":if(s.tiktok){const e=o.ttq;e?.track?.(s.tiktok,{...t,event_id:n})}break;case"reddit":s.reddit&&o.rdt?.("track",s.reddit,{...t,conversionId:n});break;case"bing_uet":{const r=o.uetq;r?.push?.("event",s.ga4??e,{...t,event_id:n});break}case"clarity":o.clarity?.("event",e);break;case"hotjar":{const t=o.hj;t?.("event",e);break}case"posthog":{const r=o.posthog;r?.capture?.(e,{...t,event_id:n});break}case"plausible":o.plausible?.(e,{props:t})}}}}(e,l,r,ie,ne),re("event fired:",e,r)):re("event handled by app:",e)},[a,d,ie,ne,W,re]),ce=t.useCallback(async(e,t={})=>{const i=function(e){return{name:"trial_started"===e.kind?"trial_started":"purchase",params:{...e.workspaceId?{workspace_id:e.workspaceId}:{},...e.planVersionId?{plan_version_id:e.planVersionId}:{},...e.creditPackageId?{credit_package_id:e.creditPackageId}:{},...e.billingInterval?{billing_interval:e.billingInterval}:{},...e.currency?{currency:e.currency.toUpperCase()}:{},..."number"==typeof e.value?{value:e.value}:{},...e.sessionId?{transaction_id:e.sessionId}:{}}}}(e);let o=i.params;if(e.sessionId&&n&&r){const t=await async function(e,t){try{const n=e.serverUrl.replace(/\/$/,""),r=await fetch(`${n}/api/v1/public/${encodeURIComponent(e.orgId)}/checkout/${encodeURIComponent(t)}`,{credentials:"omit",..."undefined"!=typeof AbortSignal&&AbortSignal.timeout?{signal:AbortSignal.timeout(2e3)}:{}});if(!r.ok)return null;const i=await r.json(),o=i?.data??i;return"number"!=typeof o?.amount?null:{value:x(o.amount,o.currency),currency:"string"==typeof o.currency?o.currency:void 0,...Array.isArray(o.items)&&o.items.length?{items:o.items}:{}}}catch{return null}}({serverUrl:n,orgId:r},e.sessionId);t&&"number"==typeof t.value&&(o={...o,value:t.value,...t.currency?{currency:t.currency.toUpperCase()}:{},...t.items?.length?{items:t.items}:{}})}if(se(i.name,{...o,...t},{eventId:e.eventId}),"purchase"===i.name&&e.sessionId&&n&&r){const t=(v?.scripts??[]).find(e=>"ga4"===e.provider&&e.providerId);t&&Z("ga4",t.providerId??"")&&function(e,t,n){try{const r=e.serverUrl.replace(/\/$/,"");fetch(`${r}/api/v1/public/${encodeURIComponent(e.orgId)}/checkout/${encodeURIComponent(t)}/reported`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:n}),keepalive:!0,credentials:"omit"}).catch(()=>{})}catch{}}({serverUrl:n,orgId:r},e.sessionId,"ga4")}},[n,r,se,v]),[de]=t.useState(()=>"undefined"==typeof window?"":window.location.search);t.useEffect(()=>{if(!a||!q)return;if("undefined"==typeof window)return;const e=k(window.location.search);if(e)return void ce(e);const t=b(de);t&&se("checkout_abandoned",{...t.workspaceId?{workspace_id:t.workspaceId}:{},...t.planVersionId?{plan_version_id:t.planVersionId}:{},...t.creditPackageId?{credit_package_id:t.creditPackageId}:{},...t.billingInterval?{billing_interval:t.billingInterval}:{},...t.currency?{currency:t.currency.toUpperCase()}:{},..."number"==typeof t.value?{value:t.value}:{},seconds_at_checkout:Math.max(0,Math.round((Date.now()-t.startedAt)/1e3))})},[a,q,ce,de,se]);const le=t.useCallback(e=>{N.current=e,R(e),j(e)},[]),ue=t.useCallback((e,t)=>function(e,t,n){const r=D();if(!r)return;const i=!!n&&Object.keys(n).length>0;for(const o of t)switch(o.provider){case"ga4":case"google_ads":r.gtag?.("set",{user_id:e}),i&&r.gtag?.("set",{user_properties:n});break;case"meta_pixel":o.providerId&&r.fbq?.("init",o.providerId,{external_id:e});break;case"posthog":r.posthog?.identify?.(e,i?n:void 0);break;case"clarity":if(r.clarity?.("identify",e),i)for(const[e,t]of Object.entries(n))r.clarity?.("set",e,String(t));break;case"hotjar":r.hj?.("identify",e,{});break;case"tiktok":{const t=r.ttq;t?.identify?.({external_id:e});break}}}(e,ie,t),[ie]),pe=t.useMemo(()=>({consent:{manifest:v?.consent?.manifest??[],state:U,set:le},track:se,setUser:ue,setProperties:J,getProperties:H,completeCheckout:ce,installed:{...Y.current},ready:q,attribution:W}),[v,U,le,se,ue,J,H,ce,q,ee,W]);return e.jsx(X.Provider,{value:pe,children:y})};te.displayName="BuildBaseTracking";exports.ATTRIBUTION_PARAMS=a,exports.BuildBaseTracking=te,exports.EVENT_MAPPINGS=L,exports.FUNNEL_EVENTS={sign_in_started:"The sign-in / sign-up button was pressed.",pricing_viewed:"A <PricingPage> finished loading its plans.",pricing_plan_selected:"A plan was chosen on a <PricingPage>.",workspace_switcher_opened:"The workspace switcher was opened.",workspace_settings_opened:"The workspace settings modal was opened.",workspace_settings_section_viewed:"A different section of the settings modal was opened.",plan_picker_opened:"The plan picker was shown.",billing_interval_changed:"Monthly / quarterly / yearly was switched in the plan picker.",plan_selected:"A plan was chosen in the plan picker.",plan_picker_dismissed:"The plan picker was closed without choosing a plan.",checkout_abandoned:"The customer came back from Stripe without paying.",billing_portal_opened:"Stripe’s billing portal was opened.",subscription_cancel_started:"The cancel-subscription confirmation was opened.",subscription_cancelled:"A subscription was cancelled.",subscription_resumed:"A cancelled subscription was resumed.",feature_gate_shown:'A feature gate rendered its "not on your plan" side.',quota_limit_reached:"A quota gate rendered because a quota is used up.",quota_threshold_reached:"A usage-threshold gate rendered.",plan_gate_shown:'A plan gate rendered its "needs another plan" side.',subscription_notice_shown:"A billing notice (trial ending, payment failed…) was shown.",sdk_error:"An SDK operation failed (component, action and code only)."},exports.TAG_PROVIDERS=A,exports.TAG_PROVIDER_IDS=q,exports.TAG_SCRIPT_ORIGINS=U,exports.captureAttribution=u,exports.getAttribution=function(){const e=c();return e?l(e.document):{}},exports.isCanonicalEvent=M,exports.isTagProviderId=P,exports.isValidProviderId=S,exports.useCheckoutCompleted=function(e={}){const{completeCheckout:n,ready:r}=ee(),i=t.useRef(e);i.current=e;const o=t.useRef(!1);t.useEffect(()=>{if(!r)return;if(o.current)return;const e=k(window.location.search)??v();e&&(o.current=!0,n(e,i.current))},[r,n])},exports.useTracking=ee;
|
package/dist/tracking/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as e}from"react/jsx-runtime";import{useRef as t,useState as n,useCallback as r,useEffect as i,useMemo as o,useContext as a,createContext as s}from"react";const c="bb_attr",d=["gclid","gbraid","wbraid","dclid","fbclid","msclkid","li_fat_id","twclid","ttclid","rdt_cid","epik","irclickid","utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_id"],l=/^[\w.~-]{1,200}$/;function u(){return"undefined"==typeof window?null:window}function p(e,t){if(!e||!e.includes("."))return"";if(/^\d{1,3}(\.\d{1,3}){3}$/.test(e))return"";const n=t??u()?.document;if(!n)return"";const r=e.split(".");for(let e=r.length-2;e>=0;e--){const t="."+r.slice(e).join("."),i=`__bb_probe_${Date.now()}`;n.cookie=`${i}=1; domain=${t}; path=/; SameSite=Lax`;const o=n.cookie.includes(`${i}=1`);if(n.cookie=`${i}=; domain=${t}; path=/; max-age=0; SameSite=Lax`,o)return t}return""}function g(e){const t=e.cookie.split("; ").find(e=>e.startsWith(`${c}=`));if(!t)return{};try{const e=JSON.parse(decodeURIComponent(t.slice(8)));return"object"==typeof e&&e?e:{}}catch{return{}}}function f(){const e=u();if(!e)return{};const t=e.document,n=g(t),r={...function(e){const t=new URLSearchParams(e),n={};for(const e of d){const r=t.get(e);r&&(r.length>200||l.test(r)&&(n[e]=r))}return n}(e.location.search),...n};if(0===Object.keys(r).length)return{};return Object.keys(r).some(e=>void 0===n[e])&&function(e,t,n){const r=encodeURIComponent(JSON.stringify(t));e.cookie=`${c}=${r}; path=/; max-age=7776000; SameSite=Lax`+(n?`; domain=${n}`:"")}(t,r,p(e.location.hostname,t)),r}function m(){const e=u();return e?g(e.document):{}}function h(e){try{const t=new URLSearchParams(e);return t.has("code")&&t.has("state")}catch{return!1}}const y="bb_pending_checkout";function w(){try{return"undefined"==typeof window?null:window.sessionStorage}catch{return null}}const v="bb_co";function _(){try{return"undefined"==typeof window?null:window.document??null}catch{return null}}function k(){const e=_();if(e)try{const t=p(window.location?.hostname??"",e);e.cookie=`${v}=; path=/; max-age=0; SameSite=Lax`+(t?`; domain=${t}`:"")}catch{}}function b(e,t){if(!e)return null;try{const n=JSON.parse(e);return n&&"string"==typeof n.eventId&&n.eventId?"number"!=typeof n.startedAt||t-n.startedAt>216e5?null:n:null}catch{return null}}function I(e=Date.now()){const t=w();if(!t)return null;let n=null;try{n=t.getItem(y),t.removeItem(y)}catch{return null}const r=b(n,e);return r&&k(),r}function C(e){try{return b(w()?.getItem(y)??null,e)}catch{return null}}function $(e,t=Date.now()){let n=null;try{n=new URLSearchParams(e).get("session_id")}catch{return null}if(!n)return null;const r=C(t);if(r?.sessionId===n)return I(t);const i=function(e){const t=_();if(!t||"string"!=typeof t.cookie)return null;const n=t.cookie.split("; ").find(e=>e.startsWith(`${v}=`));return n?b(decodeURIComponent(n.slice(6)),e):null}(t);return i?.sessionId!==n?null:(k(),i)}function j(e,t=Date.now()){return function(e){let t=null;try{t=new URLSearchParams(e).get("bb")}catch{return!1}if(!t)return!1;const n={};for(const e of t.split(",")){const t=e.indexOf(":");if(-1!==t)try{n[decodeURIComponent(e.slice(0,t))]=decodeURIComponent(e.slice(t+1))}catch{}}return"checkout"===n.action&&"cancel"===n.status}(e)&&C(t)?I(t):null}const x=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"]),q=new Set(["bhd","jod","kwd","omr","tnd"]);function A(e,t){if("number"!=typeof e||!Number.isFinite(e))return;const n=(t??"").toLowerCase();return x.has(n)?e:e/(q.has(n)?1e3:100)}function P(){return"undefined"==typeof window?null:window}function S(e){const t=P();if(!t)return;t.gtag?.("consent","update",{ad_storage:e.marketing?"granted":"denied",ad_user_data:e.marketing?"granted":"denied",ad_personalization:e.marketing?"granted":"denied",analytics_storage:e.analytics?"granted":"denied"});const n=t.fbq;n?.("consent",e.marketing?"grant":"revoke")}const O={gtm:{title:"Google Tag Manager",vendor:"Google LLC",privacyUrl:"https://policies.google.com/privacy",idLabel:"Container ID",idPattern:"^GTM-[A-Z0-9]{4,10}$",idExample:"GTM-ABC1234",scriptOrigin:"https://www.googletagmanager.com",defaultConsentCategory:"analytics",supportsConsentMode:!0,needsConversionIds:!1},ga4:{title:"Google Analytics 4",vendor:"Google LLC",privacyUrl:"https://policies.google.com/privacy",idLabel:"Measurement ID",idPattern:"^G-[A-Z0-9]{8,12}$",idExample:"G-ABCD123456",scriptOrigin:"https://www.googletagmanager.com",defaultConsentCategory:"analytics",supportsConsentMode:!0,needsConversionIds:!1},google_ads:{title:"Google Ads",vendor:"Google LLC",privacyUrl:"https://policies.google.com/privacy",idLabel:"Conversion ID",idPattern:"^AW-[0-9]{9,12}$",idExample:"AW-123456789",scriptOrigin:"https://www.googletagmanager.com",defaultConsentCategory:"marketing",supportsConsentMode:!0,needsConversionIds:!0},meta_pixel:{title:"Meta Pixel",vendor:"Meta Platforms Ireland Limited",privacyUrl:"https://www.facebook.com/privacy/policy",idLabel:"Pixel ID",idPattern:"^[0-9]{15,16}$",idExample:"123456789012345",scriptOrigin:"https://connect.facebook.net",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},x_pixel:{title:"X (Twitter) Pixel",vendor:"X Corp.",privacyUrl:"https://x.com/en/privacy",idLabel:"Pixel ID",idPattern:"^o[a-z0-9]{4,6}$",idExample:"o1a2b3",scriptOrigin:"https://static.ads-twitter.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!0,multiInstance:!0},linkedin:{title:"LinkedIn Insight Tag",vendor:"LinkedIn Ireland Unlimited Company",privacyUrl:"https://www.linkedin.com/legal/privacy-policy",idLabel:"Partner ID",idPattern:"^[0-9]{6,9}$",idExample:"1234567",scriptOrigin:"https://snap.licdn.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!0,multiInstance:!0},tiktok:{title:"TikTok Pixel",vendor:"TikTok Information Technologies UK Limited",privacyUrl:"https://www.tiktok.com/legal/privacy-policy",idLabel:"Pixel ID",idPattern:"^[A-Z0-9]{20}$",idExample:"C4A1B2C3D4E5F6G7H8I9",scriptOrigin:"https://analytics.tiktok.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},reddit:{title:"Reddit Pixel",vendor:"Reddit, Inc.",privacyUrl:"https://www.reddit.com/policies/privacy-policy",idLabel:"Advertiser ID",idPattern:"^t2_[a-z0-9]{4,12}$",idExample:"t2_abc123",scriptOrigin:"https://www.redditstatic.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},bing_uet:{title:"Microsoft Advertising (UET)",vendor:"Microsoft Corporation",privacyUrl:"https://privacy.microsoft.com/en-us/privacystatement",idLabel:"Tag ID",idPattern:"^[0-9]{7,9}$",idExample:"12345678",scriptOrigin:"https://bat.bing.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},clarity:{title:"Microsoft Clarity",vendor:"Microsoft Corporation",privacyUrl:"https://privacy.microsoft.com/en-us/privacystatement",idLabel:"Project ID",idPattern:"^[a-z0-9]{10}$",idExample:"ab12cd34ef",scriptOrigin:"https://www.clarity.ms",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1},hotjar:{title:"Hotjar",vendor:"Hotjar Limited",privacyUrl:"https://www.hotjar.com/legal/policies/privacy/",idLabel:"Site ID",idPattern:"^[0-9]{6,9}$",idExample:"1234567",scriptOrigin:"https://static.hotjar.com",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1},posthog:{title:"PostHog",vendor:"PostHog, Inc.",privacyUrl:"https://posthog.com/privacy",idLabel:"Project API key",idPattern:"^phc_[A-Za-z0-9]{32,48}$",idExample:"phc_abcdefghijklmnopqrstuvwxyz012345",scriptOrigin:"https://us-assets.i.posthog.com",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1,hosts:["us.i.posthog.com","eu.i.posthog.com"]},plausible:{title:"Plausible Analytics",vendor:"Plausible Insights OÜ",privacyUrl:"https://plausible.io/privacy",idLabel:"Domain",idPattern:"^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$",idExample:"example.com",scriptOrigin:"https://plausible.io",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1},ahrefs:{title:"Ahrefs Analytics",vendor:"Ahrefs Pte. Ltd.",privacyUrl:"https://ahrefs.com/privacy",idLabel:"Analytics key",idPattern:"^[A-Za-z0-9+/=]{20,64}$",idExample:"AbCdEfGhIjKlMnOpQrStUv==",scriptOrigin:"https://analytics.ahrefs.com",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1}},U=Object.keys(O);function L(e){return"string"==typeof e&&Object.prototype.hasOwnProperty.call(O,e)}function E(e,t){return!!L(e)&&("string"==typeof t&&0!==t.length&&new RegExp(O[e].idPattern).test(t))}const T=/^[a-z][a-z0-9-]{0,40}$/,M=/^[\w.:/@+=-]{1,200}$/;function D(e){return function(e){if("string"!=typeof e)return!1;if(0===e.length||e.length>300)return!1;let t;try{t=new URL(e)}catch{return!1}return!("https:"!==t.protocol||!t.hostname||!t.hostname.includes(".")||e.includes("?")||e.includes("#")||t.username||t.password)}(e.src)&&function(e){if(null==e)return!0;if("object"!=typeof e||Array.isArray(e))return!1;const t=Object.entries(e);return!(t.length>12)&&t.every(([e,t])=>T.test(e)&&"string"==typeof t&&M.test(t))}(e.dataAttributes)}const N=Array.from(new Set(U.map(e=>O[e].scriptOrigin))).sort(),B={sign_up:{ga4:"sign_up",meta:"CompleteRegistration",tiktok:"CompleteRegistration",reddit:"SignUp"},login:{ga4:"login",meta:null,tiktok:null,reddit:null},trial_started:{ga4:"begin_checkout",meta:"StartTrial",tiktok:"StartTrial",reddit:"Lead"},checkout_started:{ga4:"begin_checkout",meta:"InitiateCheckout",tiktok:"InitiateCheckout",reddit:"AddToCart"},purchase:{ga4:"purchase",meta:"Purchase",tiktok:"CompletePayment",reddit:"Purchase"},subscription_created:{ga4:"purchase",meta:"Subscribe",tiktok:"Subscribe",reddit:"Purchase"},subscription_upgraded:{ga4:"subscription_upgraded",meta:null,tiktok:null,reddit:null},lead:{ga4:"generate_lead",meta:"Lead",tiktok:"SubmitForm",reddit:"Lead"},workspace_created:{ga4:"workspace_created",meta:null,tiktok:null,reddit:null}},R=Object.keys(B);function z(e){return R.includes(e)}function G(){return"undefined"==typeof window?null:window}const V={gtm:"dataLayer",ga4:"gtag",google_ads:"gtag",meta_pixel:"fbq",x_pixel:"twq",linkedin:"lintrk",tiktok:"ttq",reddit:"rdt",bing_uet:"uetq",clarity:"clarity",hotjar:"hj",posthog:"posthog",plausible:"plausible",ahrefs:"__ahrefs_loaded"};function F(){return"undefined"==typeof window?null:window}function H(e,t={}){const n=F();if(!n)return null;const r=n.document.createElement("script");r.async=!0,r.src=e;for(const[e,n]of Object.entries(t))r.setAttribute(e,n);return n.document.head.appendChild(r),r}function Z(e){const t=F();if(!t)return;const n=t.document.createElement("script");n.text=e,t.document.head.appendChild(n)}function J(e){const t=F();t&&(Array.isArray(t[e])||(t[e]=[]),"function"!=typeof t.gtag&&(t.gtag=function(){t[e].push(arguments)}))}const K=new Set;function W(e){for(const t of K)if(t.slice(0,t.indexOf(":"))===e)return!0;return!1}function Q(e,t){const n=F();if(!n)return!1;if("gtm"===e||"ga4"===e||"google_ads"===e){const e=n.google_tag_manager;return!(!e||"object"!=typeof e)&&Object.prototype.hasOwnProperty.call(e,t)}const r=V[e];if(!r)return!1;if(void 0===n[r])return!1;if(K.has(`${e}:${t}`))return!0;return!O[e].multiInstance||!W(e)}const X={meta_pixel:e=>`fbq('init','${e}');fbq('track','PageView');`,x_pixel:e=>`twq('config','${e}');`,tiktok:e=>`ttq.load('${e}');ttq.page();`,reddit:e=>`rdt('init','${e}');rdt('track','PageVisit');`,bing_uet:e=>`window.uetq=window.uetq||[];window.uetq.push({ti:'${e}',enableAutoSpaTracking:false});`,linkedin:e=>`window._linkedin_data_partner_ids=window._linkedin_data_partner_ids||[];window._linkedin_data_partner_ids.push('${e}');`};function Y(e,t,n){const r=function(e,t,n){const r=F();if(!r)return!1;if("external"===e.provider){if(!e.src)return!1;const t={};for(const[n,r]of Object.entries(e.dataAttributes??{}))t[`data-${n}`]=r;return H(e.src,t),!0}const i=e.provider,o=O[i];if(!o)return!1;const a=e.providerId;if(!a)return!1;const s=X[i];if(s&&W(i))return Z(s(a)),!0;switch(i){case"gtm":{J(t),r[t].push({"gtm.start":Date.now(),event:"gtm.js"});const e="dataLayer"===t?"":`&l=${t}`;return H(`${o.scriptOrigin}/gtm.js?id=${a}${e}`),!0}case"ga4":case"google_ads":{J(t),H(`${o.scriptOrigin}/gtag/js?id=${a}`);const e=r.gtag;e("js",new Date);const s="ga4"===i&&n?.gaClientId?{client_id:n.gaClientId}:void 0;return s?e("config",a,s):e("config",a),!0}case"meta_pixel":return Z(`!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','${o.scriptOrigin}/en_US/fbevents.js');fbq('init','${a}');fbq('track','PageView');`),!0;case"x_pixel":return Z(`!function(e,t,n,s,u,a){e.twq||(s=e.twq=function(){s.exe?s.exe.apply(s,arguments):s.queue.push(arguments)},s.version='1.1',s.queue=[],u=t.createElement(n),u.async=!0,u.src='${o.scriptOrigin}/uwt.js',a=t.getElementsByTagName(n)[0],a.parentNode.insertBefore(u,a))}(window,document,'script');twq('config','${a}');`),!0;case"linkedin":return Z(`window._linkedin_partner_id='${a}';window._linkedin_data_partner_ids=window._linkedin_data_partner_ids||[];window._linkedin_data_partner_ids.push('${a}');window.lintrk=window.lintrk||function(a,b){(window.lintrk.q=window.lintrk.q||[]).push([a,b])};window.lintrk.q=window.lintrk.q||[];`),H(`${o.scriptOrigin}/li.lms-analytics/insight.min.js`),!0;case"tiktok":return Z(`!function(w,d,t){w.TiktokAnalyticsObject=t;var ttq=w[t]=w[t]||[];ttq.methods=['page','track','identify','instances','debug','on','off','once','ready','alias','group','enableCookie','disableCookie'];ttq.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var i=0;i<ttq.methods.length;i++)ttq.setAndDefer(ttq,ttq.methods[i]);ttq.load=function(e,n){var r='${o.scriptOrigin}/i18n/pixel/events.js';ttq._i=ttq._i||{};ttq._i[e]=[];ttq._i[e]._u=r;ttq._t=ttq._t||{};ttq._t[e]=+new Date;ttq._o=ttq._o||{};ttq._o[e]=n||{};var o=d.createElement('script');o.type='text/javascript';o.async=!0;o.src=r+'?sdkid='+e+'&lib='+t;var a=d.getElementsByTagName('script')[0];a.parentNode.insertBefore(o,a)};ttq.load('${a}');ttq.page()}(window,document,'ttq');`),!0;case"reddit":return Z(`!function(w,d){if(!w.rdt){var p=w.rdt=function(){p.sendEvent?p.sendEvent.apply(p,arguments):p.callQueue.push(arguments)};p.callQueue=[];var t=d.createElement('script');t.src='${o.scriptOrigin}/ads/pixel.js';t.async=!0;var s=d.getElementsByTagName('script')[0];s.parentNode.insertBefore(t,s)}}(window,document);rdt('init','${a}');rdt('track','PageVisit');`),!0;case"bing_uet":return Z(`(function(w,d,t,r,u){w[u]=w[u]||[];w[u].push({ti:'${a}',enableAutoSpaTracking:false});var o=d.createElement(t);o.src='${o.scriptOrigin}/bat.js';o.async=1;var i=d.getElementsByTagName(t)[0];i.parentNode.insertBefore(o,i)})(window,document,'script',0,'uetq');`),!0;case"clarity":return Z(`(function(c,l,a,r,i,t,y){c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};t=l.createElement(r);t.async=1;t.src='${o.scriptOrigin}/tag/'+i;y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y)})(window,document,'clarity','script','${a}');`),!0;case"hotjar":return Z(`(function(h,o,t,j,a,r){h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};h._hjSettings={hjid:${a},hjsv:6};a=o.getElementsByTagName('head')[0];r=o.createElement('script');r.async=1;r.src='${o.scriptOrigin}/hotjar-'+h._hjSettings.hjid+'.js?sv='+h._hjSettings.hjsv;a.appendChild(r)})(window,document);`),!0;case"posthog":{const t=o.hosts,n=t?.includes(e.host??"")?e.host:t?.[0]??"us.i.posthog.com";return Z(`!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split('.');2==o.length&&(t=t[o[0]],e=o[1]);t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement('script')).type='text/javascript',p.async=!0,p.src='${o.scriptOrigin}/static/array.js',(r=t.getElementsByTagName('script')[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a='posthog',u.people=u.people||[],u.toString=function(t){var e='posthog';return'posthog'!==a&&(e+='.'+a),t||(e+=' (stub)'),e},u.people.toString=function(){return u.toString(1)+'.people (stub)'},o='init capture register register_once identify alias people.set people.set_once set_config get_distinct_id getFeatureFlag isFeatureEnabled onFeatureFlags reloadFeatureFlags group reset'.split(' '),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);posthog.init('${a}',{api_host:'https://${n}'});`),!0}case"plausible":return Z("window.plausible=window.plausible||function(){(window.plausible.q=window.plausible.q||[]).push(arguments)};"),H(`${o.scriptOrigin}/js/script.js`,{"data-domain":a,defer:"true"}),!0;case"ahrefs":return H(`${o.scriptOrigin}/analytics.js`,{"data-key":a}),r.__ahrefs_loaded=!0,!0;default:return!1}}(e,t,n);return r&&"external"!==e.provider&&e.providerId&&K.add(`${e.provider}:${e.providerId}`),r}const ee=Symbol.for("@buildbase/sdk.tracking.context"),te=globalThis,ne=te[ee]??(te[ee]=s(null)),re={consent:{manifest:[],state:null,set:()=>{}},track:()=>{},setUser:()=>{},setProperties:()=>{},getProperties:()=>({}),completeCheckout:async()=>{},installed:{},ready:!0,attribution:{}};function ie(){return a(ne)??re}const oe=({serverUrl:a,orgId:s,clientId:c,enabled:d=!0,consent:l="auto",autoPageview:u=!0,events:p,onEvent:g,properties:m,enrich:y,identity:w,debug:v=!1,children:_})=>{const k=t(w);k.current=w;const[b,I]=n(null),[C,x]=n(!1),[q,U]=n(!1),T="granted"===l?{analytics:!0,marketing:!0}:"denied"===l?{analytics:!1,marketing:!1}:null,[M,N]=n(T),R=t(null),V=t(g);V.current=g;const F=t(y);F.current=y;const H=t({});H.current=m??{};const Z=t({}),K=r(()=>({...H.current,...Z.current}),[]),W=r(e=>{const t={...Z.current,...e};for(const[e,n]of Object.entries(t))void 0===n&&delete t[e];Z.current=t},[]),[X,ee]=n({}),te=t({}),[re,ie]=n(0),oe=b?.dataLayerName??"dataLayer",ae=r((...e)=>{v&&console.info("[buildbase:tracking]",...e)},[v]);i(()=>{if(!(d&&a&&s&&c))return void x(!0);let e=!1;const t=`${a.replace(/\/$/,"")}/api/v1/public/${s}/tracking?clientId=${encodeURIComponent(c)}`;return fetch(t).then(e=>e.ok?e.json():null).then(t=>{if(e||!t)return;const n=t.data??t;n&&Array.isArray(n.scripts)&&I(n)}).catch(()=>{ae("config fetch failed; nothing installed")}).finally(()=>{e||x(!0)}),()=>{e=!0}},[d,a,s,c,ae]),i(()=>{d&&ee(f())},[d]),i(()=>{d&&b?.enabled&&(J(oe),function(e,t){const n=P();if(!n)return;Array.isArray(n[e])||(n[e]=[]),"function"!=typeof n.gtag&&(n.gtag=function(){n[e].push(arguments)});const r="granted"===t?"granted":"denied";n.gtag("consent","default",{ad_storage:r,ad_user_data:r,ad_personalization:r,analytics_storage:r,wait_for_update:500})}(oe,l),R.current&&S(R.current))},[d,b?.enabled,oe,l]);const se=o(()=>b?.enabled?b.scripts.filter(e=>{const t=L(e.provider)&&O[e.provider].supportsConsentMode;return function(e,t,n,r){return"denied"!==r&&("granted"===r||(n?"marketing"===e?n.marketing:n.analytics:t&&"analytics"===e))}(e.consentCategory,t,M,l)}):[],[b,M,l]),[ce,de]=n(()=>"undefined"==typeof window||!h(window.location.search));i(()=>{if(ce)return;const e=setInterval(()=>{h(window.location.search)||de(!0)},50),t=setTimeout(()=>de(!0),5e3);return()=>{clearInterval(e),clearTimeout(t)}},[ce]),i(()=>{if(!ce)return;if(!d||!b?.enabled)return void(C&&U(!0));let e=0;for(const t of se)if(!te.current[t.key]){if("external"===t.provider){if(!D({src:t.src,dataAttributes:t.dataAttributes})){ae("rejected external script",t.key);continue}}else{if(!L(t.provider)){ae("rejected unknown provider",t.provider);continue}if(!E(t.provider,t.providerId)){ae("rejected id for",t.provider);continue}if(Q(t.provider,t.providerId??"")){ae(`${t.provider} ${t.providerId} is already on the page; skipping. Configure each tag in exactly one place.`);continue}}Y(t,oe,k.current)&&(te.current[t.key]=t.providerId??t.src??"",e+=1,ae("installed",t.key))}e&&ie(e=>e+1);const t=window;t.__buildbase=t.__buildbase??{},t.__buildbase.tracking={installed:{...te.current},dataLayerName:oe,clientId:c};const n=Object.keys(te.current).length>0,r=null!==M||0===b.scripts.length;(n||r)&&U(!0)},[d,b,se,C,M,oe,ae,ce,c]),i(()=>{if(!d||!u||!b?.enabled)return;if("undefined"==typeof window)return;if(!ce)return;let e=null;const t=()=>{e&&clearTimeout(e),e=setTimeout(()=>function(e,t){const n=G();if(!n)return;const r=n[t];Array.isArray(r)&&r.push({event:"page_view",page_path:n.location.pathname,page_location:n.location.href,page_title:n.document.title});for(const t of e)switch(t.provider){case"ga4":n.gtag?.("event","page_view",{send_to:t.providerId,page_path:n.location.pathname,page_location:n.location.href,page_title:n.document.title});break;case"meta_pixel":n.fbq?.("track","PageView");break;case"tiktok":{const e=n.ttq;e?.page?.();break}case"reddit":n.rdt?.("track","PageVisit")}}(se,oe),50)},n=window.history,r=n.pushState,i=n.replaceState;return n.pushState=function(...e){const n=r.apply(this,e);return t(),n},n.replaceState=function(...e){const n=i.apply(this,e);return t(),n},window.addEventListener("popstate",t),()=>{n.pushState=r,n.replaceState=i,window.removeEventListener("popstate",t),e&&clearTimeout(e)}},[d,u,b?.enabled,se,oe,ce]),i(()=>{if(!d)return;const e=function(e,t){const n=e?.mode??"auto",r=e?.overrides??{};if(("manual"===n||Object.values(r).some(e=>"manual"===e))&&!t)return'[buildbase:tracking] events are set to "manual" but no onEvent handler was provided, so those events would never fire anywhere. Pass onEvent, or use mode "auto".';for(const e of Object.keys(r))if(!z(e))return`[buildbase:tracking] unknown event "${e}" in events.overrides. Overrides only apply to the events the SDK fires itself.`;return null}(p,!!g);if(e)throw new Error(e)},[d,p,g]);const le=r((e,t={},n)=>{if(!d)return;const r=n?.eventId||function(){const e=globalThis.crypto;return e?.randomUUID?e.randomUUID():`${Date.now().toString(16)}-${Math.random().toString(16).slice(2,10)}`}(),i=p?.mode??"auto",o=(z(e)?p?.overrides?.[e]:void 0)??i,a={...H.current,...Z.current,...X,...t},s=F.current?.({name:e,params:a})??{},c={...a,...s},l=V.current?.({name:e,params:c,eventId:r,handledBy:o});"manual"!==o&&!0!==l?(!function(e,t,n,r,i){const o=G();if(!o)return;const a=o[i];Array.isArray(a)&&a.push({event:e,...t,event_id:n});const s=z(e)?B[e]:{ga4:e,meta:null,tiktok:null,reddit:null};for(const i of r){const r=i.provider,a=O[r];if(a){if(a.needsConversionIds){const a=i.conversionIds?.[e];if(!a)continue;"google_ads"===r?o.gtag?.("event","conversion",{send_to:`${i.providerId}/${a}`,transaction_id:n,...t}):"x_pixel"===r?o.twq?.("event",a,{...t,conversion_id:n}):"linkedin"===r&&o.lintrk?.("track",{conversion_id:a});continue}switch(r){case"ga4":s.ga4&&o.gtag?.("event",s.ga4,{...t,send_to:i.providerId,event_id:n});break;case"meta_pixel":s.meta&&o.fbq?.("track",s.meta,t,{eventID:n});break;case"tiktok":if(s.tiktok){const e=o.ttq;e?.track?.(s.tiktok,{...t,event_id:n})}break;case"reddit":s.reddit&&o.rdt?.("track",s.reddit,{...t,conversionId:n});break;case"bing_uet":{const r=o.uetq;r?.push?.("event",s.ga4??e,{...t,event_id:n});break}case"clarity":o.clarity?.("event",e);break;case"hotjar":{const t=o.hj;t?.("event",e);break}case"posthog":{const r=o.posthog;r?.capture?.(e,{...t,event_id:n});break}case"plausible":o.plausible?.(e,{props:t})}}}}(e,c,r,se,oe),ae("event fired:",e,r)):ae("event handled by app:",e)},[d,p,se,oe,X,ae]),ue=r(async(e,t={})=>{const n=function(e){return{name:"trial_started"===e.kind?"trial_started":"purchase",params:{...e.workspaceId?{workspace_id:e.workspaceId}:{},...e.planVersionId?{plan_version_id:e.planVersionId}:{},...e.creditPackageId?{credit_package_id:e.creditPackageId}:{},...e.billingInterval?{billing_interval:e.billingInterval}:{},...e.currency?{currency:e.currency.toUpperCase()}:{},..."number"==typeof e.value?{value:e.value}:{},...e.sessionId?{transaction_id:e.sessionId}:{}}}}(e);let r=n.params;if(e.sessionId&&a&&s){const t=await async function(e,t){try{const n=e.serverUrl.replace(/\/$/,""),r=await fetch(`${n}/api/v1/public/${encodeURIComponent(e.orgId)}/checkout/${encodeURIComponent(t)}`,{credentials:"omit",..."undefined"!=typeof AbortSignal&&AbortSignal.timeout?{signal:AbortSignal.timeout(2e3)}:{}});if(!r.ok)return null;const i=await r.json(),o=i?.data??i;return"number"!=typeof o?.amount?null:{value:A(o.amount,o.currency),currency:"string"==typeof o.currency?o.currency:void 0,...Array.isArray(o.items)&&o.items.length?{items:o.items}:{}}}catch{return null}}({serverUrl:a,orgId:s},e.sessionId);t&&"number"==typeof t.value&&(r={...r,value:t.value,...t.currency?{currency:t.currency.toUpperCase()}:{},...t.items?.length?{items:t.items}:{}})}if(le(n.name,{...r,...t},{eventId:e.eventId}),"purchase"===n.name&&e.sessionId&&a&&s){const t=(b?.scripts??[]).find(e=>"ga4"===e.provider&&e.providerId);t&&Q("ga4",t.providerId??"")&&function(e,t,n){try{const r=e.serverUrl.replace(/\/$/,"");fetch(`${r}/api/v1/public/${encodeURIComponent(e.orgId)}/checkout/${encodeURIComponent(t)}/reported`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:n}),keepalive:!0,credentials:"omit"}).catch(()=>{})}catch{}}({serverUrl:a,orgId:s},e.sessionId,"ga4")}},[a,s,le,b]),[pe]=n(()=>"undefined"==typeof window?"":window.location.search);i(()=>{if(!d||!q)return;if("undefined"==typeof window)return;const e=$(window.location.search);if(e)return void ue(e);const t=j(pe);t&&le("checkout_abandoned",{...t.workspaceId?{workspace_id:t.workspaceId}:{},...t.planVersionId?{plan_version_id:t.planVersionId}:{},...t.creditPackageId?{credit_package_id:t.creditPackageId}:{},...t.billingInterval?{billing_interval:t.billingInterval}:{},...t.currency?{currency:t.currency.toUpperCase()}:{},..."number"==typeof t.value?{value:t.value}:{},seconds_at_checkout:Math.max(0,Math.round((Date.now()-t.startedAt)/1e3))})},[d,q,ue,pe,le]);const ge=r(e=>{R.current=e,N(e),S(e)},[]),fe=r((e,t)=>function(e,t,n){const r=G();if(!r)return;const i=!!n&&Object.keys(n).length>0;for(const o of t)switch(o.provider){case"ga4":case"google_ads":r.gtag?.("set",{user_id:e}),i&&r.gtag?.("set",{user_properties:n});break;case"meta_pixel":o.providerId&&r.fbq?.("init",o.providerId,{external_id:e});break;case"posthog":r.posthog?.identify?.(e,i?n:void 0);break;case"clarity":if(r.clarity?.("identify",e),i)for(const[e,t]of Object.entries(n))r.clarity?.("set",e,String(t));break;case"hotjar":r.hj?.("identify",e,{});break;case"tiktok":{const t=r.ttq;t?.identify?.({external_id:e});break}}}(e,se,t),[se]),me=o(()=>({consent:{manifest:b?.consent?.manifest??[],state:M,set:ge},track:le,setUser:fe,setProperties:W,getProperties:K,completeCheckout:ue,installed:{...te.current},ready:q,attribution:X}),[b,M,ge,le,fe,W,K,ue,q,re,X]);return e(ne.Provider,{value:me,children:_})};function ae(e={}){const{completeCheckout:n,ready:r}=ie(),o=t(e);o.current=e;const a=t(!1);i(()=>{if(!r)return;if(a.current)return;const e=$(window.location.search)??I();e&&(a.current=!0,n(e,o.current))},[r,n])}oe.displayName="BuildBaseTracking";const se={sign_in_started:"The sign-in / sign-up button was pressed.",pricing_viewed:"A <PricingPage> finished loading its plans.",pricing_plan_selected:"A plan was chosen on a <PricingPage>.",workspace_switcher_opened:"The workspace switcher was opened.",workspace_settings_opened:"The workspace settings modal was opened.",workspace_settings_section_viewed:"A different section of the settings modal was opened.",plan_picker_opened:"The plan picker was shown.",billing_interval_changed:"Monthly / quarterly / yearly was switched in the plan picker.",plan_selected:"A plan was chosen in the plan picker.",plan_picker_dismissed:"The plan picker was closed without choosing a plan.",checkout_abandoned:"The customer came back from Stripe without paying.",billing_portal_opened:"Stripe’s billing portal was opened.",subscription_cancel_started:"The cancel-subscription confirmation was opened.",subscription_cancelled:"A subscription was cancelled.",subscription_resumed:"A cancelled subscription was resumed.",feature_gate_shown:'A feature gate rendered its "not on your plan" side.',quota_limit_reached:"A quota gate rendered because a quota is used up.",quota_threshold_reached:"A usage-threshold gate rendered.",plan_gate_shown:'A plan gate rendered its "needs another plan" side.',subscription_notice_shown:"A billing notice (trial ending, payment failed…) was shown.",sdk_error:"An SDK operation failed (component, action and code only)."};export{d as ATTRIBUTION_PARAMS,oe as BuildBaseTracking,B as EVENT_MAPPINGS,se as FUNNEL_EVENTS,O as TAG_PROVIDERS,U as TAG_PROVIDER_IDS,N as TAG_SCRIPT_ORIGINS,f as captureAttribution,m as getAttribution,z as isCanonicalEvent,L as isTagProviderId,E as isValidProviderId,ae as useCheckoutCompleted,ie as useTracking};
|
|
2
|
+
import{jsx as e}from"react/jsx-runtime";import{useRef as t,useState as n,useCallback as r,useEffect as i,useMemo as o,useContext as a,createContext as s}from"react";const c="__buildbaseBeforeLeave",d=globalThis,l=d[c]??(d[c]=new Set);const u="bb_attr",p=["gclid","gbraid","wbraid","dclid","fbclid","msclkid","li_fat_id","twclid","ttclid","rdt_cid","epik","irclickid","utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_id"],g=/^[\w.~-]{1,200}$/;function f(){return"undefined"==typeof window?null:window}function m(e,t){if(!e||!e.includes("."))return"";if(/^\d{1,3}(\.\d{1,3}){3}$/.test(e))return"";const n=t??f()?.document;if(!n)return"";const r=e.split(".");for(let e=r.length-2;e>=0;e--){const t="."+r.slice(e).join("."),i=`__bb_probe_${Date.now()}`;n.cookie=`${i}=1; domain=${t}; path=/; SameSite=Lax`;const o=n.cookie.includes(`${i}=1`);if(n.cookie=`${i}=; domain=${t}; path=/; max-age=0; SameSite=Lax`,o)return t}return""}function h(e){const t=e.cookie.split("; ").find(e=>e.startsWith(`${u}=`));if(!t)return{};try{const e=JSON.parse(decodeURIComponent(t.slice(8)));return"object"==typeof e&&e?e:{}}catch{return{}}}function y(){const e=f();if(!e)return{};const t=e.document,n=h(t),r={...function(e){const t=new URLSearchParams(e),n={};for(const e of p){const r=t.get(e);r&&(r.length>200||g.test(r)&&(n[e]=r))}return n}(e.location.search),...n};if(0===Object.keys(r).length)return{};return Object.keys(r).some(e=>void 0===n[e])&&function(e,t,n){const r=encodeURIComponent(JSON.stringify(t));e.cookie=`${u}=${r}; path=/; max-age=7776000; SameSite=Lax`+(n?`; domain=${n}`:"")}(t,r,m(e.location.hostname,t)),r}function w(){const e=f();return e?h(e.document):{}}function v(e){try{const t=new URLSearchParams(e);return t.has("code")&&t.has("state")}catch{return!1}}const _="bb_pending_checkout";function k(){try{return"undefined"==typeof window?null:window.sessionStorage}catch{return null}}const b="bb_co";function I(){try{return"undefined"==typeof window?null:window.document??null}catch{return null}}function C(){const e=I();if(e)try{const t=m(window.location?.hostname??"",e);e.cookie=`${b}=; path=/; max-age=0; SameSite=Lax`+(t?`; domain=${t}`:"")}catch{}}function $(e,t){if(!e)return null;try{const n=JSON.parse(e);return n&&"string"==typeof n.eventId&&n.eventId?"number"!=typeof n.startedAt||t-n.startedAt>216e5?null:n:null}catch{return null}}function j(e=Date.now()){const t=k();if(!t)return null;let n=null;try{n=t.getItem(_),t.removeItem(_)}catch{return null}const r=$(n,e);return r&&C(),r}function x(e){try{return $(k()?.getItem(_)??null,e)}catch{return null}}function q(e,t=Date.now()){let n=null;try{n=new URLSearchParams(e).get("session_id")}catch{return null}if(!n)return null;const r=x(t);if(r?.sessionId===n)return j(t);const i=function(e){const t=I();if(!t||"string"!=typeof t.cookie)return null;const n=t.cookie.split("; ").find(e=>e.startsWith(`${b}=`));return n?$(decodeURIComponent(n.slice(6)),e):null}(t);return i?.sessionId!==n?null:(C(),i)}function A(e,t=Date.now()){return function(e){let t=null;try{t=new URLSearchParams(e).get("bb")}catch{return!1}if(!t)return!1;const n={};for(const e of t.split(",")){const t=e.indexOf(":");if(-1!==t)try{n[decodeURIComponent(e.slice(0,t))]=decodeURIComponent(e.slice(t+1))}catch{}}return"checkout"===n.action&&"cancel"===n.status}(e)&&x(t)?j(t):null}const P=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"]),S=new Set(["bhd","jod","kwd","omr","tnd"]);function O(e,t){if("number"!=typeof e||!Number.isFinite(e))return;const n=(t??"").toLowerCase();return P.has(n)?e:e/(S.has(n)?1e3:100)}function E(){return"undefined"==typeof window?null:window}function U(e){const t=E();if(!t)return;t.gtag?.("consent","update",{ad_storage:e.marketing?"granted":"denied",ad_user_data:e.marketing?"granted":"denied",ad_personalization:e.marketing?"granted":"denied",analytics_storage:e.analytics?"granted":"denied"});const n=t.fbq;n?.("consent",e.marketing?"grant":"revoke")}const L={gtm:{title:"Google Tag Manager",vendor:"Google LLC",privacyUrl:"https://policies.google.com/privacy",idLabel:"Container ID",idPattern:"^GTM-[A-Z0-9]{4,10}$",idExample:"GTM-ABC1234",scriptOrigin:"https://www.googletagmanager.com",defaultConsentCategory:"analytics",supportsConsentMode:!0,needsConversionIds:!1},ga4:{title:"Google Analytics 4",vendor:"Google LLC",privacyUrl:"https://policies.google.com/privacy",idLabel:"Measurement ID",idPattern:"^G-[A-Z0-9]{8,12}$",idExample:"G-ABCD123456",scriptOrigin:"https://www.googletagmanager.com",defaultConsentCategory:"analytics",supportsConsentMode:!0,needsConversionIds:!1},google_ads:{title:"Google Ads",vendor:"Google LLC",privacyUrl:"https://policies.google.com/privacy",idLabel:"Conversion ID",idPattern:"^AW-[0-9]{9,12}$",idExample:"AW-123456789",scriptOrigin:"https://www.googletagmanager.com",defaultConsentCategory:"marketing",supportsConsentMode:!0,needsConversionIds:!0},meta_pixel:{title:"Meta Pixel",vendor:"Meta Platforms Ireland Limited",privacyUrl:"https://www.facebook.com/privacy/policy",idLabel:"Pixel ID",idPattern:"^[0-9]{15,16}$",idExample:"123456789012345",scriptOrigin:"https://connect.facebook.net",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},x_pixel:{title:"X (Twitter) Pixel",vendor:"X Corp.",privacyUrl:"https://x.com/en/privacy",idLabel:"Pixel ID",idPattern:"^o[a-z0-9]{4,6}$",idExample:"o1a2b3",scriptOrigin:"https://static.ads-twitter.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!0,multiInstance:!0},linkedin:{title:"LinkedIn Insight Tag",vendor:"LinkedIn Ireland Unlimited Company",privacyUrl:"https://www.linkedin.com/legal/privacy-policy",idLabel:"Partner ID",idPattern:"^[0-9]{6,9}$",idExample:"1234567",scriptOrigin:"https://snap.licdn.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!0,multiInstance:!0},tiktok:{title:"TikTok Pixel",vendor:"TikTok Information Technologies UK Limited",privacyUrl:"https://www.tiktok.com/legal/privacy-policy",idLabel:"Pixel ID",idPattern:"^[A-Z0-9]{20}$",idExample:"C4A1B2C3D4E5F6G7H8I9",scriptOrigin:"https://analytics.tiktok.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},reddit:{title:"Reddit Pixel",vendor:"Reddit, Inc.",privacyUrl:"https://www.reddit.com/policies/privacy-policy",idLabel:"Advertiser ID",idPattern:"^t2_[a-z0-9]{4,12}$",idExample:"t2_abc123",scriptOrigin:"https://www.redditstatic.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},bing_uet:{title:"Microsoft Advertising (UET)",vendor:"Microsoft Corporation",privacyUrl:"https://privacy.microsoft.com/en-us/privacystatement",idLabel:"Tag ID",idPattern:"^[0-9]{7,9}$",idExample:"12345678",scriptOrigin:"https://bat.bing.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},clarity:{title:"Microsoft Clarity",vendor:"Microsoft Corporation",privacyUrl:"https://privacy.microsoft.com/en-us/privacystatement",idLabel:"Project ID",idPattern:"^[a-z0-9]{10}$",idExample:"ab12cd34ef",scriptOrigin:"https://www.clarity.ms",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1},hotjar:{title:"Hotjar",vendor:"Hotjar Limited",privacyUrl:"https://www.hotjar.com/legal/policies/privacy/",idLabel:"Site ID",idPattern:"^[0-9]{6,9}$",idExample:"1234567",scriptOrigin:"https://static.hotjar.com",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1},posthog:{title:"PostHog",vendor:"PostHog, Inc.",privacyUrl:"https://posthog.com/privacy",idLabel:"Project API key",idPattern:"^phc_[A-Za-z0-9]{32,48}$",idExample:"phc_abcdefghijklmnopqrstuvwxyz012345",scriptOrigin:"https://us-assets.i.posthog.com",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1,hosts:["us.i.posthog.com","eu.i.posthog.com"]},plausible:{title:"Plausible Analytics",vendor:"Plausible Insights OÜ",privacyUrl:"https://plausible.io/privacy",idLabel:"Domain",idPattern:"^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$",idExample:"example.com",scriptOrigin:"https://plausible.io",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1},ahrefs:{title:"Ahrefs Analytics",vendor:"Ahrefs Pte. Ltd.",privacyUrl:"https://ahrefs.com/privacy",idLabel:"Analytics key",idPattern:"^[A-Za-z0-9+/=]{20,64}$",idExample:"AbCdEfGhIjKlMnOpQrStUv==",scriptOrigin:"https://analytics.ahrefs.com",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1}},T=Object.keys(L);function M(e){return"string"==typeof e&&Object.prototype.hasOwnProperty.call(L,e)}function D(e,t){return!!M(e)&&("string"==typeof t&&0!==t.length&&new RegExp(L[e].idPattern).test(t))}const N=/^[a-z][a-z0-9-]{0,40}$/,B=/^[\w.:/@+=-]{1,200}$/;function R(e){return function(e){if("string"!=typeof e)return!1;if(0===e.length||e.length>300)return!1;let t;try{t=new URL(e)}catch{return!1}return!("https:"!==t.protocol||!t.hostname||!t.hostname.includes(".")||e.includes("?")||e.includes("#")||t.username||t.password)}(e.src)&&function(e){if(null==e)return!0;if("object"!=typeof e||Array.isArray(e))return!1;const t=Object.entries(e);return!(t.length>12)&&t.every(([e,t])=>N.test(e)&&"string"==typeof t&&B.test(t))}(e.dataAttributes)}const z=Array.from(new Set(T.map(e=>L[e].scriptOrigin))).sort(),G={sign_up:{ga4:"sign_up",meta:"CompleteRegistration",tiktok:"CompleteRegistration",reddit:"SignUp"},login:{ga4:"login",meta:null,tiktok:null,reddit:null},trial_started:{ga4:"begin_checkout",meta:"StartTrial",tiktok:"StartTrial",reddit:"Lead"},checkout_started:{ga4:"begin_checkout",meta:"InitiateCheckout",tiktok:"InitiateCheckout",reddit:"AddToCart"},purchase:{ga4:"purchase",meta:"Purchase",tiktok:"CompletePayment",reddit:"Purchase"},subscription_created:{ga4:"purchase",meta:"Subscribe",tiktok:"Subscribe",reddit:"Purchase"},subscription_upgraded:{ga4:"subscription_upgraded",meta:null,tiktok:null,reddit:null},lead:{ga4:"generate_lead",meta:"Lead",tiktok:"SubmitForm",reddit:"Lead"},workspace_created:{ga4:"workspace_created",meta:null,tiktok:null,reddit:null}},V=Object.keys(G);function F(e){return V.includes(e)}function H(){return"undefined"==typeof window?null:window}const Z={gtm:"dataLayer",ga4:"gtag",google_ads:"gtag",meta_pixel:"fbq",x_pixel:"twq",linkedin:"lintrk",tiktok:"ttq",reddit:"rdt",bing_uet:"uetq",clarity:"clarity",hotjar:"hj",posthog:"posthog",plausible:"plausible",ahrefs:"__ahrefs_loaded"};function J(){return"undefined"==typeof window?null:window}function K(e,t={}){const n=J();if(!n)return null;const r=n.document.createElement("script");r.async=!0,r.src=e;for(const[e,n]of Object.entries(t))r.setAttribute(e,n);return n.document.head.appendChild(r),r}function W(e){const t=J();if(!t)return;const n=t.document.createElement("script");n.text=e,t.document.head.appendChild(n)}function Q(e){const t=J();t&&(Array.isArray(t[e])||(t[e]=[]),"function"!=typeof t.gtag&&(t.gtag=function(){t[e].push(arguments)}))}const X=new Set;function Y(e){for(const t of X)if(t.slice(0,t.indexOf(":"))===e)return!0;return!1}function ee(e,t){const n=J();if(!n)return!1;if("gtm"===e||"ga4"===e||"google_ads"===e){const e=n.google_tag_manager;return!(!e||"object"!=typeof e)&&Object.prototype.hasOwnProperty.call(e,t)}const r=Z[e];if(!r)return!1;if(void 0===n[r])return!1;if(X.has(`${e}:${t}`))return!0;return!L[e].multiInstance||!Y(e)}const te={meta_pixel:e=>`fbq('init','${e}');fbq('track','PageView');`,x_pixel:e=>`twq('config','${e}');`,tiktok:e=>`ttq.load('${e}');ttq.page();`,reddit:e=>`rdt('init','${e}');rdt('track','PageVisit');`,bing_uet:e=>`window.uetq=window.uetq||[];window.uetq.push({ti:'${e}',enableAutoSpaTracking:false});`,linkedin:e=>`window._linkedin_data_partner_ids=window._linkedin_data_partner_ids||[];window._linkedin_data_partner_ids.push('${e}');`};function ne(e,t,n){const r=function(e,t,n){const r=J();if(!r)return!1;if("external"===e.provider){if(!e.src)return!1;const t={};for(const[n,r]of Object.entries(e.dataAttributes??{}))t[`data-${n}`]=r;return K(e.src,t),!0}const i=e.provider,o=L[i];if(!o)return!1;const a=e.providerId;if(!a)return!1;const s=te[i];if(s&&Y(i))return W(s(a)),!0;switch(i){case"gtm":{Q(t),r[t].push({"gtm.start":Date.now(),event:"gtm.js"});const e="dataLayer"===t?"":`&l=${t}`;return K(`${o.scriptOrigin}/gtm.js?id=${a}${e}`),!0}case"ga4":case"google_ads":{Q(t),K(`${o.scriptOrigin}/gtag/js?id=${a}`);const e=r.gtag;e("js",new Date);const s="ga4"===i&&n?.gaClientId?{client_id:n.gaClientId}:void 0;return s?e("config",a,s):e("config",a),!0}case"meta_pixel":return W(`!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','${o.scriptOrigin}/en_US/fbevents.js');fbq('init','${a}');fbq('track','PageView');`),!0;case"x_pixel":return W(`!function(e,t,n,s,u,a){e.twq||(s=e.twq=function(){s.exe?s.exe.apply(s,arguments):s.queue.push(arguments)},s.version='1.1',s.queue=[],u=t.createElement(n),u.async=!0,u.src='${o.scriptOrigin}/uwt.js',a=t.getElementsByTagName(n)[0],a.parentNode.insertBefore(u,a))}(window,document,'script');twq('config','${a}');`),!0;case"linkedin":return W(`window._linkedin_partner_id='${a}';window._linkedin_data_partner_ids=window._linkedin_data_partner_ids||[];window._linkedin_data_partner_ids.push('${a}');window.lintrk=window.lintrk||function(a,b){(window.lintrk.q=window.lintrk.q||[]).push([a,b])};window.lintrk.q=window.lintrk.q||[];`),K(`${o.scriptOrigin}/li.lms-analytics/insight.min.js`),!0;case"tiktok":return W(`!function(w,d,t){w.TiktokAnalyticsObject=t;var ttq=w[t]=w[t]||[];ttq.methods=['page','track','identify','instances','debug','on','off','once','ready','alias','group','enableCookie','disableCookie'];ttq.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var i=0;i<ttq.methods.length;i++)ttq.setAndDefer(ttq,ttq.methods[i]);ttq.load=function(e,n){var r='${o.scriptOrigin}/i18n/pixel/events.js';ttq._i=ttq._i||{};ttq._i[e]=[];ttq._i[e]._u=r;ttq._t=ttq._t||{};ttq._t[e]=+new Date;ttq._o=ttq._o||{};ttq._o[e]=n||{};var o=d.createElement('script');o.type='text/javascript';o.async=!0;o.src=r+'?sdkid='+e+'&lib='+t;var a=d.getElementsByTagName('script')[0];a.parentNode.insertBefore(o,a)};ttq.load('${a}');ttq.page()}(window,document,'ttq');`),!0;case"reddit":return W(`!function(w,d){if(!w.rdt){var p=w.rdt=function(){p.sendEvent?p.sendEvent.apply(p,arguments):p.callQueue.push(arguments)};p.callQueue=[];var t=d.createElement('script');t.src='${o.scriptOrigin}/ads/pixel.js';t.async=!0;var s=d.getElementsByTagName('script')[0];s.parentNode.insertBefore(t,s)}}(window,document);rdt('init','${a}');rdt('track','PageVisit');`),!0;case"bing_uet":return W(`(function(w,d,t,r,u){w[u]=w[u]||[];w[u].push({ti:'${a}',enableAutoSpaTracking:false});var o=d.createElement(t);o.src='${o.scriptOrigin}/bat.js';o.async=1;var i=d.getElementsByTagName(t)[0];i.parentNode.insertBefore(o,i)})(window,document,'script',0,'uetq');`),!0;case"clarity":return W(`(function(c,l,a,r,i,t,y){c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};t=l.createElement(r);t.async=1;t.src='${o.scriptOrigin}/tag/'+i;y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y)})(window,document,'clarity','script','${a}');`),!0;case"hotjar":return W(`(function(h,o,t,j,a,r){h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};h._hjSettings={hjid:${a},hjsv:6};a=o.getElementsByTagName('head')[0];r=o.createElement('script');r.async=1;r.src='${o.scriptOrigin}/hotjar-'+h._hjSettings.hjid+'.js?sv='+h._hjSettings.hjsv;a.appendChild(r)})(window,document);`),!0;case"posthog":{const t=o.hosts,n=t?.includes(e.host??"")?e.host:t?.[0]??"us.i.posthog.com";return W(`!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split('.');2==o.length&&(t=t[o[0]],e=o[1]);t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement('script')).type='text/javascript',p.async=!0,p.src='${o.scriptOrigin}/static/array.js',(r=t.getElementsByTagName('script')[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a='posthog',u.people=u.people||[],u.toString=function(t){var e='posthog';return'posthog'!==a&&(e+='.'+a),t||(e+=' (stub)'),e},u.people.toString=function(){return u.toString(1)+'.people (stub)'},o='init capture register register_once identify alias people.set people.set_once set_config get_distinct_id getFeatureFlag isFeatureEnabled onFeatureFlags reloadFeatureFlags group reset'.split(' '),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);posthog.init('${a}',{api_host:'https://${n}'});`),!0}case"plausible":return W("window.plausible=window.plausible||function(){(window.plausible.q=window.plausible.q||[]).push(arguments)};"),K(`${o.scriptOrigin}/js/script.js`,{"data-domain":a,defer:"true"}),!0;case"ahrefs":return K(`${o.scriptOrigin}/analytics.js`,{"data-key":a}),r.__ahrefs_loaded=!0,!0;default:return!1}}(e,t,n);return r&&"external"!==e.provider&&e.providerId&&X.add(`${e.provider}:${e.providerId}`),r}const re=Symbol.for("@buildbase/sdk.tracking.context"),ie=globalThis,oe=ie[re]??(ie[re]=s(null)),ae={consent:{manifest:[],state:null,set:()=>{}},track:()=>{},setUser:()=>{},setProperties:()=>{},getProperties:()=>({}),completeCheckout:async()=>{},installed:{},ready:!0,attribution:{}};function se(){return a(oe)??ae}const ce=({serverUrl:a,orgId:s,clientId:c,enabled:d=!0,consent:u="auto",autoPageview:p=!0,events:g,onEvent:f,properties:m,enrich:h,identity:w,debug:_=!1,children:k})=>{const b=t(w);b.current=w;const[I,C]=n(null),[$,j]=n(!1),[x,P]=n(!1),S="granted"===u?{analytics:!0,marketing:!0}:"denied"===u?{analytics:!1,marketing:!1}:null,[T,N]=n(S),B=t(null),z=t(f);z.current=f;const V=t(h);V.current=h;const Z=t({});Z.current=m??{};const J=t({}),K=r(()=>({...Z.current,...J.current}),[]),W=r(e=>{const t={...J.current,...e};for(const[e,n]of Object.entries(t))void 0===n&&delete t[e];J.current=t},[]),[X,Y]=n({}),te=t({}),[re,ie]=n(0),ae=I?.dataLayerName??"dataLayer",se=r((...e)=>{_&&console.info("[buildbase:tracking]",...e)},[_]);i(()=>{return e=()=>{0!==Object.keys(te.current).length&&window.dispatchEvent("function"==typeof PageTransitionEvent?new PageTransitionEvent("pagehide",{persisted:!1}):new Event("pagehide"))},l.add(e),()=>{l.delete(e)};var e},[]),i(()=>{if(!(d&&a&&s&&c))return void j(!0);let e=!1;const t=`${a.replace(/\/$/,"")}/api/v1/public/${s}/tracking?clientId=${encodeURIComponent(c)}`;return fetch(t).then(e=>e.ok?e.json():null).then(t=>{if(e||!t)return;const n=t.data??t;n&&Array.isArray(n.scripts)&&C(n)}).catch(()=>{se("config fetch failed; nothing installed")}).finally(()=>{e||j(!0)}),()=>{e=!0}},[d,a,s,c,se]),i(()=>{d&&Y(y())},[d]),i(()=>{d&&I?.enabled&&(Q(ae),function(e,t){const n=E();if(!n)return;Array.isArray(n[e])||(n[e]=[]),"function"!=typeof n.gtag&&(n.gtag=function(){n[e].push(arguments)});const r="granted"===t?"granted":"denied";n.gtag("consent","default",{ad_storage:r,ad_user_data:r,ad_personalization:r,analytics_storage:r,wait_for_update:500})}(ae,u),B.current&&U(B.current))},[d,I?.enabled,ae,u]);const ce=o(()=>I?.enabled?I.scripts.filter(e=>{const t=M(e.provider)&&L[e.provider].supportsConsentMode;return function(e,t,n,r){return"denied"!==r&&("granted"===r||(n?"marketing"===e?n.marketing:n.analytics:t&&"analytics"===e))}(e.consentCategory,t,T,u)}):[],[I,T,u]),[de,le]=n(()=>"undefined"==typeof window||!v(window.location.search));i(()=>{if(de)return;const e=setInterval(()=>{v(window.location.search)||le(!0)},50),t=setTimeout(()=>le(!0),5e3);return()=>{clearInterval(e),clearTimeout(t)}},[de]),i(()=>{if(!de)return;if(!d||!I?.enabled)return void($&&P(!0));let e=0;for(const t of ce)if(!te.current[t.key]){if("external"===t.provider){if(!R({src:t.src,dataAttributes:t.dataAttributes})){se("rejected external script",t.key);continue}}else{if(!M(t.provider)){se("rejected unknown provider",t.provider);continue}if(!D(t.provider,t.providerId)){se("rejected id for",t.provider);continue}if(ee(t.provider,t.providerId??"")){se(`${t.provider} ${t.providerId} is already on the page; skipping. Configure each tag in exactly one place.`);continue}}ne(t,ae,b.current)&&(te.current[t.key]=t.providerId??t.src??"",e+=1,se("installed",t.key))}e&&ie(e=>e+1);const t=window;t.__buildbase=t.__buildbase??{},t.__buildbase.tracking={installed:{...te.current},dataLayerName:ae,clientId:c};const n=Object.keys(te.current).length>0,r=null!==T||0===I.scripts.length;(n||r)&&P(!0)},[d,I,ce,$,T,ae,se,de,c]),i(()=>{if(!d||!p||!I?.enabled)return;if("undefined"==typeof window)return;if(!de)return;let e=null;const t=()=>{e&&clearTimeout(e),e=setTimeout(()=>function(e,t){const n=H();if(!n)return;const r=n[t];Array.isArray(r)&&r.push({event:"page_view",page_path:n.location.pathname,page_location:n.location.href,page_title:n.document.title});for(const t of e)switch(t.provider){case"ga4":n.gtag?.("event","page_view",{send_to:t.providerId,page_path:n.location.pathname,page_location:n.location.href,page_title:n.document.title});break;case"meta_pixel":n.fbq?.("track","PageView");break;case"tiktok":{const e=n.ttq;e?.page?.();break}case"reddit":n.rdt?.("track","PageVisit")}}(ce,ae),50)},n=window.history,r=n.pushState,i=n.replaceState;return n.pushState=function(...e){const n=r.apply(this,e);return t(),n},n.replaceState=function(...e){const n=i.apply(this,e);return t(),n},window.addEventListener("popstate",t),()=>{n.pushState=r,n.replaceState=i,window.removeEventListener("popstate",t),e&&clearTimeout(e)}},[d,p,I?.enabled,ce,ae,de]),i(()=>{if(!d)return;const e=function(e,t){const n=e?.mode??"auto",r=e?.overrides??{};if(("manual"===n||Object.values(r).some(e=>"manual"===e))&&!t)return'[buildbase:tracking] events are set to "manual" but no onEvent handler was provided, so those events would never fire anywhere. Pass onEvent, or use mode "auto".';for(const e of Object.keys(r))if(!F(e))return`[buildbase:tracking] unknown event "${e}" in events.overrides. Overrides only apply to the events the SDK fires itself.`;return null}(g,!!f);if(e)throw new Error(e)},[d,g,f]);const ue=r((e,t={},n)=>{if(!d)return;const r=n?.eventId||function(){const e=globalThis.crypto;return e?.randomUUID?e.randomUUID():`${Date.now().toString(16)}-${Math.random().toString(16).slice(2,10)}`}(),i=g?.mode??"auto",o=(F(e)?g?.overrides?.[e]:void 0)??i,a={...Z.current,...J.current,...X,...t},s=V.current?.({name:e,params:a})??{},c={...a,...s},l=z.current?.({name:e,params:c,eventId:r,handledBy:o});"manual"!==o&&!0!==l?(!function(e,t,n,r,i){const o=H();if(!o)return;const a=o[i];Array.isArray(a)&&a.push({event:e,...t,event_id:n});const s=F(e)?G[e]:{ga4:e,meta:null,tiktok:null,reddit:null};for(const i of r){const r=i.provider,a=L[r];if(a){if(a.needsConversionIds){const a=i.conversionIds?.[e];if(!a)continue;"google_ads"===r?o.gtag?.("event","conversion",{send_to:`${i.providerId}/${a}`,transaction_id:n,...t}):"x_pixel"===r?o.twq?.("event",a,{...t,conversion_id:n}):"linkedin"===r&&o.lintrk?.("track",{conversion_id:a});continue}switch(r){case"ga4":s.ga4&&o.gtag?.("event",s.ga4,{...t,send_to:i.providerId,event_id:n});break;case"meta_pixel":s.meta&&o.fbq?.("track",s.meta,t,{eventID:n});break;case"tiktok":if(s.tiktok){const e=o.ttq;e?.track?.(s.tiktok,{...t,event_id:n})}break;case"reddit":s.reddit&&o.rdt?.("track",s.reddit,{...t,conversionId:n});break;case"bing_uet":{const r=o.uetq;r?.push?.("event",s.ga4??e,{...t,event_id:n});break}case"clarity":o.clarity?.("event",e);break;case"hotjar":{const t=o.hj;t?.("event",e);break}case"posthog":{const r=o.posthog;r?.capture?.(e,{...t,event_id:n});break}case"plausible":o.plausible?.(e,{props:t})}}}}(e,c,r,ce,ae),se("event fired:",e,r)):se("event handled by app:",e)},[d,g,ce,ae,X,se]),pe=r(async(e,t={})=>{const n=function(e){return{name:"trial_started"===e.kind?"trial_started":"purchase",params:{...e.workspaceId?{workspace_id:e.workspaceId}:{},...e.planVersionId?{plan_version_id:e.planVersionId}:{},...e.creditPackageId?{credit_package_id:e.creditPackageId}:{},...e.billingInterval?{billing_interval:e.billingInterval}:{},...e.currency?{currency:e.currency.toUpperCase()}:{},..."number"==typeof e.value?{value:e.value}:{},...e.sessionId?{transaction_id:e.sessionId}:{}}}}(e);let r=n.params;if(e.sessionId&&a&&s){const t=await async function(e,t){try{const n=e.serverUrl.replace(/\/$/,""),r=await fetch(`${n}/api/v1/public/${encodeURIComponent(e.orgId)}/checkout/${encodeURIComponent(t)}`,{credentials:"omit",..."undefined"!=typeof AbortSignal&&AbortSignal.timeout?{signal:AbortSignal.timeout(2e3)}:{}});if(!r.ok)return null;const i=await r.json(),o=i?.data??i;return"number"!=typeof o?.amount?null:{value:O(o.amount,o.currency),currency:"string"==typeof o.currency?o.currency:void 0,...Array.isArray(o.items)&&o.items.length?{items:o.items}:{}}}catch{return null}}({serverUrl:a,orgId:s},e.sessionId);t&&"number"==typeof t.value&&(r={...r,value:t.value,...t.currency?{currency:t.currency.toUpperCase()}:{},...t.items?.length?{items:t.items}:{}})}if(ue(n.name,{...r,...t},{eventId:e.eventId}),"purchase"===n.name&&e.sessionId&&a&&s){const t=(I?.scripts??[]).find(e=>"ga4"===e.provider&&e.providerId);t&&ee("ga4",t.providerId??"")&&function(e,t,n){try{const r=e.serverUrl.replace(/\/$/,"");fetch(`${r}/api/v1/public/${encodeURIComponent(e.orgId)}/checkout/${encodeURIComponent(t)}/reported`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:n}),keepalive:!0,credentials:"omit"}).catch(()=>{})}catch{}}({serverUrl:a,orgId:s},e.sessionId,"ga4")}},[a,s,ue,I]),[ge]=n(()=>"undefined"==typeof window?"":window.location.search);i(()=>{if(!d||!x)return;if("undefined"==typeof window)return;const e=q(window.location.search);if(e)return void pe(e);const t=A(ge);t&&ue("checkout_abandoned",{...t.workspaceId?{workspace_id:t.workspaceId}:{},...t.planVersionId?{plan_version_id:t.planVersionId}:{},...t.creditPackageId?{credit_package_id:t.creditPackageId}:{},...t.billingInterval?{billing_interval:t.billingInterval}:{},...t.currency?{currency:t.currency.toUpperCase()}:{},..."number"==typeof t.value?{value:t.value}:{},seconds_at_checkout:Math.max(0,Math.round((Date.now()-t.startedAt)/1e3))})},[d,x,pe,ge,ue]);const fe=r(e=>{B.current=e,N(e),U(e)},[]),me=r((e,t)=>function(e,t,n){const r=H();if(!r)return;const i=!!n&&Object.keys(n).length>0;for(const o of t)switch(o.provider){case"ga4":case"google_ads":r.gtag?.("set",{user_id:e}),i&&r.gtag?.("set",{user_properties:n});break;case"meta_pixel":o.providerId&&r.fbq?.("init",o.providerId,{external_id:e});break;case"posthog":r.posthog?.identify?.(e,i?n:void 0);break;case"clarity":if(r.clarity?.("identify",e),i)for(const[e,t]of Object.entries(n))r.clarity?.("set",e,String(t));break;case"hotjar":r.hj?.("identify",e,{});break;case"tiktok":{const t=r.ttq;t?.identify?.({external_id:e});break}}}(e,ce,t),[ce]),he=o(()=>({consent:{manifest:I?.consent?.manifest??[],state:T,set:fe},track:ue,setUser:me,setProperties:W,getProperties:K,completeCheckout:pe,installed:{...te.current},ready:x,attribution:X}),[I,T,fe,ue,me,W,K,pe,x,re,X]);return e(oe.Provider,{value:he,children:k})};function de(e={}){const{completeCheckout:n,ready:r}=se(),o=t(e);o.current=e;const a=t(!1);i(()=>{if(!r)return;if(a.current)return;const e=q(window.location.search)??j();e&&(a.current=!0,n(e,o.current))},[r,n])}ce.displayName="BuildBaseTracking";const le={sign_in_started:"The sign-in / sign-up button was pressed.",pricing_viewed:"A <PricingPage> finished loading its plans.",pricing_plan_selected:"A plan was chosen on a <PricingPage>.",workspace_switcher_opened:"The workspace switcher was opened.",workspace_settings_opened:"The workspace settings modal was opened.",workspace_settings_section_viewed:"A different section of the settings modal was opened.",plan_picker_opened:"The plan picker was shown.",billing_interval_changed:"Monthly / quarterly / yearly was switched in the plan picker.",plan_selected:"A plan was chosen in the plan picker.",plan_picker_dismissed:"The plan picker was closed without choosing a plan.",checkout_abandoned:"The customer came back from Stripe without paying.",billing_portal_opened:"Stripe’s billing portal was opened.",subscription_cancel_started:"The cancel-subscription confirmation was opened.",subscription_cancelled:"A subscription was cancelled.",subscription_resumed:"A cancelled subscription was resumed.",feature_gate_shown:'A feature gate rendered its "not on your plan" side.',quota_limit_reached:"A quota gate rendered because a quota is used up.",quota_threshold_reached:"A usage-threshold gate rendered.",plan_gate_shown:'A plan gate rendered its "needs another plan" side.',subscription_notice_shown:"A billing notice (trial ending, payment failed…) was shown.",sdk_error:"An SDK operation failed (component, action and code only)."};export{p as ATTRIBUTION_PARAMS,ce as BuildBaseTracking,G as EVENT_MAPPINGS,le as FUNNEL_EVENTS,L as TAG_PROVIDERS,T as TAG_PROVIDER_IDS,z as TAG_SCRIPT_ORIGINS,y as captureAttribution,w as getAttribution,F as isCanonicalEvent,M as isTagProviderId,D as isValidProviderId,de as useCheckoutCompleted,se as useTracking};
|