bitsnap-react 1.20.0 → 1.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/dist/BitsnapCart-73ESTTTH.mjs +2 -0
  2. package/dist/BitsnapCart-TWT7LVGJ.js +2 -0
  3. package/dist/BitsnapCart-TWT7LVGJ.js.map +1 -0
  4. package/dist/{CartProvider-G7FQUPXL.mjs → CartProvider-4WXJPQJB.mjs} +2 -2
  5. package/dist/CartProvider-CPF2E7JA.js +2 -0
  6. package/dist/CartProvider-CPF2E7JA.js.map +1 -0
  7. package/dist/PanelModelFiles-EKQRLF46.js.map +1 -1
  8. package/dist/analytics.js +1 -1
  9. package/dist/analytics.js.map +1 -1
  10. package/dist/analytics.mjs +1 -1
  11. package/dist/catalog.js +1 -1
  12. package/dist/catalog.js.map +1 -1
  13. package/dist/catalog.mjs +1 -1
  14. package/dist/chat.d.mts +2 -2
  15. package/dist/chat.d.ts +2 -2
  16. package/dist/chat.js +1 -1
  17. package/dist/chat.js.map +1 -1
  18. package/dist/chat.mjs +1 -1
  19. package/dist/chat.mjs.map +1 -1
  20. package/dist/{chunk-IXQCN7MR.mjs → chunk-27JN2GIQ.mjs} +2 -2
  21. package/dist/{chunk-URQBHNJK.mjs → chunk-6ALA5M44.mjs} +2 -2
  22. package/dist/{chunk-4Y233NII.js → chunk-6DEKVABT.js} +2 -2
  23. package/dist/chunk-6DEKVABT.js.map +1 -0
  24. package/dist/chunk-6Q3VGPSF.js.map +1 -1
  25. package/dist/{chunk-AQYHQY2Y.js → chunk-E5MMKBC4.js} +2 -2
  26. package/dist/chunk-E5MMKBC4.js.map +1 -0
  27. package/dist/chunk-EFN4OW2C.js.map +1 -1
  28. package/dist/{chunk-IRZJIPUF.js → chunk-EK3D44XW.js} +2 -2
  29. package/dist/chunk-EK3D44XW.js.map +1 -0
  30. package/dist/{chunk-BTERIY6N.mjs → chunk-EXC5Z5VM.mjs} +2 -2
  31. package/dist/{chunk-RJPQMDIQ.js → chunk-EZGL6DPG.js} +2 -2
  32. package/dist/chunk-EZGL6DPG.js.map +1 -0
  33. package/dist/{chunk-HP3I6D2R.js → chunk-FORZ5AH4.js} +2 -2
  34. package/dist/chunk-FORZ5AH4.js.map +1 -0
  35. package/dist/{chunk-KO7ZERN5.mjs → chunk-HLULQA3B.mjs} +2 -2
  36. package/dist/{chunk-YPA6MMGJ.js → chunk-I2RHVELR.js} +2 -2
  37. package/dist/chunk-I2RHVELR.js.map +1 -0
  38. package/dist/{chunk-GHBRR665.js → chunk-IKKMSLKC.js} +2 -2
  39. package/dist/chunk-IKKMSLKC.js.map +1 -0
  40. package/dist/{chunk-TW25G7XX.mjs → chunk-J6WKSO33.mjs} +2 -2
  41. package/dist/{chunk-TW25G7XX.mjs.map → chunk-J6WKSO33.mjs.map} +1 -1
  42. package/dist/chunk-JSDGZ4NY.js.map +1 -1
  43. package/dist/{chunk-IXX6SUMB.mjs → chunk-KO7Z3E23.mjs} +2 -2
  44. package/dist/chunk-KOYBZORL.js.map +1 -1
  45. package/dist/chunk-KYSMT6ZK.js +2 -0
  46. package/dist/chunk-KYSMT6ZK.js.map +1 -0
  47. package/dist/{chunk-LHQEM3CU.mjs → chunk-LRUBBPTV.mjs} +2 -2
  48. package/dist/chunk-MDAFPGPA.js.map +1 -1
  49. package/dist/chunk-Q337IQNA.js.map +1 -1
  50. package/dist/{chunk-5M3OUOMU.mjs → chunk-T5JO4SP7.mjs} +2 -2
  51. package/dist/{chunk-C736F727.js → chunk-TM3E3L57.js} +2 -2
  52. package/dist/chunk-TM3E3L57.js.map +1 -0
  53. package/dist/{chunk-LHNTSQYO.mjs → chunk-TMEII7BM.mjs} +2 -2
  54. package/dist/chunk-W3RGQYPD.js.map +1 -1
  55. package/dist/{chunk-A2ZDFN3J.mjs → chunk-WOA6W5RM.mjs} +2 -2
  56. package/dist/{chunk-KZWCVKLU.js → chunk-XMRGA5AN.js} +3 -3
  57. package/dist/chunk-XMRGA5AN.js.map +1 -0
  58. package/dist/chunk-Z3YOJ6NZ.js.map +1 -1
  59. package/dist/consent.js.map +1 -1
  60. package/dist/course.js +1 -1
  61. package/dist/course.js.map +1 -1
  62. package/dist/course.mjs +1 -1
  63. package/dist/embed/analytics.js +1 -1
  64. package/dist/errors.js.map +1 -1
  65. package/dist/index.css +1 -1
  66. package/dist/index.css.map +1 -1
  67. package/dist/index.d.mts +2 -2
  68. package/dist/index.d.ts +2 -2
  69. package/dist/index.js +1 -1
  70. package/dist/index.js.map +1 -1
  71. package/dist/index.mjs +1 -1
  72. package/dist/index.mjs.map +1 -1
  73. package/dist/internal.js.map +1 -1
  74. package/dist/methods-43RQLLWD.mjs +2 -0
  75. package/dist/methods-SZVF3HMF.js +2 -0
  76. package/dist/methods-SZVF3HMF.js.map +1 -0
  77. package/dist/model-files-client-P4PORZJ6.js.map +1 -1
  78. package/dist/models.js.map +1 -1
  79. package/dist/returns.js +1 -1
  80. package/dist/returns.js.map +1 -1
  81. package/dist/returns.mjs +1 -1
  82. package/dist/viewer3d.js.map +1 -1
  83. package/dist/viewer3d.mjs +1 -1
  84. package/dist/{widgets-Bsojw94g.d.ts → widgets-BL6pCMdc.d.ts} +34 -2
  85. package/dist/{widgets-u7xMJbsY.d.mts → widgets-DmHlIbp8.d.mts} +34 -2
  86. package/package.json +1 -1
  87. package/dist/BitsnapCart-V4S4EXYV.js +0 -2
  88. package/dist/BitsnapCart-V4S4EXYV.js.map +0 -1
  89. package/dist/BitsnapCart-Z6JFYNH2.mjs +0 -2
  90. package/dist/CartProvider-5NP4WACK.js +0 -2
  91. package/dist/CartProvider-5NP4WACK.js.map +0 -1
  92. package/dist/chunk-4Y233NII.js.map +0 -1
  93. package/dist/chunk-AQYHQY2Y.js.map +0 -1
  94. package/dist/chunk-C736F727.js.map +0 -1
  95. package/dist/chunk-GHBRR665.js.map +0 -1
  96. package/dist/chunk-HP3I6D2R.js.map +0 -1
  97. package/dist/chunk-IRZJIPUF.js.map +0 -1
  98. package/dist/chunk-KDL35KEI.js +0 -2
  99. package/dist/chunk-KDL35KEI.js.map +0 -1
  100. package/dist/chunk-KZWCVKLU.js.map +0 -1
  101. package/dist/chunk-RJPQMDIQ.js.map +0 -1
  102. package/dist/chunk-YPA6MMGJ.js.map +0 -1
  103. package/dist/methods-33CWGKNA.mjs +0 -2
  104. package/dist/methods-4GB652MQ.js +0 -2
  105. package/dist/methods-4GB652MQ.js.map +0 -1
  106. /package/dist/{BitsnapCart-Z6JFYNH2.mjs.map → BitsnapCart-73ESTTTH.mjs.map} +0 -0
  107. /package/dist/{CartProvider-G7FQUPXL.mjs.map → CartProvider-4WXJPQJB.mjs.map} +0 -0
  108. /package/dist/{chunk-IXQCN7MR.mjs.map → chunk-27JN2GIQ.mjs.map} +0 -0
  109. /package/dist/{chunk-URQBHNJK.mjs.map → chunk-6ALA5M44.mjs.map} +0 -0
  110. /package/dist/{chunk-BTERIY6N.mjs.map → chunk-EXC5Z5VM.mjs.map} +0 -0
  111. /package/dist/{chunk-KO7ZERN5.mjs.map → chunk-HLULQA3B.mjs.map} +0 -0
  112. /package/dist/{chunk-IXX6SUMB.mjs.map → chunk-KO7Z3E23.mjs.map} +0 -0
  113. /package/dist/{chunk-LHQEM3CU.mjs.map → chunk-LRUBBPTV.mjs.map} +0 -0
  114. /package/dist/{chunk-5M3OUOMU.mjs.map → chunk-T5JO4SP7.mjs.map} +0 -0
  115. /package/dist/{chunk-LHNTSQYO.mjs.map → chunk-TMEII7BM.mjs.map} +0 -0
  116. /package/dist/{chunk-A2ZDFN3J.mjs.map → chunk-WOA6W5RM.mjs.map} +0 -0
  117. /package/dist/{methods-33CWGKNA.mjs.map → methods-43RQLLWD.mjs.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/chat-attachments/dist/chunk-XMRGA5AN.js","../src/panel/components/PanelLogin.tsx","../src/ui/card.tsx","../src/ui/email-code-login/EmailCodeLoginForm.tsx","../src/lib/render.text.tsx","../src/panel/audio-player/media.session.coordinator.ts","../src/panel/audio-player/AudioPlayer.tsx"],"names":["Card","className","props","jsx","cn","CardHeader","CardTitle","CardDescription","CardContent","MUTED","DARK_FIELD","EMAIL_FAILURES","LINK","EmailCodeLoginForm","login","texts","allowHaveCode","emailPlaceholder","emailInputId","codeInputId","buttonClassName","children","uid","useId","emailId"],"mappings":"AAAA,ylCAAgN,sDAAyC,sDAA+F,sDAAyC,sDAAyF,sDAAiF,sDAA+E,sDAAyE,sDAAgE,oDCApuB,+BAC0C,+CCKrE,SAFKA,EAAAA,CAAK,CAAE,SAAA,CAAAC,CAAAA,CAAW,GAAGC,CAAM,CAAA,CAAgC,CAClE,OACEC,6BAAAA,KAAC,CAAA,CACC,WAAA,CAAU,MAAA,CACV,SAAA,CAAWC,gCAAAA,mFACT,CACAH,CACF,CAAA,CACC,GAAGC,CAAAA,CACN,CAEJ,CAEA,SAASG,EAAAA,CAAW,CAAE,SAAA,CAAAJ,CAAAA,CAAW,GAAGC,CAAM,CAAA,CAAgC,CACxE,OACEC,6BAAAA,KAAC,CAAA,CACC,WAAA,CAAU,aAAA,CACV,SAAA,CAAWC,gCAAAA,0JACT,CACAH,CACF,CAAA,CACC,GAAGC,CAAAA,CACN,CAEJ,CAEA,SAASI,EAAAA,CAAU,CAAE,SAAA,CAAAL,CAAAA,CAAW,GAAGC,CAAM,CAAA,CAAgC,CACvE,OACEC,6BAAAA,KAAC,CAAA,CACC,WAAA,CAAU,YAAA,CACV,SAAA,CAAWC,gCAAAA,4BAAG,CAA8BH,CAAS,CAAA,CACpD,GAAGC,CAAAA,CACN,CAEJ,CAEA,SAASK,EAAAA,CAAgB,CAAE,SAAA,CAAAN,CAAAA,CAAW,GAAGC,CAAM,CAAA,CAAgC,CAC7E,OACEC,6BAAAA,KAAC,CAAA,CACC,WAAA,CAAU,kBAAA,CACV,SAAA,CAAWC,gCAAAA,+BAAG,CAAiCH,CAAS,CAAA,CACvD,GAAGC,CAAAA,CACN,CAEJ,CAeA,SAASM,EAAAA,CAAY,CAAE,SAAA,CAAAP,CAAAA,CAAW,GAAGC,CAAM,CAAA,CAAgC,CACzE,OACEC,6BAAAA,KAAC,CAAA,CACC,WAAA,CAAU,cAAA,CACV,SAAA,CAAWC,gCAAAA,MAAG,CAAQH,CAAS,CAAA,CAC9B,GAAGC,CAAAA,CACN,CAEJ,CCvEA,2CAA4B,IA6BtBO,EAAAA,CAAQ,yCAAA,CAERC,EAAAA,CACJ,0MAAA,CAEIC,EAAAA,CAAiB,IAAI,GAAA,CAAI,CAAC,cAAA,CAAgB,eAAA,CAAiB,qBAAqB,CAAC,CAAA,CACjFC,EAAAA,CACJ,sNAAA,CAOK,SAASC,EAAAA,CAAmB,CACjC,KAAA,CAAAC,CAAAA,CACA,KAAA,CAAAC,CAAAA,CACA,aAAA,CAAAC,CAAAA,CAAgB,CAAA,CAAA,CAChB,gBAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,SAAA,CAAAlB,CAAAA,CACA,eAAA,CAAAmB,CAAAA,CACA,QAAA,CAAAC,CACF,CAAA,CAA4B,CAC1B,IAAMC,CAAAA,CAAMC,2BAAAA,CAAM,CACZC,CAAAA,kBAAUN,CAAAA,SAAgB,CAAA,EAAA;ACGlB,QAAA;ACMZ,YAAA;ACwzBQ","file":"/home/emems/.t3/worktrees/bitsnap-react/chat-attachments/dist/chunk-XMRGA5AN.js","sourcesContent":[null,"import { useAutoAnimate } from \"@formkit/auto-animate/react\";\nimport { useEffect, useMemo, useRef, useState, type CSSProperties } from \"react\";\nimport { TurnstileChallenge } from \"../../captcha/TurnstileChallenge\";\nimport {\n InstrumentProvider,\n useInstrument,\n useInstrumentContext,\n type AnalyticsOption,\n} from \"../../analytics/instrument\";\nimport { getLocale } from \"../../components/checkout/locale\";\nimport { rpcProvider, useMutation } from \"../../rpc-provider\";\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from \"../../ui/card\";\nimport { kindFromRpcError } from \"../../ui/email-code-login/errors\";\nimport {\n LoginBrandLogo,\n type LoginLogoOptions,\n} from \"../../ui/email-code-login/LoginBrandLogo\";\nimport { EmailCodeLoginForm } from \"../../ui/email-code-login/EmailCodeLoginForm\";\nimport { pendingLoginKey } from \"../../ui/email-code-login/pending\";\nimport {\n useEmailCodeLogin,\n type EmailCodeAdapter,\n} from \"../../ui/email-code-login/useEmailCodeLogin\";\nimport {\n getAllowedReturnOrigins,\n setAllowedReturnOrigins,\n} from \"../config\";\nimport { panelFailureKind } from \"../login-adapter\";\nimport { resolvePanelLoginTexts, type PanelLoginTexts } from \"../login-texts\";\nimport { usePanelConfig } from \"../PanelProvider\";\nimport type { PanelLoginProps } from \"../types\";\nimport {\n buildAccessTokenRedirect,\n getReturnURLFromSearch,\n persistReturnURL,\n readPersistedReturnURL,\n} from \"../return-url\";\nimport { getPanelSession, savePanelSession } from \"../session-storage\";\n\nif (typeof window !== \"undefined\") {\n const currentOrigin = window.location.origin;\n const knownSiblings = [\n currentOrigin,\n \"https://bitsnap.pl\",\n \"https://kursy.bitsnap.pl\",\n ];\n if (getAllowedReturnOrigins().length === 0) {\n setAllowedReturnOrigins(Array.from(new Set(knownSiblings)));\n }\n}\n\n\n/** Props of {@link PanelLogin}; `PanelLoginProps` of the package is a superset. */\nexport type PanelLoginComponentProps = Pick<\n PanelLoginProps,\n \"analytics\" | \"texts\" | \"locale\" | \"showLogo\" | \"logoUrl\" | \"logoDarkUrl\"\n>;\n\ntype PanelLoginResult = { accessToken: string };\n\nconst PanelLoginForm = ({\n texts,\n projectID,\n host,\n locale,\n logo,\n}: {\n texts: PanelLoginTexts;\n projectID?: string;\n host?: string;\n locale?: string;\n logo: LoginLogoOptions;\n}) => {\n const [challengeVisible, setChallengeVisible] = useState(false);\n const challengeWaiter = useRef<((token: string | null) => void) | undefined>(undefined);\n const captchaToken = useRef(\"\");\n const beforeSend = useMemo(() => () => new Promise<boolean>((resolve) => {\n setChallengeVisible(true);\n const timer = window.setTimeout(() => { challengeWaiter.current = undefined; setChallengeVisible(false); resolve(false); }, 5 * 60 * 1000);\n challengeWaiter.current = (token) => { window.clearTimeout(timer); challengeWaiter.current = undefined; setChallengeVisible(false); captchaToken.current = token ?? \"\"; resolve(token !== null); };\n }), []);\n const instrument = useInstrumentContext();\n const { mutateAsync: loginUserAsync } = useMutation(\n rpcProvider.publicApi.userPanelLogin,\n );\n const { mutateAsync: verifyCodeAsync } = useMutation(\n rpcProvider.publicApi.userPanelLoginWithCode,\n );\n\n const adapter = useMemo<EmailCodeAdapter<PanelLoginResult>>(\n () => ({\n async send(email) {\n try {\n const response = await loginUserAsync({ email, turnstileToken: captchaToken.current });\n captchaToken.current = \"\";\n if (response.result.case === \"success\") {\n return {\n ok: true,\n retryIn: response.result.value.retryIn || undefined,\n challengeId: response.result.value.challengeId || undefined,\n };\n }\n return {\n ok: false,\n kind: panelFailureKind(\n response.result.case === \"failure\" ? response.result.value : 0,\n ),\n };\n } catch (cause) {\n return { ok: false, kind: kindFromRpcError(cause), cause };\n }\n },\n async verify({ email, code, challengeId }) {\n try {\n const response = await verifyCodeAsync({\n code: parseInt(code, 10),\n email,\n challengeId,\n });\n if (response.result.case === \"accessToken\" && response.result.value) {\n return { ok: true, value: { accessToken: response.result.value } };\n }\n return {\n ok: false,\n kind: panelFailureKind(\n response.result.case === \"failure\" ? response.result.value : 0,\n ),\n };\n } catch (cause) {\n return { ok: false, kind: kindFromRpcError(cause), cause };\n }\n },\n }),\n [loginUserAsync, verifyCodeAsync],\n );\n\n const login = useEmailCodeLogin<PanelLoginResult>({\n adapter,\n texts,\n beforeSend,\n storageKey: pendingLoginKey(\"panel\", projectID, host),\n onVerified: ({ accessToken }, email) => {\n instrument.track(\"panel_login\", {});\n savePanelSession(projectID, accessToken, email, host);\n const returnURL =\n typeof window !== \"undefined\" ? readPersistedReturnURL() : null;\n setTimeout(() => {\n if (returnURL) {\n window.location.href = buildAccessTokenRedirect(returnURL, accessToken);\n return;\n }\n window.location.reload();\n }, 100);\n },\n });\n\n const onCodeStep = login.step === \"code\";\n const title = onCodeStep && !login.needsEmail ? texts.codeTitle : texts.title;\n const description =\n onCodeStep && !login.needsEmail ? texts.codeDescription : texts.description;\n\n return (\n // Top-aligned: a vertically centred card moved when the step changed height.\n <main className=\"mx-auto flex w-full max-w-sm flex-1 flex-col justify-start pt-4 sm:pt-[12vh]\">\n <Card>\n <LoginBrandLogo\n projectId={projectID}\n locale={locale}\n className=\"px-4 sm:px-6\"\n {...logo}\n />\n <CardHeader className=\"px-4 sm:px-6\">\n <CardTitle role=\"heading\" aria-level={1} className=\"text-2xl\">\n {title}\n </CardTitle>\n <CardDescription>{description}</CardDescription>\n </CardHeader>\n <CardContent className=\"px-4 sm:px-6\">\n <EmailCodeLoginForm\n login={login}\n texts={texts}\n emailInputId=\"email\"\n codeInputId=\"verify-code\"\n />\n {challengeVisible && <TurnstileChallenge action=\"panel_login\" locale={locale} onToken={(token) => challengeWaiter.current?.(token)} onFailure={() => challengeWaiter.current?.(null)} />}\n </CardContent>\n </Card>\n </main>\n );\n};\n\nconst PanelLoginComponentWrapper = ({\n analytics,\n texts: textOverrides,\n locale,\n showLogo,\n logoUrl,\n logoDarkUrl,\n}: PanelLoginComponentProps) => {\n const { theme, allowedReturnOrigins, projectID, host } = usePanelConfig();\n const instrument = useInstrument(projectID, analytics, \"panel\");\n const texts = useMemo(\n () => resolvePanelLoginTexts(locale ?? getLocale(), textOverrides),\n [locale, textOverrides],\n );\n\n const styles = {\n \"--button-background-color\": theme?.colors?.brand ?? \"#FFFFFF\",\n \"--button-background-color-dark\": theme?.colors?.brandDark ?? \"#000000\",\n \"--button-text-color\": theme?.colors?.brandDark ?? \"#000000\",\n \"--button-text-color-dark\": theme?.colors?.brand ?? \"#FFFFFF\",\n } as CSSProperties;\n\n const [parent] = useAutoAnimate({\n duration: 300,\n easing: \"ease-in-out\",\n disrespectUserMotionPreference: false,\n });\n\n // Already signed in: leave the login page. Declared before the return URL\n // effect below, so that one (a token redirect) wins when both apply.\n useEffect(() => {\n if (typeof window === \"undefined\") return;\n if (getPanelSession(projectID, host) != null) {\n window.location.href = window.location.href.replaceAll(\"login\", \"\");\n }\n }, [projectID, host]);\n\n useEffect(() => {\n if (typeof window === \"undefined\") return;\n if (window.parent !== window) return;\n\n const queryReturnURL = getReturnURLFromSearch(window.location.search);\n if (queryReturnURL) {\n persistReturnURL(queryReturnURL);\n }\n\n const returnURL = queryReturnURL ?? readPersistedReturnURL();\n if (!returnURL) return;\n\n const existingToken = getPanelSession(projectID, host);\n if (!existingToken) return;\n\n window.location.href = buildAccessTokenRedirect(returnURL, existingToken);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [allowedReturnOrigins, projectID, host]);\n\n return (\n <InstrumentProvider value={instrument}>\n <div className=\"bg-white text-black dark:bg-black dark:text-white\">\n <div\n className=\"font-inter flex min-h-screen w-full flex-col p-4\"\n style={styles}\n ref={parent}\n >\n <PanelLoginForm\n texts={texts}\n projectID={projectID}\n host={host}\n locale={locale}\n logo={{\n showLogo,\n logoUrl: logoUrl ?? theme?.logoURL,\n logoDarkUrl: logoDarkUrl ?? theme?.logoDarkURL,\n }}\n />\n </div>\n </div>\n </InstrumentProvider>\n );\n};\n\nexport const PanelLogin = (props: PanelLoginComponentProps = {}) => {\n return <PanelLoginComponentWrapper {...props} />;\n};\n","import * as React from \"react\"\n\nimport { cn } from \"@/src/lib/utils\"\n\nfunction Card({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card\"\n className={cn(\n \"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardHeader({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-header\"\n className={cn(\n \"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardTitle({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-title\"\n className={cn(\"leading-none font-semibold\", className)}\n {...props}\n />\n )\n}\n\nfunction CardDescription({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-description\"\n className={cn(\"text-muted-foreground text-sm\", className)}\n {...props}\n />\n )\n}\n\nfunction CardAction({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-action\"\n className={cn(\n \"col-start-2 row-span-2 row-start-1 self-start justify-self-end\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardContent({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-content\"\n className={cn(\"px-6\", className)}\n {...props}\n />\n )\n}\n\nfunction CardFooter({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-footer\"\n className={cn(\"flex items-center px-6 [.border-t]:pt-6\", className)}\n {...props}\n />\n )\n}\n\nexport {\n Card,\n CardHeader,\n CardFooter,\n CardTitle,\n CardAction,\n CardDescription,\n CardContent,\n}\n","import { CircleCheck } from \"lucide-react\";\nimport { useId, type FormEvent, type ReactNode } from \"react\";\nimport { cn } from \"@/src/lib/utils\";\nimport { Button } from \"../button\";\nimport { Input } from \"../input\";\nimport { Label } from \"../label\";\nimport { Spinner } from \"../spinner\";\nimport { OtpCodeField } from \"./OtpCodeField\";\nimport { fillText, type EmailCodeTexts } from \"./texts\";\nimport { type EmailCodeLogin } from \"./useEmailCodeLogin\";\n\nexport type EmailCodeLoginFormProps = {\n login: EmailCodeLogin;\n texts: EmailCodeTexts;\n /** Offers \"I already have a code\" under the e-mail step. */\n allowHaveCode?: boolean;\n /** Overrides the e-mail input placeholder. */\n emailPlaceholder?: string;\n /** `id` of the e-mail input; unique per instance by default. */\n emailInputId?: string;\n /** `id` of the code input; unique per instance by default. */\n codeInputId?: string;\n className?: string;\n /** Classes of the two primary buttons (brand colors). */\n buttonClassName?: string;\n /** Shown above the fields of the code step, after the \"sent to\" line. */\n children?: ReactNode;\n};\n\nconst MUTED = \"text-muted-foreground text-xs leading-5\";\n/** Borders of the dark theme: the `input` token is nearly the card colour. */\nconst DARK_FIELD =\n \"dark:border-foreground/30 dark:focus-visible:border-foreground/70 dark:focus-visible:ring-foreground/25 dark:aria-invalid:border-destructive-foreground dark:aria-invalid:ring-destructive-foreground/30\";\n/** Failures about the address itself; a throttled or failed send is not. */\nconst EMAIL_FAILURES = new Set([\"invalidEmail\", \"emailNotFound\", \"deliveryUnavailable\"]);\nconst LINK =\n \"inline-flex min-h-11 items-center px-1 text-sm underline underline-offset-4 hover:no-underline focus-visible:ring-[3px] focus-visible:ring-ring/50 rounded-sm outline-none disabled:opacity-50 disabled:no-underline\";\n\n/**\n * The two steps of the shared e-mail-code login. Markup only: all state comes\n * from {@link useEmailCodeLogin}. The surface wraps it in its own card or\n * dialog and renders the titles.\n */\nexport function EmailCodeLoginForm({\n login,\n texts,\n allowHaveCode = true,\n emailPlaceholder,\n emailInputId,\n codeInputId,\n className,\n buttonClassName,\n children,\n}: EmailCodeLoginFormProps) {\n const uid = useId();\n const emailId = emailInputId ?? `${uid}-email`;\n const codeId = codeInputId ?? `${uid}-code`;\n const noticeId = `${uid}-notice`;\n const hintId = `${uid}-hint`;\n\n const { notice } = login;\n const isError = notice?.kind === \"error\";\n const sending = login.busy === \"send\";\n const verifying = login.busy === \"verify\";\n const resending = login.busy === \"resend\";\n const buttonBase = cn(\"h-11 w-full\", buttonClassName);\n\n // Both live regions stay mounted (empty) so that a screen reader has\n // registered them before a message is put in; only their text changes.\n // The area reserves two lines, so a longer message does not push the buttons.\n const success = notice?.kind === \"success\";\n const noticeArea = (\n <div id={noticeId} className=\"min-h-10 text-sm leading-5\">\n <p\n role=\"alert\"\n className=\"font-medium text-red-700 dark:text-red-400\"\n >\n {isError ? notice.text : null}\n </p>\n <p\n role=\"status\"\n className={cn(\n \"flex items-start gap-1.5\",\n success\n ? \"font-medium text-emerald-700 dark:text-emerald-400\"\n : \"text-foreground\",\n )}\n >\n {success && <CircleCheck aria-hidden className=\"mt-0.5 size-4 shrink-0\" />}\n <span>{notice != null && !isError ? notice.text : null}</span>\n </p>\n </div>\n );\n const emailInvalid =\n isError &&\n login.step === \"email\" &&\n (notice.failure == null || EMAIL_FAILURES.has(notice.failure));\n\n const announcer = (\n <p className=\"sr-only\" role=\"status\" aria-live=\"polite\">\n {login.announcement}\n </p>\n );\n\n const emailField = (\n <div className=\"grid gap-2\">\n <Label htmlFor={emailId}>{texts.emailLabel}</Label>\n <Input\n id={emailId}\n ref={login.emailRef}\n name=\"email\"\n type=\"email\"\n autoComplete=\"email\"\n inputMode=\"email\"\n autoCapitalize=\"none\"\n autoCorrect=\"off\"\n spellCheck={false}\n autoFocus\n required\n className={cn(\n \"h-11 text-base disabled:opacity-100 disabled:text-foreground/70\",\n DARK_FIELD,\n )}\n placeholder={emailPlaceholder ?? texts.emailPlaceholder}\n value={login.email}\n disabled={login.isBusy}\n aria-invalid={emailInvalid ? true : undefined}\n aria-describedby={noticeId}\n onChange={(event) => login.setEmail(event.target.value)}\n />\n </div>\n );\n\n if (login.step === \"email\") {\n return (\n <form\n noValidate\n className={cn(\"flex flex-col gap-4\", className)}\n onSubmit={(event: FormEvent) => {\n event.preventDefault();\n void login.sendCode();\n }}\n >\n {announcer}\n {emailField}\n {noticeArea}\n <Button\n type=\"submit\"\n disabled={login.isBusy}\n aria-busy={sending}\n className={buttonBase}\n >\n {sending && <Spinner aria-hidden />}\n {sending ? texts.sending : texts.sendCode}\n </Button>\n {allowHaveCode && (\n <p className=\"flex flex-wrap items-center justify-center text-center text-sm\">\n {texts.haveCodePrompt !== \"\" && <span>{texts.haveCodePrompt}</span>}\n <button\n type=\"button\"\n className={LINK}\n disabled={login.isBusy}\n onClick={login.haveCode}\n >\n {texts.haveCode}\n </button>\n </p>\n )}\n </form>\n );\n }\n\n const [before, after] = texts.codeSentTo.split(\"{email}\");\n const dead = login.dead != null;\n const resendLabel = dead\n ? texts.resendNew\n : login.secondsLeft > 0\n ? fillText(texts.resendIn, { seconds: login.secondsLeft })\n : texts.resend;\n\n return (\n <form\n noValidate\n className={cn(\"flex flex-col gap-4\", className)}\n onSubmit={(event: FormEvent) => {\n event.preventDefault();\n void login.submitCode();\n }}\n >\n {announcer}\n {login.needsEmail ? (\n emailField\n ) : (\n <div className=\"flex flex-wrap items-center justify-between gap-x-2\">\n {/* The address moves to its own line before it is cut; the word\n joiner keeps the full stop with it. */}\n <p className=\"min-w-0 flex-[1_1_14rem] text-sm leading-5 break-words\">\n {before}\n <strong className=\"font-semibold\">{login.email}</strong>\n {\"\\u2060\"}\n {after}\n </p>\n <button\n type=\"button\"\n className={cn(LINK, \"-ml-1 shrink-0\")}\n disabled={login.isBusy}\n onClick={login.changeEmail}\n >\n {texts.changeEmail}\n </button>\n </div>\n )}\n {children}\n <div className=\"grid gap-2\">\n <Label htmlFor={codeId}>{texts.codeLabel}</Label>\n <OtpCodeField\n id={codeId}\n name=\"code\"\n inputRef={login.codeRef}\n value={login.code}\n onChange={login.setCode}\n onComplete={(value) => void login.submitCode(value)}\n disabled={login.isBusy || dead}\n invalid={isError && !login.needsEmail}\n aria-describedby={`${noticeId} ${hintId}`}\n />\n <p id={hintId} className={MUTED}>\n {texts.validity} {texts.spamHint}\n </p>\n </div>\n {noticeArea}\n <Button\n type=\"submit\"\n disabled={login.isBusy || dead}\n aria-busy={verifying}\n className={buttonBase}\n >\n {verifying && <Spinner aria-hidden />}\n {verifying ? texts.verifying : texts.verify}\n </Button>\n {login.needsEmail ? (\n <div className=\"flex justify-center\">\n <button\n type=\"button\"\n className={LINK}\n disabled={login.isBusy}\n onClick={login.changeEmail}\n >\n {texts.noCode}\n </button>\n </div>\n ) : (\n <Button\n type=\"button\"\n variant={dead ? \"default\" : \"outline\"}\n disabled={login.isBusy || (!dead && login.secondsLeft > 0)}\n aria-busy={resending}\n className={dead ? buttonBase : \"h-11 w-full\"}\n onClick={() => void login.resend()}\n >\n {resending && <Spinner aria-hidden />}\n {resendLabel}\n </Button>\n )}\n </form>\n );\n}\n","const URL_REGEX =\n /https?:\\/\\/(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b([-a-zA-Z0-9()@:%_\\+.~#?&//=]*)/g;\n\ntype Replacements = {\n url: string;\n startIndex: number;\n endIndex: number;\n replacementText?: string;\n};\n\nconst findURLIndices = (text: string) => {\n const matches = [...text.matchAll(URL_REGEX)];\n return matches.map(\n (match) =>\n ({\n url: match[0],\n startIndex: match.index,\n endIndex: match.index + match[0].length - 1,\n }) as Replacements,\n );\n};\n\nconst replaceTextByIndices = (\n originalText: string,\n replacements: Replacements[],\n) => {\n let result = \"\";\n let lastIndex = 0;\n\n // Sort replacements by startIndex to handle them in order\n replacements.sort((a, b) => a.startIndex - b.startIndex);\n\n for (const { startIndex, endIndex, replacementText } of replacements) {\n // Append text before the current replacement\n result += originalText.slice(lastIndex, startIndex);\n // Append the replacement text\n result += replacementText;\n // Update lastIndex to after the replaced segment\n lastIndex = endIndex + 1;\n }\n\n // Append any remaining text after the last replacement\n result += originalText.slice(lastIndex);\n\n return result;\n};\n\nexport const renderText = (txt: string) => {\n const urlIndices = findURLIndices(txt);\n\n return (\n <p\n dangerouslySetInnerHTML={{\n __html: replaceTextByIndices(\n txt,\n urlIndices.map((el) => {\n el[\"replacementText\"] =\n `<a key=${el.url} href=${el.url} style=\"text-decoration: underline;\" target=\"_blank\">\n ${el.url}\n </a>`;\n return el;\n }),\n ),\n }}\n ></p>\n );\n};\n","/** Skip length of the player buttons and of the lock-screen skip handlers. */\nexport const SEEK_STEP_SECONDS = 10;\n\n/** Under this position \"previous track\" restarts the chapter instead of going back. */\nexport const PREVIOUS_TRACK_RESTART_SECONDS = 3;\n\nexport type MediaSessionArtwork = {\n src: string;\n sizes?: string;\n type?: string;\n};\n\nexport type MediaSessionMetadata = {\n title: string;\n album?: string;\n artist?: string;\n artwork?: string | MediaSessionArtwork | (string | MediaSessionArtwork)[];\n};\n\nconst MIME_BY_EXTENSION: Record<string, string> = {\n png: \"image/png\",\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n webp: \"image/webp\",\n gif: \"image/gif\",\n avif: \"image/avif\",\n svg: \"image/svg+xml\",\n};\n\n/** Lock-screen artwork size we declare; the player does not decode the image. */\nconst ARTWORK_SIZES = \"512x512\";\n\nfunction mediaSessionAvailable(): boolean {\n return (\n typeof navigator != \"undefined\" &&\n typeof navigator.mediaSession != \"undefined\"\n );\n}\n\n/**\n * Turns an image URL into a media-session artwork entry. The `type` comes from\n * the file extension and is omitted when the extension is unknown, so the\n * browser does not get a wrong MIME type.\n */\nexport function mediaSessionArtworkFromUrl(url: string): MediaSessionArtwork {\n if (typeof url != \"string\" || url.length === 0) {\n return { src: url, sizes: ARTWORK_SIZES };\n }\n const withoutQuery = url.split(/[?#]/)[0];\n const extension = withoutQuery.includes(\".\")\n ? withoutQuery.slice(withoutQuery.lastIndexOf(\".\") + 1).toLowerCase()\n : \"\";\n const type = MIME_BY_EXTENSION[extension];\n const artwork: MediaSessionArtwork = { src: url, sizes: ARTWORK_SIZES };\n if (type != null) {\n artwork.type = type;\n }\n return artwork;\n}\n\nfunction normalizeArtwork(\n artwork: MediaSessionMetadata[\"artwork\"],\n): MediaSessionArtwork[] | undefined {\n if (artwork == null) {\n return undefined;\n }\n const entries = Array.isArray(artwork) ? artwork : [artwork];\n const normalized: MediaSessionArtwork[] = [];\n for (const entry of entries) {\n if (typeof entry === \"string\") {\n if (entry.length > 0) {\n normalized.push(mediaSessionArtworkFromUrl(entry));\n }\n continue;\n }\n if (entry != null && entry.src.length > 0) {\n normalized.push({\n src: entry.src,\n sizes: entry.sizes ?? ARTWORK_SIZES,\n ...(entry.type != null ? { type: entry.type } : {}),\n });\n }\n }\n return normalized.length > 0 ? normalized : undefined;\n}\n\nexport function mediaSessionSetMetadata(metadata: MediaSessionMetadata) {\n if (\n !mediaSessionAvailable() ||\n typeof MediaMetadata == \"undefined\"\n ) {\n return;\n }\n navigator.mediaSession.metadata = new MediaMetadata({\n title: metadata.title,\n album: metadata.album,\n artist: metadata.artist,\n artwork: normalizeArtwork(metadata.artwork),\n });\n}\n\nexport function mediaSessionPlay() {\n if (!mediaSessionAvailable()) return;\n navigator.mediaSession.playbackState = \"playing\";\n}\n\nexport function mediaSessionPause() {\n if (!mediaSessionAvailable()) return;\n navigator.mediaSession.playbackState = \"paused\";\n}\n\n/**\n * Reports duration, position and the real playback rate to the lock screen.\n * `setPositionState` throws on values it does not accept (no duration yet,\n * position past the end), so those calls are skipped or clamped.\n */\nexport function mediaSessionUpdateDurationAndPosition(\n duration: number | undefined,\n currentTime: number | undefined,\n playbackRate = 1,\n) {\n if (!mediaSessionAvailable()) return;\n if (duration == null || !Number.isFinite(duration) || duration <= 0) {\n return;\n }\n if (currentTime != null && isNaN(currentTime)) {\n return;\n }\n const position = Math.min(Math.max(currentTime ?? 0, 0), duration);\n const rate =\n Number.isFinite(playbackRate) && playbackRate > 0 ? playbackRate : 1;\n try {\n navigator.mediaSession.setPositionState({\n playbackRate: rate,\n duration,\n position,\n });\n } catch (e) {\n // Older browsers reject some combinations; the lock screen just keeps the\n // previous state.\n }\n}\n\nconst MEDIA_SESSION_ACTIONS: MediaSessionAction[] = [\n \"play\",\n \"pause\",\n \"stop\",\n \"seekbackward\",\n \"seekforward\",\n \"seekto\",\n \"previoustrack\",\n \"nexttrack\",\n];\n\nexport function startMediaSessionCoordinator(args: {\n title: string;\n album?: string;\n artist?: string;\n artwork?: MediaSessionMetadata[\"artwork\"];\n\n action: (details: MediaSessionActionDetails) => void;\n}) {\n if (!mediaSessionAvailable()) return;\n\n mediaSessionSetMetadata({\n title: args.title,\n album: args.album,\n artist: args.artist,\n artwork: args.artwork,\n });\n\n for (const action of MEDIA_SESSION_ACTIONS) {\n try {\n navigator.mediaSession.setActionHandler(action, (details) => {\n args.action(details);\n });\n } catch (e) {\n // The browser does not support this action (e.g. nexttrack).\n }\n }\n}\n\nexport function stopMediaSessionCoordinator() {\n if (!mediaSessionAvailable()) return;\n navigator.mediaSession.metadata = null;\n for (const action of MEDIA_SESSION_ACTIONS) {\n try {\n navigator.mediaSession.setActionHandler(action, null);\n } catch (e) {\n // Unsupported action; nothing to clear.\n }\n }\n}\n","import Hls from \"hls.js\";\nimport { Pause, Play, SkipBack, SkipForward } from \"lucide-react\";\nimport {\n forwardRef,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n type CSSProperties,\n} from \"react\";\nimport { cn } from \"../../lib/utils\";\nimport { Button } from \"../../ui/button\";\nimport LoadingIndicator from \"../LoadingIndicator\";\nimport {\n createHlsSource,\n playerErrorFromMediaError,\n prefersNativeHls,\n type HlsSource,\n type PlayerError,\n} from \"./hls-engine\";\nimport {\n PREVIOUS_TRACK_RESTART_SECONDS,\n SEEK_STEP_SECONDS,\n mediaSessionPause,\n mediaSessionPlay,\n mediaSessionSetMetadata,\n mediaSessionUpdateDurationAndPosition,\n startMediaSessionCoordinator,\n stopMediaSessionCoordinator,\n} from \"./media.session.coordinator\";\n\nimport \"./audio-player.css\";\nimport { useAudioTexts, formatTime } from \"./texts\";\nimport { playerStorage, SPEED_KEY, SPEEDS } from \"./storage\";\n\nexport type ChapterWithPublicUrl = {\n id: string;\n multimediaId?: string;\n name: string;\n description?: string;\n publicUrl: string;\n downloadableUrl?: string;\n duration?: number;\n};\n\n/** What the player could not play; `status` is the HTTP status when known. */\nexport type AudioPlayerError = PlayerError;\n\nexport type AudioPlayerMethods = {\n selectChapter: (chapter: ChapterWithPublicUrl) => void;\n /** Loads the current chapter again after an error, keeping the position. */\n retry: () => void;\n /** The error currently shown, if any. */\n getError: () => AudioPlayerError | null;\n};\n\ntype AudioPlayerProps = {\n locale?: string;\n chapters: ChapterWithPublicUrl[];\n styles: CSSProperties;\n updateCurrentTime?: (currentTime: number) => void;\n\n title?: string;\n imageURL?: string;\n /** Hide the repeated visual heading when the desktop details show the cover beside it. */\n coverShownBeside?: boolean;\n /** Book author, used as the lock-screen artist. */\n author?: string;\n\n setCurrentTimeHandler?: (seekTo: (second: number) => void) => void;\n uniqueProductID: string;\n\n onChapterChange?: (chapter: ChapterWithPublicUrl) => void;\n /** A fatal playback error the player could not recover from. */\n onError?: (error: AudioPlayerError) => void;\n /** The signed URL returned 401/403; the owner should refetch the chapters. */\n onExpiredUrl?: () => void;\n /** The last chapter ended. */\n onFinished?: () => void;\n};\n\nconst AudioPlayer = forwardRef<AudioPlayerMethods, AudioPlayerProps>(\n (\n {\n chapters,\n locale,\n styles,\n updateCurrentTime,\n setCurrentTimeHandler,\n title,\n imageURL,\n coverShownBeside,\n author,\n uniqueProductID,\n onChapterChange,\n onError,\n onExpiredUrl,\n onFinished,\n },\n ref,\n ) => {\n const t = useAudioTexts(locale);\n const [speed, setSpeed] = useState(1);\n const speedRef = useRef(1);\n const [chapterID, setChapterID] = useState<string>();\n const [sleepMode, setSleepMode] = useState(\"off\");\n const [sleepRemaining, setSleepRemaining] = useState(0);\n const sleepRef = useRef<{ mode: string; deadline: number }>({\n mode: \"off\",\n deadline: 0,\n });\n\n function cancelSleep() {\n sleepRef.current = { mode: \"off\", deadline: 0 };\n setSleepMode(\"off\");\n setSleepRemaining(0);\n }\n function changeSleep(mode: string) {\n const seconds = Number(mode) * 60;\n sleepRef.current = {\n mode,\n deadline: Number.isFinite(seconds) ? Date.now() + seconds * 1000 : 0,\n };\n setSleepMode(mode);\n setSleepRemaining(Number.isFinite(seconds) ? seconds : 0);\n }\n function changeSpeed(rate: number) {\n if (!SPEEDS.includes(rate)) return;\n setSpeed(rate);\n speedRef.current = rate;\n playerStorage.set(SPEED_KEY, String(rate));\n if (videoRef.current) videoRef.current.playbackRate = rate;\n updatePlayerDetails();\n }\n useEffect(() => {\n const saved = Number(playerStorage.get(SPEED_KEY));\n if (SPEEDS.includes(saved)) changeSpeed(saved);\n const timer = setInterval(() => {\n const { mode, deadline } = sleepRef.current;\n if (mode === \"off\" || mode === \"chapter\") return;\n const remaining = Math.max(\n 0,\n Math.ceil((deadline - Date.now()) / 1000),\n );\n setSleepRemaining(remaining);\n if (remaining === 0) {\n playWhenReadyRef.current = false;\n pause();\n cancelSleep();\n }\n }, 1000);\n return () => clearInterval(timer);\n }, []);\n\n enum PlayState {\n Playing,\n Paused,\n }\n\n const [playState, setPlayState] = useState<PlayState>(PlayState.Paused);\n const [currentTime, setCurrentTime] = useState<number | undefined>(\n undefined,\n );\n const [duration, setDuration] = useState<number | undefined>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n const [playerError, setPlayerError] = useState<AudioPlayerError | null>(\n null,\n );\n\n const videoRef = useRef<HTMLVideoElement | null>(null);\n const hlsRef = useRef<HlsSource | null>(null);\n const timerRef = useRef<ReturnType<typeof setInterval> | undefined>(\n undefined,\n );\n\n const audioPlayerContainerRef = useRef<HTMLDivElement>(null!);\n\n const currentChapterRef = useRef<ChapterWithPublicUrl | null>(null);\n const playerErrorRef = useRef<AudioPlayerError | null>(null);\n\n /** Set by a user action; the next `loadeddata` starts playback once. */\n const playWhenReadyRef = useRef(false);\n /** Position restored for the chapter that is loading, once. */\n const resumedRef = useRef(false);\n /** Position to restore instead of the remembered one (URL refresh, retry). */\n const pendingSeekRef = useRef<number | null>(null);\n /** Chapter URL that already asked the owner for a fresh signed URL. */\n const expiredUrlRef = useRef<string | null>(null);\n const chaptersRef = useRef(chapters);\n const chaptersSignatureRef = useRef<string | null>(null);\n\n // The owner passes new callbacks on every render; the player must keep the\n // current ones without restarting playback.\n const callbacksRef = useRef({\n onChapterChange,\n onError,\n onExpiredUrl,\n onFinished,\n updateCurrentTime,\n title,\n imageURL,\n author,\n });\n callbacksRef.current = {\n onChapterChange,\n onError,\n onExpiredUrl,\n onFinished,\n updateCurrentTime,\n title,\n imageURL,\n author,\n };\n\n function saveLastPlayedTime(timeInSeconds: number) {\n if (\n !resumedRef.current ||\n !Number.isFinite(timeInSeconds) ||\n timeInSeconds < 0\n ) {\n return;\n }\n playerStorage.set(\n `__player__${uniqueProductID}_${currentChapterRef.current?.id}`,\n `${Math.floor(timeInSeconds)}`,\n );\n }\n\n function getLastPlayedTime(): number | undefined {\n const time = playerStorage.get(\n `__player__${uniqueProductID}_${currentChapterRef.current?.id}`,\n );\n\n if (time == null) {\n return undefined;\n }\n try {\n const result = parseInt(time);\n\n if (isNaN(result) || result < 0) {\n return undefined;\n }\n\n return result;\n } catch (e) {\n return undefined;\n }\n }\n\n function getLastSelectedChapterID(): string | undefined {\n const lastSelectedChapterID = playerStorage.get(\n `__player__${uniqueProductID}_last_chapter`,\n );\n if (lastSelectedChapterID == null) {\n return undefined;\n }\n return lastSelectedChapterID;\n }\n\n function setLastSelectedChapterID(chapterID: string) {\n playerStorage.set(`__player__${uniqueProductID}_last_chapter`, chapterID);\n }\n\n function deleteMemoryChapter(chapterID: string) {\n playerStorage.remove(`__player__${uniqueProductID}_${chapterID}`);\n }\n\n function syncMediaSessionMetadata(chapter: ChapterWithPublicUrl | null) {\n mediaSessionSetMetadata({\n title: chapter?.name ?? callbacksRef.current.title ?? \"\",\n album: callbacksRef.current.title,\n artist: callbacksRef.current.author,\n artwork: callbacksRef.current.imageURL,\n });\n }\n\n function reportError(error: AudioPlayerError) {\n playerErrorRef.current = error;\n setPlayerError(error);\n setIsLoading(false);\n callbacksRef.current.onError?.(error);\n }\n\n function clearError() {\n playerErrorRef.current = null;\n setPlayerError(null);\n }\n\n function attemptPlay() {\n const video = videoRef.current;\n if (video == null) {\n return;\n }\n const result = video.play() as Promise<void> | undefined;\n if (result != null && typeof result.catch == \"function\") {\n result.catch(() => {\n // The browser blocked playback; the user presses play.\n });\n }\n updatePlayerDetails();\n }\n\n function play() {\n attemptPlay();\n }\n\n function pause() {\n videoRef.current?.pause();\n updatePlayerDetails();\n }\n\n function togglePlayState() {\n if (playState === PlayState.Playing) {\n pause();\n return;\n }\n play();\n }\n\n function seekTo(toSecond: number) {\n const video = videoRef.current;\n if (video == null || !Number.isFinite(toSecond)) {\n return;\n }\n const knownDuration = Number.isFinite(video.duration)\n ? video.duration\n : 0;\n const target =\n knownDuration > 0\n ? Math.min(Math.max(toSecond, 0), knownDuration)\n : Math.max(toSecond, 0);\n setCurrentTime(target);\n video.currentTime = target;\n updatePlayerDetails();\n }\n\n function seekBy(seconds: number) {\n const video = videoRef.current;\n if (video == null) {\n return;\n }\n const knownDuration = Number.isFinite(video.duration)\n ? video.duration\n : undefined;\n let target = Math.max(video.currentTime + seconds, 0);\n if (knownDuration != null && target > knownDuration) {\n target = knownDuration;\n }\n seekTo(target);\n }\n\n function loadSource(src: string) {\n const video = videoRef.current;\n if (video == null) {\n return;\n }\n clearError();\n setIsLoading(true);\n\n if (prefersNativeHls(video)) {\n destroyHls();\n video.src = src;\n video.load();\n return;\n }\n\n if (Hls.isSupported()) {\n if (hlsRef.current == null) {\n hlsRef.current = createHlsSource({\n media: video,\n handlers: {\n onError: (error) => {\n reportError(error);\n },\n onExpiredUrl: () => {\n callbacksRef.current.onExpiredUrl?.();\n },\n },\n });\n }\n hlsRef.current.load(src);\n return;\n }\n\n // No Media Source and no native HLS: let the browser try the URL itself.\n destroyHls();\n video.src = src;\n video.load();\n }\n\n function destroyHls() {\n hlsRef.current?.destroy();\n hlsRef.current = null;\n }\n\n function playChapter(\n chapter: ChapterWithPublicUrl,\n options?: { play?: boolean },\n ) {\n const shouldPlay = options?.play === true;\n if (\n currentChapterRef.current &&\n videoRef.current &&\n !videoRef.current.ended\n ) {\n saveLastPlayedTime(videoRef.current.currentTime);\n }\n resumedRef.current = false;\n pendingSeekRef.current = null;\n playWhenReadyRef.current = shouldPlay;\n currentChapterRef.current = chapter;\n setChapterID(chapter.id);\n setCurrentTime(0);\n setDuration(chapter.duration);\n loadSource(chapter.publicUrl);\n syncMediaSessionMetadata(chapter);\n callbacksRef.current.onChapterChange?.(chapter);\n setLastSelectedChapterID(chapter.id);\n }\n\n function loadChapters(list: ChapterWithPublicUrl[]) {\n if (list.length === 0) {\n return;\n }\n\n const chapterID = getLastSelectedChapterID();\n const chapter =\n (chapterID != null\n ? list.find((candidate) => candidate.id === chapterID)\n : undefined) ?? list[0];\n\n // Mount and content changes never start playback on their own.\n playChapter(chapter, { play: false });\n }\n\n function playNextChapter() {\n const list = chaptersRef.current;\n const current = currentChapterRef.current;\n if (list == null || list.length === 0 || current == null) {\n return;\n }\n const currentChapterIndex = list.findIndex(\n (chapter) => chapter.id === current.id,\n );\n if (currentChapterIndex === -1) {\n return;\n }\n const nextChapterIndex = currentChapterIndex + 1;\n if (nextChapterIndex >= list.length) {\n finishPlayback(current);\n return;\n }\n playChapter(list[nextChapterIndex], { play: true });\n }\n\n function playPreviousChapter() {\n const list = chaptersRef.current;\n const current = currentChapterRef.current;\n if (current == null) {\n return;\n }\n const video = videoRef.current;\n if (video != null && video.currentTime > PREVIOUS_TRACK_RESTART_SECONDS) {\n seekTo(0);\n return;\n }\n const currentChapterIndex =\n list == null\n ? -1\n : list.findIndex((chapter) => chapter.id === current.id);\n if (currentChapterIndex > 0) {\n playChapter(list[currentChapterIndex - 1], { play: true });\n return;\n }\n seekTo(0);\n }\n\n function finishPlayback(chapter: ChapterWithPublicUrl) {\n // The chapter is done: no resume point, and the element stays at the end.\n deleteMemoryChapter(chapter.id);\n playWhenReadyRef.current = false;\n videoRef.current?.pause();\n setPlayState(PlayState.Paused);\n callbacksRef.current.onFinished?.();\n }\n\n function handleEnded() {\n const current = currentChapterRef.current;\n if (current == null) {\n return;\n }\n playerStorage.set(\n `__player__${uniqueProductID}_${current.id}_completed`,\n \"true\",\n );\n deleteMemoryChapter(current.id);\n if (sleepRef.current.mode === \"chapter\") {\n playWhenReadyRef.current = false;\n pause();\n cancelSleep();\n return;\n }\n playNextChapter();\n updatePlayerDetails();\n }\n\n function handleLoadedData() {\n const video = videoRef.current;\n if (video == null) {\n return;\n }\n setIsLoading(false);\n video.playbackRate = speedRef.current;\n expiredUrlRef.current = null;\n if (!resumedRef.current) {\n resumedRef.current = true;\n const pending = pendingSeekRef.current;\n pendingSeekRef.current = null;\n if (pending != null) {\n seekTo(pending);\n } else {\n const lastPlayedTime = getLastPlayedTime();\n if (lastPlayedTime != null) {\n seekTo(lastPlayedTime);\n }\n }\n }\n if (playWhenReadyRef.current) {\n playWhenReadyRef.current = false;\n attemptPlay();\n }\n }\n\n function handleMediaElementError() {\n const mediaError = videoRef.current?.error;\n const src = currentChapterRef.current?.publicUrl;\n // Safari plays HLS itself and reports an expired signed URL as a network\n // error (2) or an unsupported source (4). Ask for a fresh URL once per\n // URL; an error that repeats after that refresh is a real error.\n const refreshable = mediaError?.code === 2 || mediaError?.code === 4;\n if (\n refreshable &&\n hlsRef.current == null &&\n src != null &&\n expiredUrlRef.current !== src\n ) {\n expiredUrlRef.current = src;\n callbacksRef.current.onExpiredUrl?.();\n }\n reportError(playerErrorFromMediaError(mediaError));\n }\n\n function retry() {\n const chapter = currentChapterRef.current;\n const src = chapter?.publicUrl ?? hlsRef.current?.src;\n if (src == null) {\n return;\n }\n const video = videoRef.current;\n const position = video?.currentTime ?? 0;\n clearError();\n resumedRef.current = false;\n pendingSeekRef.current = position > 0 ? position : null;\n setCurrentTime(position);\n if (hlsRef.current != null) {\n hlsRef.current.retry();\n } else {\n loadSource(src);\n }\n }\n\n function handleMediaSessionAction(details: MediaSessionActionDetails) {\n switch (details.action) {\n case \"play\":\n play();\n break;\n case \"pause\":\n case \"stop\":\n pause();\n break;\n case \"seekbackward\":\n seekBy(-(details.seekOffset ?? SEEK_STEP_SECONDS));\n break;\n case \"seekforward\":\n seekBy(details.seekOffset ?? SEEK_STEP_SECONDS);\n break;\n case \"seekto\":\n // A seek to 0 is valid: only a missing time is ignored.\n if (details.seekTime != null) {\n seekTo(details.seekTime);\n }\n break;\n case \"previoustrack\":\n playPreviousChapter();\n break;\n case \"nexttrack\":\n playNextChapter();\n break;\n default:\n break;\n }\n }\n\n useImperativeHandle(ref, () => {\n return {\n selectChapter: (chapter: ChapterWithPublicUrl) => {\n playChapter(chapter, { play: true });\n },\n retry,\n getError: () => playerErrorRef.current,\n };\n });\n\n function updatePlayerDetails() {\n const video = videoRef.current;\n if (video == null) {\n return;\n }\n setPlayState(video.paused ? PlayState.Paused : PlayState.Playing);\n setDuration(video.duration);\n setCurrentTime(video.currentTime);\n if (!video.ended) {\n saveLastPlayedTime(video.currentTime);\n }\n mediaSessionUpdateDurationAndPosition(\n video.duration,\n video.currentTime,\n video.playbackRate,\n );\n if (\n video.networkState === video.NETWORK_LOADING &&\n video.readyState <= video.HAVE_FUTURE_DATA\n ) {\n setIsLoading(true);\n } else {\n setIsLoading(false);\n }\n callbacksRef.current.updateCurrentTime?.(video.currentTime);\n }\n\n // Lock-screen handlers are registered once; they read refs, so they always\n // see the current chapters and callbacks.\n useEffect(() => {\n startMediaSessionCoordinator({\n title: title ?? \"\",\n album: title,\n artist: author,\n artwork: imageURL,\n action: handleMediaSessionAction,\n });\n\n return () => {\n stopMediaSessionCoordinator();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // The book title, cover or author arrive after the details request.\n useEffect(() => {\n syncMediaSessionMetadata(currentChapterRef.current);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [title, author, imageURL]);\n\n useEffect(() => {\n const video = videoRef.current;\n if (video == null) {\n return;\n }\n video.addEventListener(\"loadeddata\", handleLoadedData);\n video.addEventListener(\"ended\", handleEnded);\n video.addEventListener(\"error\", handleMediaElementError);\n video.addEventListener(\"timeupdate\", updatePlayerDetails);\n video.addEventListener(\"play\", updatePlayerDetails);\n video.addEventListener(\"pause\", updatePlayerDetails);\n video.addEventListener(\"ratechange\", updatePlayerDetails);\n\n updatePlayerDetails();\n timerRef.current = setInterval(updatePlayerDetails, 500);\n\n return () => {\n video.removeEventListener(\"loadeddata\", handleLoadedData);\n video.removeEventListener(\"ended\", handleEnded);\n video.removeEventListener(\"error\", handleMediaElementError);\n video.removeEventListener(\"timeupdate\", updatePlayerDetails);\n video.removeEventListener(\"play\", updatePlayerDetails);\n video.removeEventListener(\"pause\", updatePlayerDetails);\n video.removeEventListener(\"ratechange\", updatePlayerDetails);\n if (timerRef.current != null) {\n clearInterval(timerRef.current);\n timerRef.current = undefined;\n }\n if (!video.ended) saveLastPlayedTime(video.currentTime);\n setCurrentTime(undefined);\n video.pause();\n destroyHls();\n video.removeAttribute(\"src\");\n video.load();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useEffect(() => {\n if (setCurrentTimeHandler != null) {\n setCurrentTimeHandler(seekTo);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // Compare by chapter ids and URLs: a new array with the same content must\n // not reload the stream or restart playback.\n const chaptersSignature = chapters\n .map((chapter) => `${chapter.id}|${chapter.publicUrl ?? \"\"}`)\n .join(\"\\n\");\n\n useEffect(() => {\n chaptersRef.current = chapters;\n const previousSignature = chaptersSignatureRef.current;\n if (previousSignature === chaptersSignature) {\n return;\n }\n chaptersSignatureRef.current = chaptersSignature;\n\n if (previousSignature == null) {\n loadChapters(chapters);\n return;\n }\n\n const current = currentChapterRef.current;\n if (current == null) {\n loadChapters(chapters);\n return;\n }\n const replacement = chapters.find((chapter) => chapter.id === current.id);\n if (replacement != null && replacement.publicUrl === current.publicUrl) {\n // Same stream, different array: keep playing.\n return;\n }\n if (replacement != null) {\n // A fresh signed URL for the chapter that is playing: keep the position\n // and whether it was playing.\n const video = videoRef.current;\n const position = video?.currentTime ?? 0;\n const wasPlaying = video != null && !video.paused;\n currentChapterRef.current = replacement;\n resumedRef.current = false;\n pendingSeekRef.current = position > 0 ? position : null;\n playWhenReadyRef.current = wasPlaying;\n loadSource(replacement.publicUrl);\n syncMediaSessionMetadata(replacement);\n callbacksRef.current.onChapterChange?.(replacement);\n setLastSelectedChapterID(replacement.id);\n return;\n }\n loadChapters(chapters);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [chaptersSignature]);\n\n useEffect(() => {\n switch (playState) {\n case PlayState.Playing:\n mediaSessionPlay();\n break;\n case PlayState.Paused:\n mediaSessionPause();\n break;\n }\n }, [playState]);\n\n const currentIndex = chapters.findIndex(\n (chapter) => chapter.id === chapterID,\n );\n const knownDuration =\n Number.isFinite(duration) && duration! > 0\n ? duration!\n : (chapters[currentIndex]?.duration ?? 0);\n const position = Math.min(\n Math.max(currentTime ?? 0, 0),\n knownDuration || Infinity,\n );\n const wholeBookKnown =\n chapters.length > 0 &&\n chapters.every(\n (chapter) => Number.isFinite(chapter.duration) && chapter.duration! > 0,\n );\n const remaining =\n Math.max(\n 0,\n knownDuration -\n position +\n (wholeBookKnown\n ? chapters\n .slice(currentIndex + 1)\n .reduce((sum, chapter) => sum + chapter.duration!, 0)\n : 0),\n ) / speed;\n const minutesLeft = Math.ceil(remaining / 60);\n const leftText = `${Math.floor(minutesLeft / 60) > 0 ? `${Math.floor(minutesLeft / 60)} h ` : \"\"}${minutesLeft % 60} min`;\n\n return (\n <div\n id=\"audio-player-container\"\n className=\"bitsnap-audio-player flex min-w-0 flex-col gap-3 text-neutral-900 dark:text-neutral-100\"\n style={\n {\n ...styles,\n \"--seek-before-width\": `${knownDuration > 0 ? (position / knownDuration) * 100 : 0}%`,\n } as CSSProperties\n }\n ref={audioPlayerContainerRef}\n data-player-error={playerError?.kind}\n >\n <video\n ref={videoRef}\n className=\"hidden\"\n poster={imageURL}\n title={title}\n />\n <div className={cn(\"flex min-w-0 items-center gap-3\", coverShownBeside && \"lg:hidden\")}>\n {imageURL && (\n <img\n src={imageURL}\n alt=\"\"\n className=\"h-16 w-16 shrink-0 rounded object-contain\"\n />\n )}\n <div className=\"min-w-0 break-words\">\n <p className=\"font-semibold\">\n {chapters[currentIndex]?.name ?? title}\n </p>\n {author && (\n <p className=\"text-sm text-neutral-600 dark:text-neutral-300\">\n {author}\n </p>\n )}\n </div>\n </div>\n {playerError && (\n <div\n role=\"alert\"\n className=\"rounded-lg bg-red-50 p-3 text-red-800 dark:bg-red-950 dark:text-red-200\"\n >\n <p>{t.error}</p>\n <Button variant=\"outline\" onClick={retry}>\n {t.retry}\n </Button>\n </div>\n )}\n <input\n type=\"range\"\n min=\"0\"\n max={knownDuration || 100}\n value={position}\n disabled={!knownDuration}\n aria-label={t.progress}\n aria-valuetext={`${formatTime(position)} ${t.of} ${formatTime(knownDuration)}`}\n onChange={(event) => seekTo(Number(event.target.value))}\n />\n <section className=\"flex w-full justify-between text-sm tabular-nums\">\n <span id=\"current-time\">{formatTime(position)}</span>\n <span id=\"duration\">{formatTime(knownDuration)}</span>\n </section>\n {knownDuration > 0 && (\n <p className=\"text-sm text-neutral-600 dark:text-neutral-300\">\n {t.left === \"left\"\n ? `${leftText} ${t.left}`\n : `${t.left} ${leftText}`}{\" \"}\n · {wholeBookKnown ? t.book : t.chapter} ({speed}×)\n </p>\n )}\n <div className=\"flex flex-wrap items-center justify-center gap-2\">\n <Button\n variant=\"outline\"\n onClick={playPreviousChapter}\n disabled={currentIndex < 0}\n aria-label={t.previous}\n >\n <SkipBack className=\"h-5 w-5\" />\n </Button>\n <Button\n variant=\"outline\"\n onClick={() => seekBy(-SEEK_STEP_SECONDS)}\n aria-label={t.rewind}\n >\n −{SEEK_STEP_SECONDS}\n </Button>\n <Button\n variant=\"outline\"\n onClick={togglePlayState}\n aria-label={playState === PlayState.Paused ? t.play : t.pause}\n >\n {playState === PlayState.Paused ? (\n <Play className=\"h-5 w-5\" />\n ) : (\n <Pause className=\"h-5 w-5\" />\n )}\n </Button>\n <Button\n variant=\"outline\"\n onClick={() => seekBy(SEEK_STEP_SECONDS)}\n aria-label={t.forward}\n >\n +{SEEK_STEP_SECONDS}\n </Button>\n <Button\n variant=\"outline\"\n onClick={playNextChapter}\n disabled={currentIndex < 0 || currentIndex >= chapters.length - 1}\n aria-label={t.next}\n >\n <SkipForward className=\"h-5 w-5\" />\n </Button>\n </div>\n <div className=\"flex flex-wrap gap-3 md:grid md:grid-cols-2\">\n <label className=\"flex flex-1 items-center gap-2 text-sm md:flex-col md:items-start md:whitespace-nowrap\">\n {t.speed}\n <select\n aria-label={t.speed}\n value={speed}\n onChange={(event) => changeSpeed(Number(event.target.value))}\n >\n {SPEEDS.map((rate) => (\n <option key={rate} value={rate}>\n {rate}×\n </option>\n ))}\n </select>\n </label>\n <label className=\"flex flex-1 items-center gap-2 text-sm md:flex-col md:items-start md:whitespace-nowrap\">\n {t.sleep}\n <select\n aria-label={t.sleep}\n value={sleepMode}\n onChange={(event) => changeSleep(event.target.value)}\n >\n <option value=\"off\">{t.off}</option>\n {[15, 30, 45, 60].map((minutes) => (\n <option key={minutes} value={minutes}>\n {minutes} min\n </option>\n ))}\n <option value=\"chapter\">{t.end}</option>\n </select>\n </label>\n </div>\n {sleepMode !== \"off\" && (\n <div className=\"flex items-center justify-between gap-2 text-sm\">\n <span role=\"timer\">\n {sleepMode === \"chapter\" ? t.end : formatTime(sleepRemaining)}\n </span>\n <Button variant=\"outline\" onClick={cancelSleep}>\n {t.cancel}\n </Button>\n </div>\n )}\n {isLoading && (\n <div role=\"status\" className=\"flex justify-center\">\n <LoadingIndicator />\n </div>\n )}\n </div>\n );\n },\n);\n\nexport default AudioPlayer;\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/chat-free-pwyw/dist/chunk-Z3YOJ6NZ.js","../src/captcha/TurnstileChallenge.tsx"],"names":["challengeOrigin","host","getPanelConfig","url","TOKEN_LIFETIME_MS","parseTurnstileMessage","origin","data","action","expectedOrigin","message","TurnstileChallenge","locale","onToken","onFailure","iframe","useRef","popup","callbacks","expiry","clearExpiry","attempt","setAttempt","useState","expired","setExpired","language","src","useMemo"],"mappings":"AAAA,moBAAuC,8BCAc,+CAgE5C,SA3DOA,CAAAA,CAAgBC,CAAAA,CAAOC,gCAAAA,CAAe,CAAE,IAAA,CAAc,CACpE,GAAI,CACF,IAAMC,CAAAA,CAAM,IAAI,GAAA,CAAIF,CAAAA,EAAQ,oBAAoB,CAAA,CAChD,EAAA,C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,SAAA,CAAAC,CAAU,CAAC,CAAA,CAC/CI,CAAAA,CAAU,OAAA,CAAU,CAAE,OAAA,CAAAL,CAAAA,CAAS,SAAA,CAAAC,CAAU,CAAA,CACzC,IAAMK,CAAAA,CAASH,2BAAAA,KAA2B,CAAS,CAAA,CAC7CI,CAAAA,CAAc,CAAA,CAAA,EAAM,CAAE,MAAA,CAAO,YAAA,CAAaD,CAAAA,CAAO,OAAO,CAAA,CAAGA,CAAAA,CAAO,OAAA,CAAU,KAAA,CAAW,CAAA,CACvF,CAACE,CAAAA,CAASC,CAAU,CAAA,CAAIC,6BAAAA,CAAU,CAAA,CAClC,CAACC,CAAAA,CAASC,CAAU,CAAA,CAAIF,6BAAAA,CAAS,CAAK,CAAA,CACtCG,CAAAA,CAAWd,CAAAA,CAAO,WAAA,CAAY,CAAA,CAAE,UAAA,CAAW,IAAI,CAAA,CAAI,IAAA,CAAO,IAAA,CAC1DN,CAAAA,CAASN,CAAAA,CAAgBC,CAAI,CAAA,CAC7B0B,CAAAA,CAAMC,4BAAAA,CAAQ,CAAA,EAAM,CAAA,EAAA","file":"/home/emems/.t3/worktrees/bitsnap-react/chat-free-pwyw/dist/chunk-Z3YOJ6NZ.js","sourcesContent":[null,"import { useEffect, useMemo, useRef, useState } from \"react\";\n\nimport { getPanelConfig } from \"../panel/config\";\n\nexport type TurnstileAction = \"panel_login\" | \"free_chat_claim\";\nexport function challengeOrigin(host = getPanelConfig().host): string {\n try {\n const url = new URL(host || \"https://bitsnap.pl\");\n if (url.protocol === \"https:\" || url.protocol === \"http:\") return url.origin;\n } catch { /* Invalid host falls back to production. */ }\n return \"https://bitsnap.pl\";\n}\nconst TOKEN_LIFETIME_MS = 5 * 60 * 1000;\n\nexport function parseTurnstileMessage(origin: string, data: unknown, action: TurnstileAction, expectedOrigin = challengeOrigin()):\n | { kind: \"token\"; token: string }\n | { kind: \"disabled\" | \"failure\" }\n | null {\n if (origin !== expectedOrigin || !data || typeof data !== \"object\") return null;\n const message = data as Record<string, unknown>;\n if (message.type !== \"bitsnap:turnstile\" || message.action !== action) return null;\n if (message.disabled === true) return { kind: \"disabled\" };\n if (message.failure === true) return { kind: \"failure\" };\n return typeof message.token === \"string\" && message.token\n ? { kind: \"token\", token: message.token }\n : null;\n}\n\n/** Bitsnap-hosted Turnstile surface for merchants' own origins. */\nexport function TurnstileChallenge({ action, locale = \"pl\", host, onToken, onFailure }: {\n action: TurnstileAction;\n locale?: string;\n host?: string;\n onToken(token: string): void;\n onFailure?(): void;\n}) {\n const iframe = useRef<HTMLIFrameElement>(null);\n const popup = useRef<Window | null>(null);\n const callbacks = useRef({ onToken, onFailure });\n callbacks.current = { onToken, onFailure };\n const expiry = useRef<number | undefined>(undefined);\n const clearExpiry = () => { window.clearTimeout(expiry.current); expiry.current = undefined; };\n const [attempt, setAttempt] = useState(0);\n const [expired, setExpired] = useState(false);\n const language = locale.toLowerCase().startsWith(\"en\") ? \"en\" : \"pl\";\n const origin = challengeOrigin(host);\n const src = useMemo(() => `${origin}/challenge?action=${encodeURIComponent(action)}&origin=${encodeURIComponent(window.location.origin)}&locale=${language}`, [action, language, origin]);\n useEffect(() => {\n const onMessage = (event: MessageEvent) => {\n if (!event.source || (event.source !== iframe.current?.contentWindow && event.source !== popup.current)) return;\n const result = parseTurnstileMessage(event.origin, event.data, action, origin);\n if (result?.kind === \"failure\") { clearExpiry(); callbacks.current.onFailure?.(); return; }\n // Captcha switched off: the empty token never expires.\n if (result?.kind === \"disabled\") { clearExpiry(); callbacks.current.onToken(\"\"); return; }\n if (result?.kind === \"token\") {\n // A Turnstile token lives 5 minutes from when it was issued.\n clearExpiry();\n expiry.current = window.setTimeout(() => { expiry.current = undefined; setExpired(true); callbacks.current.onFailure?.(); }, TOKEN_LIFETIME_MS);\n callbacks.current.onToken(result.token);\n }\n };\n window.addEventListener(\"message\", onMessage);\n return () => { window.removeEventListener(\"message\", onMessage); clearExpiry(); popup.current?.close(); popup.current = null; };\n }, [action, attempt, origin]);\n return <section className=\"grid gap-2\" aria-live=\"polite\">\n <iframe ref={iframe} key={attempt} title={language === \"en\" ? \"Turnstile security check\" : \"Weryfikacja bezpieczeństwa Turnstile\"} src={src} className=\"min-h-24 w-full rounded-md border bg-background text-foreground\" />\n <button type=\"button\" className=\"text-sm underline\" onClick={() => { popup.current = window.open(src, \"bitsnap-turnstile\", \"popup,width=520,height=680\"); }}>{language === \"en\" ? \"Open in a new window\" : \"Otwórz w nowym oknie\"}</button>\n {expired && <p role=\"alert\" className=\"text-sm text-destructive\">{language === \"en\" ? \"The security check expired. Try again.\" : \"Weryfikacja wygasła. Spróbuj ponownie.\"}</p>}\n <button type=\"button\" className=\"text-sm underline\" onClick={() => { popup.current?.close(); popup.current = null; setExpired(false); setAttempt((n) => n + 1); onFailure?.(); }}>{language === \"en\" ? \"Refresh the security check\" : \"Odśwież weryfikację\"}</button>\n </section>;\n}\n"]}
1
+ {"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/chat-attachments/dist/chunk-Z3YOJ6NZ.js","../src/captcha/TurnstileChallenge.tsx"],"names":["challengeOrigin","host","getPanelConfig","url","TOKEN_LIFETIME_MS","parseTurnstileMessage","origin","data","action","expectedOrigin","message","TurnstileChallenge","locale","onToken","onFailure","iframe","useRef","popup","callbacks","expiry","clearExpiry","attempt","setAttempt","useState","expired","setExpired","language","src","useMemo"],"mappings":"AAAA,moBAAuC,8BCAc,+CAgE5C,SA3DOA,CAAAA,CAAgBC,CAAAA,CAAOC,gCAAAA,CAAe,CAAE,IAAA,CAAc,CACpE,GAAI,CACF,IAAMC,CAAAA,CAAM,IAAI,GAAA,CAAIF,CAAAA,EAAQ,oBAAoB,CAAA,CAChD,EAAA,CAAIE,CAAAA,CAAI,QAAA,GAAa,QAAA,EAAYA,CAAAA,CAAI,QAAA,GAAa,OAAA,CAAS,OAAOA,CAAAA,CAAI,MACxE,CAAA,UAAQ,CAA+C,CACvD,MAAO,oBACT,CACA,IAAMC,CAAAA,CAAoB,CAAA,CAAI,EAA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AAA,CAAc,CAAA,CAAA,EAAM,CAAE,MAAA,CAAO,YAAA,CAAaD,CAAAA,CAAO,OAAO,CAAA,CAAGA,CAAAA,CAAO,OAAA,CAAU,KAAA,CAAW,CAAA,CACvF,CAACE,CAAAA,CAASC,CAAU,CAAA,CAAIC,6BAAAA,CAAU,CAAA,CAClC,CAACC,CAAAA,CAASC,CAAU,CAAA,CAAIF,6BAAAA,CAAS,CAAK,CAAA,CACtCG,CAAAA,CAAWd,CAAAA,CAAO,WAAA,CAAY,CAAA,CAAE,UAAA,CAAW,IAAI,CAAA,CAAI,IAAA,CAAO,IAAA,CAC1DN,CAAAA,CAASN,CAAAA,CAAgBC,CAAI,CAAA,CAC7B0B,CAAAA,CAAMC,4BAAAA,CAAQ,CAAA,EAAM,CAAA,EAAA","file":"/home/emems/.t3/worktrees/bitsnap-react/chat-attachments/dist/chunk-Z3YOJ6NZ.js","sourcesContent":[null,"import { useEffect, useMemo, useRef, useState } from \"react\";\n\nimport { getPanelConfig } from \"../panel/config\";\n\nexport type TurnstileAction = \"panel_login\" | \"free_chat_claim\";\nexport function challengeOrigin(host = getPanelConfig().host): string {\n try {\n const url = new URL(host || \"https://bitsnap.pl\");\n if (url.protocol === \"https:\" || url.protocol === \"http:\") return url.origin;\n } catch { /* Invalid host falls back to production. */ }\n return \"https://bitsnap.pl\";\n}\nconst TOKEN_LIFETIME_MS = 5 * 60 * 1000;\n\nexport function parseTurnstileMessage(origin: string, data: unknown, action: TurnstileAction, expectedOrigin = challengeOrigin()):\n | { kind: \"token\"; token: string }\n | { kind: \"disabled\" | \"failure\" }\n | null {\n if (origin !== expectedOrigin || !data || typeof data !== \"object\") return null;\n const message = data as Record<string, unknown>;\n if (message.type !== \"bitsnap:turnstile\" || message.action !== action) return null;\n if (message.disabled === true) return { kind: \"disabled\" };\n if (message.failure === true) return { kind: \"failure\" };\n return typeof message.token === \"string\" && message.token\n ? { kind: \"token\", token: message.token }\n : null;\n}\n\n/** Bitsnap-hosted Turnstile surface for merchants' own origins. */\nexport function TurnstileChallenge({ action, locale = \"pl\", host, onToken, onFailure }: {\n action: TurnstileAction;\n locale?: string;\n host?: string;\n onToken(token: string): void;\n onFailure?(): void;\n}) {\n const iframe = useRef<HTMLIFrameElement>(null);\n const popup = useRef<Window | null>(null);\n const callbacks = useRef({ onToken, onFailure });\n callbacks.current = { onToken, onFailure };\n const expiry = useRef<number | undefined>(undefined);\n const clearExpiry = () => { window.clearTimeout(expiry.current); expiry.current = undefined; };\n const [attempt, setAttempt] = useState(0);\n const [expired, setExpired] = useState(false);\n const language = locale.toLowerCase().startsWith(\"en\") ? \"en\" : \"pl\";\n const origin = challengeOrigin(host);\n const src = useMemo(() => `${origin}/challenge?action=${encodeURIComponent(action)}&origin=${encodeURIComponent(window.location.origin)}&locale=${language}`, [action, language, origin]);\n useEffect(() => {\n const onMessage = (event: MessageEvent) => {\n if (!event.source || (event.source !== iframe.current?.contentWindow && event.source !== popup.current)) return;\n const result = parseTurnstileMessage(event.origin, event.data, action, origin);\n if (result?.kind === \"failure\") { clearExpiry(); callbacks.current.onFailure?.(); return; }\n // Captcha switched off: the empty token never expires.\n if (result?.kind === \"disabled\") { clearExpiry(); callbacks.current.onToken(\"\"); return; }\n if (result?.kind === \"token\") {\n // A Turnstile token lives 5 minutes from when it was issued.\n clearExpiry();\n expiry.current = window.setTimeout(() => { expiry.current = undefined; setExpired(true); callbacks.current.onFailure?.(); }, TOKEN_LIFETIME_MS);\n callbacks.current.onToken(result.token);\n }\n };\n window.addEventListener(\"message\", onMessage);\n return () => { window.removeEventListener(\"message\", onMessage); clearExpiry(); popup.current?.close(); popup.current = null; };\n }, [action, attempt, origin]);\n return <section className=\"grid gap-2\" aria-live=\"polite\">\n <iframe ref={iframe} key={attempt} title={language === \"en\" ? \"Turnstile security check\" : \"Weryfikacja bezpieczeństwa Turnstile\"} src={src} className=\"min-h-24 w-full rounded-md border bg-background text-foreground\" />\n <button type=\"button\" className=\"text-sm underline\" onClick={() => { popup.current = window.open(src, \"bitsnap-turnstile\", \"popup,width=520,height=680\"); }}>{language === \"en\" ? \"Open in a new window\" : \"Otwórz w nowym oknie\"}</button>\n {expired && <p role=\"alert\" className=\"text-sm text-destructive\">{language === \"en\" ? \"The security check expired. Try again.\" : \"Weryfikacja wygasła. Spróbuj ponownie.\"}</p>}\n <button type=\"button\" className=\"text-sm underline\" onClick={() => { popup.current?.close(); popup.current = null; setExpired(false); setAttempt((n) => n + 1); onFailure?.(); }}>{language === \"en\" ? \"Refresh the security check\" : \"Odśwież weryfikację\"}</button>\n </section>;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/chat-free-pwyw/dist/consent.js","../src/consent/react.tsx","../src/consent/core/types.ts","../src/consent/core/activate.ts","../src/consent/core/config.ts","../src/consent/core/styles.ts","../src/consent/core/ui.ts"],"names":["CONSENT_CATEGORIES","SCRIPT_SELECTOR","FRAME_SELECTOR","allowed","c","category","settled","script","resolve","run","doc","placeholder","name","value","external","loaded","activateScripts","activated","gate","loading","inline","frame","src","DEFAULT_API_HOST","DEFAULT_COLLECT_HOST","defaultConfig","THEMES","POSITIONS","HEX_COLOR","safeColor","safeUrl","url","cleanServices","services","item","cookie","mergeConfig","layers","result","layer","accent","privacy","fetchRemoteConfig","apiHost","key","timeoutMs","controller","timer","response"],"mappings":"AAAA,uuBAAwG,+BAA4B,8BCA1E,ICU7CA,CAAAA,CAAiD,CAC5D,WAAA,CACA,WAAA,CACA,aACF,CAAA,CCZA,IAAMC,EAAAA,CAAkB,4EAAA,CAClBC,EAAAA,CAAiB,wCAAA,CAEjBC,EAAAA,CAAU,CAACC,CAAAA,CAAmBC,CAAAA,CAAAA,EACjCL,CAAAA,CAAyC,QAAA,kBAASK,CAAAA,SAAY,IAAE,CAAA,EACjED,CAAAA,CAAEC,CAAgC,CAAA,CAGpC,SAASC,EAAAA,CAAQC,CAAAA,CAA0C,CACzD,OAAO,IAAI,OAAA,CAASC,CAAAA,EAA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A,OAAOD,CACT,CAmBA,MAAA,SAAsBI,EAAAA,CACpBC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAAY,GAAA,CACyB,CACrC,EAAA,CAAI,OAAO,KAAA,EAAU,UAAA,CAAY,OAAO,IAAA,CACxC,IAAMC,CAAAA,CAAa,OAAO,eAAA,EAAoB,UAAA,CAAa,IAAI,eAAA,CAAoB,KAAA,CAAA,CAC7EC,CAAAA,CAAQ,UAAA,CAAW,CAAA,CAAA,kBAAMD,CAAAA,6BAAY,KAAA,mBAAM,GAAA,CAAGD,CAAS,CAAA,CAC7D,GAAI,CACF,IAAMG,CAAAA,CAAW,MAAM,KAAA,CACrB,CAAA,EAAA;ACvFgB;AAAA;AAAA;AAIK,MAAA;AACgB,uBAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;ACoLrB","file":"/home/emems/.t3/worktrees/bitsnap-react/chat-free-pwyw/dist/consent.js","sourcesContent":[null,"import { useCallback, useRef, useSyncExternalStore } from \"react\";\nimport { useIsomorphicLayoutEffect } from \"../lib/isomorphic-layout-effect\";\nimport { createConsent } from \"./core/controller\";\nimport type {\n BitsnapConsentApi,\n ConsentChoices,\n ConsentConfig,\n ConsentOptions,\n ConsentState,\n} from \"./core/types\";\n\ndeclare global {\n interface Window {\n BitsnapConsent?: BitsnapConsentApi;\n }\n}\n\nexport type BitsnapConsentProps = {\n /** Public project key: loads the project's banner config and logs choices. */\n projectKey?: string;\n theme?: ConsentOptions[\"theme\"];\n locale?: ConsentOptions[\"locale\"];\n position?: ConsentOptions[\"position\"];\n privacyPolicyUrl?: string;\n /** `project` keeps the consent cookie per project key. */\n scope?: ConsentOptions[\"scope\"];\n apiHost?: string;\n collectHost?: string;\n /** Local config, merged over the project config. */\n config?: Partial<ConsentConfig>;\n reloadOnWithdraw?: boolean;\n /** Google Consent Mode v2: `auto` (default) is on when `gtag` or `dataLayer` already exist. */\n gcm?: ConsentOptions[\"gcm\"];\n /** Categories offered when no remote config is loaded. */\n categories?: ConsentOptions[\"categories\"];\n /** Dashboard preview: shows the banner from the local options only; touches no cookie. */\n preview?: boolean;\n /** Replaces the banner title. */\n title?: string;\n /** Replaces the banner description. */\n description?: string;\n};\n\n/** Mounts Bitsnap Consent on the page. Renders nothing itself (the banner lives in a Shadow DOM). */\nexport function BitsnapConsent(props: BitsnapConsentProps): null {\n const {\n projectKey, theme, locale, position, privacyPolicyUrl, scope, apiHost, collectHost, reloadOnWithdraw,\n gcm, preview, title, description,\n } = props;\n const configKey = JSON.stringify(props.config ?? null);\n const configRef = useRef(props.config);\n configRef.current = props.config;\n const categoriesKey = JSON.stringify(props.categories ?? null);\n const categoriesRef = useRef(props.categories);\n categoriesRef.current = props.categories;\n\n // A layout effect: the page's passive effects (first events, tracker) must find the API already there.\n useIsomorphicLayoutEffect(() => {\n // A banner from the script tag or another instance already runs on this page.\n if (window.BitsnapConsent) return;\n const api = createConsent({\n projectKey,\n theme,\n locale,\n position,\n privacyPolicyUrl,\n scope,\n apiHost,\n collectHost,\n reloadOnWithdraw,\n gcm,\n preview,\n title,\n description,\n categories: categoriesRef.current,\n config: configRef.current,\n });\n window.BitsnapConsent = api;\n return () => {\n api.destroy();\n if (window.BitsnapConsent === api) delete window.BitsnapConsent;\n };\n }, [\n projectKey, theme, locale, position, privacyPolicyUrl, scope, apiHost, collectHost, reloadOnWithdraw,\n gcm, preview, title, description, categoriesKey, configKey,\n ]);\n\n return null;\n}\n\nlet lastKey = \"null\";\nlet lastState: ConsentState | null = null;\n\nfunction getSnapshot(): ConsentState | null {\n const current = typeof window === \"undefined\" ? null : (window.BitsnapConsent?.get() ?? null);\n const key = JSON.stringify(current);\n if (key !== lastKey) {\n lastKey = key;\n lastState = current;\n }\n return lastState;\n}\n\nfunction subscribe(onChange: () => void): () => void {\n window.addEventListener(\"bitsnap:consent\", onChange);\n window.addEventListener(\"bitsnap:consent:ready\", onChange);\n return () => {\n window.removeEventListener(\"bitsnap:consent\", onChange);\n window.removeEventListener(\"bitsnap:consent:ready\", onChange);\n };\n}\n\nexport type UseConsent = {\n /** The stored choice, or `null` while there is none (or on the server). */\n consent: ConsentState | null;\n /** `true` once the visitor has made a choice that is still valid. */\n decided: boolean;\n open: () => void;\n accept: (categories?: Partial<ConsentChoices>) => void;\n acceptAll: () => void;\n rejectAll: () => void;\n reset: () => void;\n};\n\n/** Current consent state of the page, kept up to date as the visitor chooses. */\nexport function useConsent(): UseConsent {\n const consent = useSyncExternalStore(subscribe, getSnapshot, () => null);\n const open = useCallback(() => window.BitsnapConsent?.open(), []);\n const accept = useCallback((categories?: Partial<ConsentChoices>) => window.BitsnapConsent?.accept(categories), []);\n const acceptAll = useCallback(() => window.BitsnapConsent?.acceptAll(), []);\n const rejectAll = useCallback(() => window.BitsnapConsent?.rejectAll(), []);\n const reset = useCallback(() => window.BitsnapConsent?.reset(), []);\n return { consent, decided: consent !== null, open, accept, acceptAll, rejectAll, reset };\n}\n","export type ConsentCategory = \"analytics\" | \"marketing\" | \"preferences\";\n\nexport type ConsentChoices = Record<ConsentCategory, boolean>;\n\nexport type ConsentTheme = \"auto\" | \"light\" | \"dark\";\n\nexport type ConsentPosition = \"bottom\" | \"bottom-left\" | \"bottom-right\";\n\nexport type ConsentLocale = \"pl\" | \"en\";\n\nexport const CONSENT_CATEGORIES: readonly ConsentCategory[] = [\n \"analytics\",\n \"marketing\",\n \"preferences\",\n];\n\nexport const CONSENT_TEXT_KEYS = [\n \"title\",\n \"description\",\n \"acceptAll\",\n \"rejectAll\",\n \"settings\",\n \"save\",\n \"close\",\n \"necessaryTitle\",\n \"necessaryDescription\",\n \"analyticsTitle\",\n \"analyticsDescription\",\n \"marketingTitle\",\n \"marketingDescription\",\n \"preferencesTitle\",\n \"preferencesDescription\",\n \"poweredBy\",\n] as const;\n\nexport type ConsentTexts = Record<(typeof CONSENT_TEXT_KEYS)[number], string>;\n\nexport type ConsentService = {\n name: string;\n category: ConsentCategory;\n /** Cookies to delete (best effort) when the category is withdrawn. A trailing `*` matches a prefix. */\n cookies?: string[];\n};\n\nexport type ConsentConfig = {\n /** Banner version. A stored choice with a lower `bv` makes the banner ask again. */\n version: number;\n theme: ConsentTheme;\n accentColor?: string;\n position: ConsentPosition;\n privacyPolicyUrl?: string;\n categories: ConsentChoices;\n services: ConsentService[];\n texts?: Partial<Record<ConsentLocale, Partial<ConsentTexts>>>;\n poweredBy: true;\n};\n\n/** What the consent cookie holds, and what `get()` returns. */\nexport type ConsentState = {\n id: string;\n /** Unix seconds. */\n ts: number;\n /** Version of the banner the choice was made on. */\n bv: number;\n c: ConsentChoices;\n};\n\nexport type ConsentAction =\n | \"accept_all\"\n | \"reject_all\"\n | \"custom\"\n | \"withdraw\";\n\n/** `detail` of `bitsnap:consent` and the argument of `on('change')`. */\nexport type ConsentChangeDetail = ConsentState & {\n /** `reset` when the visitor's stored choice was cleared (`get()` is `null` then). */\n action: ConsentAction | \"reset\";\n};\n\nexport type ConsentOptions = {\n /** Public project key. Enables the remote config and the consent log. */\n projectKey?: string;\n theme?: ConsentTheme;\n locale?: \"auto\" | ConsentLocale;\n position?: ConsentPosition;\n privacyPolicyUrl?: string;\n /** `project` keeps one cookie per project key (`bitsnap_consent_<key>`). */\n scope?: \"global\" | \"project\";\n apiHost?: string;\n collectHost?: string;\n /** Google Consent Mode v2. `auto` is on when `gtag` or `dataLayer` already exist. */\n gcm?: \"auto\" | \"on\" | \"off\";\n /** Local overrides, merged over the defaults and the remote config. */\n config?: Partial<ConsentConfig>;\n /** Categories used when no remote config is loaded. */\n categories?: Partial<ConsentChoices>;\n reloadOnWithdraw?: boolean;\n /**\n * Dashboard preview: shows the banner at once from the local options, never\n * reads or writes the cookie, loads no remote config, sends no consent log,\n * and the buttons only close the banner.\n */\n preview?: boolean;\n /** Replaces the banner title (current locale, non-empty values only). */\n title?: string;\n /** Replaces the banner description (current locale, non-empty values only). */\n description?: string;\n};\n\nexport type BitsnapConsentApi = {\n /**\n * Whose choice this banner holds: `project` keeps one cookie per project key\n * (`bitsnap_consent_<key>`), `global` the site-wide `bitsnap_consent`.\n */\n readonly scope: \"global\" | \"project\";\n /** The bare public project key the banner was started with, if any (`pk_` stripped). */\n readonly projectKey: string | null;\n get(): ConsentState | null;\n /**\n * `true` when the visitor refused `category`, also in a choice made on an older banner\n * version (which `get()` no longer returns) that they have not answered again yet.\n */\n denied(category: ConsentCategory): boolean;\n on(event: \"change\", fn: (detail: ConsentChangeDetail) => void): () => void;\n open(): void;\n close(): void;\n accept(categories?: Partial<ConsentChoices>): void;\n acceptAll(): void;\n rejectAll(): void;\n reset(): void;\n /** Resolves with the stored choice (or `null`) once config and stored choice are applied. */\n ready: Promise<ConsentState | null>;\n destroy(): void;\n};\n","import { CONSENT_CATEGORIES, type ConsentChoices } from \"./types\";\n\nconst SCRIPT_SELECTOR = 'script[type=\"text/plain\"][data-bitsnap-consent]:not([data-bitsnap-queued])';\nconst FRAME_SELECTOR = \"iframe[data-bitsnap-consent][data-src]\";\n\nconst allowed = (c: ConsentChoices, category: string | null): boolean =>\n (CONSENT_CATEGORIES as readonly string[]).includes(category ?? \"\") &&\n c[category as keyof ConsentChoices];\n\n/** Settles when the script has loaded or failed: a broken script must not block the ones after it. */\nfunction settled(script: HTMLScriptElement): Promise<void> {\n return new Promise((resolve) => {\n script.addEventListener(\"load\", () => resolve(), { once: true });\n script.addEventListener(\"error\", () => resolve(), { once: true });\n });\n}\n\n/** Swaps the placeholder for a live script; resolves once an external one has loaded. */\nfunction run(doc: Document, placeholder: HTMLScriptElement): Promise<void> | undefined {\n const script = doc.createElement(\"script\");\n for (const { name, value } of Array.from(placeholder.attributes)) {\n if (name === \"type\" || name === \"data-bitsnap-queued\") continue;\n if (name === \"data-type\") {\n // The embed writes the original `type=\"module\"` here, as `type` itself is `text/plain`.\n if (value === \"module\") script.setAttribute(\"type\", \"module\");\n } else if (name === \"data-src\") script.setAttribute(\"src\", value);\n else script.setAttribute(name, value);\n }\n if (placeholder.nonce) script.nonce = placeholder.nonce;\n const external = script.hasAttribute(\"src\");\n if (external) {\n // Dynamic scripts are async by default; keep the order of the page.\n if (!placeholder.hasAttribute(\"async\")) script.async = false;\n } else {\n script.text = placeholder.text;\n }\n const loaded = external ? settled(script) : undefined;\n placeholder.parentNode?.replaceChild(script, placeholder);\n return loaded;\n}\n\n/**\n * Turns the consented placeholders into live elements:\n * `<script type=\"text/plain\" data-bitsnap-consent=\"marketing\" [data-src] [data-type=\"module\"]>` becomes\n * a real script (attributes copied, `type` dropped or restored from `data-type`, `data-src` -> `src`),\n * and `<iframe data-src>` gets its `src`.\n * Placeholders run in document order: an inline script waits for the external scripts before it\n * (`<script src=lib.js>` then `<script>Lib.init()</script>`), external ones only follow each other.\n */\nexport function activateScripts(doc: Document, c: ConsentChoices): number {\n let activated = 0;\n try {\n /** Set once a placeholder had to wait: everything after it queues behind it. */\n let gate: Promise<void> | null = null;\n /** External scripts inserted since the last inline one. */\n let loading: Promise<void>[] = [];\n doc.querySelectorAll<HTMLScriptElement>(SCRIPT_SELECTOR).forEach((placeholder) => {\n if (!allowed(c, placeholder.getAttribute(\"data-bitsnap-consent\"))) return;\n activated++;\n const inline = !placeholder.hasAttribute(\"data-src\") && !placeholder.hasAttribute(\"src\");\n if (gate || (inline && loading.length > 0)) {\n // Marked so that another call (a later choice) does not queue it again.\n placeholder.setAttribute(\"data-bitsnap-queued\", \"\");\n gate = (gate ?? Promise.all(loading).then(() => {})).then(() => {\n try {\n return run(doc, placeholder);\n } catch {\n // never throw into the host page\n }\n });\n loading = [];\n return;\n }\n const loaded = run(doc, placeholder);\n if (loaded) loading.push(loaded);\n });\n doc.querySelectorAll<HTMLIFrameElement>(FRAME_SELECTOR).forEach((frame) => {\n if (!allowed(c, frame.getAttribute(\"data-bitsnap-consent\"))) return;\n const src = frame.getAttribute(\"data-src\");\n if (src && frame.getAttribute(\"src\") !== src) {\n frame.setAttribute(\"src\", src);\n frame.removeAttribute(\"data-src\");\n activated++;\n }\n });\n } catch {\n // never throw into the host page\n }\n return activated;\n}\n","import {\n CONSENT_CATEGORIES,\n type ConsentChoices,\n type ConsentConfig,\n type ConsentService,\n} from \"./types\";\n\nexport const DEFAULT_API_HOST = \"https://bitsnap.pl\";\nexport const DEFAULT_COLLECT_HOST = \"https://collect.bitsnap.pl\";\n\nexport function defaultConfig(): ConsentConfig {\n return {\n version: 1,\n theme: \"auto\",\n position: \"bottom\",\n categories: { analytics: true, marketing: true, preferences: false },\n services: [],\n poweredBy: true,\n };\n}\n\nconst THEMES = [\"auto\", \"light\", \"dark\"];\nconst POSITIONS = [\"bottom\", \"bottom-left\", \"bottom-right\"];\n\nconst HEX_COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;\n\nexport function safeColor(value: unknown): string | undefined {\n return typeof value === \"string\" && HEX_COLOR.test(value.trim())\n ? value.trim()\n : undefined;\n}\n\n/** Only http(s) and relative URLs may end up in the banner. */\nexport function safeUrl(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const url = value.trim();\n return /^(?:https?:\\/\\/|\\/(?!\\/)|#|\\?)/i.test(url) ? url : undefined;\n}\n\nfunction cleanServices(value: unknown): ConsentService[] {\n if (!Array.isArray(value)) return [];\n const services: ConsentService[] = [];\n for (const item of value) {\n if (\n item &&\n typeof item.name === \"string\" &&\n (CONSENT_CATEGORIES as readonly string[]).includes(item.category)\n ) {\n services.push({\n name: item.name,\n category: item.category,\n cookies: Array.isArray(item.cookies)\n ? item.cookies.filter((cookie: unknown) => typeof cookie === \"string\")\n : undefined,\n });\n }\n }\n return services;\n}\n\n/** Layers partial configs (later wins) over the defaults, dropping invalid values. */\nexport function mergeConfig(\n ...layers: (Partial<ConsentConfig> | null | undefined)[]\n): ConsentConfig {\n const result = defaultConfig();\n for (const layer of layers) {\n if (!layer || typeof layer !== \"object\") continue;\n if (typeof layer.version === \"number\" && layer.version >= 0) {\n result.version = Math.floor(layer.version);\n }\n if (THEMES.includes(layer.theme as string)) result.theme = layer.theme!;\n if (POSITIONS.includes(layer.position as string)) result.position = layer.position!;\n const accent = safeColor(layer.accentColor);\n if (accent) result.accentColor = accent;\n const privacy = safeUrl(layer.privacyPolicyUrl);\n if (privacy) result.privacyPolicyUrl = privacy;\n if (layer.categories && typeof layer.categories === \"object\") {\n for (const category of CONSENT_CATEGORIES) {\n if (typeof layer.categories[category] === \"boolean\") {\n result.categories[category] = layer.categories[category];\n }\n }\n }\n if (layer.services !== undefined) result.services = cleanServices(layer.services);\n if (layer.texts && typeof layer.texts === \"object\") result.texts = layer.texts;\n }\n return result;\n}\n\nexport function parseCategoryList(value: string | null | undefined): ConsentChoices {\n const wanted = (value ?? \"\").split(\",\").map((item) => item.trim());\n return {\n analytics: wanted.includes(\"analytics\"),\n marketing: wanted.includes(\"marketing\"),\n preferences: wanted.includes(\"preferences\"),\n };\n}\n\n/** What `GET /api/consent/config` answers: whether the banner is on, and its config. */\nexport type RemoteConsentConfig = {\n /** `false` when the project turned the banner off: nothing is shown, stored choices still apply. */\n enabled: boolean;\n config: Partial<ConsentConfig> | null;\n};\n\n/** Loads the project's banner config. Resolves to `null` on any failure or after the timeout. */\nexport async function fetchRemoteConfig(\n apiHost: string,\n key: string,\n timeoutMs = 3000,\n): Promise<RemoteConsentConfig | null> {\n if (typeof fetch !== \"function\") return null;\n const controller = typeof AbortController === \"function\" ? new AbortController() : undefined;\n const timer = setTimeout(() => controller?.abort(), timeoutMs);\n try {\n const response = await fetch(\n `${apiHost.replace(/\\/+$/, \"\")}/api/consent/config?key=${encodeURIComponent(key)}`,\n { signal: controller?.signal, credentials: \"omit\" },\n );\n if (!response.ok) return null;\n const body = await response.json();\n if (!body || typeof body !== \"object\") return null;\n const config = body.config && typeof body.config === \"object\" ? body.config : null;\n const enabled = body.enabled !== false;\n return config || !enabled ? { enabled, config } : null;\n } catch {\n return null;\n } finally {\n clearTimeout(timer);\n }\n}\n","/** Colors of both themes. Every text/background pair is checked against WCAG AA in the tests. */\nexport const PALETTE = {\n light: {\n bg: \"#ffffff\",\n fg: \"#14171c\",\n muted: \"#495260\",\n border: \"#c9ced6\",\n off: \"#6b7280\",\n thumb: \"#ffffff\",\n accent: \"#1d4ed8\",\n onAccent: \"#ffffff\",\n link: \"#1d4ed8\",\n },\n dark: {\n bg: \"#171a20\",\n fg: \"#f1f3f6\",\n muted: \"#b7beca\",\n border: \"#3a404b\",\n off: \"#8b93a1\",\n thumb: \"#171a20\",\n accent: \"#8ab4ff\",\n onAccent: \"#0b1220\",\n link: \"#9dc0ff\",\n },\n} as const;\n\nconst vars = (p: (typeof PALETTE)[\"light\"]) =>\n `--bg:${p.bg};--fg:${p.fg};--muted:${p.muted};--border:${p.border};--off:${p.off};--thumb:${p.thumb};--accent:${p.accent};--on-accent:${p.onAccent};--link:${p.link};--focus:${p.accent}`;\n\nexport const STYLES = `\n:host{all:initial}\n*{box-sizing:border-box}\n[hidden]{display:none!important}\n.root{${vars(PALETTE.light)};position:fixed;inset:0;pointer-events:none;z-index:2147483000;font:14px/1.5 system-ui,-apple-system,\"Segoe UI\",Roboto,\"Helvetica Neue\",Arial,sans-serif;color:var(--fg);-webkit-text-size-adjust:100%}\n.root[data-theme=dark]{${vars(PALETTE.dark)};color-scheme:dark}\nbutton,input{font:inherit;color:inherit}\n.banner,.overlay{pointer-events:auto}\n@supports (color:color-mix(in srgb,red 50%,blue)){::selection{background:color-mix(in srgb,var(--accent) 24%,transparent)}}\n.banner{position:absolute;background:var(--bg);color:var(--fg);max-height:92vh;overflow:auto;outline:none}\n.banner.enter{animation:in .22s ease-out}\n.banner.closing{animation:out .2s ease-in forwards;pointer-events:none}\n.bottom{left:0;right:0;bottom:0;border-top:1px solid var(--border);box-shadow:0 -8px 28px rgba(15,23,42,.08);padding:20px 24px calc(20px + env(safe-area-inset-bottom,0px))}\n.root[data-theme=dark] .bottom{box-shadow:0 -8px 28px rgba(0,0,0,.4)}\n.bottom .inner{display:grid;grid-template-columns:minmax(min(100%,42ch),1fr) auto;grid-template-areas:\"text actions\" \"foot actions\";gap:4px 40px;align-items:center;max-width:1120px;margin:0 auto}\n.bottom .text{max-width:68ch}\n.bottom .btn,.bottom .link-btn{flex:0 0 auto}\n.card{bottom:16px;width:min(400px,calc(100vw - 32px));border:1px solid var(--border);border-radius:14px;padding:20px;box-shadow:0 12px 32px rgba(15,23,42,.14)}\n.root[data-theme=dark] .card{box-shadow:0 12px 32px rgba(0,0,0,.45)}\n.bottom-left{left:16px}\n.bottom-right{right:16px}\n.card .inner{display:flex;flex-direction:column;gap:16px}\n.text{grid-area:text}\n.actions{grid-area:actions;display:flex;flex-wrap:wrap;gap:8px;align-items:center;justify-content:flex-end}\n.card .actions{justify-content:stretch}\n.foot{grid-area:foot}\n.title{overflow-wrap:anywhere;font-size:17px;font-weight:650;line-height:1.35;letter-spacing:-.01em;text-wrap:balance;margin:0 0 6px}\n.desc{overflow-wrap:anywhere;margin:0;color:var(--muted);line-height:1.55;text-wrap:pretty}\n.desc a{color:var(--link);text-decoration:underline;text-underline-offset:3px}\n.btn,.link-btn{min-height:38px;padding:0 16px;border-radius:8px;font-size:13.5px;font-weight:600;cursor:pointer;white-space:nowrap;transition:background-color .12s ease-out,filter .12s ease-out,border-color .12s ease-out}\n.btn{border:2px solid var(--accent);background:var(--accent);color:var(--on-accent);flex:1 1 150px}\n.btn:hover{filter:brightness(.93)}\n.btn:active{filter:brightness(.87)}\n.link-btn{border:1px solid var(--off);background:transparent;color:var(--fg);text-decoration:none}\n.link-btn:hover{border-color:var(--fg)}\n@supports (color:color-mix(in srgb,red 50%,blue)){.link-btn:hover{background:color-mix(in srgb,var(--fg) 9%,transparent)}.link-btn:active{background:color-mix(in srgb,var(--fg) 14%,transparent)}}\n.card .link-btn{flex:1 1 100%}\nbutton:focus-visible,a:focus-visible,.dialog:focus-visible{outline:2px solid var(--focus);outline-offset:2px}\n.foot{font-size:12px;color:var(--muted);padding-top:8px}\n.foot a{color:var(--muted);text-decoration:none;display:inline-flex;align-items:center;gap:5px;vertical-align:middle}\n.foot a:hover{text-decoration:underline}\n.foot b{color:var(--fg);font-weight:700;letter-spacing:-.01em}\n.foot svg{display:block}\n.overlay{position:absolute;inset:0;background:rgba(10,12,16,.58);display:flex;align-items:center;justify-content:center;padding:16px}\n.overlay.enter{animation:fade .2s ease-out}\n.overlay.closing{animation:fadeout .2s ease-in forwards;pointer-events:none}\n.dialog{background:var(--bg);color:var(--fg);width:100%;max-width:560px;max-height:min(92vh,760px);display:flex;flex-direction:column;border-radius:16px;box-shadow:0 16px 48px rgba(0,0,0,.35);outline:none}\n.dialog.enter{animation:in .22s ease-out}\n.d-head{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:16px 8px 8px 24px}\n.d-head .title{margin:0;font-size:18px}\n.x{width:44px;height:44px;border:0;border-radius:10px;background:none;cursor:pointer;display:flex;align-items:center;justify-content:center;flex:none}\n.x:hover{background:var(--border)}\n.d-body{overflow:auto;padding:0 24px 8px;flex:1}\n.cat{border-top:1px solid var(--border);padding:10px 0 14px}\n.row{display:flex;align-items:center;justify-content:space-between;gap:12px}\n.cat-title{font-weight:600;font-size:15px}\n.always{font-size:12px;color:var(--muted);margin-right:4px}\n.cat p{margin:0;color:var(--muted)}\n.cat .svc{margin-top:6px;font-size:13px}\n.cat .svc b{font-weight:600;color:var(--fg)}\n.switch{position:relative;width:52px;height:44px;display:flex;align-items:center;justify-content:flex-end;flex:none}\n.switch input{position:absolute;inset:0;width:100%;height:100%;margin:0;opacity:0;cursor:pointer}\n.switch input:disabled{cursor:default}\n.track{width:44px;height:24px;border-radius:12px;background:var(--off);position:relative;transition:background .15s}\n.track::after{content:\"\";position:absolute;top:3px;left:3px;width:18px;height:18px;border-radius:50%;background:var(--thumb);transition:transform .15s}\ninput:checked+.track{background:var(--accent)}\ninput:checked+.track::after{transform:translateX(20px);background:var(--on-accent)}\ninput:disabled+.track{opacity:.6}\ninput:focus-visible+.track{outline:2px solid var(--focus);outline-offset:2px}\n.d-foot{display:flex;flex-direction:column;gap:8px;padding:12px 24px 16px;border-top:1px solid var(--border)}\n.d-foot .actions{justify-content:stretch}\n@keyframes in{from{opacity:0;transform:translateY(12px)}to{opacity:1;transform:none}}\n@keyframes fade{from{opacity:0}to{opacity:1}}\n@keyframes out{from{opacity:1;transform:none}to{opacity:0;transform:translateY(12px)}}\n@keyframes fadeout{from{opacity:1}to{opacity:0}}\n@media(max-width:960px){\n.bottom .inner{grid-template-columns:minmax(0,1fr);grid-template-areas:\"text\" \"actions\" \"foot\";gap:14px}\n.bottom .actions{justify-content:flex-start}\n}\n@media(max-width:640px){\n.bottom{padding:16px 16px calc(16px + env(safe-area-inset-bottom,0px))}\n.bottom .inner{gap:12px}\n.bottom .actions{justify-content:stretch}\n.bottom .btn{flex:1 1 130px}\n.bottom .link-btn{flex:1 1 100%}\n.card{left:8px;right:8px;bottom:8px;width:auto}\n.overlay{align-items:flex-end;padding:0}\n.dialog{max-width:none;border-radius:16px 16px 0 0;max-height:92vh}\n.d-head{padding-left:16px}\n.d-body{padding:0 16px 8px}\n.d-foot{padding:12px 16px calc(16px + env(safe-area-inset-bottom,0px))}\n.btn{flex-basis:130px}\n.btn,.link-btn{padding:0 12px;min-height:40px}\n}\n@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important;transition:none!important}}\n`.replace(/\\n/g, \"\");\n","import { contrastRatio, onColor } from \"./contrast\";\nimport { UI_LABELS } from \"./texts\";\nimport { PALETTE, STYLES } from \"./styles\";\nimport {\n CONSENT_CATEGORIES,\n type ConsentCategory,\n type ConsentChoices,\n type ConsentConfig,\n type ConsentLocale,\n type ConsentTexts,\n} from \"./types\";\n\nexport type UIOptions = {\n doc: Document;\n config: ConsentConfig;\n texts: ConsentTexts;\n locale: ConsentLocale;\n /** Current choice, used to preset the toggles. */\n getChoices(): ConsentChoices | null;\n /** Whether a valid choice exists, i.e. closing the settings must not bring back the banner. */\n hasChoice(): boolean;\n onAcceptAll(): void;\n onRejectAll(): void;\n onSave(choices: ConsentChoices): void;\n};\n\nexport type ConsentUI = {\n /** `focus` moves keyboard focus into the banner; leave it off when the banner opens on page load. */\n showBanner(focus?: boolean): void;\n showSettings(): void;\n hide(): void;\n destroy(): void;\n};\n\nconst WORDMARK =\n '<svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" aria-hidden=\"true\"><rect width=\"16\" height=\"16\" rx=\"4\" fill=\"currentColor\" style=\"color:var(--fg)\"/><circle cx=\"8\" cy=\"8\" r=\"3\" fill=\"var(--bg)\"/></svg>';\n\nconst CLOSE_ICON =\n '<svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" aria-hidden=\"true\"><path d=\"M3 3l10 10M13 3L3 13\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" fill=\"none\"/></svg>';\n\nconst FOCUSABLE = \"button:not([disabled]),input:not([disabled]),a[href]\";\n\n/**\n * How long the exit animation runs. The banner and the settings layer fade\n * out before they disappear, so the page does not blink.\n */\nexport const EXIT_ANIMATION_MS = 200;\n\n/** A running exit animation: the node, its listener and its fallback timer. */\ntype Exit = {\n node: HTMLElement;\n listener: (event: Event) => void;\n timer: number | undefined;\n};\n\nexport function createUI(options: UIOptions): ConsentUI {\n const { doc, config, texts, locale } = options;\n const labels = UI_LABELS[locale];\n let host: HTMLElement | null = null;\n let shadow: ShadowRoot | null = null;\n let root: HTMLElement;\n let banner: HTMLElement;\n let overlay: HTMLElement;\n let dialog: HTMLElement;\n let settingsButton: HTMLElement;\n let layer: \"none\" | \"banner\" | \"settings\" = \"none\";\n let opener: HTMLElement | null = null;\n let media: MediaQueryList | null = null;\n const toggles = new Map<ConsentCategory, HTMLInputElement>();\n /** The exit animations running right now; at most one per node. */\n const exits: Exit[] = [];\n\n function el<K extends keyof HTMLElementTagNameMap>(\n tag: K,\n props: Record<string, string> = {},\n ...children: (Node | string)[]\n ): HTMLElementTagNameMap[K] {\n const node = doc.createElement(tag);\n for (const key of Object.keys(props)) {\n if (key === \"class\") node.className = props[key];\n else node.setAttribute(key, props[key]);\n }\n for (const child of children) node.append(child);\n return node;\n }\n\n function button(cls: string, text: string, onClick: () => void) {\n const node = el(\"button\", { type: \"button\", class: cls }, text);\n node.addEventListener(\"click\", onClick);\n return node;\n }\n\n function powered(): HTMLElement {\n const link = el(\"a\", {\n href: `https://bitsnap.pl/?utm_source=consent_banner&utm_medium=referral&utm_content=${encodeURIComponent(doc.location?.hostname ?? \"\")}`,\n target: \"_blank\",\n rel: \"noopener\",\n });\n link.append(texts.poweredBy + \" \");\n link.insertAdjacentHTML(\"beforeend\", WORDMARK);\n link.append(el(\"b\", {}, \"bitsnap\"));\n return el(\"div\", { class: \"foot\" }, link);\n }\n\n function description(): HTMLElement {\n const node = el(\"p\", { class: \"desc\", id: \"d\" }, texts.description);\n if (config.privacyPolicyUrl) {\n node.append(\n \" \",\n el(\n \"a\",\n { href: config.privacyPolicyUrl, target: \"_blank\", rel: \"noopener\" },\n labels.privacy,\n ),\n );\n }\n return node;\n }\n\n function buildBanner() {\n settingsButton = button(\"link-btn\", texts.settings, () => showSettings());\n banner = el(\n \"div\",\n {\n class: `banner ${config.position === \"bottom\" ? \"bottom\" : `card ${config.position}`}`,\n // Not modal: the page stays usable, so it is a live region, not a dialog.\n role: \"region\",\n \"aria-live\": \"polite\",\n \"aria-labelledby\": \"t\",\n \"aria-describedby\": \"d\",\n tabindex: \"-1\",\n },\n el(\n \"div\",\n { class: \"inner\" },\n el(\"div\", { class: \"text\" }, el(\"div\", { class: \"title\", id: \"t\" }, texts.title), description()),\n el(\n \"div\",\n { class: \"actions\" },\n button(\"btn\", texts.acceptAll, options.onAcceptAll),\n button(\"btn\", texts.rejectAll, options.onRejectAll),\n settingsButton,\n ),\n powered(),\n ),\n );\n }\n\n function category(id: ConsentCategory | \"necessary\"): HTMLElement {\n const services = config.services.filter((service) => service.category === id);\n const input = el(\"input\", { type: \"checkbox\", role: \"switch\", \"aria-labelledby\": `l-${id}`, \"aria-describedby\": `p-${id}` });\n if (id === \"necessary\") {\n input.checked = true;\n input.disabled = true;\n } else {\n toggles.set(id, input);\n }\n const node = el(\n \"div\",\n { class: \"cat\" },\n el(\n \"div\",\n { class: \"row\" },\n el(\"span\", { class: \"cat-title\", id: `l-${id}` }, texts[`${id}Title` as keyof ConsentTexts]),\n el(\n \"span\",\n { style: \"display:flex;align-items:center\" },\n ...(id === \"necessary\" ? [el(\"span\", { class: \"always\" }, labels.always)] : []),\n el(\"label\", { class: \"switch\" }, input, el(\"span\", { class: \"track\" })),\n ),\n ),\n el(\"p\", { id: `p-${id}` }, texts[`${id}Description` as keyof ConsentTexts]),\n );\n if (services.length > 0) {\n node.append(\n el(\"p\", { class: \"svc\" }, el(\"b\", {}, `${labels.services}: `), services.map((s) => s.name).join(\", \")),\n );\n }\n return node;\n }\n\n function buildSettings() {\n const close = el(\"button\", { type: \"button\", class: \"x\", \"aria-label\": texts.close });\n close.insertAdjacentHTML(\"beforeend\", CLOSE_ICON);\n close.addEventListener(\"click\", () => closeSettings());\n const body = el(\"div\", { class: \"d-body\" }, category(\"necessary\"));\n for (const id of CONSENT_CATEGORIES) {\n if (config.categories[id]) body.append(category(id));\n }\n dialog = el(\n \"div\",\n { class: \"dialog\", role: \"dialog\", \"aria-modal\": \"true\", \"aria-labelledby\": \"st\", tabindex: \"-1\" },\n el(\"div\", { class: \"d-head\" }, el(\"div\", { class: \"title\", id: \"st\" }, texts.settings), close),\n body,\n el(\n \"div\",\n { class: \"d-foot\" },\n el(\n \"div\",\n { class: \"actions\" },\n button(\"btn\", texts.save, () => options.onSave(readToggles())),\n button(\"btn\", texts.acceptAll, options.onAcceptAll),\n button(\"btn\", texts.rejectAll, options.onRejectAll),\n ),\n powered(),\n ),\n );\n overlay = el(\"div\", { class: \"overlay\" }, dialog);\n overlay.addEventListener(\"mousedown\", (event) => {\n if (event.target === overlay) closeSettings();\n });\n }\n\n function readToggles(): ConsentChoices {\n const choices = { analytics: false, marketing: false, preferences: false };\n toggles.forEach((input, key) => (choices[key] = input.checked));\n return choices;\n }\n\n function applyTheme() {\n const dark = config.theme === \"dark\" || (config.theme === \"auto\" && !!media?.matches);\n root.setAttribute(\"data-theme\", dark ? \"dark\" : \"light\");\n applyAccent(dark);\n }\n\n /** A custom accent that is too faint on the dark background gives way to the dark theme's own. */\n function applyAccent(dark: boolean) {\n const accent = config.accentColor;\n if (!accent) return;\n if (dark && contrastRatio(accent, PALETTE.dark.bg) < 3) {\n for (const name of [\"--accent\", \"--focus\", \"--on-accent\"]) root.style.removeProperty(name);\n return;\n }\n root.style.setProperty(\"--accent\", accent);\n root.style.setProperty(\"--focus\", accent);\n root.style.setProperty(\"--on-accent\", onColor(accent));\n }\n\n function ensure() {\n if (host) return;\n host = el(\"div\", { id: \"bitsnap-consent\", \"data-bitsnap-consent-host\": \"\" });\n shadow = host.attachShadow({ mode: \"open\" });\n shadow.append(el(\"style\", {}, STYLES));\n root = el(\"div\", { class: \"root\", lang: locale });\n buildBanner();\n buildSettings();\n banner.hidden = true;\n overlay.hidden = true;\n root.append(banner, overlay);\n shadow.append(root);\n if (typeof doc.defaultView?.matchMedia === \"function\") {\n media = doc.defaultView.matchMedia(\"(prefers-color-scheme: dark)\");\n media.addEventListener?.(\"change\", applyTheme);\n }\n applyTheme();\n doc.body.append(host);\n }\n\n function focusables(): HTMLElement[] {\n return Array.from(dialog.querySelectorAll<HTMLElement>(FOCUSABLE));\n }\n\n /** Whether the visitor asked for less motion: the layers then come and go at once. */\n function reducedMotion(): boolean {\n try {\n return doc.defaultView?.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches === true;\n } catch {\n return false;\n }\n }\n\n /** Stops a running exit animation; the node stays where it is. */\n function stopExit(node: HTMLElement) {\n const index = exits.findIndex((exit) => exit.node === node);\n if (index === -1) return;\n const [exit] = exits.splice(index, 1);\n exit.node.removeEventListener(\"animationend\", exit.listener);\n if (exit.timer !== undefined) doc.defaultView?.clearTimeout(exit.timer);\n exit.node.classList.remove(\"closing\");\n }\n\n /** Hides the node at once, without an animation. */\n function hideNow(node: HTMLElement) {\n stopExit(node);\n node.hidden = true;\n }\n\n /**\n * Fades the node out and hides it when the animation ends. The timer is the\n * fallback for a browser that sends no event (a hidden tab, a reduced\n * motion setting): the layer always disappears.\n */\n function exitTo(node: HTMLElement) {\n stopExit(node);\n if (node.hidden) return;\n if (reducedMotion()) {\n node.hidden = true;\n return;\n }\n node.classList.add(\"closing\");\n const listener = (event: Event) => {\n // Another animation of a child ends first; only our own counts.\n if (event.target !== node) return;\n finish();\n };\n const timer = doc.defaultView?.setTimeout(finish, EXIT_ANIMATION_MS + 120);\n function finish() {\n stopExit(node);\n node.hidden = true;\n }\n node.addEventListener(\"animationend\", listener);\n exits.push({ node, listener, timer });\n }\n\n /** Shows the node and plays the entrance animation again. */\n function enter(node: HTMLElement) {\n stopExit(node);\n node.hidden = false;\n // The class has to leave and come back, or the animation does not restart.\n node.classList.remove(\"enter\");\n void node.offsetWidth;\n node.classList.add(\"enter\");\n }\n\n function onKeydown(event: KeyboardEvent) {\n if (layer !== \"settings\") return;\n if (event.key === \"Escape\") {\n event.preventDefault();\n closeSettings();\n return;\n }\n if (event.key !== \"Tab\") return;\n const items = focusables();\n if (items.length === 0) return;\n const active = shadow?.activeElement as HTMLElement | null;\n const first = items[0];\n const last = items[items.length - 1];\n const outside = !active || !dialog.contains(active);\n if (event.shiftKey && (outside || active === first || active === dialog)) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && (outside || active === last)) {\n event.preventDefault();\n first.focus();\n }\n }\n\n function showBanner(focus = false) {\n try {\n ensure();\n layer = \"banner\";\n doc.removeEventListener(\"keydown\", onKeydown, true);\n hideNow(overlay);\n enter(banner);\n if (focus) banner.focus({ preventScroll: true });\n } catch {\n // never throw into the host page\n }\n }\n\n function showSettings() {\n try {\n ensure();\n if (layer !== \"settings\") {\n const active = doc.activeElement as HTMLElement | null;\n opener = active && active !== host && active !== doc.body ? active : null;\n }\n const current = options.getChoices();\n toggles.forEach((input, key) => (input.checked = !!current?.[key]));\n layer = \"settings\";\n hideNow(banner);\n enter(overlay);\n enter(dialog);\n doc.addEventListener(\"keydown\", onKeydown, true);\n dialog.focus({ preventScroll: true });\n } catch {\n // never throw into the host page\n }\n }\n\n function closeSettings() {\n if (layer !== \"settings\") return;\n doc.removeEventListener(\"keydown\", onKeydown, true);\n exitTo(overlay);\n if (options.hasChoice()) {\n layer = \"none\";\n opener?.focus?.({ preventScroll: true });\n } else {\n layer = \"banner\";\n enter(banner);\n settingsButton.focus({ preventScroll: true });\n }\n }\n\n function hide() {\n if (!host) return;\n doc.removeEventListener(\"keydown\", onKeydown, true);\n const wasSettings = layer === \"settings\";\n layer = \"none\";\n exitTo(banner);\n exitTo(overlay);\n if (wasSettings) opener?.focus?.({ preventScroll: true });\n }\n\n function destroy() {\n doc.removeEventListener(\"keydown\", onKeydown, true);\n media?.removeEventListener?.(\"change\", applyTheme);\n while (exits.length > 0) stopExit(exits[0]!.node);\n host?.remove();\n host = null;\n shadow = null;\n layer = \"none\";\n }\n\n return { showBanner, showSettings, hide, destroy };\n}\n"]}
1
+ {"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/chat-attachments/dist/consent.js","../src/consent/react.tsx","../src/consent/core/types.ts","../src/consent/core/activate.ts","../src/consent/core/config.ts","../src/consent/core/styles.ts","../src/consent/core/ui.ts"],"names":["CONSENT_CATEGORIES","SCRIPT_SELECTOR","FRAME_SELECTOR","allowed","c","category","settled","script","resolve","run","doc","placeholder","name","value","external","loaded","activateScripts","activated","gate","loading","inline","frame","src","DEFAULT_API_HOST","DEFAULT_COLLECT_HOST","defaultConfig","THEMES","POSITIONS","HEX_COLOR","safeColor","safeUrl","url","cleanServices","services","item","cookie","mergeConfig","layers","result","layer","accent","privacy","fetchRemoteConfig","apiHost","key","timeoutMs","controller","timer","response"],"mappings":"AAAA,uuBAAwG,+BAA4B,8BCA1E,ICU7CA,CAAAA,CAAiD,CAC5D,WAAA,CACA,WAAA,CACA,aACF,CAAA,CCZA,IAAMC,EAAAA,CAAkB,4EAAA,CAClBC,EAAAA,CAAiB,wCAAA,CAEjBC,EAAAA,CAAU,CAACC,CAAAA,CAAmBC,CAAAA,CAAAA,EACjCL,CAAAA,CAAyC,QAAA,kBAASK,CAAAA,SAAY,IAAE,CAAA,EACjED,CAAAA,CAAEC,CAAgC,CAAA,CAGpC,SAASC,EAAAA,CAAQC,CAAAA,CAA0C,CACzD,OAAO,IAAI,OAAA,CAASC,CAAAA,EAAY,CAC9BD,CAAAA,CAAO,gBAAA,CAAiB,MAAA,CAAQ,CAAA,CAAA,EAAMC,CAAAA,CAAQ,CAAA,CAAG,CAAE,IAAA,CAAM,CAAA,CAAK,CAAC,CAAA,CAC/DD,CAAAA,CAAO,gBAAA,CAAiB,OAAA,CAAS,CAAA,CAAA,EAAMC,CAAAA,CAAQ,CAAA,CAAG,CAAE,IAAA,CAAM,CAAA,CAAK,CAAC,CAClE,CAAC,CACH,CAGA,SAASC,EAAAA,CAAIC,CAAAA,CAAeC,CAAAA,CAA2D,CACrF,IAAMJ,CAAAA,CAASG,CAAAA,CAAI,aAAA,CAAc,QAAQ,CAAA,CACzC,GAAA,CAAA,GAAW,CAAE,IAAA,CAAAE,CAAAA,CAAM,KAAA,CAAAC,CAAM,CAAA,GAAK,KAAA,CAAM,IAAA,CAAKF,CAAAA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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;ACoLrB","file":"/home/emems/.t3/worktrees/bitsnap-react/chat-attachments/dist/consent.js","sourcesContent":[null,"import { useCallback, useRef, useSyncExternalStore } from \"react\";\nimport { useIsomorphicLayoutEffect } from \"../lib/isomorphic-layout-effect\";\nimport { createConsent } from \"./core/controller\";\nimport type {\n BitsnapConsentApi,\n ConsentChoices,\n ConsentConfig,\n ConsentOptions,\n ConsentState,\n} from \"./core/types\";\n\ndeclare global {\n interface Window {\n BitsnapConsent?: BitsnapConsentApi;\n }\n}\n\nexport type BitsnapConsentProps = {\n /** Public project key: loads the project's banner config and logs choices. */\n projectKey?: string;\n theme?: ConsentOptions[\"theme\"];\n locale?: ConsentOptions[\"locale\"];\n position?: ConsentOptions[\"position\"];\n privacyPolicyUrl?: string;\n /** `project` keeps the consent cookie per project key. */\n scope?: ConsentOptions[\"scope\"];\n apiHost?: string;\n collectHost?: string;\n /** Local config, merged over the project config. */\n config?: Partial<ConsentConfig>;\n reloadOnWithdraw?: boolean;\n /** Google Consent Mode v2: `auto` (default) is on when `gtag` or `dataLayer` already exist. */\n gcm?: ConsentOptions[\"gcm\"];\n /** Categories offered when no remote config is loaded. */\n categories?: ConsentOptions[\"categories\"];\n /** Dashboard preview: shows the banner from the local options only; touches no cookie. */\n preview?: boolean;\n /** Replaces the banner title. */\n title?: string;\n /** Replaces the banner description. */\n description?: string;\n};\n\n/** Mounts Bitsnap Consent on the page. Renders nothing itself (the banner lives in a Shadow DOM). */\nexport function BitsnapConsent(props: BitsnapConsentProps): null {\n const {\n projectKey, theme, locale, position, privacyPolicyUrl, scope, apiHost, collectHost, reloadOnWithdraw,\n gcm, preview, title, description,\n } = props;\n const configKey = JSON.stringify(props.config ?? null);\n const configRef = useRef(props.config);\n configRef.current = props.config;\n const categoriesKey = JSON.stringify(props.categories ?? null);\n const categoriesRef = useRef(props.categories);\n categoriesRef.current = props.categories;\n\n // A layout effect: the page's passive effects (first events, tracker) must find the API already there.\n useIsomorphicLayoutEffect(() => {\n // A banner from the script tag or another instance already runs on this page.\n if (window.BitsnapConsent) return;\n const api = createConsent({\n projectKey,\n theme,\n locale,\n position,\n privacyPolicyUrl,\n scope,\n apiHost,\n collectHost,\n reloadOnWithdraw,\n gcm,\n preview,\n title,\n description,\n categories: categoriesRef.current,\n config: configRef.current,\n });\n window.BitsnapConsent = api;\n return () => {\n api.destroy();\n if (window.BitsnapConsent === api) delete window.BitsnapConsent;\n };\n }, [\n projectKey, theme, locale, position, privacyPolicyUrl, scope, apiHost, collectHost, reloadOnWithdraw,\n gcm, preview, title, description, categoriesKey, configKey,\n ]);\n\n return null;\n}\n\nlet lastKey = \"null\";\nlet lastState: ConsentState | null = null;\n\nfunction getSnapshot(): ConsentState | null {\n const current = typeof window === \"undefined\" ? null : (window.BitsnapConsent?.get() ?? null);\n const key = JSON.stringify(current);\n if (key !== lastKey) {\n lastKey = key;\n lastState = current;\n }\n return lastState;\n}\n\nfunction subscribe(onChange: () => void): () => void {\n window.addEventListener(\"bitsnap:consent\", onChange);\n window.addEventListener(\"bitsnap:consent:ready\", onChange);\n return () => {\n window.removeEventListener(\"bitsnap:consent\", onChange);\n window.removeEventListener(\"bitsnap:consent:ready\", onChange);\n };\n}\n\nexport type UseConsent = {\n /** The stored choice, or `null` while there is none (or on the server). */\n consent: ConsentState | null;\n /** `true` once the visitor has made a choice that is still valid. */\n decided: boolean;\n open: () => void;\n accept: (categories?: Partial<ConsentChoices>) => void;\n acceptAll: () => void;\n rejectAll: () => void;\n reset: () => void;\n};\n\n/** Current consent state of the page, kept up to date as the visitor chooses. */\nexport function useConsent(): UseConsent {\n const consent = useSyncExternalStore(subscribe, getSnapshot, () => null);\n const open = useCallback(() => window.BitsnapConsent?.open(), []);\n const accept = useCallback((categories?: Partial<ConsentChoices>) => window.BitsnapConsent?.accept(categories), []);\n const acceptAll = useCallback(() => window.BitsnapConsent?.acceptAll(), []);\n const rejectAll = useCallback(() => window.BitsnapConsent?.rejectAll(), []);\n const reset = useCallback(() => window.BitsnapConsent?.reset(), []);\n return { consent, decided: consent !== null, open, accept, acceptAll, rejectAll, reset };\n}\n","export type ConsentCategory = \"analytics\" | \"marketing\" | \"preferences\";\n\nexport type ConsentChoices = Record<ConsentCategory, boolean>;\n\nexport type ConsentTheme = \"auto\" | \"light\" | \"dark\";\n\nexport type ConsentPosition = \"bottom\" | \"bottom-left\" | \"bottom-right\";\n\nexport type ConsentLocale = \"pl\" | \"en\";\n\nexport const CONSENT_CATEGORIES: readonly ConsentCategory[] = [\n \"analytics\",\n \"marketing\",\n \"preferences\",\n];\n\nexport const CONSENT_TEXT_KEYS = [\n \"title\",\n \"description\",\n \"acceptAll\",\n \"rejectAll\",\n \"settings\",\n \"save\",\n \"close\",\n \"necessaryTitle\",\n \"necessaryDescription\",\n \"analyticsTitle\",\n \"analyticsDescription\",\n \"marketingTitle\",\n \"marketingDescription\",\n \"preferencesTitle\",\n \"preferencesDescription\",\n \"poweredBy\",\n] as const;\n\nexport type ConsentTexts = Record<(typeof CONSENT_TEXT_KEYS)[number], string>;\n\nexport type ConsentService = {\n name: string;\n category: ConsentCategory;\n /** Cookies to delete (best effort) when the category is withdrawn. A trailing `*` matches a prefix. */\n cookies?: string[];\n};\n\nexport type ConsentConfig = {\n /** Banner version. A stored choice with a lower `bv` makes the banner ask again. */\n version: number;\n theme: ConsentTheme;\n accentColor?: string;\n position: ConsentPosition;\n privacyPolicyUrl?: string;\n categories: ConsentChoices;\n services: ConsentService[];\n texts?: Partial<Record<ConsentLocale, Partial<ConsentTexts>>>;\n poweredBy: true;\n};\n\n/** What the consent cookie holds, and what `get()` returns. */\nexport type ConsentState = {\n id: string;\n /** Unix seconds. */\n ts: number;\n /** Version of the banner the choice was made on. */\n bv: number;\n c: ConsentChoices;\n};\n\nexport type ConsentAction =\n | \"accept_all\"\n | \"reject_all\"\n | \"custom\"\n | \"withdraw\";\n\n/** `detail` of `bitsnap:consent` and the argument of `on('change')`. */\nexport type ConsentChangeDetail = ConsentState & {\n /** `reset` when the visitor's stored choice was cleared (`get()` is `null` then). */\n action: ConsentAction | \"reset\";\n};\n\nexport type ConsentOptions = {\n /** Public project key. Enables the remote config and the consent log. */\n projectKey?: string;\n theme?: ConsentTheme;\n locale?: \"auto\" | ConsentLocale;\n position?: ConsentPosition;\n privacyPolicyUrl?: string;\n /** `project` keeps one cookie per project key (`bitsnap_consent_<key>`). */\n scope?: \"global\" | \"project\";\n apiHost?: string;\n collectHost?: string;\n /** Google Consent Mode v2. `auto` is on when `gtag` or `dataLayer` already exist. */\n gcm?: \"auto\" | \"on\" | \"off\";\n /** Local overrides, merged over the defaults and the remote config. */\n config?: Partial<ConsentConfig>;\n /** Categories used when no remote config is loaded. */\n categories?: Partial<ConsentChoices>;\n reloadOnWithdraw?: boolean;\n /**\n * Dashboard preview: shows the banner at once from the local options, never\n * reads or writes the cookie, loads no remote config, sends no consent log,\n * and the buttons only close the banner.\n */\n preview?: boolean;\n /** Replaces the banner title (current locale, non-empty values only). */\n title?: string;\n /** Replaces the banner description (current locale, non-empty values only). */\n description?: string;\n};\n\nexport type BitsnapConsentApi = {\n /**\n * Whose choice this banner holds: `project` keeps one cookie per project key\n * (`bitsnap_consent_<key>`), `global` the site-wide `bitsnap_consent`.\n */\n readonly scope: \"global\" | \"project\";\n /** The bare public project key the banner was started with, if any (`pk_` stripped). */\n readonly projectKey: string | null;\n get(): ConsentState | null;\n /**\n * `true` when the visitor refused `category`, also in a choice made on an older banner\n * version (which `get()` no longer returns) that they have not answered again yet.\n */\n denied(category: ConsentCategory): boolean;\n on(event: \"change\", fn: (detail: ConsentChangeDetail) => void): () => void;\n open(): void;\n close(): void;\n accept(categories?: Partial<ConsentChoices>): void;\n acceptAll(): void;\n rejectAll(): void;\n reset(): void;\n /** Resolves with the stored choice (or `null`) once config and stored choice are applied. */\n ready: Promise<ConsentState | null>;\n destroy(): void;\n};\n","import { CONSENT_CATEGORIES, type ConsentChoices } from \"./types\";\n\nconst SCRIPT_SELECTOR = 'script[type=\"text/plain\"][data-bitsnap-consent]:not([data-bitsnap-queued])';\nconst FRAME_SELECTOR = \"iframe[data-bitsnap-consent][data-src]\";\n\nconst allowed = (c: ConsentChoices, category: string | null): boolean =>\n (CONSENT_CATEGORIES as readonly string[]).includes(category ?? \"\") &&\n c[category as keyof ConsentChoices];\n\n/** Settles when the script has loaded or failed: a broken script must not block the ones after it. */\nfunction settled(script: HTMLScriptElement): Promise<void> {\n return new Promise((resolve) => {\n script.addEventListener(\"load\", () => resolve(), { once: true });\n script.addEventListener(\"error\", () => resolve(), { once: true });\n });\n}\n\n/** Swaps the placeholder for a live script; resolves once an external one has loaded. */\nfunction run(doc: Document, placeholder: HTMLScriptElement): Promise<void> | undefined {\n const script = doc.createElement(\"script\");\n for (const { name, value } of Array.from(placeholder.attributes)) {\n if (name === \"type\" || name === \"data-bitsnap-queued\") continue;\n if (name === \"data-type\") {\n // The embed writes the original `type=\"module\"` here, as `type` itself is `text/plain`.\n if (value === \"module\") script.setAttribute(\"type\", \"module\");\n } else if (name === \"data-src\") script.setAttribute(\"src\", value);\n else script.setAttribute(name, value);\n }\n if (placeholder.nonce) script.nonce = placeholder.nonce;\n const external = script.hasAttribute(\"src\");\n if (external) {\n // Dynamic scripts are async by default; keep the order of the page.\n if (!placeholder.hasAttribute(\"async\")) script.async = false;\n } else {\n script.text = placeholder.text;\n }\n const loaded = external ? settled(script) : undefined;\n placeholder.parentNode?.replaceChild(script, placeholder);\n return loaded;\n}\n\n/**\n * Turns the consented placeholders into live elements:\n * `<script type=\"text/plain\" data-bitsnap-consent=\"marketing\" [data-src] [data-type=\"module\"]>` becomes\n * a real script (attributes copied, `type` dropped or restored from `data-type`, `data-src` -> `src`),\n * and `<iframe data-src>` gets its `src`.\n * Placeholders run in document order: an inline script waits for the external scripts before it\n * (`<script src=lib.js>` then `<script>Lib.init()</script>`), external ones only follow each other.\n */\nexport function activateScripts(doc: Document, c: ConsentChoices): number {\n let activated = 0;\n try {\n /** Set once a placeholder had to wait: everything after it queues behind it. */\n let gate: Promise<void> | null = null;\n /** External scripts inserted since the last inline one. */\n let loading: Promise<void>[] = [];\n doc.querySelectorAll<HTMLScriptElement>(SCRIPT_SELECTOR).forEach((placeholder) => {\n if (!allowed(c, placeholder.getAttribute(\"data-bitsnap-consent\"))) return;\n activated++;\n const inline = !placeholder.hasAttribute(\"data-src\") && !placeholder.hasAttribute(\"src\");\n if (gate || (inline && loading.length > 0)) {\n // Marked so that another call (a later choice) does not queue it again.\n placeholder.setAttribute(\"data-bitsnap-queued\", \"\");\n gate = (gate ?? Promise.all(loading).then(() => {})).then(() => {\n try {\n return run(doc, placeholder);\n } catch {\n // never throw into the host page\n }\n });\n loading = [];\n return;\n }\n const loaded = run(doc, placeholder);\n if (loaded) loading.push(loaded);\n });\n doc.querySelectorAll<HTMLIFrameElement>(FRAME_SELECTOR).forEach((frame) => {\n if (!allowed(c, frame.getAttribute(\"data-bitsnap-consent\"))) return;\n const src = frame.getAttribute(\"data-src\");\n if (src && frame.getAttribute(\"src\") !== src) {\n frame.setAttribute(\"src\", src);\n frame.removeAttribute(\"data-src\");\n activated++;\n }\n });\n } catch {\n // never throw into the host page\n }\n return activated;\n}\n","import {\n CONSENT_CATEGORIES,\n type ConsentChoices,\n type ConsentConfig,\n type ConsentService,\n} from \"./types\";\n\nexport const DEFAULT_API_HOST = \"https://bitsnap.pl\";\nexport const DEFAULT_COLLECT_HOST = \"https://collect.bitsnap.pl\";\n\nexport function defaultConfig(): ConsentConfig {\n return {\n version: 1,\n theme: \"auto\",\n position: \"bottom\",\n categories: { analytics: true, marketing: true, preferences: false },\n services: [],\n poweredBy: true,\n };\n}\n\nconst THEMES = [\"auto\", \"light\", \"dark\"];\nconst POSITIONS = [\"bottom\", \"bottom-left\", \"bottom-right\"];\n\nconst HEX_COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;\n\nexport function safeColor(value: unknown): string | undefined {\n return typeof value === \"string\" && HEX_COLOR.test(value.trim())\n ? value.trim()\n : undefined;\n}\n\n/** Only http(s) and relative URLs may end up in the banner. */\nexport function safeUrl(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const url = value.trim();\n return /^(?:https?:\\/\\/|\\/(?!\\/)|#|\\?)/i.test(url) ? url : undefined;\n}\n\nfunction cleanServices(value: unknown): ConsentService[] {\n if (!Array.isArray(value)) return [];\n const services: ConsentService[] = [];\n for (const item of value) {\n if (\n item &&\n typeof item.name === \"string\" &&\n (CONSENT_CATEGORIES as readonly string[]).includes(item.category)\n ) {\n services.push({\n name: item.name,\n category: item.category,\n cookies: Array.isArray(item.cookies)\n ? item.cookies.filter((cookie: unknown) => typeof cookie === \"string\")\n : undefined,\n });\n }\n }\n return services;\n}\n\n/** Layers partial configs (later wins) over the defaults, dropping invalid values. */\nexport function mergeConfig(\n ...layers: (Partial<ConsentConfig> | null | undefined)[]\n): ConsentConfig {\n const result = defaultConfig();\n for (const layer of layers) {\n if (!layer || typeof layer !== \"object\") continue;\n if (typeof layer.version === \"number\" && layer.version >= 0) {\n result.version = Math.floor(layer.version);\n }\n if (THEMES.includes(layer.theme as string)) result.theme = layer.theme!;\n if (POSITIONS.includes(layer.position as string)) result.position = layer.position!;\n const accent = safeColor(layer.accentColor);\n if (accent) result.accentColor = accent;\n const privacy = safeUrl(layer.privacyPolicyUrl);\n if (privacy) result.privacyPolicyUrl = privacy;\n if (layer.categories && typeof layer.categories === \"object\") {\n for (const category of CONSENT_CATEGORIES) {\n if (typeof layer.categories[category] === \"boolean\") {\n result.categories[category] = layer.categories[category];\n }\n }\n }\n if (layer.services !== undefined) result.services = cleanServices(layer.services);\n if (layer.texts && typeof layer.texts === \"object\") result.texts = layer.texts;\n }\n return result;\n}\n\nexport function parseCategoryList(value: string | null | undefined): ConsentChoices {\n const wanted = (value ?? \"\").split(\",\").map((item) => item.trim());\n return {\n analytics: wanted.includes(\"analytics\"),\n marketing: wanted.includes(\"marketing\"),\n preferences: wanted.includes(\"preferences\"),\n };\n}\n\n/** What `GET /api/consent/config` answers: whether the banner is on, and its config. */\nexport type RemoteConsentConfig = {\n /** `false` when the project turned the banner off: nothing is shown, stored choices still apply. */\n enabled: boolean;\n config: Partial<ConsentConfig> | null;\n};\n\n/** Loads the project's banner config. Resolves to `null` on any failure or after the timeout. */\nexport async function fetchRemoteConfig(\n apiHost: string,\n key: string,\n timeoutMs = 3000,\n): Promise<RemoteConsentConfig | null> {\n if (typeof fetch !== \"function\") return null;\n const controller = typeof AbortController === \"function\" ? new AbortController() : undefined;\n const timer = setTimeout(() => controller?.abort(), timeoutMs);\n try {\n const response = await fetch(\n `${apiHost.replace(/\\/+$/, \"\")}/api/consent/config?key=${encodeURIComponent(key)}`,\n { signal: controller?.signal, credentials: \"omit\" },\n );\n if (!response.ok) return null;\n const body = await response.json();\n if (!body || typeof body !== \"object\") return null;\n const config = body.config && typeof body.config === \"object\" ? body.config : null;\n const enabled = body.enabled !== false;\n return config || !enabled ? { enabled, config } : null;\n } catch {\n return null;\n } finally {\n clearTimeout(timer);\n }\n}\n","/** Colors of both themes. Every text/background pair is checked against WCAG AA in the tests. */\nexport const PALETTE = {\n light: {\n bg: \"#ffffff\",\n fg: \"#14171c\",\n muted: \"#495260\",\n border: \"#c9ced6\",\n off: \"#6b7280\",\n thumb: \"#ffffff\",\n accent: \"#1d4ed8\",\n onAccent: \"#ffffff\",\n link: \"#1d4ed8\",\n },\n dark: {\n bg: \"#171a20\",\n fg: \"#f1f3f6\",\n muted: \"#b7beca\",\n border: \"#3a404b\",\n off: \"#8b93a1\",\n thumb: \"#171a20\",\n accent: \"#8ab4ff\",\n onAccent: \"#0b1220\",\n link: \"#9dc0ff\",\n },\n} as const;\n\nconst vars = (p: (typeof PALETTE)[\"light\"]) =>\n `--bg:${p.bg};--fg:${p.fg};--muted:${p.muted};--border:${p.border};--off:${p.off};--thumb:${p.thumb};--accent:${p.accent};--on-accent:${p.onAccent};--link:${p.link};--focus:${p.accent}`;\n\nexport const STYLES = `\n:host{all:initial}\n*{box-sizing:border-box}\n[hidden]{display:none!important}\n.root{${vars(PALETTE.light)};position:fixed;inset:0;pointer-events:none;z-index:2147483000;font:14px/1.5 system-ui,-apple-system,\"Segoe UI\",Roboto,\"Helvetica Neue\",Arial,sans-serif;color:var(--fg);-webkit-text-size-adjust:100%}\n.root[data-theme=dark]{${vars(PALETTE.dark)};color-scheme:dark}\nbutton,input{font:inherit;color:inherit}\n.banner,.overlay{pointer-events:auto}\n@supports (color:color-mix(in srgb,red 50%,blue)){::selection{background:color-mix(in srgb,var(--accent) 24%,transparent)}}\n.banner{position:absolute;background:var(--bg);color:var(--fg);max-height:92vh;overflow:auto;outline:none}\n.banner.enter{animation:in .22s ease-out}\n.banner.closing{animation:out .2s ease-in forwards;pointer-events:none}\n.bottom{left:0;right:0;bottom:0;border-top:1px solid var(--border);box-shadow:0 -8px 28px rgba(15,23,42,.08);padding:20px 24px calc(20px + env(safe-area-inset-bottom,0px))}\n.root[data-theme=dark] .bottom{box-shadow:0 -8px 28px rgba(0,0,0,.4)}\n.bottom .inner{display:grid;grid-template-columns:minmax(min(100%,42ch),1fr) auto;grid-template-areas:\"text actions\" \"foot actions\";gap:4px 40px;align-items:center;max-width:1120px;margin:0 auto}\n.bottom .text{max-width:68ch}\n.bottom .btn,.bottom .link-btn{flex:0 0 auto}\n.card{bottom:16px;width:min(400px,calc(100vw - 32px));border:1px solid var(--border);border-radius:14px;padding:20px;box-shadow:0 12px 32px rgba(15,23,42,.14)}\n.root[data-theme=dark] .card{box-shadow:0 12px 32px rgba(0,0,0,.45)}\n.bottom-left{left:16px}\n.bottom-right{right:16px}\n.card .inner{display:flex;flex-direction:column;gap:16px}\n.text{grid-area:text}\n.actions{grid-area:actions;display:flex;flex-wrap:wrap;gap:8px;align-items:center;justify-content:flex-end}\n.card .actions{justify-content:stretch}\n.foot{grid-area:foot}\n.title{overflow-wrap:anywhere;font-size:17px;font-weight:650;line-height:1.35;letter-spacing:-.01em;text-wrap:balance;margin:0 0 6px}\n.desc{overflow-wrap:anywhere;margin:0;color:var(--muted);line-height:1.55;text-wrap:pretty}\n.desc a{color:var(--link);text-decoration:underline;text-underline-offset:3px}\n.btn,.link-btn{min-height:38px;padding:0 16px;border-radius:8px;font-size:13.5px;font-weight:600;cursor:pointer;white-space:nowrap;transition:background-color .12s ease-out,filter .12s ease-out,border-color .12s ease-out}\n.btn{border:2px solid var(--accent);background:var(--accent);color:var(--on-accent);flex:1 1 150px}\n.btn:hover{filter:brightness(.93)}\n.btn:active{filter:brightness(.87)}\n.link-btn{border:1px solid var(--off);background:transparent;color:var(--fg);text-decoration:none}\n.link-btn:hover{border-color:var(--fg)}\n@supports (color:color-mix(in srgb,red 50%,blue)){.link-btn:hover{background:color-mix(in srgb,var(--fg) 9%,transparent)}.link-btn:active{background:color-mix(in srgb,var(--fg) 14%,transparent)}}\n.card .link-btn{flex:1 1 100%}\nbutton:focus-visible,a:focus-visible,.dialog:focus-visible{outline:2px solid var(--focus);outline-offset:2px}\n.foot{font-size:12px;color:var(--muted);padding-top:8px}\n.foot a{color:var(--muted);text-decoration:none;display:inline-flex;align-items:center;gap:5px;vertical-align:middle}\n.foot a:hover{text-decoration:underline}\n.foot b{color:var(--fg);font-weight:700;letter-spacing:-.01em}\n.foot svg{display:block}\n.overlay{position:absolute;inset:0;background:rgba(10,12,16,.58);display:flex;align-items:center;justify-content:center;padding:16px}\n.overlay.enter{animation:fade .2s ease-out}\n.overlay.closing{animation:fadeout .2s ease-in forwards;pointer-events:none}\n.dialog{background:var(--bg);color:var(--fg);width:100%;max-width:560px;max-height:min(92vh,760px);display:flex;flex-direction:column;border-radius:16px;box-shadow:0 16px 48px rgba(0,0,0,.35);outline:none}\n.dialog.enter{animation:in .22s ease-out}\n.d-head{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:16px 8px 8px 24px}\n.d-head .title{margin:0;font-size:18px}\n.x{width:44px;height:44px;border:0;border-radius:10px;background:none;cursor:pointer;display:flex;align-items:center;justify-content:center;flex:none}\n.x:hover{background:var(--border)}\n.d-body{overflow:auto;padding:0 24px 8px;flex:1}\n.cat{border-top:1px solid var(--border);padding:10px 0 14px}\n.row{display:flex;align-items:center;justify-content:space-between;gap:12px}\n.cat-title{font-weight:600;font-size:15px}\n.always{font-size:12px;color:var(--muted);margin-right:4px}\n.cat p{margin:0;color:var(--muted)}\n.cat .svc{margin-top:6px;font-size:13px}\n.cat .svc b{font-weight:600;color:var(--fg)}\n.switch{position:relative;width:52px;height:44px;display:flex;align-items:center;justify-content:flex-end;flex:none}\n.switch input{position:absolute;inset:0;width:100%;height:100%;margin:0;opacity:0;cursor:pointer}\n.switch input:disabled{cursor:default}\n.track{width:44px;height:24px;border-radius:12px;background:var(--off);position:relative;transition:background .15s}\n.track::after{content:\"\";position:absolute;top:3px;left:3px;width:18px;height:18px;border-radius:50%;background:var(--thumb);transition:transform .15s}\ninput:checked+.track{background:var(--accent)}\ninput:checked+.track::after{transform:translateX(20px);background:var(--on-accent)}\ninput:disabled+.track{opacity:.6}\ninput:focus-visible+.track{outline:2px solid var(--focus);outline-offset:2px}\n.d-foot{display:flex;flex-direction:column;gap:8px;padding:12px 24px 16px;border-top:1px solid var(--border)}\n.d-foot .actions{justify-content:stretch}\n@keyframes in{from{opacity:0;transform:translateY(12px)}to{opacity:1;transform:none}}\n@keyframes fade{from{opacity:0}to{opacity:1}}\n@keyframes out{from{opacity:1;transform:none}to{opacity:0;transform:translateY(12px)}}\n@keyframes fadeout{from{opacity:1}to{opacity:0}}\n@media(max-width:960px){\n.bottom .inner{grid-template-columns:minmax(0,1fr);grid-template-areas:\"text\" \"actions\" \"foot\";gap:14px}\n.bottom .actions{justify-content:flex-start}\n}\n@media(max-width:640px){\n.bottom{padding:16px 16px calc(16px + env(safe-area-inset-bottom,0px))}\n.bottom .inner{gap:12px}\n.bottom .actions{justify-content:stretch}\n.bottom .btn{flex:1 1 130px}\n.bottom .link-btn{flex:1 1 100%}\n.card{left:8px;right:8px;bottom:8px;width:auto}\n.overlay{align-items:flex-end;padding:0}\n.dialog{max-width:none;border-radius:16px 16px 0 0;max-height:92vh}\n.d-head{padding-left:16px}\n.d-body{padding:0 16px 8px}\n.d-foot{padding:12px 16px calc(16px + env(safe-area-inset-bottom,0px))}\n.btn{flex-basis:130px}\n.btn,.link-btn{padding:0 12px;min-height:40px}\n}\n@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important;transition:none!important}}\n`.replace(/\\n/g, \"\");\n","import { contrastRatio, onColor } from \"./contrast\";\nimport { UI_LABELS } from \"./texts\";\nimport { PALETTE, STYLES } from \"./styles\";\nimport {\n CONSENT_CATEGORIES,\n type ConsentCategory,\n type ConsentChoices,\n type ConsentConfig,\n type ConsentLocale,\n type ConsentTexts,\n} from \"./types\";\n\nexport type UIOptions = {\n doc: Document;\n config: ConsentConfig;\n texts: ConsentTexts;\n locale: ConsentLocale;\n /** Current choice, used to preset the toggles. */\n getChoices(): ConsentChoices | null;\n /** Whether a valid choice exists, i.e. closing the settings must not bring back the banner. */\n hasChoice(): boolean;\n onAcceptAll(): void;\n onRejectAll(): void;\n onSave(choices: ConsentChoices): void;\n};\n\nexport type ConsentUI = {\n /** `focus` moves keyboard focus into the banner; leave it off when the banner opens on page load. */\n showBanner(focus?: boolean): void;\n showSettings(): void;\n hide(): void;\n destroy(): void;\n};\n\nconst WORDMARK =\n '<svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" aria-hidden=\"true\"><rect width=\"16\" height=\"16\" rx=\"4\" fill=\"currentColor\" style=\"color:var(--fg)\"/><circle cx=\"8\" cy=\"8\" r=\"3\" fill=\"var(--bg)\"/></svg>';\n\nconst CLOSE_ICON =\n '<svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" aria-hidden=\"true\"><path d=\"M3 3l10 10M13 3L3 13\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" fill=\"none\"/></svg>';\n\nconst FOCUSABLE = \"button:not([disabled]),input:not([disabled]),a[href]\";\n\n/**\n * How long the exit animation runs. The banner and the settings layer fade\n * out before they disappear, so the page does not blink.\n */\nexport const EXIT_ANIMATION_MS = 200;\n\n/** A running exit animation: the node, its listener and its fallback timer. */\ntype Exit = {\n node: HTMLElement;\n listener: (event: Event) => void;\n timer: number | undefined;\n};\n\nexport function createUI(options: UIOptions): ConsentUI {\n const { doc, config, texts, locale } = options;\n const labels = UI_LABELS[locale];\n let host: HTMLElement | null = null;\n let shadow: ShadowRoot | null = null;\n let root: HTMLElement;\n let banner: HTMLElement;\n let overlay: HTMLElement;\n let dialog: HTMLElement;\n let settingsButton: HTMLElement;\n let layer: \"none\" | \"banner\" | \"settings\" = \"none\";\n let opener: HTMLElement | null = null;\n let media: MediaQueryList | null = null;\n const toggles = new Map<ConsentCategory, HTMLInputElement>();\n /** The exit animations running right now; at most one per node. */\n const exits: Exit[] = [];\n\n function el<K extends keyof HTMLElementTagNameMap>(\n tag: K,\n props: Record<string, string> = {},\n ...children: (Node | string)[]\n ): HTMLElementTagNameMap[K] {\n const node = doc.createElement(tag);\n for (const key of Object.keys(props)) {\n if (key === \"class\") node.className = props[key];\n else node.setAttribute(key, props[key]);\n }\n for (const child of children) node.append(child);\n return node;\n }\n\n function button(cls: string, text: string, onClick: () => void) {\n const node = el(\"button\", { type: \"button\", class: cls }, text);\n node.addEventListener(\"click\", onClick);\n return node;\n }\n\n function powered(): HTMLElement {\n const link = el(\"a\", {\n href: `https://bitsnap.pl/?utm_source=consent_banner&utm_medium=referral&utm_content=${encodeURIComponent(doc.location?.hostname ?? \"\")}`,\n target: \"_blank\",\n rel: \"noopener\",\n });\n link.append(texts.poweredBy + \" \");\n link.insertAdjacentHTML(\"beforeend\", WORDMARK);\n link.append(el(\"b\", {}, \"bitsnap\"));\n return el(\"div\", { class: \"foot\" }, link);\n }\n\n function description(): HTMLElement {\n const node = el(\"p\", { class: \"desc\", id: \"d\" }, texts.description);\n if (config.privacyPolicyUrl) {\n node.append(\n \" \",\n el(\n \"a\",\n { href: config.privacyPolicyUrl, target: \"_blank\", rel: \"noopener\" },\n labels.privacy,\n ),\n );\n }\n return node;\n }\n\n function buildBanner() {\n settingsButton = button(\"link-btn\", texts.settings, () => showSettings());\n banner = el(\n \"div\",\n {\n class: `banner ${config.position === \"bottom\" ? \"bottom\" : `card ${config.position}`}`,\n // Not modal: the page stays usable, so it is a live region, not a dialog.\n role: \"region\",\n \"aria-live\": \"polite\",\n \"aria-labelledby\": \"t\",\n \"aria-describedby\": \"d\",\n tabindex: \"-1\",\n },\n el(\n \"div\",\n { class: \"inner\" },\n el(\"div\", { class: \"text\" }, el(\"div\", { class: \"title\", id: \"t\" }, texts.title), description()),\n el(\n \"div\",\n { class: \"actions\" },\n button(\"btn\", texts.acceptAll, options.onAcceptAll),\n button(\"btn\", texts.rejectAll, options.onRejectAll),\n settingsButton,\n ),\n powered(),\n ),\n );\n }\n\n function category(id: ConsentCategory | \"necessary\"): HTMLElement {\n const services = config.services.filter((service) => service.category === id);\n const input = el(\"input\", { type: \"checkbox\", role: \"switch\", \"aria-labelledby\": `l-${id}`, \"aria-describedby\": `p-${id}` });\n if (id === \"necessary\") {\n input.checked = true;\n input.disabled = true;\n } else {\n toggles.set(id, input);\n }\n const node = el(\n \"div\",\n { class: \"cat\" },\n el(\n \"div\",\n { class: \"row\" },\n el(\"span\", { class: \"cat-title\", id: `l-${id}` }, texts[`${id}Title` as keyof ConsentTexts]),\n el(\n \"span\",\n { style: \"display:flex;align-items:center\" },\n ...(id === \"necessary\" ? [el(\"span\", { class: \"always\" }, labels.always)] : []),\n el(\"label\", { class: \"switch\" }, input, el(\"span\", { class: \"track\" })),\n ),\n ),\n el(\"p\", { id: `p-${id}` }, texts[`${id}Description` as keyof ConsentTexts]),\n );\n if (services.length > 0) {\n node.append(\n el(\"p\", { class: \"svc\" }, el(\"b\", {}, `${labels.services}: `), services.map((s) => s.name).join(\", \")),\n );\n }\n return node;\n }\n\n function buildSettings() {\n const close = el(\"button\", { type: \"button\", class: \"x\", \"aria-label\": texts.close });\n close.insertAdjacentHTML(\"beforeend\", CLOSE_ICON);\n close.addEventListener(\"click\", () => closeSettings());\n const body = el(\"div\", { class: \"d-body\" }, category(\"necessary\"));\n for (const id of CONSENT_CATEGORIES) {\n if (config.categories[id]) body.append(category(id));\n }\n dialog = el(\n \"div\",\n { class: \"dialog\", role: \"dialog\", \"aria-modal\": \"true\", \"aria-labelledby\": \"st\", tabindex: \"-1\" },\n el(\"div\", { class: \"d-head\" }, el(\"div\", { class: \"title\", id: \"st\" }, texts.settings), close),\n body,\n el(\n \"div\",\n { class: \"d-foot\" },\n el(\n \"div\",\n { class: \"actions\" },\n button(\"btn\", texts.save, () => options.onSave(readToggles())),\n button(\"btn\", texts.acceptAll, options.onAcceptAll),\n button(\"btn\", texts.rejectAll, options.onRejectAll),\n ),\n powered(),\n ),\n );\n overlay = el(\"div\", { class: \"overlay\" }, dialog);\n overlay.addEventListener(\"mousedown\", (event) => {\n if (event.target === overlay) closeSettings();\n });\n }\n\n function readToggles(): ConsentChoices {\n const choices = { analytics: false, marketing: false, preferences: false };\n toggles.forEach((input, key) => (choices[key] = input.checked));\n return choices;\n }\n\n function applyTheme() {\n const dark = config.theme === \"dark\" || (config.theme === \"auto\" && !!media?.matches);\n root.setAttribute(\"data-theme\", dark ? \"dark\" : \"light\");\n applyAccent(dark);\n }\n\n /** A custom accent that is too faint on the dark background gives way to the dark theme's own. */\n function applyAccent(dark: boolean) {\n const accent = config.accentColor;\n if (!accent) return;\n if (dark && contrastRatio(accent, PALETTE.dark.bg) < 3) {\n for (const name of [\"--accent\", \"--focus\", \"--on-accent\"]) root.style.removeProperty(name);\n return;\n }\n root.style.setProperty(\"--accent\", accent);\n root.style.setProperty(\"--focus\", accent);\n root.style.setProperty(\"--on-accent\", onColor(accent));\n }\n\n function ensure() {\n if (host) return;\n host = el(\"div\", { id: \"bitsnap-consent\", \"data-bitsnap-consent-host\": \"\" });\n shadow = host.attachShadow({ mode: \"open\" });\n shadow.append(el(\"style\", {}, STYLES));\n root = el(\"div\", { class: \"root\", lang: locale });\n buildBanner();\n buildSettings();\n banner.hidden = true;\n overlay.hidden = true;\n root.append(banner, overlay);\n shadow.append(root);\n if (typeof doc.defaultView?.matchMedia === \"function\") {\n media = doc.defaultView.matchMedia(\"(prefers-color-scheme: dark)\");\n media.addEventListener?.(\"change\", applyTheme);\n }\n applyTheme();\n doc.body.append(host);\n }\n\n function focusables(): HTMLElement[] {\n return Array.from(dialog.querySelectorAll<HTMLElement>(FOCUSABLE));\n }\n\n /** Whether the visitor asked for less motion: the layers then come and go at once. */\n function reducedMotion(): boolean {\n try {\n return doc.defaultView?.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches === true;\n } catch {\n return false;\n }\n }\n\n /** Stops a running exit animation; the node stays where it is. */\n function stopExit(node: HTMLElement) {\n const index = exits.findIndex((exit) => exit.node === node);\n if (index === -1) return;\n const [exit] = exits.splice(index, 1);\n exit.node.removeEventListener(\"animationend\", exit.listener);\n if (exit.timer !== undefined) doc.defaultView?.clearTimeout(exit.timer);\n exit.node.classList.remove(\"closing\");\n }\n\n /** Hides the node at once, without an animation. */\n function hideNow(node: HTMLElement) {\n stopExit(node);\n node.hidden = true;\n }\n\n /**\n * Fades the node out and hides it when the animation ends. The timer is the\n * fallback for a browser that sends no event (a hidden tab, a reduced\n * motion setting): the layer always disappears.\n */\n function exitTo(node: HTMLElement) {\n stopExit(node);\n if (node.hidden) return;\n if (reducedMotion()) {\n node.hidden = true;\n return;\n }\n node.classList.add(\"closing\");\n const listener = (event: Event) => {\n // Another animation of a child ends first; only our own counts.\n if (event.target !== node) return;\n finish();\n };\n const timer = doc.defaultView?.setTimeout(finish, EXIT_ANIMATION_MS + 120);\n function finish() {\n stopExit(node);\n node.hidden = true;\n }\n node.addEventListener(\"animationend\", listener);\n exits.push({ node, listener, timer });\n }\n\n /** Shows the node and plays the entrance animation again. */\n function enter(node: HTMLElement) {\n stopExit(node);\n node.hidden = false;\n // The class has to leave and come back, or the animation does not restart.\n node.classList.remove(\"enter\");\n void node.offsetWidth;\n node.classList.add(\"enter\");\n }\n\n function onKeydown(event: KeyboardEvent) {\n if (layer !== \"settings\") return;\n if (event.key === \"Escape\") {\n event.preventDefault();\n closeSettings();\n return;\n }\n if (event.key !== \"Tab\") return;\n const items = focusables();\n if (items.length === 0) return;\n const active = shadow?.activeElement as HTMLElement | null;\n const first = items[0];\n const last = items[items.length - 1];\n const outside = !active || !dialog.contains(active);\n if (event.shiftKey && (outside || active === first || active === dialog)) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && (outside || active === last)) {\n event.preventDefault();\n first.focus();\n }\n }\n\n function showBanner(focus = false) {\n try {\n ensure();\n layer = \"banner\";\n doc.removeEventListener(\"keydown\", onKeydown, true);\n hideNow(overlay);\n enter(banner);\n if (focus) banner.focus({ preventScroll: true });\n } catch {\n // never throw into the host page\n }\n }\n\n function showSettings() {\n try {\n ensure();\n if (layer !== \"settings\") {\n const active = doc.activeElement as HTMLElement | null;\n opener = active && active !== host && active !== doc.body ? active : null;\n }\n const current = options.getChoices();\n toggles.forEach((input, key) => (input.checked = !!current?.[key]));\n layer = \"settings\";\n hideNow(banner);\n enter(overlay);\n enter(dialog);\n doc.addEventListener(\"keydown\", onKeydown, true);\n dialog.focus({ preventScroll: true });\n } catch {\n // never throw into the host page\n }\n }\n\n function closeSettings() {\n if (layer !== \"settings\") return;\n doc.removeEventListener(\"keydown\", onKeydown, true);\n exitTo(overlay);\n if (options.hasChoice()) {\n layer = \"none\";\n opener?.focus?.({ preventScroll: true });\n } else {\n layer = \"banner\";\n enter(banner);\n settingsButton.focus({ preventScroll: true });\n }\n }\n\n function hide() {\n if (!host) return;\n doc.removeEventListener(\"keydown\", onKeydown, true);\n const wasSettings = layer === \"settings\";\n layer = \"none\";\n exitTo(banner);\n exitTo(overlay);\n if (wasSettings) opener?.focus?.({ preventScroll: true });\n }\n\n function destroy() {\n doc.removeEventListener(\"keydown\", onKeydown, true);\n media?.removeEventListener?.(\"change\", applyTheme);\n while (exits.length > 0) stopExit(exits[0]!.node);\n host?.remove();\n host = null;\n shadow = null;\n layer = \"none\";\n }\n\n return { showBanner, showSettings, hide, destroy };\n}\n"]}