@monetize.software/sdk-extension 0.1.0-alpha.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 (65) hide show
  1. package/README.md +113 -0
  2. package/dist/chunks/chrome-port-BXHR4SOG.js +2014 -0
  3. package/dist/chunks/chrome-port-BXHR4SOG.js.map +1 -0
  4. package/dist/chunks/chrome-port-EtYqHf3p.js +2 -0
  5. package/dist/chunks/chrome-port-EtYqHf3p.js.map +1 -0
  6. package/dist/chunks/port-name-BPfQKtdb.js +5 -0
  7. package/dist/chunks/port-name-BPfQKtdb.js.map +1 -0
  8. package/dist/chunks/port-name-qwB109u9.js +2 -0
  9. package/dist/chunks/port-name-qwB109u9.js.map +1 -0
  10. package/dist/content/PaywallUI.d.ts +28 -0
  11. package/dist/content/PaywallUI.d.ts.map +1 -0
  12. package/dist/content/RemoteAuthClient.d.ts +91 -0
  13. package/dist/content/RemoteAuthClient.d.ts.map +1 -0
  14. package/dist/content/RemoteBillingClient.d.ts +126 -0
  15. package/dist/content/RemoteBillingClient.d.ts.map +1 -0
  16. package/dist/content/RemoteEventTracker.d.ts +9 -0
  17. package/dist/content/RemoteEventTracker.d.ts.map +1 -0
  18. package/dist/content/RemoteTrialStore.d.ts +13 -0
  19. package/dist/content/RemoteTrialStore.d.ts.map +1 -0
  20. package/dist/content/index.d.ts +11 -0
  21. package/dist/content/index.d.ts.map +1 -0
  22. package/dist/content/transport.d.ts +6 -0
  23. package/dist/content/transport.d.ts.map +1 -0
  24. package/dist/content.cjs +26 -0
  25. package/dist/content.cjs.map +1 -0
  26. package/dist/content.js +2723 -0
  27. package/dist/content.js.map +1 -0
  28. package/dist/offscreen/index.d.ts +21 -0
  29. package/dist/offscreen/index.d.ts.map +1 -0
  30. package/dist/offscreen/server.d.ts +26 -0
  31. package/dist/offscreen/server.d.ts.map +1 -0
  32. package/dist/offscreen.cjs +2 -0
  33. package/dist/offscreen.cjs.map +1 -0
  34. package/dist/offscreen.js +239 -0
  35. package/dist/offscreen.js.map +1 -0
  36. package/dist/shared/channel.d.ts +14 -0
  37. package/dist/shared/channel.d.ts.map +1 -0
  38. package/dist/shared/chrome-port.d.ts +8 -0
  39. package/dist/shared/chrome-port.d.ts.map +1 -0
  40. package/dist/shared/errors.d.ts +4 -0
  41. package/dist/shared/errors.d.ts.map +1 -0
  42. package/dist/shared/messages.d.ts +195 -0
  43. package/dist/shared/messages.d.ts.map +1 -0
  44. package/dist/shared/port-name.d.ts +2 -0
  45. package/dist/shared/port-name.d.ts.map +1 -0
  46. package/dist/shared/protocol.d.ts +59 -0
  47. package/dist/shared/protocol.d.ts.map +1 -0
  48. package/dist/shared/transport-client.d.ts +31 -0
  49. package/dist/shared/transport-client.d.ts.map +1 -0
  50. package/dist/shared/transport-server.d.ts +32 -0
  51. package/dist/shared/transport-server.d.ts.map +1 -0
  52. package/dist/sw/ensure-offscreen.d.ts +8 -0
  53. package/dist/sw/ensure-offscreen.d.ts.map +1 -0
  54. package/dist/sw/forwarder.d.ts +3 -0
  55. package/dist/sw/forwarder.d.ts.map +1 -0
  56. package/dist/sw/index.d.ts +4 -0
  57. package/dist/sw/index.d.ts.map +1 -0
  58. package/dist/sw/types.d.ts +19 -0
  59. package/dist/sw/types.d.ts.map +1 -0
  60. package/dist/sw.cjs +2 -0
  61. package/dist/sw.cjs.map +1 -0
  62. package/dist/sw.js +94 -0
  63. package/dist/sw.js.map +1 -0
  64. package/package.json +63 -0
  65. package/src/offscreen/offscreen.html +24 -0
@@ -0,0 +1,2723 @@
1
+ import { P as T, B as ae, E as ce, c as ue, A as H, w as he, a as R, r as de, b as pe } from "./chunks/chrome-port-BXHR4SOG.js";
2
+ import { render as z, h as G } from "preact";
3
+ import { jsxs as u, jsx as o, Fragment as ne } from "preact/jsx-runtime";
4
+ import { useRef as E, useEffect as M, useState as x, useMemo as ie } from "preact/hooks";
5
+ import { P as fe } from "./chunks/port-name-BPfQKtdb.js";
6
+ const oe = '@layer theme,base,components,utilities;@layer theme{@theme default{ --font-sans: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; --font-serif: ui-serif, Georgia, Cambria, "Times New Roman", Times, serif; --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; --color-red-50: oklch(97.1% .013 17.38); --color-red-100: oklch(93.6% .032 17.717); --color-red-200: oklch(88.5% .062 18.334); --color-red-300: oklch(80.8% .114 19.571); --color-red-400: oklch(70.4% .191 22.216); --color-red-500: oklch(63.7% .237 25.331); --color-red-600: oklch(57.7% .245 27.325); --color-red-700: oklch(50.5% .213 27.518); --color-red-800: oklch(44.4% .177 26.899); --color-red-900: oklch(39.6% .141 25.723); --color-red-950: oklch(25.8% .092 26.042); --color-orange-50: oklch(98% .016 73.684); --color-orange-100: oklch(95.4% .038 75.164); --color-orange-200: oklch(90.1% .076 70.697); --color-orange-300: oklch(83.7% .128 66.29); --color-orange-400: oklch(75% .183 55.934); --color-orange-500: oklch(70.5% .213 47.604); --color-orange-600: oklch(64.6% .222 41.116); --color-orange-700: oklch(55.3% .195 38.402); --color-orange-800: oklch(47% .157 37.304); --color-orange-900: oklch(40.8% .123 38.172); --color-orange-950: oklch(26.6% .079 36.259); --color-amber-50: oklch(98.7% .022 95.277); --color-amber-100: oklch(96.2% .059 95.617); --color-amber-200: oklch(92.4% .12 95.746); --color-amber-300: oklch(87.9% .169 91.605); --color-amber-400: oklch(82.8% .189 84.429); --color-amber-500: oklch(76.9% .188 70.08); --color-amber-600: oklch(66.6% .179 58.318); --color-amber-700: oklch(55.5% .163 48.998); --color-amber-800: oklch(47.3% .137 46.201); --color-amber-900: oklch(41.4% .112 45.904); --color-amber-950: oklch(27.9% .077 45.635); --color-yellow-50: oklch(98.7% .026 102.212); --color-yellow-100: oklch(97.3% .071 103.193); --color-yellow-200: oklch(94.5% .129 101.54); --color-yellow-300: oklch(90.5% .182 98.111); --color-yellow-400: oklch(85.2% .199 91.936); --color-yellow-500: oklch(79.5% .184 86.047); --color-yellow-600: oklch(68.1% .162 75.834); --color-yellow-700: oklch(55.4% .135 66.442); --color-yellow-800: oklch(47.6% .114 61.907); --color-yellow-900: oklch(42.1% .095 57.708); --color-yellow-950: oklch(28.6% .066 53.813); --color-lime-50: oklch(98.6% .031 120.757); --color-lime-100: oklch(96.7% .067 122.328); --color-lime-200: oklch(93.8% .127 124.321); --color-lime-300: oklch(89.7% .196 126.665); --color-lime-400: oklch(84.1% .238 128.85); --color-lime-500: oklch(76.8% .233 130.85); --color-lime-600: oklch(64.8% .2 131.684); --color-lime-700: oklch(53.2% .157 131.589); --color-lime-800: oklch(45.3% .124 130.933); --color-lime-900: oklch(40.5% .101 131.063); --color-lime-950: oklch(27.4% .072 132.109); --color-green-50: oklch(98.2% .018 155.826); --color-green-100: oklch(96.2% .044 156.743); --color-green-200: oklch(92.5% .084 155.995); --color-green-300: oklch(87.1% .15 154.449); --color-green-400: oklch(79.2% .209 151.711); --color-green-500: oklch(72.3% .219 149.579); --color-green-600: oklch(62.7% .194 149.214); --color-green-700: oklch(52.7% .154 150.069); --color-green-800: oklch(44.8% .119 151.328); --color-green-900: oklch(39.3% .095 152.535); --color-green-950: oklch(26.6% .065 152.934); --color-emerald-50: oklch(97.9% .021 166.113); --color-emerald-100: oklch(95% .052 163.051); --color-emerald-200: oklch(90.5% .093 164.15); --color-emerald-300: oklch(84.5% .143 164.978); --color-emerald-400: oklch(76.5% .177 163.223); --color-emerald-500: oklch(69.6% .17 162.48); --color-emerald-600: oklch(59.6% .145 163.225); --color-emerald-700: oklch(50.8% .118 165.612); --color-emerald-800: oklch(43.2% .095 166.913); --color-emerald-900: oklch(37.8% .077 168.94); --color-emerald-950: oklch(26.2% .051 172.552); --color-teal-50: oklch(98.4% .014 180.72); --color-teal-100: oklch(95.3% .051 180.801); --color-teal-200: oklch(91% .096 180.426); --color-teal-300: oklch(85.5% .138 181.071); --color-teal-400: oklch(77.7% .152 181.912); --color-teal-500: oklch(70.4% .14 182.503); --color-teal-600: oklch(60% .118 184.704); --color-teal-700: oklch(51.1% .096 186.391); --color-teal-800: oklch(43.7% .078 188.216); --color-teal-900: oklch(38.6% .063 188.416); --color-teal-950: oklch(27.7% .046 192.524); --color-cyan-50: oklch(98.4% .019 200.873); --color-cyan-100: oklch(95.6% .045 203.388); --color-cyan-200: oklch(91.7% .08 205.041); --color-cyan-300: oklch(86.5% .127 207.078); --color-cyan-400: oklch(78.9% .154 211.53); --color-cyan-500: oklch(71.5% .143 215.221); --color-cyan-600: oklch(60.9% .126 221.723); --color-cyan-700: oklch(52% .105 223.128); --color-cyan-800: oklch(45% .085 224.283); --color-cyan-900: oklch(39.8% .07 227.392); --color-cyan-950: oklch(30.2% .056 229.695); --color-sky-50: oklch(97.7% .013 236.62); --color-sky-100: oklch(95.1% .026 236.824); --color-sky-200: oklch(90.1% .058 230.902); --color-sky-300: oklch(82.8% .111 230.318); --color-sky-400: oklch(74.6% .16 232.661); --color-sky-500: oklch(68.5% .169 237.323); --color-sky-600: oklch(58.8% .158 241.966); --color-sky-700: oklch(50% .134 242.749); --color-sky-800: oklch(44.3% .11 240.79); --color-sky-900: oklch(39.1% .09 240.876); --color-sky-950: oklch(29.3% .066 243.157); --color-blue-50: oklch(97% .014 254.604); --color-blue-100: oklch(93.2% .032 255.585); --color-blue-200: oklch(88.2% .059 254.128); --color-blue-300: oklch(80.9% .105 251.813); --color-blue-400: oklch(70.7% .165 254.624); --color-blue-500: oklch(62.3% .214 259.815); --color-blue-600: oklch(54.6% .245 262.881); --color-blue-700: oklch(48.8% .243 264.376); --color-blue-800: oklch(42.4% .199 265.638); --color-blue-900: oklch(37.9% .146 265.522); --color-blue-950: oklch(28.2% .091 267.935); --color-indigo-50: oklch(96.2% .018 272.314); --color-indigo-100: oklch(93% .034 272.788); --color-indigo-200: oklch(87% .065 274.039); --color-indigo-300: oklch(78.5% .115 274.713); --color-indigo-400: oklch(67.3% .182 276.935); --color-indigo-500: oklch(58.5% .233 277.117); --color-indigo-600: oklch(51.1% .262 276.966); --color-indigo-700: oklch(45.7% .24 277.023); --color-indigo-800: oklch(39.8% .195 277.366); --color-indigo-900: oklch(35.9% .144 278.697); --color-indigo-950: oklch(25.7% .09 281.288); --color-violet-50: oklch(96.9% .016 293.756); --color-violet-100: oklch(94.3% .029 294.588); --color-violet-200: oklch(89.4% .057 293.283); --color-violet-300: oklch(81.1% .111 293.571); --color-violet-400: oklch(70.2% .183 293.541); --color-violet-500: oklch(60.6% .25 292.717); --color-violet-600: oklch(54.1% .281 293.009); --color-violet-700: oklch(49.1% .27 292.581); --color-violet-800: oklch(43.2% .232 292.759); --color-violet-900: oklch(38% .189 293.745); --color-violet-950: oklch(28.3% .141 291.089); --color-purple-50: oklch(97.7% .014 308.299); --color-purple-100: oklch(94.6% .033 307.174); --color-purple-200: oklch(90.2% .063 306.703); --color-purple-300: oklch(82.7% .119 306.383); --color-purple-400: oklch(71.4% .203 305.504); --color-purple-500: oklch(62.7% .265 303.9); --color-purple-600: oklch(55.8% .288 302.321); --color-purple-700: oklch(49.6% .265 301.924); --color-purple-800: oklch(43.8% .218 303.724); --color-purple-900: oklch(38.1% .176 304.987); --color-purple-950: oklch(29.1% .149 302.717); --color-fuchsia-50: oklch(97.7% .017 320.058); --color-fuchsia-100: oklch(95.2% .037 318.852); --color-fuchsia-200: oklch(90.3% .076 319.62); --color-fuchsia-300: oklch(83.3% .145 321.434); --color-fuchsia-400: oklch(74% .238 322.16); --color-fuchsia-500: oklch(66.7% .295 322.15); --color-fuchsia-600: oklch(59.1% .293 322.896); --color-fuchsia-700: oklch(51.8% .253 323.949); --color-fuchsia-800: oklch(45.2% .211 324.591); --color-fuchsia-900: oklch(40.1% .17 325.612); --color-fuchsia-950: oklch(29.3% .136 325.661); --color-pink-50: oklch(97.1% .014 343.198); --color-pink-100: oklch(94.8% .028 342.258); --color-pink-200: oklch(89.9% .061 343.231); --color-pink-300: oklch(82.3% .12 346.018); --color-pink-400: oklch(71.8% .202 349.761); --color-pink-500: oklch(65.6% .241 354.308); --color-pink-600: oklch(59.2% .249 .584); --color-pink-700: oklch(52.5% .223 3.958); --color-pink-800: oklch(45.9% .187 3.815); --color-pink-900: oklch(40.8% .153 2.432); --color-pink-950: oklch(28.4% .109 3.907); --color-rose-50: oklch(96.9% .015 12.422); --color-rose-100: oklch(94.1% .03 12.58); --color-rose-200: oklch(89.2% .058 10.001); --color-rose-300: oklch(81% .117 11.638); --color-rose-400: oklch(71.2% .194 13.428); --color-rose-500: oklch(64.5% .246 16.439); --color-rose-600: oklch(58.6% .253 17.585); --color-rose-700: oklch(51.4% .222 16.935); --color-rose-800: oklch(45.5% .188 13.697); --color-rose-900: oklch(41% .159 10.272); --color-rose-950: oklch(27.1% .105 12.094); --color-slate-50: oklch(98.4% .003 247.858); --color-slate-100: oklch(96.8% .007 247.896); --color-slate-200: oklch(92.9% .013 255.508); --color-slate-300: oklch(86.9% .022 252.894); --color-slate-400: oklch(70.4% .04 256.788); --color-slate-500: oklch(55.4% .046 257.417); --color-slate-600: oklch(44.6% .043 257.281); --color-slate-700: oklch(37.2% .044 257.287); --color-slate-800: oklch(27.9% .041 260.031); --color-slate-900: oklch(20.8% .042 265.755); --color-slate-950: oklch(12.9% .042 264.695); --color-gray-50: oklch(98.5% .002 247.839); --color-gray-100: oklch(96.7% .003 264.542); --color-gray-200: oklch(92.8% .006 264.531); --color-gray-300: oklch(87.2% .01 258.338); --color-gray-400: oklch(70.7% .022 261.325); --color-gray-500: oklch(55.1% .027 264.364); --color-gray-600: oklch(44.6% .03 256.802); --color-gray-700: oklch(37.3% .034 259.733); --color-gray-800: oklch(27.8% .033 256.848); --color-gray-900: oklch(21% .034 264.665); --color-gray-950: oklch(13% .028 261.692); --color-zinc-50: oklch(98.5% 0 0); --color-zinc-100: oklch(96.7% .001 286.375); --color-zinc-200: oklch(92% .004 286.32); --color-zinc-300: oklch(87.1% .006 286.286); --color-zinc-400: oklch(70.5% .015 286.067); --color-zinc-500: oklch(55.2% .016 285.938); --color-zinc-600: oklch(44.2% .017 285.786); --color-zinc-700: oklch(37% .013 285.805); --color-zinc-800: oklch(27.4% .006 286.033); --color-zinc-900: oklch(21% .006 285.885); --color-zinc-950: oklch(14.1% .005 285.823); --color-neutral-50: oklch(98.5% 0 0); --color-neutral-100: oklch(97% 0 0); --color-neutral-200: oklch(92.2% 0 0); --color-neutral-300: oklch(87% 0 0); --color-neutral-400: oklch(70.8% 0 0); --color-neutral-500: oklch(55.6% 0 0); --color-neutral-600: oklch(43.9% 0 0); --color-neutral-700: oklch(37.1% 0 0); --color-neutral-800: oklch(26.9% 0 0); --color-neutral-900: oklch(20.5% 0 0); --color-neutral-950: oklch(14.5% 0 0); --color-stone-50: oklch(98.5% .001 106.423); --color-stone-100: oklch(97% .001 106.424); --color-stone-200: oklch(92.3% .003 48.717); --color-stone-300: oklch(86.9% .005 56.366); --color-stone-400: oklch(70.9% .01 56.259); --color-stone-500: oklch(55.3% .013 58.071); --color-stone-600: oklch(44.4% .011 73.639); --color-stone-700: oklch(37.4% .01 67.558); --color-stone-800: oklch(26.8% .007 34.298); --color-stone-900: oklch(21.6% .006 56.043); --color-stone-950: oklch(14.7% .004 49.25); --color-mauve-50: oklch(98.5% 0 0); --color-mauve-100: oklch(96% .003 325.6); --color-mauve-200: oklch(92.2% .005 325.62); --color-mauve-300: oklch(86.5% .012 325.68); --color-mauve-400: oklch(71.1% .019 323.02); --color-mauve-500: oklch(54.2% .034 322.5); --color-mauve-600: oklch(43.5% .029 321.78); --color-mauve-700: oklch(36.4% .029 323.89); --color-mauve-800: oklch(26.3% .024 320.12); --color-mauve-900: oklch(21.2% .019 322.12); --color-mauve-950: oklch(14.5% .008 326); --color-olive-50: oklch(98.8% .003 106.5); --color-olive-100: oklch(96.6% .005 106.5); --color-olive-200: oklch(93% .007 106.5); --color-olive-300: oklch(88% .011 106.6); --color-olive-400: oklch(73.7% .021 106.9); --color-olive-500: oklch(58% .031 107.3); --color-olive-600: oklch(46.6% .025 107.3); --color-olive-700: oklch(39.4% .023 107.4); --color-olive-800: oklch(28.6% .016 107.4); --color-olive-900: oklch(22.8% .013 107.4); --color-olive-950: oklch(15.3% .006 107.1); --color-mist-50: oklch(98.7% .002 197.1); --color-mist-100: oklch(96.3% .002 197.1); --color-mist-200: oklch(92.5% .005 214.3); --color-mist-300: oklch(87.2% .007 219.6); --color-mist-400: oklch(72.3% .014 214.4); --color-mist-500: oklch(56% .021 213.5); --color-mist-600: oklch(45% .017 213.2); --color-mist-700: oklch(37.8% .015 216); --color-mist-800: oklch(27.5% .011 216.9); --color-mist-900: oklch(21.8% .008 223.9); --color-mist-950: oklch(14.8% .004 228.8); --color-taupe-50: oklch(98.6% .002 67.8); --color-taupe-100: oklch(96% .002 17.2); --color-taupe-200: oklch(92.2% .005 34.3); --color-taupe-300: oklch(86.8% .007 39.5); --color-taupe-400: oklch(71.4% .014 41.2); --color-taupe-500: oklch(54.7% .021 43.1); --color-taupe-600: oklch(43.8% .017 39.3); --color-taupe-700: oklch(36.7% .016 35.7); --color-taupe-800: oklch(26.8% .011 36.5); --color-taupe-900: oklch(21.4% .009 43.1); --color-taupe-950: oklch(14.7% .004 49.3); --color-black: #000; --color-white: #fff; --spacing: .25rem; --breakpoint-sm: 40rem; --breakpoint-md: 48rem; --breakpoint-lg: 64rem; --breakpoint-xl: 80rem; --breakpoint-2xl: 96rem; --container-3xs: 16rem; --container-2xs: 18rem; --container-xs: 20rem; --container-sm: 24rem; --container-md: 28rem; --container-lg: 32rem; --container-xl: 36rem; --container-2xl: 42rem; --container-3xl: 48rem; --container-4xl: 56rem; --container-5xl: 64rem; --container-6xl: 72rem; --container-7xl: 80rem; --text-xs: .75rem; --text-xs--line-height: calc(1 / .75); --text-sm: .875rem; --text-sm--line-height: calc(1.25 / .875); --text-base: 1rem; --text-base--line-height: 1.5 ; --text-lg: 1.125rem; --text-lg--line-height: calc(1.75 / 1.125); --text-xl: 1.25rem; --text-xl--line-height: calc(1.75 / 1.25); --text-2xl: 1.5rem; --text-2xl--line-height: calc(2 / 1.5); --text-3xl: 1.875rem; --text-3xl--line-height: 1.2 ; --text-4xl: 2.25rem; --text-4xl--line-height: calc(2.5 / 2.25); --text-5xl: 3rem; --text-5xl--line-height: 1; --text-6xl: 3.75rem; --text-6xl--line-height: 1; --text-7xl: 4.5rem; --text-7xl--line-height: 1; --text-8xl: 6rem; --text-8xl--line-height: 1; --text-9xl: 8rem; --text-9xl--line-height: 1; --font-weight-thin: 100; --font-weight-extralight: 200; --font-weight-light: 300; --font-weight-normal: 400; --font-weight-medium: 500; --font-weight-semibold: 600; --font-weight-bold: 700; --font-weight-extrabold: 800; --font-weight-black: 900; --tracking-tighter: -.05em; --tracking-tight: -.025em; --tracking-normal: 0em; --tracking-wide: .025em; --tracking-wider: .05em; --tracking-widest: .1em; --leading-tight: 1.25; --leading-snug: 1.375; --leading-normal: 1.5; --leading-relaxed: 1.625; --leading-loose: 2; --radius-xs: .125rem; --radius-sm: .25rem; --radius-md: .375rem; --radius-lg: .5rem; --radius-xl: .75rem; --radius-2xl: 1rem; --radius-3xl: 1.5rem; --radius-4xl: 2rem; --shadow-2xs: 0 1px rgb(0 0 0 / .05); --shadow-xs: 0 1px 2px 0 rgb(0 0 0 / .05); --shadow-sm: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1); --shadow-md: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1); --shadow-lg: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1); --shadow-xl: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1); --shadow-2xl: 0 25px 50px -12px rgb(0 0 0 / .25); --inset-shadow-2xs: inset 0 1px rgb(0 0 0 / .05); --inset-shadow-xs: inset 0 1px 1px rgb(0 0 0 / .05); --inset-shadow-sm: inset 0 2px 4px rgb(0 0 0 / .05); --drop-shadow-xs: 0 1px 1px rgb(0 0 0 / .05); --drop-shadow-sm: 0 1px 2px rgb(0 0 0 / .15); --drop-shadow-md: 0 3px 3px rgb(0 0 0 / .12); --drop-shadow-lg: 0 4px 4px rgb(0 0 0 / .15); --drop-shadow-xl: 0 9px 7px rgb(0 0 0 / .1); --drop-shadow-2xl: 0 25px 25px rgb(0 0 0 / .15); --text-shadow-2xs: 0px 1px 0px rgb(0 0 0 / .15); --text-shadow-xs: 0px 1px 1px rgb(0 0 0 / .2); --text-shadow-sm: 0px 1px 0px rgb(0 0 0 / .075), 0px 1px 1px rgb(0 0 0 / .075), 0px 2px 2px rgb(0 0 0 / .075); --text-shadow-md: 0px 1px 1px rgb(0 0 0 / .1), 0px 1px 2px rgb(0 0 0 / .1), 0px 2px 4px rgb(0 0 0 / .1); --text-shadow-lg: 0px 1px 2px rgb(0 0 0 / .1), 0px 3px 2px rgb(0 0 0 / .1), 0px 4px 8px rgb(0 0 0 / .1); --ease-in: cubic-bezier(.4, 0, 1, 1); --ease-out: cubic-bezier(0, 0, .2, 1); --ease-in-out: cubic-bezier(.4, 0, .2, 1); --animate-spin: spin 1s linear infinite; --animate-ping: ping 1s cubic-bezier(0, 0, .2, 1) infinite; --animate-pulse: pulse 2s cubic-bezier(.4, 0, .6, 1) infinite; --animate-bounce: bounce 1s infinite; @keyframes spin { to { transform: rotate(360deg); } } @keyframes ping { 75%, 100% { transform: scale(2); opacity: 0; } } @keyframes pulse { 50% { opacity: .5; } } @keyframes bounce { 0%, 100% { transform: translateY(-25%); animation-timing-function: cubic-bezier(.8, 0, 1, 1); } 50% { transform: none; animation-timing-function: cubic-bezier(0, 0, .2, 1); } } --blur-xs: 4px; --blur-sm: 8px; --blur-md: 12px; --blur-lg: 16px; --blur-xl: 24px; --blur-2xl: 40px; --blur-3xl: 64px; --perspective-dramatic: 100px; --perspective-near: 300px; --perspective-normal: 500px; --perspective-midrange: 800px; --perspective-distant: 1200px; --aspect-video: 16 / 9; --default-transition-duration: .15s; --default-transition-timing-function: cubic-bezier(.4, 0, .2, 1); --default-font-family: --theme(--font-sans, initial); --default-font-feature-settings: --theme( --font-sans--font-feature-settings, initial ); --default-font-variation-settings: --theme( --font-sans--font-variation-settings, initial ); --default-mono-font-family: --theme(--font-mono, initial); --default-mono-font-feature-settings: --theme( --font-mono--font-feature-settings, initial ); --default-mono-font-variation-settings: --theme( --font-mono--font-variation-settings, initial ); }@theme default inline reference{ --blur: 8px; --shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1); --shadow-inner: inset 0 2px 4px 0 rgb(0 0 0 / .05); --drop-shadow: 0 1px 2px rgb(0 0 0 / .1), 0 1px 1px rgb(0 0 0 / .06); --radius: .25rem; --max-width-prose: 65ch; }}@layer base{*,:after,:before,::backdrop,::file-selector-button{box-sizing:border-box;margin:0;padding:0;border:0 solid}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;tab-size:4;font-family:--theme(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:--theme(--default-font-feature-settings,normal);font-variation-settings:--theme(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:--theme(--default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace);font-feature-settings:--theme(--default-mono-font-feature-settings,normal);font-variation-settings:--theme(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea,::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;border-radius:0;background-color:transparent;opacity:1}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit,::-webkit-datetime-edit-year-field,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-minute-field,::-webkit-datetime-edit-second-field,::-webkit-datetime-edit-millisecond-field,::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]),::file-selector-button{appearance:button}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer utilities{@tailwind utilities;}@source "../**/*.{ts,tsx,js,jsx}";@layer base{:host{all:initial;color-scheme:light;font-family:ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,sans-serif}*,*:before,*:after{box-sizing:border-box}button{font-family:inherit;cursor:pointer}button:disabled{cursor:not-allowed}[role=button],[role=radio]{cursor:pointer}}';
7
+ let W = !1;
8
+ function ge() {
9
+ if (W || (W = !0, typeof CSS > "u" || typeof CSS.registerProperty != "function")) return;
10
+ let r;
11
+ try {
12
+ const e = new CSSStyleSheet();
13
+ e.replaceSync(oe), r = e.cssRules;
14
+ } catch {
15
+ return;
16
+ }
17
+ for (const e of r) {
18
+ if (e.constructor.name !== "CSSPropertyRule") continue;
19
+ const t = e;
20
+ try {
21
+ CSS.registerProperty({
22
+ name: t.name,
23
+ syntax: t.syntax,
24
+ inherits: t.inherits,
25
+ ...t.initialValue != null ? { initialValue: t.initialValue } : {}
26
+ });
27
+ } catch {
28
+ }
29
+ }
30
+ }
31
+ function me(r, e, t = {}) {
32
+ if (typeof document > "u")
33
+ throw new Error("mountShadow called in non-DOM environment");
34
+ ge();
35
+ const n = t.host ?? document.createElement("div");
36
+ n.setAttribute("data-paywall-host", ""), n.style.cssText = "all: initial; position: fixed; inset: 0; z-index: 2147483647; pointer-events: none;", n.isConnected || document.body.appendChild(n);
37
+ const i = n.attachShadow({ mode: t.shadowMode ?? "closed" }), s = `
38
+ :host {
39
+ all: initial !important;
40
+ display: block !important;
41
+ color: #111827 !important;
42
+ font-family: ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif !important;
43
+ font-size: 16px !important;
44
+ font-weight: 400 !important;
45
+ font-style: normal !important;
46
+ line-height: 1.5 !important;
47
+ letter-spacing: normal !important;
48
+ text-transform: none !important;
49
+ text-decoration: none !important;
50
+ text-align: left !important;
51
+ direction: ltr !important;
52
+ cursor: auto !important;
53
+ visibility: visible !important;
54
+ }
55
+ `, l = document.createElement("style");
56
+ l.textContent = s + oe + (t.injectCss ?? ""), i.appendChild(l);
57
+ const a = document.createElement("div");
58
+ a.style.pointerEvents = "auto", i.appendChild(a);
59
+ let c = e;
60
+ return z(G(r, c), a), {
61
+ shadowRoot: i,
62
+ update(p) {
63
+ c = { ...c, ...p }, z(G(r, c), a);
64
+ },
65
+ unmount() {
66
+ z(null, a), n.remove();
67
+ }
68
+ };
69
+ }
70
+ const Z = 'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])';
71
+ function ye({
72
+ open: r,
73
+ onClose: e,
74
+ labelledBy: t,
75
+ brandColor: n,
76
+ testMode: i,
77
+ allowClose: s = !0,
78
+ children: l
79
+ }) {
80
+ const a = E(null), c = E(null);
81
+ return M(() => {
82
+ if (!r) return;
83
+ c.current = document.activeElement ?? null;
84
+ const b = a.current;
85
+ b && (b.querySelector(Z) ?? b).focus({ preventScroll: !0 });
86
+ const f = (y) => {
87
+ if (y.key === "Escape") {
88
+ if (!s) return;
89
+ y.stopPropagation(), e();
90
+ return;
91
+ }
92
+ if (y.key !== "Tab" || !a.current) return;
93
+ const _ = Array.from(
94
+ a.current.querySelectorAll(Z)
95
+ ).filter((w) => !w.hasAttribute("disabled") && w.tabIndex !== -1);
96
+ if (_.length === 0) {
97
+ y.preventDefault();
98
+ return;
99
+ }
100
+ const A = _[0], v = _[_.length - 1], S = document.activeElement;
101
+ y.shiftKey && S === A ? (y.preventDefault(), v.focus()) : !y.shiftKey && S === v && (y.preventDefault(), A.focus());
102
+ };
103
+ document.addEventListener("keydown", f, !0);
104
+ const m = document.body.style.overflow;
105
+ return document.body.style.overflow = "hidden", () => {
106
+ document.removeEventListener("keydown", f, !0), document.body.style.overflow = m, c.current?.focus?.({ preventScroll: !0 });
107
+ };
108
+ }, [r, e, s]), r ? /* @__PURE__ */ u(
109
+ "div",
110
+ {
111
+ class: "fixed inset-0 z-[2147483647] flex items-center justify-center bg-slate-950/50 p-2 sm:p-4 backdrop-blur-md animate-[pw-fade-in_180ms_ease-out]",
112
+ onClick: (b) => {
113
+ s && b.target === b.currentTarget && e();
114
+ },
115
+ "data-pw-root": !0,
116
+ children: [
117
+ /* @__PURE__ */ u(
118
+ "div",
119
+ {
120
+ ref: a,
121
+ role: "dialog",
122
+ "aria-modal": "true",
123
+ "aria-labelledby": t,
124
+ tabIndex: -1,
125
+ class: "relative flex max-h-[calc(100dvh-1rem)] sm:max-h-[calc(100dvh-2rem)] w-full max-w-md flex-col overflow-hidden rounded-3xl bg-white outline-none ring-1 ring-black/5 animate-[pw-scale-in_220ms_cubic-bezier(0.16,1,0.3,1)]",
126
+ style: {
127
+ "--pw-accent": n ?? "#3b82f6",
128
+ boxShadow: "0 1px 2px rgba(15,23,42,0.04), 0 12px 32px -8px rgba(15,23,42,0.18), 0 24px 64px -16px rgba(15,23,42,0.22)"
129
+ },
130
+ children: [
131
+ i && /* @__PURE__ */ u(
132
+ "div",
133
+ {
134
+ class: "flex items-center justify-center gap-1.5 bg-gradient-to-r from-amber-300 to-amber-400 px-3 py-1.5 text-[11px] font-semibold uppercase tracking-wider text-amber-950",
135
+ role: "status",
136
+ children: [
137
+ /* @__PURE__ */ u("svg", { width: "12", height: "12", viewBox: "0 0 16 16", fill: "none", "aria-hidden": "true", children: [
138
+ /* @__PURE__ */ o(
139
+ "path",
140
+ {
141
+ d: "M8 1L15 14H1L8 1Z",
142
+ stroke: "currentColor",
143
+ "stroke-width": "1.5",
144
+ "stroke-linejoin": "round"
145
+ }
146
+ ),
147
+ /* @__PURE__ */ o("path", { d: "M8 6v3", stroke: "currentColor", "stroke-width": "1.5", "stroke-linecap": "round" }),
148
+ /* @__PURE__ */ o("circle", { cx: "8", cy: "11.5", r: "0.5", fill: "currentColor" })
149
+ ] }),
150
+ "Test mode — no real charge"
151
+ ]
152
+ }
153
+ ),
154
+ /* @__PURE__ */ o("div", { class: "flex-1 overflow-y-auto p-7", children: l }),
155
+ s ? /* @__PURE__ */ o(
156
+ "button",
157
+ {
158
+ type: "button",
159
+ onClick: e,
160
+ "aria-label": "Close",
161
+ class: `absolute right-3 ${i ? "top-10" : "top-3"} z-10 flex h-8 w-8 items-center justify-center rounded-full bg-white/80 text-gray-400 backdrop-blur-sm transition-colors hover:bg-gray-100 hover:text-gray-700 focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--pw-accent)]`,
162
+ children: /* @__PURE__ */ o("svg", { width: "14", height: "14", viewBox: "0 0 16 16", fill: "none", "aria-hidden": "true", children: /* @__PURE__ */ o(
163
+ "path",
164
+ {
165
+ d: "M3 3l10 10M13 3L3 13",
166
+ stroke: "currentColor",
167
+ "stroke-width": "1.75",
168
+ "stroke-linecap": "round"
169
+ }
170
+ ) })
171
+ }
172
+ ) : null
173
+ ]
174
+ }
175
+ ),
176
+ /* @__PURE__ */ o("style", { children: `
177
+ @keyframes pw-fade-in { from { opacity: 0 } to { opacity: 1 } }
178
+ @keyframes pw-scale-in {
179
+ from { opacity: 0; transform: translateY(12px) scale(0.96) }
180
+ to { opacity: 1; transform: none }
181
+ }
182
+ ` })
183
+ ]
184
+ }
185
+ ) : null;
186
+ }
187
+ const xe = {
188
+ google: "Continue with Google",
189
+ apple: "Continue with Apple",
190
+ github: "Continue with GitHub",
191
+ facebook: "Continue with Facebook"
192
+ };
193
+ function se({ block: r, ctx: e }) {
194
+ const t = e.auth, n = e.authSession, i = r.allow_signup !== !1, s = r.allow_password_reset !== !1, l = r.hide_when_authenticated !== !1;
195
+ if (!t)
196
+ return typeof console < "u" && console.warn("[paywall] auth_panel rendered without AuthClient — pass `auth: true` to PaywallUI"), null;
197
+ const a = n && !n.user.is_anonymous ? n : null;
198
+ return a && l ? null : a ? /* @__PURE__ */ o(be, { email: a.user.email ?? "", onSignOut: () => t.signOut().catch(() => {
199
+ }) }) : /* @__PURE__ */ o(
200
+ ke,
201
+ {
202
+ block: r,
203
+ allowSignup: i,
204
+ allowReset: s,
205
+ ctx: e
206
+ }
207
+ );
208
+ }
209
+ function be({ email: r, onSignOut: e }) {
210
+ return /* @__PURE__ */ u("div", { class: "flex items-center justify-between gap-3 rounded-2xl border border-gray-200 bg-gray-50/60 px-4 py-3", children: [
211
+ /* @__PURE__ */ u("div", { class: "flex flex-col", children: [
212
+ /* @__PURE__ */ o("span", { class: "text-[10px] font-semibold uppercase tracking-wider text-gray-500", children: "Signed in" }),
213
+ /* @__PURE__ */ o("span", { class: "text-sm font-medium text-gray-900", children: r })
214
+ ] }),
215
+ /* @__PURE__ */ o(
216
+ "button",
217
+ {
218
+ type: "button",
219
+ onClick: e,
220
+ class: "rounded-md px-1.5 py-0.5 text-xs font-medium text-gray-600 transition-colors hover:bg-white hover:text-gray-900 focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--pw-accent)]",
221
+ children: "Sign out"
222
+ }
223
+ )
224
+ ] });
225
+ }
226
+ function ke({ block: r, allowSignup: e, allowReset: t, ctx: n }) {
227
+ const i = n.auth, s = r.providers ?? [], [l, a] = x("signin"), [c, p] = x(""), [g, b] = x(""), [f, m] = x(""), [y, _] = x(null), [A, v] = x(null), [S, w] = x(null), P = async (C) => {
228
+ if (C.preventDefault(), !y) {
229
+ _("email"), v(null), w(null);
230
+ try {
231
+ l === "signin" ? await i.signInWithEmail({ email: c, password: g }) : l === "signup" ? (await i.signUp({ email: c, password: g })).kind === "confirmation_required" && (a("reset_verify"), w("Check your email for a confirmation code.")) : l === "forgot" ? (await i.requestPasswordReset({ email: c }), a("reset_sent"), w("If that email exists, a reset code has been sent.")) : l === "reset_verify" && (await i.verifyOtp({
232
+ email: c,
233
+ token: f,
234
+ type: g ? "recovery" : "email"
235
+ }), g && await i.updatePassword({ password: g }));
236
+ } catch (I) {
237
+ const d = I instanceof T ? I.message : "Something went wrong";
238
+ v(d);
239
+ } finally {
240
+ _(null);
241
+ }
242
+ }
243
+ }, L = async (C) => {
244
+ if (!y) {
245
+ _(C), v(null), w(null);
246
+ try {
247
+ await i.signInWithOAuth({
248
+ provider: C,
249
+ onPopupOpened: () => _(null)
250
+ });
251
+ } catch (I) {
252
+ if (I instanceof T) {
253
+ if (I.code === "oauth_cancelled" || I.code === "oauth_timeout") return;
254
+ v(I.message);
255
+ } else
256
+ v("Sign-in failed");
257
+ } finally {
258
+ _(null);
259
+ }
260
+ }
261
+ };
262
+ return /* @__PURE__ */ u("div", { class: "flex flex-col gap-3", children: [
263
+ r.heading ? /* @__PURE__ */ o("h2", { class: "text-lg font-semibold tracking-tight text-gray-900", children: r.heading }) : null,
264
+ s.length > 0 && (l === "signin" || l === "signup") ? /* @__PURE__ */ u("div", { class: "flex flex-col gap-2", children: [
265
+ s.map((C) => /* @__PURE__ */ u(
266
+ "button",
267
+ {
268
+ type: "button",
269
+ onClick: () => L(C),
270
+ disabled: y !== null,
271
+ class: "flex h-11 w-full items-center justify-center gap-2 rounded-xl border border-gray-200 bg-white px-4 text-sm font-medium text-gray-900 shadow-[0_1px_0_rgba(15,23,42,0.04)] transition-all hover:-translate-y-px hover:border-gray-300 hover:bg-gray-50 hover:shadow-sm disabled:cursor-not-allowed disabled:opacity-60 disabled:hover:translate-y-0 disabled:hover:shadow-[0_1px_0_rgba(15,23,42,0.04)] focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--pw-accent)]",
272
+ children: [
273
+ y === C ? /* @__PURE__ */ o("span", { class: "inline-block h-4 w-4 animate-spin rounded-full border-2 border-gray-300 border-t-gray-700" }) : /* @__PURE__ */ o(_e, { provider: C }),
274
+ /* @__PURE__ */ o("span", { children: xe[C] })
275
+ ]
276
+ },
277
+ C
278
+ )),
279
+ /* @__PURE__ */ o(ve, {})
280
+ ] }) : null,
281
+ /* @__PURE__ */ u("form", { onSubmit: P, class: "flex flex-col gap-2", children: [
282
+ (l === "signin" || l === "signup" || l === "forgot") && /* @__PURE__ */ o(
283
+ j,
284
+ {
285
+ type: "email",
286
+ label: "Email",
287
+ value: c,
288
+ onInput: p,
289
+ autocomplete: "email",
290
+ required: !0
291
+ }
292
+ ),
293
+ (l === "signin" || l === "signup") && /* @__PURE__ */ o(
294
+ j,
295
+ {
296
+ type: "password",
297
+ label: "Password",
298
+ value: g,
299
+ onInput: b,
300
+ autocomplete: l === "signin" ? "current-password" : "new-password",
301
+ required: !0
302
+ }
303
+ ),
304
+ l === "reset_verify" && /* @__PURE__ */ u(ne, { children: [
305
+ /* @__PURE__ */ o(
306
+ j,
307
+ {
308
+ type: "text",
309
+ label: "Confirmation code",
310
+ value: f,
311
+ onInput: m,
312
+ autocomplete: "one-time-code",
313
+ inputMode: "numeric",
314
+ required: !0
315
+ }
316
+ ),
317
+ /* @__PURE__ */ o(
318
+ j,
319
+ {
320
+ type: "password",
321
+ label: "New password (optional — only for password reset)",
322
+ value: g,
323
+ onInput: b,
324
+ autocomplete: "new-password"
325
+ }
326
+ )
327
+ ] }),
328
+ l === "reset_sent" && S && /* @__PURE__ */ o("p", { class: "rounded-lg bg-gray-50 px-3 py-2 text-xs text-gray-600", children: S }),
329
+ A && /* @__PURE__ */ o("p", { class: "text-xs text-red-600", children: A }),
330
+ S && l !== "reset_sent" && /* @__PURE__ */ o("p", { class: "text-xs text-gray-500", children: S }),
331
+ l !== "reset_sent" && /* @__PURE__ */ o(
332
+ "button",
333
+ {
334
+ type: "submit",
335
+ disabled: y !== null,
336
+ class: "flex h-11 w-full items-center justify-center rounded-xl px-4 text-sm font-semibold tracking-tight text-white transition-all hover:-translate-y-px hover:brightness-105 disabled:cursor-not-allowed disabled:opacity-60 disabled:hover:translate-y-0 disabled:hover:brightness-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-[var(--pw-accent)]",
337
+ style: {
338
+ background: "linear-gradient(180deg, color-mix(in srgb, var(--pw-accent) 92%, white), var(--pw-accent))",
339
+ boxShadow: "0 1px 2px rgba(15,23,42,0.08), 0 6px 14px -4px color-mix(in srgb, var(--pw-accent) 50%, transparent)"
340
+ },
341
+ children: y === "email" ? /* @__PURE__ */ o("span", { class: "inline-block h-4 w-4 animate-spin rounded-full border-2 border-white/40 border-t-white" }) : we(l)
342
+ }
343
+ )
344
+ ] }),
345
+ /* @__PURE__ */ u("div", { class: "flex flex-wrap items-center justify-between gap-x-3 gap-y-1 text-xs text-gray-500", children: [
346
+ l === "signin" && e && /* @__PURE__ */ o("button", { type: "button", onClick: () => O(a, v, w, "signup"), class: "font-medium text-gray-700 hover:underline", children: "Create account" }),
347
+ l === "signup" && /* @__PURE__ */ o("button", { type: "button", onClick: () => O(a, v, w, "signin"), class: "font-medium text-gray-700 hover:underline", children: "I already have an account" }),
348
+ l === "signin" && t && /* @__PURE__ */ o("button", { type: "button", onClick: () => O(a, v, w, "forgot"), class: "hover:underline", children: "Forgot password?" }),
349
+ (l === "forgot" || l === "reset_sent" || l === "reset_verify") && /* @__PURE__ */ o("button", { type: "button", onClick: () => O(a, v, w, "signin"), class: "hover:underline", children: "Back to sign in" }),
350
+ l === "reset_sent" && /* @__PURE__ */ o("button", { type: "button", onClick: () => O(a, v, w, "reset_verify"), class: "font-medium text-gray-700 hover:underline", children: "I have a code" })
351
+ ] })
352
+ ] });
353
+ }
354
+ function we(r) {
355
+ switch (r) {
356
+ case "signin":
357
+ return "Sign in";
358
+ case "signup":
359
+ return "Create account";
360
+ case "forgot":
361
+ return "Send reset code";
362
+ case "reset_verify":
363
+ return "Verify";
364
+ default:
365
+ return "Continue";
366
+ }
367
+ }
368
+ function O(r, e, t, n) {
369
+ r(n), e(null), t(null);
370
+ }
371
+ function j({ type: r, label: e, value: t, onInput: n, autocomplete: i, inputMode: s, required: l }) {
372
+ return /* @__PURE__ */ u("label", { class: "flex flex-col gap-1.5", children: [
373
+ /* @__PURE__ */ o("span", { class: "text-xs font-medium text-gray-700", children: e }),
374
+ /* @__PURE__ */ o(
375
+ "input",
376
+ {
377
+ type: r,
378
+ value: t,
379
+ onInput: (a) => n(a.target.value),
380
+ autocomplete: i,
381
+ inputMode: s,
382
+ required: l,
383
+ class: "h-11 w-full rounded-xl border border-gray-200 bg-white px-3.5 text-sm text-gray-900 shadow-[0_1px_0_rgba(15,23,42,0.02)] outline-none transition-all placeholder:text-gray-400 hover:border-gray-300 focus:border-[var(--pw-accent)] focus:shadow-[0_0_0_3px_color-mix(in_srgb,var(--pw-accent)_18%,transparent)]"
384
+ }
385
+ )
386
+ ] });
387
+ }
388
+ function ve() {
389
+ return /* @__PURE__ */ u("div", { class: "flex items-center gap-2 py-1 text-[10px] uppercase tracking-[0.14em] text-gray-400", children: [
390
+ /* @__PURE__ */ o("div", { class: "h-px flex-1 bg-gradient-to-r from-gray-200 to-transparent" }),
391
+ /* @__PURE__ */ o("span", { children: "or" }),
392
+ /* @__PURE__ */ o("div", { class: "h-px flex-1 bg-gradient-to-r from-transparent to-gray-200" })
393
+ ] });
394
+ }
395
+ function _e({ provider: r }) {
396
+ return r === "google" ? /* @__PURE__ */ u("svg", { width: "16", height: "16", viewBox: "0 0 18 18", "aria-hidden": "true", children: [
397
+ /* @__PURE__ */ o("path", { fill: "#4285F4", d: "M17.64 9.2c0-.64-.06-1.25-.16-1.84H9v3.49h4.84a4.14 4.14 0 0 1-1.79 2.71v2.26h2.9c1.7-1.56 2.69-3.87 2.69-6.62Z" }),
398
+ /* @__PURE__ */ o("path", { fill: "#34A853", d: "M9 18c2.43 0 4.47-.8 5.96-2.18l-2.9-2.26c-.8.54-1.83.86-3.06.86-2.36 0-4.36-1.59-5.07-3.74H.92v2.33A9 9 0 0 0 9 18Z" }),
399
+ /* @__PURE__ */ o("path", { fill: "#FBBC05", d: "M3.93 10.68a5.4 5.4 0 0 1 0-3.36V4.99H.92a9 9 0 0 0 0 8.02l3-2.33Z" }),
400
+ /* @__PURE__ */ o("path", { fill: "#EA4335", d: "M9 3.58c1.32 0 2.5.45 3.44 1.34l2.58-2.58A9 9 0 0 0 .92 4.99l3.01 2.33C4.64 5.17 6.64 3.58 9 3.58Z" })
401
+ ] }) : r === "apple" ? /* @__PURE__ */ o("svg", { width: "14", height: "16", viewBox: "0 0 14 16", fill: "currentColor", "aria-hidden": "true", children: /* @__PURE__ */ o("path", { d: "M11.4 8.5c0-2 1.6-3 1.7-3-.9-1.3-2.4-1.5-2.9-1.5-1.2-.1-2.4.7-3 .7-.6 0-1.6-.7-2.6-.7-1.3 0-2.6.8-3.3 2C-.4 8.4.7 12.5 2.2 14.7c.7 1.1 1.6 2.3 2.7 2.3 1.1 0 1.5-.7 2.8-.7 1.3 0 1.7.7 2.8.7 1.2 0 1.9-1.1 2.6-2.2.6-.9 1-1.8 1.1-2.7-1.4-.5-2.8-1.7-2.8-3.6Zm-2-6.5C10 1.3 10.4.4 10.3 0c-.7 0-1.6.5-2.1 1.1-.5.5-1 1.4-.9 2.2.7 0 1.5-.4 2.1-1.3Z" }) }) : r === "github" ? /* @__PURE__ */ o("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "currentColor", "aria-hidden": "true", children: /* @__PURE__ */ o("path", { d: "M8 0C3.6 0 0 3.6 0 8a8 8 0 0 0 5.5 7.6c.4.1.5-.2.5-.4v-1.5c-2.2.5-2.7-1-2.7-1-.4-.9-.9-1.2-.9-1.2-.7-.5.1-.5.1-.5.8.1 1.2.8 1.2.8.7 1.2 1.9.9 2.4.7 0-.5.3-.9.5-1.1-1.8-.2-3.6-.9-3.6-4 0-.9.3-1.6.8-2.1-.1-.2-.4-1 .1-2.1 0 0 .7-.2 2.2.8a7.6 7.6 0 0 1 4 0c1.5-1 2.2-.8 2.2-.8.4 1.1.2 1.9.1 2.1.5.5.8 1.2.8 2.1 0 3.1-1.9 3.7-3.6 3.9.3.3.6.8.6 1.6V15c0 .2.1.5.6.4A8 8 0 0 0 16 8c0-4.4-3.6-8-8-8Z" }) }) : /* @__PURE__ */ o("svg", { width: "14", height: "16", viewBox: "0 0 14 16", fill: "currentColor", "aria-hidden": "true", children: /* @__PURE__ */ o("path", { d: "M14 2.7C14 1.2 12.8 0 11.3 0H2.7C1.2 0 0 1.2 0 2.7v10.6C0 14.8 1.2 16 2.7 16h4V9.8H4.7v-2H6.7V6.4c0-2 1.2-3.1 3-3.1.9 0 1.7.1 2 .2V5h-1.4c-.8 0-1 .4-1 1v1.5h2.4l-.3 2H9.3V16h2c1.5 0 2.7-1.2 2.7-2.7V2.7Z" }) });
402
+ }
403
+ function Se({
404
+ block: r,
405
+ bootstrap: e,
406
+ auth: t,
407
+ authSession: n,
408
+ onBack: i,
409
+ showBack: s = !0
410
+ }) {
411
+ return /* @__PURE__ */ u("div", { class: "flex flex-col gap-3", children: [
412
+ s ? /* @__PURE__ */ o(
413
+ "button",
414
+ {
415
+ type: "button",
416
+ onClick: i,
417
+ class: "-ml-1 self-start rounded-md px-1.5 py-0.5 text-xs font-medium text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-900 focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--pw-accent)]",
418
+ children: "← Back"
419
+ }
420
+ ) : null,
421
+ /* @__PURE__ */ o(se, { block: r, ctx: {
422
+ bootstrap: e,
423
+ selectedPriceId: null,
424
+ setSelectedPriceId: () => {
425
+ },
426
+ onAction: () => {
427
+ },
428
+ auth: t,
429
+ authSession: n
430
+ } })
431
+ ] });
432
+ }
433
+ function Ce({
434
+ auth: r,
435
+ onSuccess: e,
436
+ onBack: t,
437
+ heading: n = "Continue as guest",
438
+ description: i = "Setting up your guest session…"
439
+ }) {
440
+ const [s, l] = x({ kind: "signing-in" }), a = E(!0);
441
+ M(() => () => {
442
+ a.current = !1;
443
+ }, []);
444
+ const c = () => {
445
+ l({ kind: "signing-in" }), (async () => {
446
+ try {
447
+ const p = await r.signInAnonymously();
448
+ if (!a.current) return;
449
+ e(p);
450
+ } catch (p) {
451
+ if (!a.current) return;
452
+ l({
453
+ kind: "error",
454
+ message: p instanceof Error ? p.message : "Anonymous sign-in failed"
455
+ });
456
+ }
457
+ })();
458
+ };
459
+ return M(() => {
460
+ c();
461
+ }, []), /* @__PURE__ */ u("div", { class: "flex flex-col gap-3", children: [
462
+ t ? /* @__PURE__ */ o(
463
+ "button",
464
+ {
465
+ type: "button",
466
+ onClick: t,
467
+ class: "-ml-1 self-start rounded-md px-1.5 py-0.5 text-xs font-medium text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-900 focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--pw-accent)]",
468
+ children: "← Back"
469
+ }
470
+ ) : null,
471
+ /* @__PURE__ */ u("div", { class: "flex flex-col gap-1", children: [
472
+ /* @__PURE__ */ o("h2", { class: "text-xl font-semibold text-gray-900", children: n }),
473
+ /* @__PURE__ */ o("p", { class: "text-sm text-gray-500", children: i })
474
+ ] }),
475
+ s.kind === "signing-in" ? /* @__PURE__ */ o("div", { class: "flex items-center justify-center py-6", children: /* @__PURE__ */ o(Ie, {}) }) : null,
476
+ s.kind === "error" ? /* @__PURE__ */ u("div", { class: "flex flex-col gap-3", children: [
477
+ /* @__PURE__ */ o("div", { class: "rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700", children: s.message }),
478
+ /* @__PURE__ */ o(
479
+ "button",
480
+ {
481
+ type: "button",
482
+ onClick: c,
483
+ class: "self-start rounded-md bg-[var(--pw-accent)] px-3 py-1.5 text-sm font-medium text-white hover:opacity-90 focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--pw-accent)] focus-visible:ring-offset-2",
484
+ children: "Try again"
485
+ }
486
+ )
487
+ ] }) : null
488
+ ] });
489
+ }
490
+ function Ie() {
491
+ return /* @__PURE__ */ u("svg", { class: "h-5 w-5 animate-spin text-[var(--pw-accent)]", viewBox: "0 0 24 24", fill: "none", children: [
492
+ /* @__PURE__ */ o("circle", { cx: "12", cy: "12", r: "10", stroke: "currentColor", "stroke-width": "3", "stroke-opacity": "0.2" }),
493
+ /* @__PURE__ */ o("path", { d: "M22 12a10 10 0 0 0-10-10", stroke: "currentColor", "stroke-width": "3", "stroke-linecap": "round" })
494
+ ] });
495
+ }
496
+ const D = 3, F = 200, V = 5e3, $ = 5, Ae = 10 * 1024 * 1024, X = ["image/jpeg", "image/png", "image/webp"], Y = /.+@.+\..+/;
497
+ function Te({ client: r, authSession: e, origin: t, onBack: n }) {
498
+ const i = e?.user.email ?? "", s = i || null, [l, a] = x(i), [c, p] = x(""), [g, b] = x(""), [f, m] = x([]), [y, _] = x(!1), [A, v] = x(null), [S, w] = x({}), P = ie(() => {
499
+ const d = (s ?? l).trim().toLowerCase(), h = c.trim(), k = g.trim();
500
+ return Y.test(d) && h.length >= D && h.length <= F && k.length >= 1 && k.length <= V;
501
+ }, [s, l, c, g]), L = () => {
502
+ const d = {}, h = (s ?? l).trim(), k = c.trim(), U = g.trim();
503
+ return h ? Y.test(h.toLowerCase()) || (d.email = "Invalid email") : d.email = "Required", (k.length < D || k.length > F) && (d.subject = `${D}–${F} characters`), (U.length < 1 || U.length > V) && (d.message = `1–${V} characters`), w(d), Object.keys(d).length === 0;
504
+ }, C = async (d) => {
505
+ if (d.preventDefault(), !y && L()) {
506
+ _(!0), w((h) => ({ ...h, submit: void 0 }));
507
+ try {
508
+ const h = (s ?? l).trim();
509
+ await r.createSupportTicket({
510
+ subject: c.trim(),
511
+ content: g.trim(),
512
+ email: h || void 0,
513
+ files: f.length > 0 ? f : void 0
514
+ }), v(h);
515
+ } catch (h) {
516
+ const k = h instanceof T && h.message || "Failed to send. Please try again.";
517
+ w((U) => ({ ...U, submit: k }));
518
+ } finally {
519
+ _(!1);
520
+ }
521
+ }
522
+ }, I = () => {
523
+ p(""), b(""), m([]), w({}), v(null);
524
+ };
525
+ return A ? /* @__PURE__ */ u("div", { class: "flex flex-col items-center gap-4 py-2 text-center", children: [
526
+ /* @__PURE__ */ o(
527
+ "div",
528
+ {
529
+ class: "flex h-14 w-14 items-center justify-center rounded-full",
530
+ style: {
531
+ background: "linear-gradient(135deg, color-mix(in srgb, var(--pw-accent) 85%, white), var(--pw-accent))",
532
+ color: "#fff",
533
+ boxShadow: "0 0 0 8px color-mix(in srgb, var(--pw-accent) 12%, transparent), 0 8px 20px -6px color-mix(in srgb, var(--pw-accent) 45%, transparent)"
534
+ },
535
+ "aria-hidden": "true",
536
+ children: /* @__PURE__ */ o("svg", { viewBox: "0 0 24 24", class: "h-7 w-7", children: /* @__PURE__ */ o(
537
+ "path",
538
+ {
539
+ fill: "currentColor",
540
+ d: "M12 0a12 12 0 1 0 0 24 12 12 0 0 0 0-24Zm6.93 8.2-6.85 9.29a1.01 1.01 0 0 1-1.43.19L5.76 13.77a1 1 0 1 1 1.25-1.56l4.08 3.26 6.23-8.45a1 1 0 1 1 1.61 1.18Z"
541
+ }
542
+ ) })
543
+ }
544
+ ),
545
+ /* @__PURE__ */ o("div", { class: "text-lg font-semibold tracking-tight text-gray-900", children: "Request submitted" }),
546
+ /* @__PURE__ */ u("div", { class: "max-w-[320px] text-sm leading-relaxed text-gray-500", children: [
547
+ "We've received your message and will respond to",
548
+ " ",
549
+ /* @__PURE__ */ o("b", { class: "text-gray-700", children: A }),
550
+ "."
551
+ ] }),
552
+ /* @__PURE__ */ u("div", { class: "mt-2 flex items-center justify-center gap-3", children: [
553
+ /* @__PURE__ */ o(
554
+ "button",
555
+ {
556
+ type: "button",
557
+ onClick: n,
558
+ class: "rounded-xl px-3 py-2 text-sm font-medium text-gray-600 transition-colors hover:bg-gray-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--pw-accent)]",
559
+ children: t === "standalone" ? "Done" : "Back"
560
+ }
561
+ ),
562
+ /* @__PURE__ */ o(
563
+ "button",
564
+ {
565
+ type: "button",
566
+ onClick: I,
567
+ class: "flex h-10 items-center justify-center rounded-xl px-4 text-sm font-semibold text-white transition-all hover:-translate-y-px hover:brightness-105 focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-[var(--pw-accent)]",
568
+ style: {
569
+ background: "linear-gradient(180deg, color-mix(in srgb, var(--pw-accent) 92%, white), var(--pw-accent))",
570
+ boxShadow: "0 1px 2px rgba(15,23,42,0.08), 0 6px 14px -4px color-mix(in srgb, var(--pw-accent) 50%, transparent)"
571
+ },
572
+ children: "Send another request"
573
+ }
574
+ )
575
+ ] })
576
+ ] }) : /* @__PURE__ */ u("div", { class: "flex flex-col gap-3", children: [
577
+ /* @__PURE__ */ o("div", { class: "flex items-center justify-between", children: /* @__PURE__ */ u(
578
+ "button",
579
+ {
580
+ type: "button",
581
+ onClick: n,
582
+ class: "-ml-1 rounded-md px-1.5 py-0.5 text-xs font-medium text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-900 focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--pw-accent)]",
583
+ children: [
584
+ "← ",
585
+ t === "standalone" ? "Close" : "Back"
586
+ ]
587
+ }
588
+ ) }),
589
+ /* @__PURE__ */ o("h2", { class: "text-lg font-semibold tracking-tight text-gray-900", children: "Contact Support" }),
590
+ /* @__PURE__ */ o("p", { class: "text-xs leading-relaxed text-gray-500", children: "Fill out the form below and we'll get back to you." }),
591
+ /* @__PURE__ */ u("form", { onSubmit: C, class: "flex flex-col gap-3", children: [
592
+ s ? /* @__PURE__ */ u("div", { class: "rounded-xl border border-gray-200 bg-gray-50/60 px-3 py-2 text-xs text-gray-500", children: [
593
+ "Sending as ",
594
+ /* @__PURE__ */ o("b", { class: "font-medium text-gray-700", children: s })
595
+ ] }) : /* @__PURE__ */ o(
596
+ J,
597
+ {
598
+ type: "email",
599
+ label: "Your email",
600
+ value: l,
601
+ onInput: a,
602
+ error: S.email,
603
+ autocomplete: "email",
604
+ required: !0
605
+ }
606
+ ),
607
+ /* @__PURE__ */ o(
608
+ J,
609
+ {
610
+ type: "text",
611
+ label: "Subject",
612
+ value: c,
613
+ onInput: p,
614
+ error: S.subject,
615
+ required: !0
616
+ }
617
+ ),
618
+ /* @__PURE__ */ o(
619
+ Me,
620
+ {
621
+ label: "Message",
622
+ value: g,
623
+ onInput: b,
624
+ error: S.message,
625
+ required: !0
626
+ }
627
+ ),
628
+ /* @__PURE__ */ o(Ee, { files: f, onChange: m, disabled: y }),
629
+ S.submit && /* @__PURE__ */ o("p", { class: "text-xs text-red-600", children: S.submit }),
630
+ /* @__PURE__ */ u("div", { class: "mt-1 flex items-center justify-end gap-2", children: [
631
+ /* @__PURE__ */ o(
632
+ "button",
633
+ {
634
+ type: "button",
635
+ onClick: n,
636
+ disabled: y,
637
+ class: "rounded-xl px-3 py-2 text-sm font-medium text-gray-600 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-60 focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--pw-accent)]",
638
+ children: t === "standalone" ? "Close" : "Back"
639
+ }
640
+ ),
641
+ /* @__PURE__ */ o(
642
+ "button",
643
+ {
644
+ type: "submit",
645
+ disabled: !P || y,
646
+ class: "flex h-10 items-center justify-center rounded-xl px-4 text-sm font-semibold text-white transition-all hover:-translate-y-px hover:brightness-105 disabled:cursor-not-allowed disabled:opacity-60 disabled:hover:translate-y-0 disabled:hover:brightness-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-[var(--pw-accent)]",
647
+ style: {
648
+ background: "linear-gradient(180deg, color-mix(in srgb, var(--pw-accent) 92%, white), var(--pw-accent))",
649
+ boxShadow: "0 1px 2px rgba(15,23,42,0.08), 0 6px 14px -4px color-mix(in srgb, var(--pw-accent) 50%, transparent)"
650
+ },
651
+ children: y ? /* @__PURE__ */ o("span", { class: "inline-block h-4 w-4 animate-spin rounded-full border-2 border-white/40 border-t-white" }) : "Send"
652
+ }
653
+ )
654
+ ] })
655
+ ] })
656
+ ] });
657
+ }
658
+ function J({ type: r, label: e, value: t, onInput: n, error: i, autocomplete: s, required: l }) {
659
+ return /* @__PURE__ */ u("label", { class: "flex flex-col gap-1.5", children: [
660
+ /* @__PURE__ */ o("span", { class: "text-xs font-medium text-gray-700", children: e }),
661
+ /* @__PURE__ */ o(
662
+ "input",
663
+ {
664
+ type: r,
665
+ value: t,
666
+ onInput: (a) => n(a.target.value),
667
+ autocomplete: s,
668
+ required: l,
669
+ class: `h-11 w-full rounded-xl border bg-white px-3.5 text-sm text-gray-900 shadow-[0_1px_0_rgba(15,23,42,0.02)] outline-none transition-all placeholder:text-gray-400 ${i ? "border-red-400 focus:border-red-500 focus:shadow-[0_0_0_3px_rgba(239,68,68,0.18)]" : "border-gray-200 hover:border-gray-300 focus:border-[var(--pw-accent)] focus:shadow-[0_0_0_3px_color-mix(in_srgb,var(--pw-accent)_18%,transparent)]"}`
670
+ }
671
+ ),
672
+ i && /* @__PURE__ */ o("span", { class: "text-xs text-red-600", children: i })
673
+ ] });
674
+ }
675
+ function Me({ label: r, value: e, onInput: t, error: n, required: i }) {
676
+ return /* @__PURE__ */ u("label", { class: "flex flex-col gap-1.5", children: [
677
+ /* @__PURE__ */ o("span", { class: "text-xs font-medium text-gray-700", children: r }),
678
+ /* @__PURE__ */ o(
679
+ "textarea",
680
+ {
681
+ value: e,
682
+ onInput: (s) => t(s.target.value),
683
+ required: i,
684
+ rows: 4,
685
+ class: `min-h-[104px] w-full rounded-xl border bg-white px-3.5 py-2.5 text-sm leading-relaxed text-gray-900 shadow-[0_1px_0_rgba(15,23,42,0.02)] outline-none transition-all placeholder:text-gray-400 ${n ? "border-red-400 focus:border-red-500 focus:shadow-[0_0_0_3px_rgba(239,68,68,0.18)]" : "border-gray-200 hover:border-gray-300 focus:border-[var(--pw-accent)] focus:shadow-[0_0_0_3px_color-mix(in_srgb,var(--pw-accent)_18%,transparent)]"}`
686
+ }
687
+ ),
688
+ n && /* @__PURE__ */ o("span", { class: "text-xs text-red-600", children: n })
689
+ ] });
690
+ }
691
+ function Ee({ files: r, onChange: e, disabled: t }) {
692
+ const n = E(null), [i, s] = x(!1), [l, a] = x(null), c = (p) => {
693
+ if (!p || t) return;
694
+ a(null);
695
+ const g = Array.from(p);
696
+ if (r.length + g.length > $) {
697
+ a(`Up to ${$} files`);
698
+ return;
699
+ }
700
+ const b = g.filter(
701
+ (f) => X.includes(f.type) && f.size <= Ae
702
+ );
703
+ if (b.length !== g.length) {
704
+ a("Only JPEG/PNG/WebP, ≤ 10MB each");
705
+ return;
706
+ }
707
+ e([...r, ...b]);
708
+ };
709
+ return /* @__PURE__ */ u("div", { children: [
710
+ /* @__PURE__ */ o("span", { class: "text-xs font-medium text-gray-700", children: "Attachments (optional)" }),
711
+ /* @__PURE__ */ u(
712
+ "div",
713
+ {
714
+ role: "button",
715
+ tabIndex: 0,
716
+ "aria-label": "Attachments upload",
717
+ onClick: () => !t && n.current?.click(),
718
+ onDragOver: (p) => {
719
+ p.preventDefault(), t || s(!0);
720
+ },
721
+ onDragLeave: () => s(!1),
722
+ onDrop: (p) => {
723
+ p.preventDefault(), s(!1), c(p.dataTransfer?.files ?? null);
724
+ },
725
+ class: `mt-1.5 cursor-pointer rounded-2xl border border-dashed p-3.5 text-center transition-all ${i ? "border-[var(--pw-accent)] bg-[color-mix(in_srgb,var(--pw-accent)_6%,white)]" : "border-gray-300 hover:border-gray-400 hover:bg-gray-50/60"} ${t ? "cursor-not-allowed opacity-60" : ""}`,
726
+ children: [
727
+ /* @__PURE__ */ o("div", { class: "text-xs text-gray-500", children: "Drop images here or click to select" }),
728
+ /* @__PURE__ */ u("div", { class: "mt-0.5 text-[11px] text-gray-400", children: [
729
+ "JPEG/PNG/WebP, up to ",
730
+ $,
731
+ " files, ≤ 10MB each"
732
+ ] })
733
+ ]
734
+ }
735
+ ),
736
+ /* @__PURE__ */ o(
737
+ "input",
738
+ {
739
+ ref: n,
740
+ type: "file",
741
+ multiple: !0,
742
+ accept: X.join(","),
743
+ class: "hidden",
744
+ onChange: (p) => {
745
+ c(p.target.files), p.currentTarget.value = "";
746
+ }
747
+ }
748
+ ),
749
+ l && /* @__PURE__ */ o("p", { class: "mt-1 text-xs text-red-600", children: l }),
750
+ r.length > 0 && /* @__PURE__ */ o("ul", { class: "mt-2 flex flex-col gap-1", children: r.map((p, g) => /* @__PURE__ */ u(
751
+ "li",
752
+ {
753
+ class: "flex items-center justify-between gap-2 rounded bg-gray-50 px-2 py-1 text-xs",
754
+ children: [
755
+ /* @__PURE__ */ o("span", { class: "truncate text-gray-700", children: p.name }),
756
+ /* @__PURE__ */ o(
757
+ "button",
758
+ {
759
+ type: "button",
760
+ onClick: () => {
761
+ const b = [...r];
762
+ b.splice(g, 1), e(b);
763
+ },
764
+ disabled: t,
765
+ class: "text-gray-500 hover:text-red-600 disabled:cursor-not-allowed disabled:opacity-60",
766
+ "aria-label": `Remove ${p.name}`,
767
+ children: "✕"
768
+ }
769
+ )
770
+ ]
771
+ },
772
+ `${p.name}-${p.size}-${g}`
773
+ )) })
774
+ ] });
775
+ }
776
+ function Be({ block: r, ctx: e }) {
777
+ const [t, n] = x(!1), i = r.priceId ?? e.selectedPriceId, s = t || r.action === "checkout" && !i;
778
+ return /* @__PURE__ */ o(
779
+ "button",
780
+ {
781
+ type: "button",
782
+ disabled: s,
783
+ onClick: async () => {
784
+ if (!s) {
785
+ n(!0);
786
+ try {
787
+ await e.onAction(r.action, { priceId: i });
788
+ } finally {
789
+ n(!1);
790
+ }
791
+ }
792
+ },
793
+ class: "relative flex h-12 w-full items-center justify-center overflow-hidden rounded-2xl px-4 text-sm font-semibold tracking-tight text-white transition-all duration-150 hover:-translate-y-px hover:brightness-105 active:translate-y-0 active:brightness-95 disabled:cursor-not-allowed disabled:opacity-60 disabled:hover:translate-y-0 disabled:hover:brightness-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-[var(--pw-accent)]",
794
+ style: {
795
+ background: "linear-gradient(180deg, color-mix(in srgb, var(--pw-accent) 92%, white), var(--pw-accent))",
796
+ boxShadow: "0 1px 0 rgba(255,255,255,0.25) inset, 0 1px 2px rgba(15,23,42,0.08), 0 8px 20px -6px color-mix(in srgb, var(--pw-accent) 50%, transparent)"
797
+ },
798
+ children: t ? /* @__PURE__ */ o("span", { class: "inline-block h-4 w-4 animate-spin rounded-full border-2 border-white/40 border-t-white" }) : r.label
799
+ }
800
+ );
801
+ }
802
+ function Pe({ ctx: r }) {
803
+ const e = r.authSession, t = r.auth, [n, i] = x(!1), s = () => r.onAction("support");
804
+ if (e && !e.user.is_anonymous) {
805
+ const l = async () => {
806
+ if (!(!t || n)) {
807
+ i(!0);
808
+ try {
809
+ await t.signOut();
810
+ } catch {
811
+ } finally {
812
+ i(!1);
813
+ }
814
+ }
815
+ };
816
+ return /* @__PURE__ */ u("div", { class: "mt-2 text-center text-xs text-gray-500", children: [
817
+ /* @__PURE__ */ o("span", { children: "Signed in as " }),
818
+ /* @__PURE__ */ o("b", { class: "font-medium text-gray-700", children: e.user.email }),
819
+ /* @__PURE__ */ u("div", { class: "mt-1 flex items-center justify-center gap-3", children: [
820
+ /* @__PURE__ */ o(
821
+ "button",
822
+ {
823
+ type: "button",
824
+ onClick: l,
825
+ disabled: !t || n,
826
+ class: "font-medium text-gray-600 underline-offset-2 hover:underline disabled:cursor-not-allowed disabled:opacity-60 focus:outline-none focus-visible:underline",
827
+ children: n ? "Signing out…" : "Sign out"
828
+ }
829
+ ),
830
+ /* @__PURE__ */ o(Q, {}),
831
+ /* @__PURE__ */ o(K, { onClick: s })
832
+ ] })
833
+ ] });
834
+ }
835
+ return /* @__PURE__ */ u("div", { class: "mt-2 flex items-center justify-center gap-3 text-center text-xs text-gray-500", children: [
836
+ /* @__PURE__ */ o(
837
+ "button",
838
+ {
839
+ type: "button",
840
+ onClick: () => r.onAction("restore"),
841
+ class: "font-medium text-gray-600 underline-offset-2 hover:underline focus:outline-none focus-visible:underline",
842
+ children: "Restore purchases"
843
+ }
844
+ ),
845
+ /* @__PURE__ */ o(Q, {}),
846
+ /* @__PURE__ */ o(K, { onClick: s })
847
+ ] });
848
+ }
849
+ function K({ onClick: r }) {
850
+ return /* @__PURE__ */ o(
851
+ "button",
852
+ {
853
+ type: "button",
854
+ onClick: r,
855
+ class: "font-medium text-gray-600 underline-offset-2 hover:underline focus:outline-none focus-visible:underline",
856
+ children: "Contact Support"
857
+ }
858
+ );
859
+ }
860
+ function Q() {
861
+ return /* @__PURE__ */ o("span", { class: "h-1 w-1 rounded-full bg-gray-300", "aria-hidden": "true" });
862
+ }
863
+ function Le({ block: r }) {
864
+ return r.items.length ? /* @__PURE__ */ o("ul", { class: "flex flex-col gap-2.5", role: "list", children: r.items.map((e) => /* @__PURE__ */ u("li", { class: "flex items-start gap-3 text-sm text-gray-700", children: [
865
+ /* @__PURE__ */ o(
866
+ "span",
867
+ {
868
+ class: "mt-px flex h-5 w-5 flex-shrink-0 items-center justify-center rounded-full",
869
+ style: {
870
+ background: "color-mix(in srgb, var(--pw-accent) 12%, white)",
871
+ color: "var(--pw-accent)"
872
+ },
873
+ "aria-hidden": "true",
874
+ children: /* @__PURE__ */ o("svg", { width: "12", height: "12", viewBox: "0 0 20 20", fill: "none", children: /* @__PURE__ */ o(
875
+ "path",
876
+ {
877
+ d: "M5 10l3 3 7-7",
878
+ stroke: "currentColor",
879
+ "stroke-width": "2.5",
880
+ "stroke-linecap": "round",
881
+ "stroke-linejoin": "round"
882
+ }
883
+ ) })
884
+ }
885
+ ),
886
+ /* @__PURE__ */ u("div", { class: "flex flex-col gap-0.5", children: [
887
+ /* @__PURE__ */ o("span", { class: "font-medium leading-snug text-gray-900", children: e.name }),
888
+ e.desc ? /* @__PURE__ */ o("span", { class: "text-xs leading-relaxed text-gray-500", children: e.desc }) : null
889
+ ] })
890
+ ] }, e.id)) }) : null;
891
+ }
892
+ const le = 26, Ue = 14, Oe = 2;
893
+ function je(r, e) {
894
+ const t = e * Oe;
895
+ let n = le;
896
+ for (r.style.fontSize = `${n}px`; r.scrollHeight > t && n > Ue; )
897
+ n -= 1, r.style.fontSize = `${n}px`;
898
+ }
899
+ function qe({ block: r, ctx: e }) {
900
+ const t = r.level ?? 1, n = `h${t}`, i = t === 1 ? "text-[1.625rem] font-semibold leading-tight text-gray-900 tracking-[-0.02em]" : t === 2 ? "text-xl font-semibold leading-snug text-gray-900 tracking-tight" : "text-base font-medium text-gray-900", s = E(null), l = t === 1 && !!e.bootstrap.settings.title_auto_fit;
901
+ return M(() => {
902
+ if (!l || !s.current) return;
903
+ const a = getComputedStyle(s.current), c = parseFloat(a.lineHeight) || le * 1.5;
904
+ je(s.current, c);
905
+ }, [l, r.text]), /* @__PURE__ */ o(n, { ref: s, class: i, children: r.text });
906
+ }
907
+ function Re(r) {
908
+ const e = r.local ?? { currency: r.currency, amount: r.amount };
909
+ try {
910
+ return new Intl.NumberFormat(void 0, {
911
+ style: "currency",
912
+ currency: e.currency,
913
+ maximumFractionDigits: e.amount % 1 === 0 ? 0 : 2
914
+ }).format(e.amount);
915
+ } catch {
916
+ return `${e.amount} ${e.currency}`;
917
+ }
918
+ }
919
+ function ee(r) {
920
+ if (!r.interval || r.interval === "lifetime") return "one-time";
921
+ const e = r.interval_count ?? 1;
922
+ return e === 1 ? `per ${r.interval}` : `every ${e} ${r.interval}s`;
923
+ }
924
+ function ze({ block: r, ctx: e }) {
925
+ const t = r.priceIds && r.priceIds.length > 0 ? new Set(r.priceIds) : null, n = e.bootstrap.prices.filter((a) => !t || t.has(a.id));
926
+ if (n.length === 0)
927
+ return /* @__PURE__ */ o("p", { class: "text-sm text-gray-500", children: "No prices available." });
928
+ const i = r.view === "horizontal", s = r.popular_label ?? "Most popular", l = i ? Math.min(n.length, 3) : 1;
929
+ return /* @__PURE__ */ o(
930
+ "div",
931
+ {
932
+ class: i ? "grid gap-2.5" : "flex flex-col gap-2.5",
933
+ style: i ? { gridTemplateColumns: `repeat(${l}, minmax(0, 1fr))` } : void 0,
934
+ role: "radiogroup",
935
+ "aria-label": "Plans",
936
+ children: n.map((a) => {
937
+ const c = e.selectedPriceId === a.id, p = r.popular_price_id === a.id;
938
+ return /* @__PURE__ */ u(
939
+ "button",
940
+ {
941
+ type: "button",
942
+ role: "radio",
943
+ "aria-checked": c,
944
+ onClick: () => {
945
+ e.setSelectedPriceId(a.id), e.onAction("price_selected", { priceId: a.id, price: a });
946
+ },
947
+ class: [
948
+ "group relative rounded-2xl border px-4 py-3.5 text-left transition-all duration-150 focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-[var(--pw-accent)]",
949
+ i ? "flex w-full flex-col items-start gap-1" : "flex w-full items-center justify-between gap-3",
950
+ c ? "border-[var(--pw-accent)] bg-[color-mix(in_srgb,var(--pw-accent)_6%,white)] shadow-[0_0_0_3px_color-mix(in_srgb,var(--pw-accent)_12%,transparent)]" : "border-gray-200 bg-white hover:border-gray-300 hover:shadow-sm",
951
+ p ? "mt-2.5" : ""
952
+ ].join(" "),
953
+ children: [
954
+ p ? /* @__PURE__ */ o(
955
+ "span",
956
+ {
957
+ class: "absolute -top-2.5 left-4 rounded-full px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-white shadow-sm",
958
+ style: {
959
+ background: "linear-gradient(135deg, var(--pw-accent), color-mix(in srgb, var(--pw-accent) 70%, black))"
960
+ },
961
+ children: s
962
+ }
963
+ ) : null,
964
+ /* @__PURE__ */ u("div", { class: i ? "flex w-full items-start gap-2.5" : "flex flex-1 items-start gap-2.5", children: [
965
+ /* @__PURE__ */ o(
966
+ "span",
967
+ {
968
+ class: [
969
+ "mt-0.5 flex h-4 w-4 flex-shrink-0 items-center justify-center rounded-full border transition-colors",
970
+ c ? "border-[var(--pw-accent)] bg-[var(--pw-accent)]" : "border-gray-300 bg-white group-hover:border-gray-400"
971
+ ].join(" "),
972
+ "aria-hidden": "true",
973
+ children: c ? /* @__PURE__ */ o("span", { class: "h-1.5 w-1.5 rounded-full bg-white" }) : null
974
+ }
975
+ ),
976
+ /* @__PURE__ */ u("div", { class: "flex flex-col", children: [
977
+ /* @__PURE__ */ o("span", { class: "text-sm font-semibold text-gray-900", children: a.label ?? ee(a) }),
978
+ a.description ? /* @__PURE__ */ o("span", { class: "text-xs leading-relaxed text-gray-500", children: a.description }) : null,
979
+ a.trial_days ? /* @__PURE__ */ u("span", { class: "text-xs font-medium text-[var(--pw-accent)]", children: [
980
+ a.trial_days,
981
+ "-day free trial"
982
+ ] }) : null
983
+ ] })
984
+ ] }),
985
+ /* @__PURE__ */ u("div", { class: i ? "mt-1 flex flex-col items-start" : "flex flex-col items-end", children: [
986
+ /* @__PURE__ */ o("span", { class: "text-base font-semibold tracking-tight text-gray-900", children: Re(a) }),
987
+ /* @__PURE__ */ o("span", { class: "text-[11px] text-gray-500", children: ee(a) })
988
+ ] })
989
+ ]
990
+ },
991
+ a.id
992
+ );
993
+ })
994
+ }
995
+ );
996
+ }
997
+ function De({ block: r }) {
998
+ return /* @__PURE__ */ o("p", { class: "text-[0.9375rem] leading-relaxed text-gray-600", children: r.text });
999
+ }
1000
+ const Fe = {
1001
+ week: 0.25,
1002
+ month: 1,
1003
+ year: 12
1004
+ };
1005
+ function Ve(r) {
1006
+ return r || "period";
1007
+ }
1008
+ function $e({ block: r, ctx: e }) {
1009
+ if (!r.queries.length) return null;
1010
+ const n = e.bootstrap.prices.find((s) => s.id === e.selectedPriceId)?.interval ?? null, i = n ? Fe[n] : void 0;
1011
+ return /* @__PURE__ */ u("div", { class: "flex flex-col gap-2", children: [
1012
+ /* @__PURE__ */ u("div", { class: "text-sm font-semibold text-gray-800", children: [
1013
+ "Included per ",
1014
+ /* @__PURE__ */ o("span", { children: Ve(n) }),
1015
+ ":"
1016
+ ] }),
1017
+ /* @__PURE__ */ o("ul", { class: "flex flex-col gap-2", role: "list", children: r.queries.map((s) => {
1018
+ const l = Number.isFinite(s.count) ? s.count : 0, a = i !== void 0 ? Math.round(l * i) : l;
1019
+ return /* @__PURE__ */ u("li", { class: `flex gap-2 ${s.desc ? "" : "items-center"}`, children: [
1020
+ /* @__PURE__ */ o(
1021
+ "span",
1022
+ {
1023
+ class: `flex h-5 w-5 flex-shrink-0 items-center justify-center rounded-full ${s.desc ? "mt-0.5" : ""}`,
1024
+ style: {
1025
+ background: "color-mix(in srgb, var(--pw-accent) 12%, white)",
1026
+ color: "var(--pw-accent)"
1027
+ },
1028
+ "aria-hidden": "true",
1029
+ children: /* @__PURE__ */ o("svg", { width: "12", height: "12", viewBox: "0 0 20 20", fill: "none", children: /* @__PURE__ */ o(
1030
+ "path",
1031
+ {
1032
+ d: "M5 10l3 3 7-7",
1033
+ stroke: "currentColor",
1034
+ "stroke-width": "2.5",
1035
+ "stroke-linecap": "round",
1036
+ "stroke-linejoin": "round"
1037
+ }
1038
+ ) })
1039
+ }
1040
+ ),
1041
+ /* @__PURE__ */ u("div", { children: [
1042
+ /* @__PURE__ */ o("span", { class: "font-semibold text-gray-900 text-sm", children: a }),
1043
+ " ",
1044
+ /* @__PURE__ */ o("span", { class: "text-sm text-gray-800", children: s.name }),
1045
+ s.desc ? /* @__PURE__ */ u(ne, { children: [
1046
+ /* @__PURE__ */ o("br", {}),
1047
+ /* @__PURE__ */ o("span", { class: "text-xs text-gray-500", children: s.desc })
1048
+ ] }) : null
1049
+ ] })
1050
+ ] }, s.id);
1051
+ }) })
1052
+ ] });
1053
+ }
1054
+ const Ne = {
1055
+ heading: qe,
1056
+ text: De,
1057
+ price_grid: ze,
1058
+ cta_button: Be,
1059
+ auth_panel: se,
1060
+ current_session: Pe,
1061
+ features_list: Le,
1062
+ tokenization_gate: $e
1063
+ };
1064
+ function He({ layout: r, bootstrap: e, onAction: t, auth: n, authSession: i }) {
1065
+ const s = ie(() => e.prices[0]?.id ?? null, [e.prices]), [l, a] = x(s), c = {
1066
+ bootstrap: e,
1067
+ selectedPriceId: l,
1068
+ setSelectedPriceId: a,
1069
+ onAction: t,
1070
+ auth: n,
1071
+ authSession: i
1072
+ };
1073
+ return /* @__PURE__ */ o("div", { class: "flex flex-col gap-4", children: r.blocks.map((p, g) => {
1074
+ const b = Ne[p.type];
1075
+ return b ? /* @__PURE__ */ o(b, { block: p, ctx: c }, g) : (typeof console < "u" && console.warn(`[paywall] unknown block type: ${p.type}`), null);
1076
+ }) });
1077
+ }
1078
+ function Ge(r, e, t, n) {
1079
+ return r ? n ? { open: !0, view: "purchased", error: null } : e.status === "idle" || e.status === "loading" ? { open: !0, view: "loading", error: null } : e.status === "error" ? { open: !0, view: "error", error: e.error } : t.kind === "support" ? { open: !0, view: "support", error: null } : t.kind === "auth_gate" ? { open: !0, view: "auth", error: null } : t.kind === "anon_gate" ? { open: !0, view: "anon", error: null } : t.kind === "awaiting_payment" ? { open: !0, view: "awaiting_payment", error: null } : t.kind === "popup_blocked" ? { open: !0, view: "popup_blocked", error: null } : t.kind === "purchase_success" ? { open: !0, view: "purchased", error: null } : t.kind === "verifying" ? { open: !0, view: "loading", error: null } : { open: !0, view: "layout", error: null } : { open: !1, view: null, error: null };
1080
+ }
1081
+ function We(r, e) {
1082
+ return r.open === e.open && r.view === e.view && r.error === e.error;
1083
+ }
1084
+ function Ze({
1085
+ client: r,
1086
+ open: e,
1087
+ onClose: t,
1088
+ onEvent: n,
1089
+ initialView: i,
1090
+ purchased: s,
1091
+ renew: l,
1092
+ onState: a
1093
+ }) {
1094
+ const [c, p] = x({ status: "idle" }), [g, b] = x(
1095
+ () => r.auth?.getCachedSession() ?? null
1096
+ ), [f, m] = x(() => i === "support" ? { kind: "support", origin: "standalone" } : i === "auth" ? { kind: "auth_gate", origin: "standalone" } : i === "anon" ? { kind: "anon_gate", origin: "standalone" } : { kind: "layout" }), y = E(!1), _ = E(null);
1097
+ M(() => {
1098
+ if (!a) return;
1099
+ const d = Ge(e, c, f, s), h = _.current;
1100
+ h && We(h, d) || (_.current = d, a(d));
1101
+ }, [e, c, f, s, a]), M(() => {
1102
+ if (r.auth)
1103
+ return r.auth.onAuthChange((d) => b(d));
1104
+ }, [r.auth]), M(() => {
1105
+ if (!e || c.status === "ready" || c.status === "loading") return;
1106
+ let d = !1;
1107
+ return p({ status: "loading" }), r.bootstrap().then((h) => {
1108
+ d || (p({ status: "ready", data: h }), n("ready", h), h.user?.has_active_subscription && !l && (n("purchase_completed", {
1109
+ priceId: null,
1110
+ sessionId: null,
1111
+ restored: !0
1112
+ }), m({ kind: "purchase_success", restored: !0 })));
1113
+ }).catch((h) => {
1114
+ if (d) return;
1115
+ const k = h instanceof T ? h : new T("unknown", "Failed to load paywall", { cause: h });
1116
+ p({ status: "error", error: k }), n("error", k);
1117
+ }), () => {
1118
+ d = !0;
1119
+ };
1120
+ }, [e, r]), M(() => {
1121
+ if (!e) {
1122
+ m({ kind: "layout" }), y.current = !1;
1123
+ return;
1124
+ }
1125
+ i === "support" ? m({ kind: "support", origin: "standalone" }) : i === "auth" ? m({ kind: "auth_gate", origin: "standalone" }) : i === "anon" && m({ kind: "anon_gate", origin: "standalone" });
1126
+ }, [e, i]);
1127
+ const A = async (d) => {
1128
+ try {
1129
+ const h = await r.createCheckout({
1130
+ priceId: d,
1131
+ ignoreActivePurchase: l === !0
1132
+ });
1133
+ if (n("checkout_started", { priceId: d, url: h.url, acquiring: h.acquiring }), typeof window > "u" || !h.url) return;
1134
+ const k = window.open(h.url, "_blank");
1135
+ if (k) {
1136
+ try {
1137
+ k.opener = null;
1138
+ } catch {
1139
+ }
1140
+ m({ kind: "awaiting_payment", priceId: d, url: h.url });
1141
+ } else
1142
+ m({ kind: "popup_blocked", priceId: d, url: h.url });
1143
+ } catch (h) {
1144
+ if (h instanceof T && h.code === "already_purchased") {
1145
+ try {
1146
+ await r.getUser({ force: !0 });
1147
+ } catch {
1148
+ }
1149
+ n("purchase_completed", { priceId: d, sessionId: null, restored: !0 }), m({ kind: "purchase_success", restored: !0 });
1150
+ return;
1151
+ }
1152
+ const k = h instanceof T ? h : new T("checkout_failed", "Checkout failed", { cause: h });
1153
+ n("error", k), m({ kind: "layout" });
1154
+ }
1155
+ }, v = (d, h) => {
1156
+ if (typeof window > "u") return;
1157
+ const k = window.open(h, "_blank");
1158
+ if (k) {
1159
+ try {
1160
+ k.opener = null;
1161
+ } catch {
1162
+ }
1163
+ m({ kind: "awaiting_payment", priceId: d, url: h });
1164
+ }
1165
+ };
1166
+ M(() => {
1167
+ if (f.kind !== "auth_gate" || !g || g.user.is_anonymous || y.current) return;
1168
+ y.current = !0;
1169
+ const d = f.pendingCheckout, h = f.origin;
1170
+ m({ kind: "verifying" }), (async () => {
1171
+ if (!l)
1172
+ try {
1173
+ if ((await r.getUser({ force: !0 })).has_active_subscription) {
1174
+ n("purchase_completed", {
1175
+ priceId: d?.priceId ?? null,
1176
+ sessionId: null,
1177
+ restored: !0
1178
+ }), m({ kind: "purchase_success", restored: !0 });
1179
+ return;
1180
+ }
1181
+ } catch {
1182
+ }
1183
+ if (!d) {
1184
+ h === "standalone" ? t() : m({ kind: "layout" });
1185
+ return;
1186
+ }
1187
+ await A(d.priceId);
1188
+ })().finally(() => {
1189
+ y.current = !1;
1190
+ });
1191
+ }, [g, f]);
1192
+ const S = async (d, h) => {
1193
+ if (d === "close") {
1194
+ t();
1195
+ return;
1196
+ }
1197
+ if (d === "price_selected") {
1198
+ n("price_selected", h);
1199
+ return;
1200
+ }
1201
+ if (d === "restore") {
1202
+ if (!r.auth || r.auth.getCachedSession()) return;
1203
+ m({ kind: "auth_gate" });
1204
+ return;
1205
+ }
1206
+ if (d === "support") {
1207
+ m({ kind: "support", origin: "layout" });
1208
+ return;
1209
+ }
1210
+ if (d === "checkout" && c.status === "ready") {
1211
+ const k = h?.priceId;
1212
+ if (!k) {
1213
+ n("error", new T("no_price", "No price selected"));
1214
+ return;
1215
+ }
1216
+ if ((c.data.settings.checkout_mode ?? "guest") === "preauth" && !!r.auth && !r.auth.getCachedSession()) {
1217
+ m({ kind: "auth_gate", pendingCheckout: { priceId: k } });
1218
+ return;
1219
+ }
1220
+ await A(k);
1221
+ }
1222
+ }, w = c.status === "ready" ? c.data.settings.brand_color : null, P = c.status === "ready" ? !!c.data.settings.is_test_mode : !1, L = c.status === "ready" ? c.data.settings.allow_close !== !1 : !0, C = {
1223
+ type: "auth_panel",
1224
+ heading: "Sign in to continue",
1225
+ allow_signup: !0,
1226
+ allow_password_reset: !0,
1227
+ // Не скрываем при наличии сессии — auto-resume useEffect отрабатывает быстрее,
1228
+ // чем хотим показывать "Signed in as ..." промежуточным экраном.
1229
+ hide_when_authenticated: !1,
1230
+ providers: c.status === "ready" ? c.data.settings.auth_providers : void 0
1231
+ }, I = f.kind === "support" ? /* @__PURE__ */ o(
1232
+ Te,
1233
+ {
1234
+ client: r,
1235
+ authSession: g,
1236
+ origin: f.origin,
1237
+ onBack: () => {
1238
+ f.origin === "standalone" ? t() : m({ kind: "layout" });
1239
+ }
1240
+ }
1241
+ ) : null;
1242
+ return /* @__PURE__ */ o(
1243
+ ye,
1244
+ {
1245
+ open: e,
1246
+ onClose: t,
1247
+ brandColor: w,
1248
+ testMode: P,
1249
+ allowClose: L,
1250
+ labelledBy: "pw-title",
1251
+ children: s ? /* @__PURE__ */ o(te, { onContinue: t }) : f.kind === "purchase_success" ? /* @__PURE__ */ o(te, { restored: f.restored, onContinue: t }) : I || (c.status === "loading" || c.status === "idle" || f.kind === "verifying" ? /* @__PURE__ */ u("div", { class: "flex flex-col items-center justify-center gap-3 py-12", children: [
1252
+ /* @__PURE__ */ o("span", { class: "inline-block h-7 w-7 animate-spin rounded-full border-[2.5px] border-gray-200 border-t-[var(--pw-accent)]" }),
1253
+ /* @__PURE__ */ o("span", { class: "text-xs font-medium tracking-wide text-gray-500", children: f.kind === "verifying" ? "Checking your subscription…" : "Loading…" })
1254
+ ] }) : c.status === "error" ? /* @__PURE__ */ u("div", { class: "flex flex-col items-center gap-2 py-8 text-center", children: [
1255
+ /* @__PURE__ */ o("div", { class: "flex h-11 w-11 items-center justify-center rounded-full bg-red-50", children: /* @__PURE__ */ u("svg", { width: "20", height: "20", viewBox: "0 0 20 20", fill: "none", "aria-hidden": "true", children: [
1256
+ /* @__PURE__ */ o(
1257
+ "path",
1258
+ {
1259
+ d: "M10 6v5M10 14h.01",
1260
+ stroke: "#dc2626",
1261
+ "stroke-width": "2",
1262
+ "stroke-linecap": "round"
1263
+ }
1264
+ ),
1265
+ /* @__PURE__ */ o("circle", { cx: "10", cy: "10", r: "8", stroke: "#dc2626", "stroke-width": "1.75" })
1266
+ ] }) }),
1267
+ /* @__PURE__ */ o("p", { class: "text-sm font-semibold tracking-tight text-gray-900", children: "Something went wrong" }),
1268
+ /* @__PURE__ */ o("p", { class: "text-xs leading-relaxed text-gray-500", children: c.error.message })
1269
+ ] }) : f.kind === "auth_gate" && r.auth ? /* @__PURE__ */ o(
1270
+ Se,
1271
+ {
1272
+ block: C,
1273
+ bootstrap: c.data,
1274
+ auth: r.auth,
1275
+ authSession: g,
1276
+ showBack: f.origin !== "standalone",
1277
+ onBack: () => {
1278
+ f.origin === "standalone" ? t() : m({ kind: "layout" });
1279
+ }
1280
+ }
1281
+ ) : f.kind === "anon_gate" && r.auth ? /* @__PURE__ */ o(
1282
+ Ce,
1283
+ {
1284
+ auth: r.auth,
1285
+ onSuccess: () => {
1286
+ f.origin === "standalone" ? t() : m({ kind: "layout" });
1287
+ },
1288
+ onBack: f.origin === "standalone" ? void 0 : () => m({ kind: "layout" })
1289
+ }
1290
+ ) : f.kind === "awaiting_payment" ? /* @__PURE__ */ o(
1291
+ Xe,
1292
+ {
1293
+ client: r,
1294
+ onBack: () => m({ kind: "layout" }),
1295
+ onReopen: () => {
1296
+ if (typeof window > "u") return;
1297
+ const d = window.open(f.url, "_blank");
1298
+ if (d)
1299
+ try {
1300
+ d.opener = null;
1301
+ } catch {
1302
+ }
1303
+ },
1304
+ onRetry: () => A(f.priceId)
1305
+ }
1306
+ ) : f.kind === "popup_blocked" ? /* @__PURE__ */ u("div", { class: "flex flex-col items-center gap-3 py-8 text-center", children: [
1307
+ /* @__PURE__ */ o(
1308
+ "div",
1309
+ {
1310
+ class: "flex h-11 w-11 items-center justify-center rounded-full",
1311
+ style: { background: "color-mix(in srgb, var(--pw-accent) 12%, white)", color: "var(--pw-accent)" },
1312
+ "aria-hidden": "true",
1313
+ children: /* @__PURE__ */ u("svg", { width: "20", height: "20", viewBox: "0 0 20 20", fill: "none", children: [
1314
+ /* @__PURE__ */ o(
1315
+ "path",
1316
+ {
1317
+ d: "M4 5h12v10H4z",
1318
+ stroke: "currentColor",
1319
+ "stroke-width": "1.75",
1320
+ "stroke-linejoin": "round"
1321
+ }
1322
+ ),
1323
+ /* @__PURE__ */ o("path", { d: "M7 9l3 3 4-5", stroke: "currentColor", "stroke-width": "1.75", "stroke-linecap": "round", "stroke-linejoin": "round" })
1324
+ ] })
1325
+ }
1326
+ ),
1327
+ /* @__PURE__ */ o("p", { class: "text-sm font-semibold tracking-tight text-gray-900", children: "Allow popups to continue" }),
1328
+ /* @__PURE__ */ o("p", { class: "max-w-[18rem] text-xs leading-relaxed text-gray-500", children: "Your browser blocked the checkout tab. Click below to open it." }),
1329
+ /* @__PURE__ */ o(
1330
+ "button",
1331
+ {
1332
+ type: "button",
1333
+ onClick: () => v(f.priceId, f.url),
1334
+ class: "mt-1 rounded-xl px-4 py-2 text-xs font-semibold text-white transition-all hover:-translate-y-px hover:brightness-105 focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-[var(--pw-accent)]",
1335
+ style: {
1336
+ background: "linear-gradient(180deg, color-mix(in srgb, var(--pw-accent) 92%, white), var(--pw-accent))",
1337
+ boxShadow: "0 1px 2px rgba(15,23,42,0.08), 0 6px 14px -4px color-mix(in srgb, var(--pw-accent) 50%, transparent)"
1338
+ },
1339
+ children: "Open checkout"
1340
+ }
1341
+ )
1342
+ ] }) : /* @__PURE__ */ o(
1343
+ He,
1344
+ {
1345
+ layout: c.data.layout,
1346
+ bootstrap: c.data,
1347
+ onAction: S,
1348
+ auth: r.auth,
1349
+ authSession: g
1350
+ }
1351
+ ))
1352
+ }
1353
+ );
1354
+ }
1355
+ function Xe({
1356
+ client: r,
1357
+ onBack: e,
1358
+ onReopen: t,
1359
+ onRetry: n
1360
+ }) {
1361
+ const [i, s] = x(!1), [l, a] = x(!1), c = E(null);
1362
+ return M(() => () => {
1363
+ c.current !== null && clearTimeout(c.current);
1364
+ }, []), /* @__PURE__ */ u("div", { class: "flex flex-col gap-3", children: [
1365
+ /* @__PURE__ */ o(
1366
+ "button",
1367
+ {
1368
+ type: "button",
1369
+ onClick: e,
1370
+ class: "-ml-1 self-start rounded-md px-1.5 py-0.5 text-xs font-medium text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-900 focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--pw-accent)]",
1371
+ children: "← Back"
1372
+ }
1373
+ ),
1374
+ /* @__PURE__ */ u("div", { class: "flex flex-col items-center gap-3 py-6 text-center", children: [
1375
+ /* @__PURE__ */ u("div", { class: "relative flex h-12 w-12 items-center justify-center", children: [
1376
+ /* @__PURE__ */ o(
1377
+ "span",
1378
+ {
1379
+ class: "absolute inset-0 animate-ping rounded-full opacity-40",
1380
+ style: { background: "color-mix(in srgb, var(--pw-accent) 30%, transparent)" },
1381
+ "aria-hidden": "true"
1382
+ }
1383
+ ),
1384
+ /* @__PURE__ */ o("span", { class: "relative inline-block h-7 w-7 animate-spin rounded-full border-[2.5px] border-gray-200 border-t-[var(--pw-accent)]" })
1385
+ ] }),
1386
+ /* @__PURE__ */ o("p", { class: "text-sm font-semibold tracking-tight text-gray-900", children: "Complete payment in the new tab" }),
1387
+ /* @__PURE__ */ o("p", { class: "max-w-[20rem] text-xs leading-relaxed text-gray-500", children: "We'll detect your payment automatically — or click below once you're done." }),
1388
+ /* @__PURE__ */ o(
1389
+ "button",
1390
+ {
1391
+ type: "button",
1392
+ onClick: async () => {
1393
+ if (!i) {
1394
+ s(!0), a(!1);
1395
+ try {
1396
+ if ((await r.getUser({ force: !0 })).has_active_subscription) {
1397
+ typeof window < "u" && window.postMessage({ type: "paywall_purchase" }, "*");
1398
+ return;
1399
+ }
1400
+ a(!0), c.current !== null && clearTimeout(c.current), c.current = setTimeout(() => {
1401
+ a(!1), c.current = null;
1402
+ }, 5e3);
1403
+ } catch {
1404
+ a(!0);
1405
+ } finally {
1406
+ s(!1);
1407
+ }
1408
+ }
1409
+ },
1410
+ disabled: i,
1411
+ class: "mt-1 rounded-xl px-5 py-2.5 text-sm font-semibold text-white transition-all hover:-translate-y-px hover:brightness-105 disabled:cursor-not-allowed disabled:opacity-60 disabled:hover:translate-y-0 disabled:hover:brightness-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-[var(--pw-accent)]",
1412
+ style: {
1413
+ background: "linear-gradient(180deg, color-mix(in srgb, var(--pw-accent) 92%, white), var(--pw-accent))",
1414
+ boxShadow: "0 1px 2px rgba(15,23,42,0.08), 0 6px 14px -4px color-mix(in srgb, var(--pw-accent) 50%, transparent)"
1415
+ },
1416
+ children: i ? "Checking…" : "I've paid"
1417
+ }
1418
+ ),
1419
+ l ? /* @__PURE__ */ o("p", { class: "text-xs leading-relaxed text-gray-500", children: "Payment is still being processed. Please try again in a moment." }) : null
1420
+ ] }),
1421
+ /* @__PURE__ */ u("div", { class: "rounded-2xl border border-gray-200 bg-gray-50/60 p-3.5", children: [
1422
+ /* @__PURE__ */ o("p", { class: "text-xs leading-relaxed text-gray-600", children: "Checkout window didn't open or got blocked? Click here to open it again." }),
1423
+ /* @__PURE__ */ o(
1424
+ "button",
1425
+ {
1426
+ type: "button",
1427
+ onClick: t,
1428
+ class: "mt-2.5 w-full rounded-xl border border-gray-200 bg-white px-3 py-2 text-xs font-semibold text-gray-700 transition-colors hover:border-gray-300 hover:bg-gray-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--pw-accent)]",
1429
+ children: "Open checkout again"
1430
+ }
1431
+ )
1432
+ ] }),
1433
+ /* @__PURE__ */ o(
1434
+ "button",
1435
+ {
1436
+ type: "button",
1437
+ onClick: n,
1438
+ class: "self-center rounded-md px-2 py-1 text-xs text-gray-500 underline-offset-2 hover:text-gray-900 hover:underline focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--pw-accent)]",
1439
+ children: "Tab closed? Try again"
1440
+ }
1441
+ )
1442
+ ] });
1443
+ }
1444
+ function te({
1445
+ onContinue: r,
1446
+ restored: e = !1
1447
+ }) {
1448
+ return /* @__PURE__ */ u("div", { class: "flex flex-col items-center gap-3 py-8 text-center", children: [
1449
+ /* @__PURE__ */ o(
1450
+ "div",
1451
+ {
1452
+ class: "flex h-14 w-14 items-center justify-center rounded-full ring-8",
1453
+ style: {
1454
+ background: "linear-gradient(135deg, #4ade80, #16a34a)",
1455
+ color: "#fff",
1456
+ // emerald ring with low alpha for a halo effect
1457
+ boxShadow: "0 0 0 8px rgba(74,222,128,0.12), 0 8px 20px -6px rgba(22,163,74,0.45)"
1458
+ },
1459
+ "aria-hidden": "true",
1460
+ children: /* @__PURE__ */ o("svg", { width: "28", height: "28", viewBox: "0 0 24 24", fill: "none", children: /* @__PURE__ */ o(
1461
+ "path",
1462
+ {
1463
+ d: "M5 13l4 4L19 7",
1464
+ stroke: "currentColor",
1465
+ "stroke-width": "2.5",
1466
+ "stroke-linecap": "round",
1467
+ "stroke-linejoin": "round"
1468
+ }
1469
+ ) })
1470
+ }
1471
+ ),
1472
+ /* @__PURE__ */ o("p", { id: "pw-title", class: "mt-1 text-lg font-semibold tracking-tight text-gray-900", children: e ? "Subscription restored" : "Payment received" }),
1473
+ /* @__PURE__ */ o("p", { class: "text-sm leading-relaxed text-gray-500", children: e ? "Welcome back — your subscription is already active." : "Your subscription is now active." }),
1474
+ /* @__PURE__ */ o(
1475
+ "button",
1476
+ {
1477
+ type: "button",
1478
+ onClick: r,
1479
+ class: "mt-3 rounded-xl px-5 py-2.5 text-sm font-semibold text-white transition-all hover:-translate-y-px hover:brightness-105 focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-[var(--pw-accent)]",
1480
+ style: {
1481
+ background: "linear-gradient(180deg, color-mix(in srgb, var(--pw-accent) 92%, white), var(--pw-accent))",
1482
+ boxShadow: "0 1px 2px rgba(15,23,42,0.08), 0 8px 20px -6px color-mix(in srgb, var(--pw-accent) 50%, transparent)"
1483
+ },
1484
+ children: "Continue"
1485
+ }
1486
+ )
1487
+ ] });
1488
+ }
1489
+ const Ye = 10 * 6e4, Je = 5e3, Ke = 3e4;
1490
+ class Qe {
1491
+ constructor(e) {
1492
+ this.timer = null, this.timeoutTimer = null, this.visibilityHandler = null, this.focusHandler = null, this.messageHandler = null, this.stopped = !1, this.checking = !1, this.opts = {
1493
+ client: e.client,
1494
+ onActive: e.onActive,
1495
+ onTimeout: e.onTimeout ?? (() => {
1496
+ }),
1497
+ timeoutMs: e.timeoutMs ?? Ye,
1498
+ visibleIntervalMs: e.visibleIntervalMs ?? Je,
1499
+ hiddenIntervalMs: e.hiddenIntervalMs ?? Ke
1500
+ };
1501
+ }
1502
+ start() {
1503
+ this.stopped || typeof document > "u" || typeof window > "u" || (this.check(), this.scheduleNext(), this.visibilityHandler = () => this.handleVisibilityChange(), document.addEventListener("visibilitychange", this.visibilityHandler), this.focusHandler = () => void this.check(), window.addEventListener("focus", this.focusHandler), this.messageHandler = (e) => this.handleMessage(e), window.addEventListener("message", this.messageHandler), this.timeoutTimer = setTimeout(() => {
1504
+ this.stopped || (this.stop(), this.opts.onTimeout());
1505
+ }, this.opts.timeoutMs));
1506
+ }
1507
+ stop() {
1508
+ this.stopped = !0, this.timer !== null && clearTimeout(this.timer), this.timer = null, this.timeoutTimer !== null && clearTimeout(this.timeoutTimer), this.timeoutTimer = null, typeof document < "u" && this.visibilityHandler && document.removeEventListener("visibilitychange", this.visibilityHandler), typeof window < "u" && (this.focusHandler && window.removeEventListener("focus", this.focusHandler), this.messageHandler && window.removeEventListener("message", this.messageHandler)), this.visibilityHandler = null, this.focusHandler = null, this.messageHandler = null;
1509
+ }
1510
+ async check() {
1511
+ if (!(this.stopped || this.checking)) {
1512
+ this.checking = !0;
1513
+ try {
1514
+ const e = await this.opts.client.getUser({ force: !0 });
1515
+ if (this.stopped) return;
1516
+ e.has_active_subscription && (this.stop(), this.opts.onActive(e));
1517
+ } catch {
1518
+ } finally {
1519
+ this.checking = !1;
1520
+ }
1521
+ }
1522
+ }
1523
+ scheduleNext() {
1524
+ if (this.stopped) return;
1525
+ const t = typeof document < "u" && document.visibilityState === "visible" ? this.opts.visibleIntervalMs : this.opts.hiddenIntervalMs;
1526
+ this.timer = setTimeout(async () => {
1527
+ await this.check(), this.scheduleNext();
1528
+ }, t);
1529
+ }
1530
+ handleVisibilityChange() {
1531
+ typeof document > "u" || (document.visibilityState === "visible" && this.check(), this.timer !== null && (clearTimeout(this.timer), this.timer = null), this.scheduleNext());
1532
+ }
1533
+ handleMessage(e) {
1534
+ const t = e.data;
1535
+ !t || typeof t != "object" || t.type === "paywall_purchase" && this.check();
1536
+ }
1537
+ }
1538
+ function et() {
1539
+ return !(typeof document > "u" || typeof window > "u" || typeof location < "u" && location.protocol === "chrome-extension:");
1540
+ }
1541
+ const N = { open: !1, view: null, error: null }, B = {
1542
+ status: "paywall_status",
1543
+ priceId: "paywall_price_id",
1544
+ sessionId: "paywall_session_id"
1545
+ };
1546
+ let tt = class {
1547
+ constructor(e) {
1548
+ this.handle = null, this.isOpen = !1, this.listeners = /* @__PURE__ */ new Map(), this.userUnsub = null, this.authUnsub = null, this.watcher = null, this.tracker = null, this.purchased = !1, this.trialStore = null, this.trialStoreConfig = null, this.lastTrialStatus = null, this.trialExpiredFired = !1, this.lastVisibility = null, this.currentState = N, this.stateListeners = /* @__PURE__ */ new Set();
1549
+ const { auth: t, ownsAuth: n } = rt(e);
1550
+ this.auth = t, this.ownsAuth = n, this.billing = e.client ?? new ae({ ...e, auth: this.auth }), this.host = e.host, this.shadowMode = e.shadowMode ?? "closed", this.mountThenLoad = e.mountThenLoad ?? !0, this.userUnsub = this.billing.onUserChange((i) => {
1551
+ this.emit("userChange", i);
1552
+ }), this.auth && (this.authUnsub = this.auth.onAuthChange((i) => {
1553
+ this.emit("authChange", i);
1554
+ })), this.initTracker(e.analytics), e.autoDetectReturn !== !1 && typeof window < "u" && queueMicrotask(() => this.checkReturn());
1555
+ }
1556
+ initTracker(e) {
1557
+ if (e === !1) return;
1558
+ const t = typeof e == "object" && e !== null ? e : {};
1559
+ if (t.enabled === !1) return;
1560
+ const n = t.endpoint ?? `${this.billing.apiOrigin}/api/v1/paywall/${this.billing.paywallId}/events`;
1561
+ this.tracker = new ce({
1562
+ endpoint: n,
1563
+ paywallId: this.billing.paywallId,
1564
+ capabilities: this.billing.capabilities,
1565
+ getVisitorId: () => this.billing.getVisitorId(),
1566
+ getCachedVisitorId: () => this.billing.getCachedVisitorId(),
1567
+ getUserId: () => this.billing.getIdentity()?.userId ?? null,
1568
+ flushIntervalMs: t.flushIntervalMs,
1569
+ maxBufferSize: t.maxBufferSize,
1570
+ fetch: t.fetch,
1571
+ sendBeacon: t.sendBeacon
1572
+ }), this.on("open", () => this.tracker?.track("paywall_opened")), this.on(
1573
+ "ready",
1574
+ (i) => this.tracker?.track("paywall_viewed", {
1575
+ is_test_mode: i.settings.is_test_mode,
1576
+ prices_count: i.prices.length,
1577
+ offers_count: i.offers.length
1578
+ })
1579
+ ), this.on(
1580
+ "price_selected",
1581
+ (i) => this.tracker?.track("price_selected", { price_id: i.priceId })
1582
+ ), this.on(
1583
+ "checkout_started",
1584
+ (i) => this.tracker?.track("checkout_started", {
1585
+ price_id: i.priceId,
1586
+ acquiring: i.acquiring
1587
+ })
1588
+ ), this.on(
1589
+ "purchase_completed",
1590
+ (i) => this.tracker?.track("purchase_completed", {
1591
+ price_id: i.priceId,
1592
+ session_id: i.sessionId
1593
+ })
1594
+ ), this.on(
1595
+ "purchase_failed",
1596
+ (i) => this.tracker?.track("purchase_failed", { reason: i.reason })
1597
+ ), this.on("close", () => this.tracker?.track("paywall_closed")), this.on(
1598
+ "trial_blocked",
1599
+ (i) => this.tracker?.track("trial_blocked", {
1600
+ mode: i.mode,
1601
+ ...i.mode === "time" ? { remaining_ms: i.remainingMs, total_ms: i.totalMs } : i.mode === "opens" ? { remaining_actions: i.remainingActions, total_actions: i.totalActions } : {}
1602
+ })
1603
+ ), this.on("trial_expired", () => this.tracker?.track("trial_expired")), this.on(
1604
+ "visibility_blocked",
1605
+ (i) => this.tracker?.track("visibility_blocked", {
1606
+ reason: i.reason,
1607
+ country: i.country,
1608
+ tier: i.tier
1609
+ })
1610
+ ), this.on(
1611
+ "error",
1612
+ (i) => this.tracker?.track("error", { code: i.code, message: i.message })
1613
+ );
1614
+ }
1615
+ /**
1616
+ * Отправить произвольное аналитическое событие. Имена из системного whitelist'а
1617
+ * (`app_opened`, `paywall_viewed`, ...) разрешены как есть. Кастомные —
1618
+ * с префиксом `host:` (например `host:user_clicked_upgrade`). Сервер
1619
+ * дропает события с неразрешёнными именами.
1620
+ *
1621
+ * Самый частый кейс — `track('app_opened')` от хоста сразу после загрузки
1622
+ * приложения, чтобы зафиксировать воронку до открытия пейвола.
1623
+ */
1624
+ track(e, t) {
1625
+ this.tracker?.track(e, t);
1626
+ }
1627
+ /**
1628
+ * Удобный шорткат вместо `paywall.on('userChange', cb)` — самый частый
1629
+ * паттерн в host-коде, поэтому отдельный named метод. Колбек получает
1630
+ * last-known user из кеша синхронно через microtask, если он есть.
1631
+ */
1632
+ onUserChange(e) {
1633
+ return this.on("userChange", e);
1634
+ }
1635
+ on(e, t) {
1636
+ let n = this.listeners.get(e);
1637
+ return n || (n = /* @__PURE__ */ new Set(), this.listeners.set(e, n)), n.add(t), () => n.delete(t);
1638
+ }
1639
+ off(e, t) {
1640
+ this.listeners.get(e)?.delete(t);
1641
+ }
1642
+ emit(e, ...t) {
1643
+ const n = this.listeners.get(e);
1644
+ if (!n) return;
1645
+ const i = t[0];
1646
+ for (const s of n)
1647
+ try {
1648
+ s(i);
1649
+ } catch (l) {
1650
+ typeof console < "u" && console.error("[paywall] listener error", l);
1651
+ }
1652
+ }
1653
+ open(e = {}) {
1654
+ this.openInternal("layout", e);
1655
+ }
1656
+ /**
1657
+ * Прогревает bootstrap-кеш и balance-кеш заранее, без открытия модалки.
1658
+ * Полезно когда host знает, что юзер скоро откроет paywall (hover на CTA,
1659
+ * mount компонента) — первый `open()` рендерится мгновенно, без loading-flash.
1660
+ *
1661
+ * Не throw'ает: если сеть упала, тихо игнорирует (повторный open() сделает
1662
+ * fresh-bootstrap с error-state как обычно). `signal` для отмены — например,
1663
+ * если хост размонтирует компонент быстрее, чем bootstrap вернётся.
1664
+ *
1665
+ * Вызывать можно сколько угодно раз — последующие вызовы возвращают cached
1666
+ * Promise (BillingClient уже дедуплицирует).
1667
+ */
1668
+ async preload(e = {}) {
1669
+ try {
1670
+ await this.billing.bootstrap({ signal: e.signal }), this.billing.auth && await this.billing.getBalances({ signal: e.signal });
1671
+ } catch {
1672
+ }
1673
+ }
1674
+ /**
1675
+ * Открывает модалку сразу с саппорт-формой (минуя layout с тарифами).
1676
+ * Полезно, когда host-приложение хочет дать юзеру кнопку «Help / Support»,
1677
+ * не связанную с пейволом-апгрейдом. Back/Done в саппорт-форме закрывают
1678
+ * модалку (не возвращают к тарифам), потому что юзер пришёл сюда напрямую.
1679
+ *
1680
+ * Из обычного `paywall.open()`-flow саппорт всё равно доступен через
1681
+ * Contact Support-ссылку в `current_session`-блоке (там Back возвращает
1682
+ * к layout).
1683
+ */
1684
+ openSupport(e = {}) {
1685
+ this.openInternal("support", e);
1686
+ }
1687
+ /**
1688
+ * Открывает модалку сразу с auth-gate (логин/регистрация), без layout с
1689
+ * тарифами. Сценарий: returning customer уже купил, ему просто нужно
1690
+ * залогиниться, чтобы SDK подцепил его purchases. После signIn модалка
1691
+ * закрывается; Back тоже закрывает (юзер пришёл только за логином).
1692
+ *
1693
+ * Без `auth` (managed-auth не подключён) метод — no-op: некому делать
1694
+ * signIn. Если юзер уже залогинен — модалка всё равно откроется и
1695
+ * закроется через auto-resume в auth_gate effect'е (мгновение).
1696
+ *
1697
+ * Триал не блокирует этот флоу — auth не connect'ится с trial-механикой.
1698
+ */
1699
+ openAuth(e = {}) {
1700
+ this.auth && this.openInternal("auth", { ...e, skipTrial: !0 });
1701
+ }
1702
+ /**
1703
+ * Открывает модалку с anonymous-gate. AnonGate сразу зовёт
1704
+ * `auth.signInAnonymously()`:
1705
+ * - если в storage есть `anonRefreshToken` — silent resume через
1706
+ * /auth/refresh, модалка схлопывается мгновенно (юзер видит лёгкий
1707
+ * спиннер ~100мс);
1708
+ * - иначе — fresh POST /auth/anonymous/signin без captcha (защита от
1709
+ * abuse держится на Supabase per-real-IP rate-limit + CF Bot Fight Mode).
1710
+ *
1711
+ * После успешного signIn'а модалка закрывается; host подхватывает свежую
1712
+ * session через `auth.onAuthChange` или `paywall.onUserChange`. Для UX
1713
+ * "просто залогиниться чтобы api-gateway работал, без покупок".
1714
+ *
1715
+ * Без managed-auth (`auth` не подключён) метод — no-op. Триал и
1716
+ * visibility-таргетинг этот flow обходит: анон-логин не должен зависеть
1717
+ * от страны юзера или trial-стейджа.
1718
+ */
1719
+ openAnonGate(e = {}) {
1720
+ this.auth && this.openInternal("anon", { ...e, skipTrial: !0, skipVisibility: !0 });
1721
+ }
1722
+ openInternal(e, t) {
1723
+ t.identity && this.billing.setIdentity(t.identity), this.purchased = !1;
1724
+ const n = t.skipTrial === !0 || e === "support", i = t.skipVisibility === !0 || e === "support" || e === "auth" || e === "anon", s = t.renew === !0;
1725
+ if (n && i) {
1726
+ this.mountAndShow(e, { renew: s });
1727
+ return;
1728
+ }
1729
+ const l = this.billing.getCachedBootstrap();
1730
+ if (l) {
1731
+ this.runOpenGates(e, l, { skipTrial: n, skipVisibility: i, renew: s });
1732
+ return;
1733
+ }
1734
+ if (this.mountThenLoad) {
1735
+ this.mountAndShow(e, { renew: s }), this.billing.bootstrap().then((a) => this.runDelayedGates(a, { skipTrial: n, skipVisibility: i })).catch(() => {
1736
+ });
1737
+ return;
1738
+ }
1739
+ this.billing.bootstrap().then((a) => this.runOpenGates(e, a, { skipTrial: n, skipVisibility: i, renew: s })).catch(() => {
1740
+ this.mountAndShow(e, { renew: s });
1741
+ });
1742
+ }
1743
+ /** Применить gates ПОСЛЕ того, как модалка уже смонтирована (mount-then-load
1744
+ * путь). Если gate блокирует — close() + emit. Если юзер уже сам закрыл
1745
+ * модалку до резолва bootstrap'а — no-op (isOpen=false). */
1746
+ runDelayedGates(e, t) {
1747
+ if (!this.isOpen) return;
1748
+ if (!t.skipVisibility) {
1749
+ const s = e.settings.visibility;
1750
+ if (s && (this.lastVisibility = s, !s.visible)) {
1751
+ this.close(), this.emit("visibility_blocked", s);
1752
+ return;
1753
+ }
1754
+ }
1755
+ if (t.skipTrial) return;
1756
+ const n = e.settings.trial;
1757
+ if (!n) return;
1758
+ const i = this.ensureTrialStore(n);
1759
+ i.check().then(async (s) => {
1760
+ if (this.isOpen && (this.lastTrialStatus = s, s.mode !== "none")) {
1761
+ if (s.blocked) {
1762
+ const l = await i.recordBlock();
1763
+ if (this.lastTrialStatus = l, !this.isOpen) return;
1764
+ this.close(), this.emit("trial_blocked", l);
1765
+ return;
1766
+ }
1767
+ this.trialExpiredFired || (this.trialExpiredFired = !0, this.emit("trial_expired"));
1768
+ }
1769
+ }).catch((s) => {
1770
+ typeof console < "u" && console.warn("[paywall] trial check failed", s);
1771
+ });
1772
+ }
1773
+ // Порядок гейтов: visibility → trial. Country-mismatch ≠ trial-block, и
1774
+ // вести trial-стейт «осталось N показов» под юзером, который вообще не
1775
+ // должен увидеть пейвол по таргетингу — бессмысленно: при возврате в
1776
+ // правильную страну он окажется со «слипшимся» триал-счётчиком.
1777
+ runOpenGates(e, t, n) {
1778
+ if (!n.skipVisibility) {
1779
+ const i = t.settings.visibility;
1780
+ if (i && (this.lastVisibility = i, !i.visible)) {
1781
+ this.emit("visibility_blocked", i);
1782
+ return;
1783
+ }
1784
+ }
1785
+ if (n.skipTrial) {
1786
+ this.mountAndShow(e, { renew: n.renew });
1787
+ return;
1788
+ }
1789
+ this.gateThroughTrial(e, t, n.renew);
1790
+ }
1791
+ gateThroughTrial(e, t, n) {
1792
+ const i = t.settings.trial;
1793
+ if (!i) {
1794
+ this.mountAndShow(e, { renew: n });
1795
+ return;
1796
+ }
1797
+ const s = this.ensureTrialStore(i);
1798
+ s.check().then(async (l) => {
1799
+ if (this.lastTrialStatus = l, l.mode === "none") {
1800
+ this.mountAndShow(e, { renew: n });
1801
+ return;
1802
+ }
1803
+ if (l.blocked) {
1804
+ const a = await s.recordBlock();
1805
+ this.lastTrialStatus = a, this.emit("trial_blocked", a);
1806
+ return;
1807
+ }
1808
+ this.trialExpiredFired || (this.trialExpiredFired = !0, this.emit("trial_expired")), this.mountAndShow(e, { renew: n });
1809
+ }).catch((l) => {
1810
+ typeof console < "u" && console.warn("[paywall] trial check failed", l), this.mountAndShow(e, { renew: n });
1811
+ });
1812
+ }
1813
+ ensureTrialStore(e) {
1814
+ if (this.trialStore && this.trialStoreConfig && ot(this.trialStoreConfig, e))
1815
+ return this.trialStore;
1816
+ this.trialStoreConfig = e;
1817
+ const t = this.billing.createTrialStore;
1818
+ return this.trialStore = typeof t == "function" ? t.call(this.billing, e) : ue(this.billing.getStorage(), this.billing.paywallId, e), this.trialStore;
1819
+ }
1820
+ mountAndShow(e, t = {}) {
1821
+ const n = t.renew === !0;
1822
+ if (this.handle) {
1823
+ this.isOpen = !0, this.handle.update({ open: !0, initialView: e, purchased: !1, renew: n }), this.emit("open");
1824
+ return;
1825
+ }
1826
+ this.isOpen = !0, this.handle = me(
1827
+ Ze,
1828
+ {
1829
+ client: this.billing,
1830
+ open: !0,
1831
+ initialView: e,
1832
+ purchased: !1,
1833
+ renew: n,
1834
+ onClose: () => this.close(),
1835
+ onEvent: (i, s) => {
1836
+ this.emit(i, s), i === "checkout_started" && this.startUserWatcher();
1837
+ },
1838
+ onState: (i) => this.applyState(i)
1839
+ },
1840
+ { host: this.host, shadowMode: this.shadowMode }
1841
+ ), this.emit("open");
1842
+ }
1843
+ applyState(e) {
1844
+ if (!it(this.currentState, e)) {
1845
+ this.currentState = e;
1846
+ for (const t of this.stateListeners)
1847
+ try {
1848
+ t(e);
1849
+ } catch (n) {
1850
+ console.warn("[paywall] onStateChange listener threw", n);
1851
+ }
1852
+ }
1853
+ }
1854
+ /**
1855
+ * Sync-snapshot текущего состояния модалки. Подходит для `useSyncExternalStore`
1856
+ * в React (`useSyncExternalStore(paywall.onStateChange, paywall.getState)`)
1857
+ * и для одноразовых проверок («открыт ли пейвол сейчас?»).
1858
+ *
1859
+ * Snapshot стабилен — пока state не изменился, повторный getState() вернёт
1860
+ * `===`-равный объект (важно для useSyncExternalStore чтобы не ре-рендерить).
1861
+ */
1862
+ getState() {
1863
+ return this.currentState;
1864
+ }
1865
+ /**
1866
+ * Подписка на изменения state. Колбек вызывается при каждом реальном
1867
+ * изменении (closed → loading → ready → ...). По умолчанию initial snapshot
1868
+ * отдаётся через microtask после подписки; через `{immediate: 'sync'|'none'}`
1869
+ * можно сделать sync-доставку (для useSyncExternalStore — там она не нужна,
1870
+ * snapshot читается через getSnapshot отдельно) или вовсе пропустить
1871
+ * initial.
1872
+ *
1873
+ * Возвращает unsubscribe.
1874
+ */
1875
+ onStateChange(e, t = {}) {
1876
+ this.stateListeners.add(e);
1877
+ const n = t.immediate ?? "microtask";
1878
+ if (n !== "none") {
1879
+ const i = this.currentState;
1880
+ if (n === "sync")
1881
+ try {
1882
+ e(i);
1883
+ } catch (s) {
1884
+ console.warn("[paywall] onStateChange initial sync threw", s);
1885
+ }
1886
+ else
1887
+ queueMicrotask(() => {
1888
+ this.stateListeners.has(e) && e(i);
1889
+ });
1890
+ }
1891
+ return () => {
1892
+ this.stateListeners.delete(e);
1893
+ };
1894
+ }
1895
+ /** Sync-доступ к последнему известному статусу триала. null — `paywall.open()`
1896
+ * ещё не вызывался либо триал отключён в конфиге пейвола. Удобно для
1897
+ * собственного UI хоста («осталось 3 показа», «триал истечёт через 2ч»). */
1898
+ getTrialStatus() {
1899
+ return this.lastTrialStatus;
1900
+ }
1901
+ /** Sync-доступ к последнему server-computed visibility-статусу. null —
1902
+ * bootstrap ещё не загружен или сервер не отдаёт `settings.visibility`
1903
+ * (например, старая версия online без targeting-патча). Хост может
1904
+ * использовать для собственного fallback'а: «сервис недоступен в вашей
1905
+ * стране». Обновляется на каждом open(), который проходит через gate. */
1906
+ getVisibility() {
1907
+ return this.lastVisibility;
1908
+ }
1909
+ /**
1910
+ * Цены пейвола — шорткат над `bootstrap()`. Локали уже применены, кэш и
1911
+ * stale-while-revalidate идентичны `billing.bootstrap()`. Подходит для
1912
+ * pricing-страниц/карточек на сайте, где host хочет показать те же цены,
1913
+ * что и в модалке, не вытаскивая bootstrap руками.
1914
+ */
1915
+ getPrices(e = {}) {
1916
+ return this.billing.getPrices(e);
1917
+ }
1918
+ /** Sync-снимок цен. null — bootstrap ещё не загружали. */
1919
+ getCachedPrices() {
1920
+ return this.billing.getCachedPrices();
1921
+ }
1922
+ /** Снимок текущего «языка юзера» — proxy над `billing.getUserLanguage()`.
1923
+ * Используй, чтобы синхронизировать i18n host'а с тем, что фактически
1924
+ * показывает пейвол. См. подробности в `BillingClient.getUserLanguage`. */
1925
+ getUserLanguage() {
1926
+ return this.billing.getUserLanguage();
1927
+ }
1928
+ /**
1929
+ * Решает, нужно ли блокировать фичу для текущего юзера. Без побочных эффектов
1930
+ * (на trial-storage `recordBlock` не вызывается, модалка не монтируется).
1931
+ *
1932
+ * Порядок проверок (первый сработавший — финальный):
1933
+ * 1. `has_active_subscription` — самый сильный сигнал, перебивает остальные.
1934
+ * Юзер с подпиской получает доступ независимо от visibility/trial.
1935
+ * 2. `visibility` (страна/девайс/disabled-флаг) — юзер вне monetization-scope'а
1936
+ * пейвола, гейтить нельзя.
1937
+ * 3. `trial` — пре-пейвольный бесплатный период активен.
1938
+ * 4. Иначе — `blocked`, host лочит фичу и зовёт `paywall.open()`.
1939
+ *
1940
+ * Bootstrap кешируется в BillingClient — `getAccess()` можно дёргать на
1941
+ * каждый рендер host-компонента, /bootstrap не дублируется. При упавшей сети
1942
+ * fallback на persistent-cached user из storage: юзер с прошлой подпиской
1943
+ * получает `granted` офлайн, иначе `blocked` (host покажет пейвол с
1944
+ * error-state, юзер сможет ретрайнуть). Side-эффект: обновляются
1945
+ * `lastVisibility` / `lastTrialStatus`, чтобы синхронные геттеры
1946
+ * `getVisibility()` / `getTrialStatus()` видели свежие данные после первого
1947
+ * `getAccess()`, а не только после первого `open()`.
1948
+ */
1949
+ async getAccess(e = {}) {
1950
+ let t = this.billing.getCachedBootstrap();
1951
+ if (!t)
1952
+ try {
1953
+ t = await this.billing.bootstrap({ signal: e.signal });
1954
+ } catch {
1955
+ const l = this.billing.getCachedUser();
1956
+ return l?.has_active_subscription ? {
1957
+ access: "granted",
1958
+ reason: "has_subscription",
1959
+ visibility: null,
1960
+ trial: null,
1961
+ user: l
1962
+ } : {
1963
+ access: "blocked",
1964
+ reason: "no_subscription",
1965
+ visibility: null,
1966
+ trial: null,
1967
+ user: l
1968
+ };
1969
+ }
1970
+ const n = t.user ?? null;
1971
+ if (n?.has_active_subscription)
1972
+ return {
1973
+ access: "granted",
1974
+ reason: "has_subscription",
1975
+ visibility: t.settings.visibility ?? null,
1976
+ trial: null,
1977
+ user: n
1978
+ };
1979
+ let i = null;
1980
+ if (!e.skipVisibility) {
1981
+ const l = t.settings.visibility;
1982
+ if (l && (i = l, this.lastVisibility = l, !l.visible))
1983
+ return { access: "granted", reason: "visibility_blocked", visibility: i, trial: null, user: n };
1984
+ }
1985
+ let s = null;
1986
+ if (!e.skipTrial) {
1987
+ const l = t.settings.trial;
1988
+ if (l)
1989
+ try {
1990
+ if (s = await this.ensureTrialStore(l).check(), this.lastTrialStatus = s, s.blocked)
1991
+ return { access: "granted", reason: "trial_blocked", visibility: i, trial: s, user: n };
1992
+ } catch (a) {
1993
+ typeof console < "u" && console.warn("[paywall] getAccess: trial check failed", a);
1994
+ }
1995
+ }
1996
+ return { access: "blocked", reason: "no_subscription", visibility: i, trial: s, user: n };
1997
+ }
1998
+ /** Сбросить состояние триала в storage. Полезно для дев-режима / админ-кнопки
1999
+ * «прогнать сценарий заново». В проде хост обычно не дёргает. */
2000
+ async resetTrial() {
2001
+ this.trialStore && (await this.trialStore.reset(), this.lastTrialStatus = null, this.trialExpiredFired = !1);
2002
+ }
2003
+ // Запускает polling user-state до has_active_subscription=true либо до
2004
+ // таймаута. Идемпотентен: повторный вызов на уже работающем watcher'е —
2005
+ // no-op (юзер мог нажать Continue повторно после возврата).
2006
+ //
2007
+ // В extension popup runtime — no-op (popup не доживёт). Там полагаемся на
2008
+ // bootstrap при следующем открытии.
2009
+ startUserWatcher() {
2010
+ this.watcher || et() && (this.watcher = new Qe({
2011
+ client: this.billing,
2012
+ onActive: (e) => {
2013
+ this.watcher = null, this.emit("purchase_completed", { priceId: null, sessionId: null });
2014
+ const t = this.billing.getCachedBootstrap()?.settings.success_redirect_url;
2015
+ if (t && typeof window < "u")
2016
+ try {
2017
+ window.location.assign(t);
2018
+ return;
2019
+ } catch {
2020
+ }
2021
+ this.isOpen && this.handle && (this.purchased = !0, this.handle.update({ purchased: !0 }));
2022
+ },
2023
+ onTimeout: () => {
2024
+ this.watcher = null;
2025
+ }
2026
+ }), this.watcher.start());
2027
+ }
2028
+ close() {
2029
+ !this.isOpen || !this.handle || (this.isOpen = !1, this.purchased = !1, this.handle.update({ open: !1, purchased: !1 }), this.applyState(N), this.emit("close"));
2030
+ }
2031
+ /**
2032
+ * Сканирует текущий URL на маркеры возврата с checkout и эмитит
2033
+ * purchase_completed / purchase_failed. Маркеры удаляются из URL
2034
+ * через history.replaceState. Ищет и в hash, и в search (hash приоритетнее —
2035
+ * защита от клиентских SPA-роутеров, перехватывающих query).
2036
+ */
2037
+ checkReturn() {
2038
+ if (typeof window > "u") return;
2039
+ const e = new URL(window.location.href), t = re(e.hash.replace(/^#/, "")), n = re(e.search.replace(/^\?/, "")), i = t ?? n;
2040
+ i && (i.status === "paid" ? (this.emit("purchase_completed", {
2041
+ priceId: i.priceId,
2042
+ sessionId: i.sessionId
2043
+ }), st(i)) : (i.status === "failed" || i.status === "cancelled") && this.emit("purchase_failed", { reason: i.status }), lt(e));
2044
+ }
2045
+ destroy() {
2046
+ this.tracker?.destroy(), this.tracker = null, this.listeners.clear(), this.stateListeners.clear(), this.watcher?.stop(), this.watcher = null, this.userUnsub?.(), this.userUnsub = null, this.authUnsub?.(), this.authUnsub = null, this.ownsAuth && this.auth && this.auth.destroy?.(), this.ownsAuth = !1, this.billing.destroy?.(), this.handle?.unmount(), this.handle = null, this.isOpen = !1, this.currentState = N;
2047
+ }
2048
+ };
2049
+ function rt(r) {
2050
+ if (!r.auth) return { auth: void 0, ownsAuth: !1 };
2051
+ if (r.auth instanceof H || nt(r.auth))
2052
+ return { auth: r.auth, ownsAuth: !1 };
2053
+ const e = r.auth === !0 ? {} : r.auth;
2054
+ return {
2055
+ auth: new H({
2056
+ paywallId: r.paywallId,
2057
+ apiOrigin: e.apiOrigin ?? r.apiOrigin,
2058
+ storage: e.storage ?? r.storage,
2059
+ fetch: e.fetch ?? r.fetch,
2060
+ openPopup: e.openPopup
2061
+ }),
2062
+ ownsAuth: !0
2063
+ };
2064
+ }
2065
+ function nt(r) {
2066
+ if (typeof r != "object" || r === null) return !1;
2067
+ const e = r;
2068
+ return typeof e.onAuthChange == "function" && typeof e.getCachedSession == "function" && typeof e.signOut == "function";
2069
+ }
2070
+ function it(r, e) {
2071
+ return r.open === e.open && r.view === e.view && r.error === e.error;
2072
+ }
2073
+ function ot(r, e) {
2074
+ return r.mode === e.mode && r.payload === e.payload && r.storage === e.storage;
2075
+ }
2076
+ function re(r) {
2077
+ if (!r) return null;
2078
+ const e = new URLSearchParams(r), t = e.get(B.status);
2079
+ return t ? {
2080
+ status: t,
2081
+ priceId: e.get(B.priceId),
2082
+ sessionId: e.get(B.sessionId)
2083
+ } : null;
2084
+ }
2085
+ function st(r) {
2086
+ if (!(typeof window > "u" || !window.opener))
2087
+ try {
2088
+ window.opener.postMessage(
2089
+ {
2090
+ type: "paywall_purchase",
2091
+ status: r.status,
2092
+ priceId: r.priceId,
2093
+ sessionId: r.sessionId
2094
+ },
2095
+ "*"
2096
+ );
2097
+ } catch {
2098
+ }
2099
+ }
2100
+ function lt(r) {
2101
+ const e = (n, i) => {
2102
+ if (!n) return "";
2103
+ const s = new URLSearchParams(n.replace(/^[?#]/, ""));
2104
+ s.delete(B.status), s.delete(B.priceId), s.delete(B.sessionId);
2105
+ const l = s.toString();
2106
+ return l ? i + l : "";
2107
+ }, t = r.pathname + e(r.search, "?") + e(r.hash, "#");
2108
+ window.history.replaceState(null, "", t);
2109
+ }
2110
+ class at {
2111
+ constructor(e, t, n) {
2112
+ this.transport = e, this.paywallId = t, this.config = n;
2113
+ }
2114
+ async check() {
2115
+ return this.transport.request("trial.check", {
2116
+ paywallId: this.paywallId,
2117
+ config: this.config
2118
+ });
2119
+ }
2120
+ async recordBlock() {
2121
+ return this.transport.request("trial.recordBlock", {
2122
+ paywallId: this.paywallId,
2123
+ config: this.config
2124
+ });
2125
+ }
2126
+ async reset() {
2127
+ await this.transport.request("trial.reset", {
2128
+ paywallId: this.paywallId,
2129
+ config: this.config
2130
+ });
2131
+ }
2132
+ }
2133
+ class ct {
2134
+ constructor(e, t) {
2135
+ this.transport = e, this.cachedBootstrap = null, this.cachedUser = null, this.cachedBalances = null, this.identity = null, this.userListeners = /* @__PURE__ */ new Set(), this.balanceListeners = /* @__PURE__ */ new Set(), this.unsubUserBroadcast = null, this.unsubBalancesBroadcast = null, this.paywallId = t.paywallId, this.apiOrigin = t.apiOrigin, this.remoteStorageAdapter = {
2136
+ getItem: (n) => this.transport.request("storage.get", { key: n }),
2137
+ setItem: async (n, i) => {
2138
+ await this.transport.request("storage.set", { key: n, value: i });
2139
+ },
2140
+ removeItem: async (n) => {
2141
+ await this.transport.request("storage.remove", { key: n });
2142
+ }
2143
+ // watch не реализуем — для cross-context уведомлений consumer'ы (AuthClient,
2144
+ // TrialStore) подписываются на broadcast-events напрямую через transport.
2145
+ // Если когда-то понадобится — добавим storage.watch broadcast.
2146
+ }, this.unsubUserBroadcast = this.transport.on("userChange", (n) => {
2147
+ this.applyUser(n);
2148
+ }), this.unsubBalancesBroadcast = this.transport.on("balancesChange", (n) => {
2149
+ this.applyBalances([...n]);
2150
+ });
2151
+ }
2152
+ // === Bootstrap ===
2153
+ async bootstrap(e = {}) {
2154
+ const t = await this.transport.request(
2155
+ "billing.bootstrap",
2156
+ { force: e.force },
2157
+ { signal: e.signal }
2158
+ );
2159
+ return this.cachedBootstrap = t, t.user && this.applyUser(t.user), t;
2160
+ }
2161
+ getCachedBootstrap() {
2162
+ return this.cachedBootstrap;
2163
+ }
2164
+ /** Шорткат над `bootstrap()` — возвращает цены пейвола (locale-оверрайды
2165
+ * уже применены в offscreen'е). Те же кэш-семантики, что у `bootstrap()`. */
2166
+ async getPrices(e = {}) {
2167
+ return (await this.bootstrap(e)).prices;
2168
+ }
2169
+ /** Sync-снимок цен из локального mirror'а bootstrap'а. null = ещё не грузили. */
2170
+ getCachedPrices() {
2171
+ return this.cachedBootstrap?.prices ?? null;
2172
+ }
2173
+ // === Visitor ===
2174
+ async getVisitorId() {
2175
+ return this.transport.request("billing.getVisitorId", void 0);
2176
+ }
2177
+ // === User ===
2178
+ async getUser(e = {}) {
2179
+ const t = await this.transport.request(
2180
+ "billing.getUser",
2181
+ { force: e.force },
2182
+ { signal: e.signal }
2183
+ );
2184
+ return this.applyUser(t), t;
2185
+ }
2186
+ getCachedUser() {
2187
+ return this.cachedUser;
2188
+ }
2189
+ /** Подписка на user-state. Mirror'имся на broadcast'ы offscreen'а; initial
2190
+ * snapshot отдаётся через microtask из локального cache (если есть) —
2191
+ * ровно как в BillingClient.onUserChange. Возвращает функцию отписки. */
2192
+ onUserChange(e, t = {}) {
2193
+ this.userListeners.add(e);
2194
+ const n = t.immediate ?? "microtask";
2195
+ if (this.cachedUser && n !== "none") {
2196
+ const i = this.cachedUser;
2197
+ if (n === "sync")
2198
+ try {
2199
+ e(i);
2200
+ } catch (s) {
2201
+ console.warn("[paywall] onUserChange initial sync threw", s);
2202
+ }
2203
+ else
2204
+ queueMicrotask(() => {
2205
+ this.userListeners.has(e) && e(i);
2206
+ });
2207
+ }
2208
+ return () => {
2209
+ this.userListeners.delete(e);
2210
+ };
2211
+ }
2212
+ // === Balances ===
2213
+ async getBalances(e = {}) {
2214
+ const n = [...await this.transport.request(
2215
+ "billing.getBalances",
2216
+ { force: e.force },
2217
+ { signal: e.signal }
2218
+ )];
2219
+ return this.applyBalances(n), n;
2220
+ }
2221
+ getCachedBalances() {
2222
+ return this.cachedBalances;
2223
+ }
2224
+ onBalanceChange(e, t = {}) {
2225
+ this.balanceListeners.add(e);
2226
+ const n = t.immediate ?? "microtask";
2227
+ if (this.cachedBalances && n !== "none") {
2228
+ const i = this.cachedBalances;
2229
+ if (n === "sync")
2230
+ try {
2231
+ e(i);
2232
+ } catch (s) {
2233
+ console.warn("[paywall] onBalanceChange initial sync threw", s);
2234
+ }
2235
+ else
2236
+ queueMicrotask(() => {
2237
+ this.balanceListeners.has(e) && e(i);
2238
+ });
2239
+ }
2240
+ return () => {
2241
+ this.balanceListeners.delete(e);
2242
+ };
2243
+ }
2244
+ // === Checkout ===
2245
+ async createCheckout(e) {
2246
+ const { signal: t, ...n } = e;
2247
+ return this.transport.request("billing.createCheckout", n, { signal: t });
2248
+ }
2249
+ // === Customer portal: list/cancel purchases ===
2250
+ /** Rich-shape список покупок юзера (с ценой, валютой, interval, discount,
2251
+ * cancel-метаданными). Через offscreen — там настоящий BillingClient
2252
+ * ходит на `/api/v1/paywall/[id]/user` с Bearer'ом. Полезно для
2253
+ * customer-portal UI: cards + Cancel/Renew кнопки. */
2254
+ async listPurchases(e = {}) {
2255
+ return [...await this.transport.request("billing.listPurchases", void 0, {
2256
+ signal: e.signal
2257
+ })];
2258
+ }
2259
+ /** Отменить подписку через бэк. По умолчанию cancel в конце текущего
2260
+ * периода (юзер сохраняет access до renewal date'ы). reason обязательна
2261
+ * (валидируется бэком) — собирается через select причин в host-UI. */
2262
+ async cancelSubscription(e) {
2263
+ const { signal: t, ...n } = e;
2264
+ return this.transport.request("billing.cancelSubscription", n, { signal: t });
2265
+ }
2266
+ // === Storage ===
2267
+ /** PaywallUI просит storage у billing-клиента для TrialStore и других
2268
+ * consumer'ов. Возвращает proxy: get/set/remove идут через transport
2269
+ * в offscreen'овский storage = single source of truth для всех вкладок. */
2270
+ getStorage() {
2271
+ return this.remoteStorageAdapter;
2272
+ }
2273
+ /** Factory-метод для PaywallUI: вместо локального createTrialStore'а на
2274
+ * storage-proxy, возвращаем RemoteTrialStore — он шлёт каждую операцию
2275
+ * одним атомарным RPC в offscreen, где navigator.locks сериализуют
2276
+ * read-modify-write. PaywallUI duck-types этот метод и предпочитает его
2277
+ * локальной фабрике, если он есть. */
2278
+ createTrialStore(e) {
2279
+ return new at(this.transport, this.paywallId, e);
2280
+ }
2281
+ // === Identity ===
2282
+ getIdentity() {
2283
+ return this.identity;
2284
+ }
2285
+ async setIdentity(e) {
2286
+ this.identity = e, await this.transport.request("billing.setIdentity", { identity: e });
2287
+ }
2288
+ /** Подгрузить identity с offscreen'а. Используется при первом подключении
2289
+ * content-script'а — если другая вкладка уже залогинила юзера, текущая
2290
+ * тут же подхватит identity без ожидания authChange. */
2291
+ async syncIdentity() {
2292
+ const e = await this.transport.request("billing.getIdentity", void 0);
2293
+ return this.identity = e, e;
2294
+ }
2295
+ destroy() {
2296
+ this.unsubUserBroadcast?.(), this.unsubBalancesBroadcast?.(), this.unsubUserBroadcast = null, this.unsubBalancesBroadcast = null, this.userListeners.clear(), this.balanceListeners.clear(), this.cachedBootstrap = null, this.cachedUser = null, this.cachedBalances = null, this.identity = null;
2297
+ }
2298
+ /** Обновить mirror user'а и эмитнуть listener'ам если он реально изменился.
2299
+ * Используется и для self-инициированных RPC (bootstrap/getUser), и для
2300
+ * broadcast'ов от offscreen — чтобы host'овский onUserChange handler
2301
+ * получил signal независимо от того, кто триггернул обновление. */
2302
+ applyUser(e) {
2303
+ ut(this.cachedUser, e) || (this.cachedUser = e, this.fireUserListeners(e));
2304
+ }
2305
+ applyBalances(e) {
2306
+ ht(this.cachedBalances, e) || (this.cachedBalances = e, this.fireBalanceListeners(e));
2307
+ }
2308
+ fireUserListeners(e) {
2309
+ for (const t of [...this.userListeners])
2310
+ try {
2311
+ t(e);
2312
+ } catch (n) {
2313
+ console.warn("[paywall] onUserChange listener threw", n);
2314
+ }
2315
+ }
2316
+ fireBalanceListeners(e) {
2317
+ for (const t of [...this.balanceListeners])
2318
+ try {
2319
+ t(e);
2320
+ } catch (n) {
2321
+ console.warn("[paywall] onBalanceChange listener threw", n);
2322
+ }
2323
+ }
2324
+ }
2325
+ function ut(r, e) {
2326
+ return r === e ? !0 : !r || !e ? !1 : r.has_active_subscription === e.has_active_subscription && (r.purchases?.length ?? 0) === (e.purchases?.length ?? 0);
2327
+ }
2328
+ function ht(r, e) {
2329
+ if (r === e) return !0;
2330
+ if (!r || !e || r.length !== e.length) return !1;
2331
+ for (let t = 0; t < r.length; t++)
2332
+ if (r[t].type !== e[t].type || r[t].count !== e[t].count) return !1;
2333
+ return !0;
2334
+ }
2335
+ class dt {
2336
+ constructor(e, t) {
2337
+ this.transport = e, this.session = null, this.listeners = /* @__PURE__ */ new Set(), this.unsubBroadcast = null, this.paywallId = t.paywallId, this.apiOrigin = t.apiOrigin, this.unsubBroadcast = this.transport.on("authChange", (n) => {
2338
+ this.applySession(n);
2339
+ }), this.hydrated = this.transport.request("auth.getCachedSession", void 0).then((n) => {
2340
+ this.session === null && n !== null && this.applySession(n);
2341
+ }).catch(() => {
2342
+ });
2343
+ }
2344
+ /** Promise, который резолвится после первичной синхронизации session с
2345
+ * offscreen'а. Аналог AuthClient.ready(). */
2346
+ ready() {
2347
+ return this.hydrated;
2348
+ }
2349
+ getCachedSession() {
2350
+ return this.session;
2351
+ }
2352
+ getCachedUser() {
2353
+ return this.session?.user ?? null;
2354
+ }
2355
+ onAuthChange(e) {
2356
+ if (this.listeners.add(e), this.session) {
2357
+ const t = this.session;
2358
+ queueMicrotask(() => {
2359
+ this.listeners.has(e) && e(t);
2360
+ });
2361
+ }
2362
+ return () => {
2363
+ this.listeners.delete(e);
2364
+ };
2365
+ }
2366
+ // === Email/password ===
2367
+ async signInWithEmail(e) {
2368
+ const t = await this.transport.request("auth.signInWithEmail", e);
2369
+ return this.applySession(t), t;
2370
+ }
2371
+ async signUp(e) {
2372
+ const t = await this.transport.request("auth.signUp", e);
2373
+ return t.kind === "signed_in" && this.applySession(t.session), t;
2374
+ }
2375
+ async signOut() {
2376
+ await this.transport.request("auth.signOut", void 0);
2377
+ }
2378
+ async refresh() {
2379
+ const e = await this.transport.request("auth.refresh", void 0);
2380
+ return this.applySession(e), e;
2381
+ }
2382
+ // === OTP / password reset / confirmation ===
2383
+ async sendOtp(e) {
2384
+ await this.transport.request("auth.sendOtp", e);
2385
+ }
2386
+ async verifyOtp(e) {
2387
+ const t = await this.transport.request("auth.verifyOtp", e);
2388
+ return this.applySession(t), t;
2389
+ }
2390
+ async resendConfirmation(e) {
2391
+ await this.transport.request("auth.resendConfirmation", e);
2392
+ }
2393
+ async requestPasswordReset(e) {
2394
+ await this.transport.request("auth.requestPasswordReset", e);
2395
+ }
2396
+ async updatePassword(e) {
2397
+ await this.transport.request("auth.updatePassword", e);
2398
+ }
2399
+ async revokeAllSessions() {
2400
+ await this.transport.request("auth.revokeAllSessions", void 0);
2401
+ }
2402
+ // === Anonymous sign-in ===
2403
+ /** Анонимный sign-in (Supabase user без email). Логика (idempotent-check +
2404
+ * resume через сохранённый refresh_token + fresh signin) живёт в
2405
+ * offscreen-AuthClient'е — content только проксирует. captchaToken и
2406
+ * forceCaptcha — pass-through для forward-compat / switch-account flow. */
2407
+ async signInAnonymously(e = {}) {
2408
+ const t = await this.transport.request("auth.signInAnonymously", {
2409
+ captchaToken: e.captchaToken,
2410
+ userMeta: e.userMeta,
2411
+ forceCaptcha: e.forceCaptcha
2412
+ });
2413
+ return this.applySession(t), t;
2414
+ }
2415
+ /** Текущий access token (lazy-refreshable в offscreen'е). content/popup
2416
+ * использует для Bearer'а в внешние fetch'и — ApiGatewayClient в
2417
+ * content-script'е, прямые запросы из demo-UI. null если разлогинен или
2418
+ * offscreen'овский AuthClient не смог рефрешнуть. */
2419
+ async getAccessToken() {
2420
+ return this.transport.request("auth.getAccessToken", void 0);
2421
+ }
2422
+ // === OAuth (web-flow через split-API) ===
2423
+ /** OAuth через web-вариант: window.open в content-script'е, provider
2424
+ * redirect, callback page постит code в opener. Под капотом split на
2425
+ * два request'а в offscreen — startOAuthFlow (дёргаем /init, получаем
2426
+ * authorize_url) → открываем popup → waitForOAuthCode → exchange.
2427
+ *
2428
+ * PKCE verifier живёт ТОЛЬКО в offscreen'е (внутри AuthClient'а), через
2429
+ * runtime-границу не идёт. Content получает только authorize_url и state.
2430
+ *
2431
+ * Popup-gesture: `window.open(authorize_url, ...)` идёт в том же synchronous
2432
+ * flow'е, что startOAuthFlow ответ; user-gesture сохраняется потому что
2433
+ * content-script unloaded не за этот tick (gesture сохраняется через все
2434
+ * microtask'и одного call stack'а). Если в каком-то браузере gesture
2435
+ * всё-таки теряется — host получит `popup_blocked` (тот же что в @monetize.software/sdk).
2436
+ */
2437
+ async signInWithOAuth(e) {
2438
+ if (typeof window > "u")
2439
+ throw new T("oauth_unavailable", "window is required for OAuth");
2440
+ const t = `pw-oauth-pending-${Math.random().toString(36).slice(2, 10)}`, n = window.open("about:blank", t, "width=480,height=640,popup=yes");
2441
+ if (!n)
2442
+ throw new T(
2443
+ "popup_blocked",
2444
+ "browser blocked auth popup — call from a user gesture"
2445
+ );
2446
+ gt(n, e.provider);
2447
+ try {
2448
+ const { authorizeUrl: i, state: s } = await this.transport.request("auth.oauthStart", {
2449
+ provider: e.provider,
2450
+ scopes: e.scopes,
2451
+ userMeta: e.userMeta
2452
+ });
2453
+ n.name = `pw-oauth-${s}`, n.location.replace(i), e.onPopupOpened?.();
2454
+ const l = await he(n, s), a = await this.transport.request("auth.oauthExchange", { state: s, code: l });
2455
+ return this.applySession(a), a;
2456
+ } catch (i) {
2457
+ try {
2458
+ n.close();
2459
+ } catch {
2460
+ }
2461
+ throw i;
2462
+ }
2463
+ }
2464
+ destroy() {
2465
+ this.unsubBroadcast?.(), this.unsubBroadcast = null, this.listeners.clear(), this.session = null;
2466
+ }
2467
+ applySession(e) {
2468
+ if (!pt(this.session, e)) {
2469
+ this.session = e;
2470
+ for (const t of [...this.listeners])
2471
+ try {
2472
+ t(e);
2473
+ } catch (n) {
2474
+ console.warn("[paywall] onAuthChange listener threw", n);
2475
+ }
2476
+ }
2477
+ }
2478
+ }
2479
+ function pt(r, e) {
2480
+ return r === e ? !0 : !r || !e ? !1 : r.access_token === e.access_token && r.refresh_token === e.refresh_token && r.expires_at === e.expires_at && r.user.id === e.user.id;
2481
+ }
2482
+ const ft = {
2483
+ google: "Google",
2484
+ apple: "Apple",
2485
+ github: "GitHub",
2486
+ facebook: "Facebook"
2487
+ };
2488
+ function gt(r, e) {
2489
+ const t = ft[e] ?? e;
2490
+ try {
2491
+ const n = r.document;
2492
+ n.title = `Sign in with ${t}`;
2493
+ const i = n.createElement("style");
2494
+ i.textContent = "html,body{margin:0;padding:0;height:100%;font-family:-apple-system,system-ui,sans-serif;background:#fafafa;color:#475569}.pw-oauth-wrap{display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;gap:16px}.pw-oauth-spinner{width:36px;height:36px;border:3px solid #e2e8f0;border-top-color:#7c3aed;border-radius:50%;animation:pw-oauth-spin 800ms linear infinite}.pw-oauth-label{font-size:14px;font-weight:500;letter-spacing:-0.01em}@keyframes pw-oauth-spin{to{transform:rotate(360deg)}}", n.head.appendChild(i);
2495
+ const s = n.createElement("div");
2496
+ s.className = "pw-oauth-wrap";
2497
+ const l = n.createElement("div");
2498
+ l.className = "pw-oauth-spinner";
2499
+ const a = n.createElement("div");
2500
+ a.className = "pw-oauth-label", a.textContent = `Connecting to ${t}…`, s.appendChild(l), s.appendChild(a), n.body.appendChild(s);
2501
+ } catch {
2502
+ }
2503
+ }
2504
+ class mt {
2505
+ constructor(e) {
2506
+ this.transport = e;
2507
+ }
2508
+ /** Отправить событие. Fire-and-forget — не возвращает Promise, не throw'ает.
2509
+ * Сетевые/транспортные ошибки логируются в console и не блокируют caller. */
2510
+ track(e, t) {
2511
+ typeof e != "string" || e.length === 0 || this.transport.request("tracker.track", { name: e, props: t }).catch((n) => {
2512
+ console.warn("[paywall] track failed", n);
2513
+ });
2514
+ }
2515
+ }
2516
+ class yt {
2517
+ constructor(e) {
2518
+ this.factory = e, this.channel = null, this.channelDisposers = [], this.pending = /* @__PURE__ */ new Map(), this.listeners = /* @__PURE__ */ new Map(), this.destroyed = !1, this.nextId = 0, this.clientId = `c-${Math.random().toString(36).slice(2, 10)}`;
2519
+ }
2520
+ /** Гарантирует наличие живого канала. Lazy — поднимается при первом request.
2521
+ * Сразу после connect'а fire-and-forget шлёт handshake — на mismatch
2522
+ * логируем warning, но не блокируем дальнейшие запросы. */
2523
+ ensureChannel() {
2524
+ if (this.destroyed) throw new Error("TransportClient destroyed");
2525
+ if (this.channel) return this.channel;
2526
+ const e = this.factory();
2527
+ this.channel = e;
2528
+ const t = e.onMessage((i) => this.handleMessage(i)), n = e.onDisconnect(() => this.handleDisconnect());
2529
+ return this.channelDisposers = [t, n], this.request("handshake", {
2530
+ protocolVersion: R,
2531
+ clientId: this.clientId
2532
+ }).then((i) => {
2533
+ i.protocolVersion !== R && console.warn(
2534
+ `[sdk-extension] protocol version mismatch: client=${R}, offscreen=${i.protocolVersion}. Update host's @monetize.software/sdk-extension.`
2535
+ );
2536
+ }).catch(() => {
2537
+ }), e;
2538
+ }
2539
+ handleMessage(e) {
2540
+ if (bt(e)) {
2541
+ if (e.type === "response") {
2542
+ const t = this.pending.get(e.id);
2543
+ if (!t) return;
2544
+ this.pending.delete(e.id), t.signal?.removeEventListener("abort", t.abortListener), e.ok ? t.resolve(e.result) : t.reject(de(e.error));
2545
+ return;
2546
+ }
2547
+ if (e.type === "event") {
2548
+ const t = this.listeners.get(e.kind);
2549
+ if (!t) return;
2550
+ for (const n of [...t])
2551
+ try {
2552
+ n(e.payload);
2553
+ } catch (i) {
2554
+ console.error("[sdk-extension] event handler threw", i);
2555
+ }
2556
+ }
2557
+ }
2558
+ }
2559
+ handleDisconnect() {
2560
+ for (const t of this.channelDisposers) t();
2561
+ this.channelDisposers = [], this.channel = null;
2562
+ const e = Array.from(this.pending.values());
2563
+ this.pending.clear();
2564
+ for (const t of e)
2565
+ t.signal?.removeEventListener("abort", t.abortListener), t.reject(new xt());
2566
+ }
2567
+ request(e, t, n = {}) {
2568
+ if (this.destroyed)
2569
+ return Promise.reject(new Error("TransportClient destroyed"));
2570
+ if (n.signal?.aborted)
2571
+ return Promise.reject(new DOMException("Aborted", "AbortError"));
2572
+ const i = this.ensureChannel(), s = `r${++this.nextId}`;
2573
+ return new Promise((l, a) => {
2574
+ const c = {
2575
+ resolve: l,
2576
+ reject: a,
2577
+ signal: n.signal
2578
+ };
2579
+ n.signal && (c.abortListener = () => {
2580
+ if (this.pending.delete(s)) {
2581
+ a(new DOMException("Aborted", "AbortError"));
2582
+ try {
2583
+ i.send({ type: "cancel", id: s });
2584
+ } catch {
2585
+ }
2586
+ }
2587
+ }, n.signal.addEventListener("abort", c.abortListener)), this.pending.set(s, c);
2588
+ const p = {
2589
+ type: "request",
2590
+ id: s,
2591
+ kind: e,
2592
+ params: t
2593
+ };
2594
+ try {
2595
+ i.send(p);
2596
+ } catch (g) {
2597
+ this.pending.delete(s), n.signal?.removeEventListener("abort", c.abortListener), a(g);
2598
+ }
2599
+ });
2600
+ }
2601
+ on(e, t) {
2602
+ let n = this.listeners.get(e);
2603
+ n || (n = /* @__PURE__ */ new Set(), this.listeners.set(e, n));
2604
+ const i = t;
2605
+ return n.add(i), this.ensureChannel(), () => {
2606
+ n.delete(i);
2607
+ };
2608
+ }
2609
+ destroy() {
2610
+ if (this.destroyed) return;
2611
+ this.destroyed = !0;
2612
+ for (const t of this.channelDisposers) t();
2613
+ this.channelDisposers = [], this.listeners.clear();
2614
+ const e = Array.from(this.pending.values());
2615
+ this.pending.clear();
2616
+ for (const t of e)
2617
+ t.signal?.removeEventListener("abort", t.abortListener), t.reject(new Error("TransportClient destroyed"));
2618
+ this.channel?.close(), this.channel = null;
2619
+ }
2620
+ }
2621
+ class xt extends Error {
2622
+ constructor() {
2623
+ super("Transport channel disconnected mid-request"), this.code = "transport_disconnected", this.name = "TransportDisconnectedError";
2624
+ }
2625
+ }
2626
+ function bt(r) {
2627
+ if (typeof r != "object" || r === null) return !1;
2628
+ const e = r.type;
2629
+ return e === "request" || e === "response" || e === "event";
2630
+ }
2631
+ let q = null;
2632
+ function kt() {
2633
+ return q || (q = new yt(() => pe(fe)), q);
2634
+ }
2635
+ class Tt extends tt {
2636
+ constructor(e) {
2637
+ const t = kt(), n = new ct(t, {
2638
+ paywallId: e.paywallId,
2639
+ apiOrigin: e.apiOrigin
2640
+ });
2641
+ let i;
2642
+ e.auth === !0 ? i = new dt(t, {
2643
+ paywallId: e.paywallId,
2644
+ apiOrigin: e.apiOrigin
2645
+ }) : e.auth && console.warn(
2646
+ "[sdk-extension] passing AuthClient instance to PaywallUI.opts.auth is not supported in extension mode — pass `auth: true` to use offscreen-shared auth, or omit for hybrid identity-only mode."
2647
+ ), i && (n.auth = i), super({
2648
+ ...e,
2649
+ // Cast'ы безопасны: PaywallUI'ев resolveAuth duck-type'ит auth (см.
2650
+ // sdk/src/ui/PaywallUI.ts isAuthClientLike), а billing-параметр идёт
2651
+ // через `opts.client ?? new BillingClient(...)` — RemoteBillingClient
2652
+ // там используется как есть, методы все сходятся.
2653
+ client: n,
2654
+ auth: i,
2655
+ // Внутренний EventTracker отключаем — единственный tracker живёт в
2656
+ // offscreen'е. Манчиально подписываемся ниже.
2657
+ analytics: !1
2658
+ }), this.remoteTracker = null, this.trackerUnsubs = [], e.analytics !== !1 && (this.remoteTracker = new mt(t), this.bindAnalytics());
2659
+ }
2660
+ /** Зеркало sdk/PaywallUI.initTracker'овских биндингов, но с RemoteEventTracker.
2661
+ * Когда @monetize.software/sdk экспоузнет публичный hook для inject'а tracker'а,
2662
+ * этот метод заменится на одну строку. */
2663
+ bindAnalytics() {
2664
+ const e = this.remoteTracker;
2665
+ e && this.trackerUnsubs.push(
2666
+ this.on("open", () => e.track("paywall_opened")),
2667
+ this.on(
2668
+ "ready",
2669
+ (t) => e.track("paywall_viewed", {
2670
+ is_test_mode: t.settings.is_test_mode,
2671
+ prices_count: t.prices.length,
2672
+ offers_count: t.offers.length
2673
+ })
2674
+ ),
2675
+ this.on(
2676
+ "price_selected",
2677
+ (t) => e.track("price_selected", { price_id: t.priceId })
2678
+ ),
2679
+ this.on(
2680
+ "checkout_started",
2681
+ (t) => e.track("checkout_started", { price_id: t.priceId, acquiring: t.acquiring })
2682
+ ),
2683
+ this.on(
2684
+ "purchase_completed",
2685
+ (t) => e.track("purchase_completed", { price_id: t.priceId, session_id: t.sessionId })
2686
+ ),
2687
+ this.on("purchase_failed", (t) => e.track("purchase_failed", { reason: t.reason })),
2688
+ this.on("close", () => e.track("paywall_closed")),
2689
+ this.on(
2690
+ "trial_blocked",
2691
+ (t) => e.track("trial_blocked", {
2692
+ mode: t.mode,
2693
+ ...t.mode === "time" ? { remaining_ms: t.remainingMs, total_ms: t.totalMs } : t.mode === "opens" ? { remaining_actions: t.remainingActions, total_actions: t.totalActions } : {}
2694
+ })
2695
+ ),
2696
+ this.on("trial_expired", () => e.track("trial_expired")),
2697
+ this.on(
2698
+ "visibility_blocked",
2699
+ (t) => e.track("visibility_blocked", { reason: t.reason, country: t.country, tier: t.tier })
2700
+ ),
2701
+ this.on("error", (t) => e.track("error", { code: t.code, message: t.message }))
2702
+ );
2703
+ }
2704
+ /** Прокси через RemoteEventTracker. Hosts могут вызывать paywall.track
2705
+ * для произвольных аналитических событий — летит в единственный
2706
+ * offscreen-tracker наряду с auto-emit'ами PaywallUI. */
2707
+ track(e, t) {
2708
+ this.remoteTracker?.track(e, t);
2709
+ }
2710
+ destroy() {
2711
+ for (const e of this.trackerUnsubs) e();
2712
+ this.trackerUnsubs = [], this.remoteTracker = null, super.destroy();
2713
+ }
2714
+ }
2715
+ export {
2716
+ R as PROTOCOL_VERSION,
2717
+ Tt as PaywallUI,
2718
+ dt as RemoteAuthClient,
2719
+ ct as RemoteBillingClient,
2720
+ mt as RemoteEventTracker,
2721
+ kt as getContentTransport
2722
+ };
2723
+ //# sourceMappingURL=content.js.map