@tma.js/sdk 1.5.3 → 2.0.1

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 (255) hide show
  1. package/dist/dts/bridge/events/event-emitter/createMiniAppsEventEmitter.d.ts +15 -0
  2. package/dist/dts/bridge/events/event-emitter/singleton.d.ts +8 -0
  3. package/dist/dts/bridge/events/event-handlers/cleanupEventHandlers.d.ts +4 -0
  4. package/dist/dts/bridge/events/event-handlers/defineEventHandlers.d.ts +6 -0
  5. package/dist/dts/bridge/events/event-handlers/emitMiniAppsEvent.d.ts +9 -0
  6. package/dist/dts/bridge/events/{off.d.ts → listening/off.d.ts} +3 -2
  7. package/dist/dts/bridge/events/listening/on.d.ts +12 -0
  8. package/dist/dts/bridge/events/listening/subscribe.d.ts +9 -0
  9. package/dist/dts/bridge/events/listening/unsubscribe.d.ts +7 -0
  10. package/dist/dts/bridge/events/types.d.ts +294 -2
  11. package/dist/dts/bridge/methods/createPostEvent.d.ts +7 -4
  12. package/dist/dts/bridge/methods/postEvent.d.ts +24 -15
  13. package/dist/dts/bridge/methods/{custom-methods.d.ts → types/custom-methods.d.ts} +2 -1
  14. package/dist/dts/bridge/methods/types/index.d.ts +4 -0
  15. package/dist/dts/bridge/methods/{methods.d.ts → types/methods.d.ts} +70 -17
  16. package/dist/dts/{globals.d.ts → bridge/target-origin.d.ts} +0 -9
  17. package/dist/dts/bridge/{invokeCustomMethod.d.ts → utils/invokeCustomMethod.d.ts} +7 -2
  18. package/dist/dts/bridge/utils/request.d.ts +35 -0
  19. package/dist/dts/classes/State/State.d.ts +46 -0
  20. package/dist/dts/classes/State/types.d.ts +29 -0
  21. package/dist/dts/classes/WithStateUtils.d.ts +18 -0
  22. package/dist/dts/classes/WithSupports.d.ts +19 -0
  23. package/dist/dts/classes/WithSupportsAndStateUtils.d.ts +24 -0
  24. package/dist/dts/classes/WithSupportsAndTrackableState.d.ts +16 -0
  25. package/dist/dts/classes/WithTrackableState.d.ts +16 -0
  26. package/dist/dts/classnames/mergeClassNames.d.ts +2 -1
  27. package/dist/dts/colors/isRGB.d.ts +2 -1
  28. package/dist/dts/colors/isRGBShort.d.ts +2 -1
  29. package/dist/dts/colors/toRGB.d.ts +2 -1
  30. package/dist/dts/components/BackButton/BackButton.d.ts +41 -0
  31. package/dist/dts/components/BackButton/initBackButton.d.ts +7 -0
  32. package/dist/dts/components/BackButton/types.d.ts +25 -0
  33. package/dist/dts/components/BiometryManager/BiometryManager.d.ts +61 -0
  34. package/dist/dts/components/BiometryManager/formatEvent.d.ts +34 -0
  35. package/dist/dts/components/BiometryManager/initBiometryManager.d.ts +7 -0
  36. package/dist/dts/components/BiometryManager/requestBiometryInfo.d.ts +8 -0
  37. package/dist/dts/components/BiometryManager/types.d.ts +40 -0
  38. package/dist/dts/components/ClosingBehavior/ClosingBehavior.d.ts +26 -0
  39. package/dist/dts/components/ClosingBehavior/initClosingBehavior.d.ts +7 -0
  40. package/dist/dts/components/{closing-behavior → ClosingBehavior}/types.d.ts +14 -1
  41. package/dist/dts/components/{cloud-storage → CloudStorage}/CloudStorage.d.ts +11 -11
  42. package/dist/dts/components/CloudStorage/initCloudStorage.d.ts +7 -0
  43. package/dist/dts/components/{haptic-feedback → HapticFeedback}/HapticFeedback.d.ts +9 -13
  44. package/dist/dts/components/HapticFeedback/initHapticFeedback.d.ts +7 -0
  45. package/dist/dts/components/{init-data → InitData}/InitData.d.ts +4 -2
  46. package/dist/dts/components/InitData/initInitData.d.ts +7 -0
  47. package/dist/dts/components/{init-data → InitData}/parseInitData.d.ts +2 -1
  48. package/dist/dts/components/InitData/parsers/chat.d.ts +3 -0
  49. package/dist/dts/components/InitData/parsers/initData.d.ts +7 -0
  50. package/dist/dts/components/InitData/parsers/user.d.ts +3 -0
  51. package/dist/dts/components/{init-data → InitData}/types.d.ts +2 -3
  52. package/dist/dts/components/Invoice/Invoice.d.ts +31 -0
  53. package/dist/dts/components/Invoice/initInvoice.d.ts +7 -0
  54. package/dist/dts/components/{invoice → Invoice}/types.d.ts +14 -1
  55. package/dist/dts/components/MainButton/MainButton.d.ts +106 -0
  56. package/dist/dts/components/MainButton/initMainButton.d.ts +7 -0
  57. package/dist/dts/components/MainButton/types.d.ts +40 -0
  58. package/dist/dts/components/{mini-app → MiniApp}/MiniApp.d.ts +29 -43
  59. package/dist/dts/components/MiniApp/initMiniApp.d.ts +7 -0
  60. package/dist/dts/components/MiniApp/parsing/contact.d.ts +7 -0
  61. package/dist/dts/components/MiniApp/types.d.ts +53 -0
  62. package/dist/dts/components/Popup/Popup.d.ts +30 -0
  63. package/dist/dts/components/Popup/initPopup.d.ts +7 -0
  64. package/dist/dts/components/{popup → Popup}/preparePopupParams.d.ts +3 -2
  65. package/dist/dts/components/{popup → Popup}/types.d.ts +2 -1
  66. package/dist/dts/components/QRScanner/QRScanner.d.ts +28 -0
  67. package/dist/dts/components/QRScanner/initQRScanner.d.ts +7 -0
  68. package/dist/dts/components/{qr-scanner → QRScanner}/types.d.ts +14 -1
  69. package/dist/dts/components/SettingsButton/SettingsButton.d.ts +37 -0
  70. package/dist/dts/components/SettingsButton/initSettingsButton.d.ts +7 -0
  71. package/dist/dts/components/{settings-button → SettingsButton}/types.d.ts +18 -3
  72. package/dist/dts/components/ThemeParams/ThemeParams.d.ts +53 -0
  73. package/dist/dts/components/ThemeParams/initThemeParams.d.ts +7 -0
  74. package/dist/dts/components/ThemeParams/keys.d.ts +11 -0
  75. package/dist/dts/components/{theme-params → ThemeParams/parsing}/parseThemeParams.d.ts +2 -1
  76. package/dist/dts/components/{theme-params → ThemeParams/parsing}/serializeThemeParams.d.ts +2 -1
  77. package/dist/dts/components/ThemeParams/parsing/themeParams.d.ts +4 -0
  78. package/dist/dts/components/ThemeParams/requestThemeParams.d.ts +8 -0
  79. package/dist/dts/components/ThemeParams/types.d.ts +29 -0
  80. package/dist/dts/components/{utils → Utils}/Utils.d.ts +10 -12
  81. package/dist/dts/components/Utils/initUtils.d.ts +7 -0
  82. package/dist/dts/components/Viewport/Viewport.d.ts +77 -0
  83. package/dist/dts/components/Viewport/initViewport.d.ts +8 -0
  84. package/dist/dts/components/Viewport/initViewportFromRequest.d.ts +10 -0
  85. package/dist/dts/components/{viewport → Viewport}/requestViewport.d.ts +3 -2
  86. package/dist/dts/components/Viewport/types.d.ts +35 -0
  87. package/dist/dts/css-vars/bindMiniAppCSSVars.d.ts +29 -0
  88. package/dist/dts/css-vars/bindThemeParamsCSSVars.d.ts +29 -0
  89. package/dist/dts/css-vars/bindViewportCSSVars.d.ts +32 -0
  90. package/dist/dts/{css → css-vars}/setCSSVar.d.ts +1 -1
  91. package/dist/dts/debug/debug.d.ts +14 -0
  92. package/dist/dts/{bridge/env → env}/hasExternalNotify.d.ts +5 -7
  93. package/dist/dts/{bridge/env → env}/hasWebviewProxy.d.ts +5 -7
  94. package/dist/dts/env/initWeb.d.ts +11 -0
  95. package/dist/dts/env/isSSR.d.ts +4 -0
  96. package/dist/dts/{misc → env}/isTMA.d.ts +1 -1
  97. package/dist/dts/errors/SDKError.d.ts +9 -0
  98. package/dist/dts/errors/createError.d.ts +10 -0
  99. package/dist/dts/errors/errors.d.ts +53 -0
  100. package/dist/dts/errors/isSDKError.d.ts +7 -0
  101. package/dist/dts/errors/isSDKErrorOfType.d.ts +8 -0
  102. package/dist/dts/{event-emitter → events/event-emitter}/EventEmitter.d.ts +20 -30
  103. package/dist/dts/{event-emitter → events/event-emitter}/types.d.ts +10 -9
  104. package/dist/dts/events/onWindow.d.ts +10 -0
  105. package/dist/dts/events/types.d.ts +6 -0
  106. package/dist/dts/index.d.ts +114 -92
  107. package/dist/dts/index.low-level.d.ts +41 -0
  108. package/dist/dts/launch-params/parseLaunchParams.d.ts +2 -1
  109. package/dist/dts/launch-params/retrieveFromLocation.d.ts +2 -1
  110. package/dist/dts/launch-params/retrieveFromPerformance.d.ts +3 -3
  111. package/dist/dts/launch-params/{storage.d.ts → retrieveFromStorage.d.ts} +2 -6
  112. package/dist/dts/launch-params/retrieveFromUrl.d.ts +2 -1
  113. package/dist/dts/launch-params/retrieveLaunchParams.d.ts +2 -1
  114. package/dist/dts/launch-params/saveToStorage.d.ts +7 -0
  115. package/dist/dts/launch-params/serializeLaunchParams.d.ts +2 -1
  116. package/dist/dts/launch-params/types.d.ts +12 -13
  117. package/dist/dts/logger/Logger.d.ts +9 -18
  118. package/dist/dts/misc/createComponentInitFn/createComponentInitFn.d.ts +15 -0
  119. package/dist/dts/misc/createComponentInitFn/types.d.ts +47 -0
  120. package/dist/dts/misc/createSingleton.d.ts +15 -0
  121. package/dist/dts/misc/objectFromKeys.d.ts +6 -0
  122. package/dist/dts/navigation/BasicNavigator/BasicNavigator.d.ts +118 -0
  123. package/dist/dts/navigation/BasicNavigator/prepareItem.d.ts +8 -0
  124. package/dist/dts/navigation/BasicNavigator/types.d.ts +37 -0
  125. package/dist/dts/navigation/BrowserNavigator/BrowserNavigator.d.ts +198 -0
  126. package/dist/dts/navigation/BrowserNavigator/basicItemToBrowser.d.ts +7 -0
  127. package/dist/dts/navigation/BrowserNavigator/createBrowserNavigatorFromLocation.d.ts +4 -0
  128. package/dist/dts/navigation/BrowserNavigator/prepareItem.d.ts +25 -0
  129. package/dist/dts/navigation/BrowserNavigator/types.d.ts +63 -0
  130. package/dist/dts/navigation/createSafeURL.d.ts +7 -0
  131. package/dist/dts/navigation/getHash.d.ts +2 -1
  132. package/dist/dts/navigation/getPathname.d.ts +7 -0
  133. package/dist/dts/navigation/initNavigator.d.ts +9 -0
  134. package/dist/dts/navigation/urlToPath.d.ts +7 -0
  135. package/dist/dts/parsing/ArrayParser/ArrayParser.d.ts +17 -0
  136. package/dist/dts/parsing/ArrayParser/types.d.ts +12 -0
  137. package/dist/dts/parsing/ValueParser/ValueParser.d.ts +17 -0
  138. package/dist/dts/parsing/{ValueParser.d.ts → ValueParser/types.d.ts} +6 -14
  139. package/dist/dts/parsing/createTypeError.d.ts +6 -0
  140. package/dist/dts/parsing/createValueParserGenerator.d.ts +3 -2
  141. package/dist/dts/parsing/parseBySchema.d.ts +2 -1
  142. package/dist/dts/parsing/parsers/array.d.ts +3 -2
  143. package/dist/dts/parsing/parsers/boolean.d.ts +2 -1
  144. package/dist/dts/parsing/parsers/date.d.ts +2 -1
  145. package/dist/dts/parsing/parsers/json.d.ts +3 -2
  146. package/dist/dts/parsing/parsers/number.d.ts +2 -1
  147. package/dist/dts/parsing/parsers/rgb.d.ts +3 -2
  148. package/dist/dts/parsing/parsers/searchParams.d.ts +3 -2
  149. package/dist/dts/parsing/parsers/string.d.ts +2 -1
  150. package/dist/dts/{init/creators → request-id}/createRequestIdGenerator.d.ts +3 -2
  151. package/dist/dts/{types/request-id.d.ts → request-id/types.d.ts} +1 -1
  152. package/dist/dts/storage/storage.d.ts +42 -0
  153. package/dist/dts/supports/createSupportsFn.d.ts +12 -0
  154. package/dist/dts/supports/{createSupportsParamFunc.d.ts → createSupportsParamFn.d.ts} +5 -4
  155. package/dist/dts/supports/supports.d.ts +3 -2
  156. package/dist/dts/supports/types.d.ts +1 -1
  157. package/dist/dts/timeout/createTimeoutError.d.ts +7 -0
  158. package/dist/dts/timeout/sleep.d.ts +1 -1
  159. package/dist/dts/timeout/withTimeout.d.ts +1 -2
  160. package/dist/dts/types/index.d.ts +6 -0
  161. package/dist/dts/types/methods.d.ts +2 -1
  162. package/dist/dts/types/misc.d.ts +12 -0
  163. package/dist/dts/types/utils.d.ts +16 -0
  164. package/dist/dts/version/compareVersions.d.ts +2 -1
  165. package/dist/index.cjs +2 -1
  166. package/dist/index.cjs.map +1 -0
  167. package/dist/index.iife.js +2 -1
  168. package/dist/index.iife.js.map +1 -0
  169. package/dist/index.js +3001 -0
  170. package/dist/index.js.map +1 -0
  171. package/dist/index.low-level.iife.js +2 -0
  172. package/dist/index.low-level.iife.js.map +1 -0
  173. package/package.json +7 -9
  174. package/dist/dts/bridge/errors/MethodUnsupportedError.d.ts +0 -8
  175. package/dist/dts/bridge/errors/ParameterUnsupportedError.d.ts +0 -8
  176. package/dist/dts/bridge/events/createEmitter.d.ts +0 -6
  177. package/dist/dts/bridge/events/events.d.ts +0 -140
  178. package/dist/dts/bridge/events/on.d.ts +0 -9
  179. package/dist/dts/bridge/events/onTelegramEvent.d.ts +0 -7
  180. package/dist/dts/bridge/events/once.d.ts +0 -8
  181. package/dist/dts/bridge/events/parsers/clipboardTextReceived.d.ts +0 -13
  182. package/dist/dts/bridge/events/parsers/customMethodInvoked.d.ts +0 -16
  183. package/dist/dts/bridge/events/parsers/invoiceClosed.d.ts +0 -12
  184. package/dist/dts/bridge/events/parsers/phoneRequested.d.ts +0 -8
  185. package/dist/dts/bridge/events/parsers/popupClosed.d.ts +0 -8
  186. package/dist/dts/bridge/events/parsers/qrTextReceived.d.ts +0 -7
  187. package/dist/dts/bridge/events/parsers/theme-changed.d.ts +0 -42
  188. package/dist/dts/bridge/events/parsers/viewportChanged.d.ts +0 -19
  189. package/dist/dts/bridge/events/parsers/writeAccessRequested.d.ts +0 -8
  190. package/dist/dts/bridge/events/singletonEmitter.d.ts +0 -6
  191. package/dist/dts/bridge/events/subscribe.d.ts +0 -8
  192. package/dist/dts/bridge/events/unsubscribe.d.ts +0 -6
  193. package/dist/dts/bridge/request.d.ts +0 -54
  194. package/dist/dts/components/back-button/BackButton.d.ts +0 -47
  195. package/dist/dts/components/back-button/types.d.ts +0 -10
  196. package/dist/dts/components/closing-behavior/ClosingBehavior.d.ts +0 -39
  197. package/dist/dts/components/init-data/chatParser.d.ts +0 -6
  198. package/dist/dts/components/init-data/initDataParser.d.ts +0 -6
  199. package/dist/dts/components/init-data/userParser.d.ts +0 -6
  200. package/dist/dts/components/invoice/Invoice.d.ts +0 -47
  201. package/dist/dts/components/main-button/MainButton.d.ts +0 -104
  202. package/dist/dts/components/main-button/types.d.ts +0 -20
  203. package/dist/dts/components/mini-app/contactParser.d.ts +0 -2
  204. package/dist/dts/components/mini-app/types.d.ts +0 -32
  205. package/dist/dts/components/popup/Popup.d.ts +0 -48
  206. package/dist/dts/components/qr-scanner/QRScanner.d.ts +0 -44
  207. package/dist/dts/components/settings-button/SettingsButton.d.ts +0 -42
  208. package/dist/dts/components/theme-params/ThemeParams.d.ts +0 -66
  209. package/dist/dts/components/theme-params/keys.d.ts +0 -11
  210. package/dist/dts/components/theme-params/requestThemeParams.d.ts +0 -7
  211. package/dist/dts/components/theme-params/themeParamsParser.d.ts +0 -3
  212. package/dist/dts/components/theme-params/types.d.ts +0 -14
  213. package/dist/dts/components/viewport/Viewport.d.ts +0 -90
  214. package/dist/dts/components/viewport/isStableViewportPlatform.d.ts +0 -7
  215. package/dist/dts/components/viewport/types.d.ts +0 -18
  216. package/dist/dts/components/viewport/utils.d.ts +0 -5
  217. package/dist/dts/css/bindMiniAppCSSVars.d.ts +0 -16
  218. package/dist/dts/css/bindThemeCSSVars.d.ts +0 -12
  219. package/dist/dts/css/bindViewportCSSVars.d.ts +0 -20
  220. package/dist/dts/init/catchCustomStyles.d.ts +0 -4
  221. package/dist/dts/init/creators/createBackButton.d.ts +0 -10
  222. package/dist/dts/init/creators/createClosingBehavior.d.ts +0 -9
  223. package/dist/dts/init/creators/createMainButton.d.ts +0 -12
  224. package/dist/dts/init/creators/createMiniApp.d.ts +0 -16
  225. package/dist/dts/init/creators/createSettingsButton.d.ts +0 -10
  226. package/dist/dts/init/creators/createThemeParams.d.ts +0 -7
  227. package/dist/dts/init/creators/createViewport.d.ts +0 -11
  228. package/dist/dts/init/css/processCSSVarsOption.d.ts +0 -12
  229. package/dist/dts/init/init.d.ts +0 -9
  230. package/dist/dts/init/types.d.ts +0 -85
  231. package/dist/dts/launch-params/launchParamsParser.d.ts +0 -6
  232. package/dist/dts/launch-params/retrieveLaunchData.d.ts +0 -7
  233. package/dist/dts/navigation/HashNavigator/HashNavigator.d.ts +0 -46
  234. package/dist/dts/navigation/HashNavigator/types.d.ts +0 -33
  235. package/dist/dts/navigation/Navigator/Navigator.d.ts +0 -104
  236. package/dist/dts/navigation/Navigator/types.d.ts +0 -44
  237. package/dist/dts/parsing/ArrayValueParser.d.ts +0 -18
  238. package/dist/dts/parsing/ParseError.d.ts +0 -22
  239. package/dist/dts/parsing/ParseSchemaFieldError.d.ts +0 -17
  240. package/dist/dts/parsing/unexpectedTypeError.d.ts +0 -4
  241. package/dist/dts/state/State.d.ts +0 -28
  242. package/dist/dts/state/types.d.ts +0 -27
  243. package/dist/dts/storage.d.ts +0 -50
  244. package/dist/dts/supports/createSupportsFunc.d.ts +0 -10
  245. package/dist/dts/timeout/TimeoutError.d.ts +0 -3
  246. package/dist/dts/timeout/isTimeoutError.d.ts +0 -6
  247. package/dist/index.mjs +0 -2813
  248. /package/dist/dts/bridge/methods/{haptic.d.ts → types/haptic.d.ts} +0 -0
  249. /package/dist/dts/bridge/methods/{popup.d.ts → types/popup.d.ts} +0 -0
  250. /package/dist/dts/bridge/{captureSameReq.d.ts → utils/captureSameReq.d.ts} +0 -0
  251. /package/dist/dts/{misc → env}/isIframe.d.ts +0 -0
  252. /package/dist/dts/navigation/{HashNavigator/drop.d.ts → drop.d.ts} +0 -0
  253. /package/dist/dts/{misc → navigation}/getFirstNavigationEntry.d.ts +0 -0
  254. /package/dist/dts/navigation/{HashNavigator/go.d.ts → go.d.ts} +0 -0
  255. /package/dist/dts/{misc → navigation}/isPageReload.d.ts +0 -0
@@ -1,36 +1,28 @@
1
- import type { Parser } from './types.js';
2
- import type { If } from '../types/logical.js';
1
+ import { If } from '../../types/logical.js';
2
+
3
3
  /**
4
4
  * Result of "parse" function.
5
5
  */
6
- export type ParseResult<ResultType, IsOptional extends boolean> = ResultType | If<IsOptional, undefined, never>;
6
+ export type ValueParserParseResult<ResultType, IsOptional extends boolean> = ResultType | If<IsOptional, undefined, never>;
7
7
  /**
8
8
  * Result of "optional" function in ValueParser.
9
9
  */
10
- export type OptionalResult<BaseClass, ResultType> = ValueParserType<BaseClass, ResultType, true>;
10
+ export type ValueParserOptionalResult<BaseClass, ResultType> = ValueParserType<BaseClass, ResultType, true>;
11
11
  export interface ValueParserOverrides<BaseClass, ResultType, IsOptional extends boolean> {
12
12
  /**
13
13
  * Parses incoming value applying parsing function passed via constructor.
14
14
  * @param value - value to parse.
15
15
  */
16
- parse(value: unknown): ParseResult<ResultType, IsOptional>;
16
+ parse(value: unknown): ValueParserParseResult<ResultType, IsOptional>;
17
17
  /**
18
18
  * Marks this parser result as optional. This makes the parser to check if passed value
19
19
  * is empty. If so, parser will return undefined value instead of passing it to the actual
20
20
  * parser.
21
21
  */
22
- optional(): OptionalResult<BaseClass, ResultType>;
22
+ optional(): ValueParserOptionalResult<BaseClass, ResultType>;
23
23
  }
24
24
  /**
25
25
  * Describes generated ValueParser interface. Shortly saying, this type overrides BaseClass
26
26
  * properties defined in ValueParser.
27
27
  */
28
28
  export type ValueParserType<BaseClass, ResultType, IsOptional extends boolean> = Omit<BaseClass, keyof ValueParserOverrides<any, any, any>> & ValueParserOverrides<BaseClass, ResultType, IsOptional>;
29
- export declare class ValueParser<ResultType, IsOptional extends boolean> {
30
- protected parser: Parser<ResultType>;
31
- protected isOptional: IsOptional;
32
- protected type?: string | undefined;
33
- constructor(parser: Parser<ResultType>, isOptional: IsOptional, type?: string | undefined);
34
- parse(value: unknown): ParseResult<ResultType, IsOptional>;
35
- optional(): OptionalResult<this, ResultType>;
36
- }
@@ -0,0 +1,6 @@
1
+ import { SDKError } from '../errors/SDKError.js';
2
+
3
+ /**
4
+ * Creates instance of TypeError stating, that value has unexpected type.
5
+ */
6
+ export declare function createTypeError(): SDKError;
@@ -1,5 +1,6 @@
1
- import type { Parser } from './types.js';
2
- import { ValueParser } from './ValueParser.js';
1
+ import { ValueParser } from './ValueParser/ValueParser.js';
2
+ import { Parser } from './types.js';
3
+
3
4
  export type ValueParserGenerator<T> = () => ValueParser<T, false>;
4
5
  /**
5
6
  * Creates function which generates new scalar value parser based on the specified one.
@@ -1,4 +1,5 @@
1
- import type { Schema } from './types.js';
1
+ import { Schema } from './types.js';
2
+
2
3
  /**
3
4
  * Parses external value by specified schema. Functions iterates over each schema field
4
5
  * and uses getField function to get its value from the external source.
@@ -1,6 +1,7 @@
1
- import { ArrayValueParser } from '../ArrayValueParser.js';
1
+ import { ArrayParser } from '../ArrayParser/ArrayParser.js';
2
+
2
3
  /**
3
4
  * Parses incoming value as an array.
4
5
  * @param parserTypeName - parser type name.
5
6
  */
6
- export declare function array(parserTypeName?: string): ArrayValueParser<unknown, false>;
7
+ export declare function array(parserTypeName?: string): ArrayParser<unknown, false>;
@@ -1,4 +1,5 @@
1
- import type { ValueParserGenerator } from '../createValueParserGenerator.js';
1
+ import { ValueParserGenerator } from '../createValueParserGenerator.js';
2
+
2
3
  /**
3
4
  * Returns parser to parse value as boolean.
4
5
  */
@@ -1,4 +1,5 @@
1
- import type { ValueParserGenerator } from '../createValueParserGenerator.js';
1
+ import { ValueParserGenerator } from '../createValueParserGenerator.js';
2
+
2
3
  /**
3
4
  * Returns parser to parse value as Date.
4
5
  */
@@ -1,5 +1,6 @@
1
- import type { Schema } from '../types.js';
2
- import { ValueParser } from '../ValueParser.js';
1
+ import { ValueParser } from '../ValueParser/ValueParser.js';
2
+ import { Schema } from '../types.js';
3
+
3
4
  /**
4
5
  * Creates new Json parser according to passed schema.
5
6
  * @param schema - object schema.
@@ -1,4 +1,5 @@
1
- import type { ValueParserGenerator } from '../createValueParserGenerator.js';
1
+ import { ValueParserGenerator } from '../createValueParserGenerator.js';
2
+
2
3
  /**
3
4
  * Returns parser to parse value as number.
4
5
  */
@@ -1,5 +1,6 @@
1
- import type { RGB } from '../../colors/types.js';
2
- import type { ValueParserGenerator } from '../createValueParserGenerator.js';
1
+ import { RGB } from '../../colors/types.js';
2
+ import { ValueParserGenerator } from '../createValueParserGenerator.js';
3
+
3
4
  /**
4
5
  * Returns parser to parse value as RGB color.
5
6
  */
@@ -1,5 +1,6 @@
1
- import type { Schema } from '../types.js';
2
- import { ValueParser } from '../ValueParser.js';
1
+ import { ValueParser } from '../ValueParser/ValueParser.js';
2
+ import { Schema } from '../types.js';
3
+
3
4
  /**
4
5
  * Creates new search params parser according to passed schema.
5
6
  * @param schema - object schema.
@@ -1,4 +1,5 @@
1
- import type { ValueParserGenerator } from '../createValueParserGenerator.js';
1
+ import { ValueParserGenerator } from '../createValueParserGenerator.js';
2
+
2
3
  /**
3
4
  * Returns parser to parse value as string.
4
5
  */
@@ -1,5 +1,6 @@
1
- import type { CreateRequestIdFunc } from '../../types/request-id.js';
1
+ import { CreateRequestIdFn } from './types.js';
2
+
2
3
  /**
3
4
  * Creates function which generated request identifiers.
4
5
  */
5
- export declare function createRequestIdGenerator(): CreateRequestIdFunc;
6
+ export declare function createRequestIdGenerator(): CreateRequestIdFn;
@@ -6,4 +6,4 @@ export type RequestId = string;
6
6
  /**
7
7
  * Function which generates unique request identifiers.
8
8
  */
9
- export type CreateRequestIdFunc = () => RequestId;
9
+ export type CreateRequestIdFn = () => RequestId;
@@ -0,0 +1,42 @@
1
+ import { BackButtonState } from '../components/BackButton/types.js';
2
+ import { BiometryManagerState } from '../components/BiometryManager/types.js';
3
+ import { ClosingBehaviorState } from '../components/ClosingBehavior/types.js';
4
+ import { MainButtonState } from '../components/MainButton/types.js';
5
+ import { MiniAppState } from '../components/MiniApp/types.js';
6
+ import { SettingsButtonState } from '../components/SettingsButton/types.js';
7
+ import { ThemeParamsParsed } from '../components/ThemeParams/types.js';
8
+ import { ViewportState } from '../components/Viewport/types.js';
9
+
10
+ /**
11
+ * Describes storage keys and according values.
12
+ */
13
+ export interface StorageParams {
14
+ backButton: BackButtonState;
15
+ biometryManager: BiometryManagerState;
16
+ closingBehavior: ClosingBehaviorState;
17
+ launchParams: string;
18
+ mainButton: MainButtonState;
19
+ miniApp: MiniAppState;
20
+ settingsButton: SettingsButtonState;
21
+ themeParams: ThemeParamsParsed;
22
+ viewport: ViewportState;
23
+ }
24
+ /**
25
+ * Key which could be used to store data in the storage.
26
+ */
27
+ export type StorageKey = keyof StorageParams;
28
+ /**
29
+ * Type specific to the specified storage key.
30
+ */
31
+ export type StorageValue<K extends StorageKey> = StorageParams[K];
32
+ /**
33
+ * Saves value in the storage.
34
+ * @param key - storage key.
35
+ * @param value - storage value.
36
+ */
37
+ export declare function setStorageValue<K extends StorageKey>(key: K, value: StorageValue<K>): void;
38
+ /**
39
+ * Extracts value from the storage.
40
+ * @param key - storage key.
41
+ */
42
+ export declare function getStorageValue<K extends StorageKey>(key: K): StorageValue<K> | undefined;
@@ -0,0 +1,12 @@
1
+ import { MiniAppsMethodName } from '../bridge/methods/types/methods.js';
2
+ import { SupportsFn } from './types.js';
3
+ import { Version } from '../version/types.js';
4
+
5
+ export type SupportsSchema<Method extends string> = Record<Method, MiniAppsMethodName>;
6
+ /**
7
+ * Returns function, which accepts predefined method name and checks if it is supported
8
+ * via passed schema and version.
9
+ * @param schema - object which contains methods names and TWA method as a dependency.
10
+ * @param version - platform version.
11
+ */
12
+ export declare function createSupportsFn<Method extends string>(version: Version, schema: SupportsSchema<Method>): SupportsFn<Method>;
@@ -1,6 +1,7 @@
1
- import type { SupportsFunc } from './types.js';
2
- import type { MiniAppsMethodVersionedParams, MiniAppsMethodWithVersionedParams } from '../bridge/methods/methods.js';
3
- import type { Version } from '../version/types.js';
1
+ import { MiniAppsMethodVersionedParams, MiniAppsMethodWithVersionedParams } from '../bridge/methods/types/methods.js';
2
+ import { SupportsFn } from './types.js';
3
+ import { Version } from '../version/types.js';
4
+
4
5
  type HasCheckSupportMethodTuple = {
5
6
  [M in MiniAppsMethodWithVersionedParams]: [M, MiniAppsMethodVersionedParams<M>];
6
7
  }[MiniAppsMethodWithVersionedParams];
@@ -11,5 +12,5 @@ type HasCheckSupportMethodTuple = {
11
12
  * as a dependency.
12
13
  * @param version - platform version.
13
14
  */
14
- export declare function createSupportsParamFunc<P extends string>(version: Version, schema: Record<P, HasCheckSupportMethodTuple>): SupportsFunc<P>;
15
+ export declare function createSupportsParamFn<Method extends string>(version: Version, schema: Record<Method, HasCheckSupportMethodTuple>): SupportsFn<Method>;
15
16
  export {};
@@ -1,5 +1,6 @@
1
- import type { MiniAppsMethodName, MiniAppsMethodVersionedParams, MiniAppsMethodWithVersionedParams } from '../bridge/methods/methods.js';
2
- import type { Version } from '../version/types.js';
1
+ import { MiniAppsMethodName, MiniAppsMethodVersionedParams, MiniAppsMethodWithVersionedParams } from '../bridge/methods/types/methods.js';
2
+ import { Version } from '../version/types.js';
3
+
3
4
  /**
4
5
  * Returns true in case, passed parameter in specified method is supported.
5
6
  * @param method - method name
@@ -1,4 +1,4 @@
1
1
  /**
2
2
  * Function which returns true in case, specified method is supported.
3
3
  */
4
- export type SupportsFunc<M extends string> = (method: M) => boolean;
4
+ export type SupportsFn<M extends string> = (method: M) => boolean;
@@ -0,0 +1,7 @@
1
+ import { SDKError } from '../errors/SDKError.js';
2
+
3
+ /**
4
+ * Creates new timeout error.
5
+ * @param timeout - timeout in ms.
6
+ */
7
+ export declare function createTimeoutError(timeout: number): SDKError;
@@ -1,5 +1,5 @@
1
1
  /**
2
2
  * Awaits for specified amount of time.
3
- * @param duration - duration to await.
3
+ * @param duration - duration in ms to await.
4
4
  */
5
5
  export declare function sleep(duration: number): Promise<void>;
@@ -1,6 +1,5 @@
1
1
  /**
2
- * Accepts specified function and instantly executes. It waits for timeout milliseconds for
3
- * it to complete and throws an error in case, deadline was reached.
2
+ * Runs passed function or promise with specified deadline presented via timeout argument.
4
3
  * @param funcOrPromise - function to execute or pending promise.
5
4
  * @param timeout - completion timeout.
6
5
  */
@@ -0,0 +1,6 @@
1
+ export * from './logical.js';
2
+ export * from './methods.js';
3
+ export * from './misc.js';
4
+ export * from './platform.js';
5
+ export * from './unions.js';
6
+ export * from './utils.js';
@@ -1,4 +1,5 @@
1
- import type { PostEvent } from '../bridge/methods/postEvent.js';
1
+ import { PostEvent } from '../bridge/methods/postEvent.js';
2
+
2
3
  export interface ExecuteWithTimeout {
3
4
  /**
4
5
  * Timeout to execute method.
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Any function.
3
+ */
4
+ export interface AnyFn {
5
+ (...args: any): any;
6
+ }
7
+ /**
8
+ * Function which performs some cleanup.
9
+ */
10
+ export interface CleanupFn {
11
+ (): void;
12
+ }
@@ -2,7 +2,23 @@
2
2
  * Returns true in case, T is never.
3
3
  */
4
4
  export type IsNever<T> = [T] extends [never] ? true : false;
5
+ /**
6
+ * Returns true in case, T is undefined.
7
+ */
8
+ export type IsUndefined<T> = [T] extends [undefined] ? true : false;
5
9
  /**
6
10
  * Returns object string keys.
7
11
  */
8
12
  export type StringKeys<T extends object> = Extract<keyof T, string>;
13
+ /**
14
+ * Marks specified properties as optional.
15
+ */
16
+ export type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
17
+ /**
18
+ * Marks specified properties as required.
19
+ */
20
+ export type RequiredBy<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;
21
+ /**
22
+ * Appends `null` and `undefined`.
23
+ */
24
+ export type Maybe<T> = T | null | undefined;
@@ -1,4 +1,5 @@
1
- import type { Version } from './types.js';
1
+ import { Version } from './types.js';
2
+
2
3
  /**
3
4
  * Returns 1 in case, version "a" is greater than "b".
4
5
  * Returns 0 in case, version "a" equal to "b".
package/dist/index.cjs CHANGED
@@ -1 +1,2 @@
1
- "use strict";var ot=Object.defineProperty;var at=(r,e,t)=>e in r?ot(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var o=(r,e,t)=>(at(r,typeof e!="symbol"?e+"":e,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class ve{constructor(e,t){this.prefix=e,this.enabled=t}print(e,...t){if(!this.enabled)return;const s=new Date,n=Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZone:"UTC"}).format(s);console[e](`[${n}]`,this.prefix,...t)}disable(){this.enabled=!1}error(...e){this.print("error",...e)}enable(){this.enabled=!0}log(...e){this.print("log",...e)}warn(...e){this.print("warn",...e)}}let Pe="https://web.telegram.org";const x=new ve("[SDK]",!1);function ct(r){if(r){x.enable();return}x.disable()}function ht(r){Pe=r}function ut(){return Pe}function ne(){try{return window.self!==window.top}catch{return!0}}function T(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function pt(r){return"external"in r&&T(r.external)&&"notify"in r.external&&typeof r.external.notify=="function"}function lt(r){return"TelegramWebviewProxy"in r&&T(r.TelegramWebviewProxy)&&"postEvent"in r.TelegramWebviewProxy&&typeof r.TelegramWebviewProxy.postEvent=="function"}function d(r,e,t){let s={},n;e===void 0&&t===void 0?s={}:e!==void 0&&t!==void 0?(s=t,n=e):e!==void 0&&("targetOrigin"in e?s=e:n=e);const{targetOrigin:i=ut()}=s;if(x.log(`Calling method "${r}"`,n),ne()){window.parent.postMessage(JSON.stringify({eventType:r,eventData:n}),i);return}if(pt(window)){window.external.notify(JSON.stringify({eventType:r,eventData:n}));return}if(lt(window)){window.TelegramWebviewProxy.postEvent(r,JSON.stringify(n));return}throw new Error("Unable to determine current environment and possible way to send event.")}function Se(r,e){const t=r.split("."),s=e.split("."),n=Math.max(t.length,s.length);for(let i=0;i<n;i+=1){const a=parseInt(t[i]||"0",10),c=parseInt(s[i]||"0",10);if(a!==c)return a>c?1:-1}return 0}function S(r,e){return Se(r,e)<=0}function q(r,e,t){if(typeof t=="string"){if(r==="web_app_open_link"&&e==="try_instant_view")return S("6.4",t);if(r==="web_app_set_header_color"&&e==="color")return S("6.9",t)}switch(r){case"web_app_open_tg_link":case"web_app_open_invoice":case"web_app_setup_back_button":case"web_app_set_background_color":case"web_app_set_header_color":case"web_app_trigger_haptic_feedback":return S("6.1",e);case"web_app_open_popup":return S("6.2",e);case"web_app_close_scan_qr_popup":case"web_app_open_scan_qr_popup":case"web_app_read_text_from_clipboard":return S("6.4",e);case"web_app_switch_inline_query":return S("6.7",e);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return S("6.9",e);case"web_app_setup_settings_button":return S("6.10",e);default:return!0}}class z extends Error{constructor(e,t){super(`Method "${e}" is unsupported in the Mini Apps version ${t}.`),Object.setPrototypeOf(this,z.prototype)}}class J extends Error{constructor(e,t,s){super(`Parameter "${t}" in method "${e}" is unsupported in the Mini Apps version ${s}.`),Object.setPrototypeOf(this,J.prototype)}}function ke(r){return(e,t)=>{if(!q(e,r))throw new z(e,r);if(T(t)){let s;if(e==="web_app_open_link"&&"try_instant_view"in t?s="try_instant_view":e==="web_app_set_header_color"&&"color"in t&&(s="color"),s&&!q(e,s,r))throw new J(e,s,r)}return d(e,t)}}function xe(r){return({req_id:e})=>e===r}class W extends Error{constructor(t,{cause:s,type:n}={}){super(`Unable to parse value${n?` as ${n}`:""}`,{cause:s});o(this,"type");this.value=t,Object.setPrototypeOf(this,W.prototype),this.type=n}}class H extends Error{constructor(e,{cause:t,type:s}={}){super(`Unable to parse field "${e}"${s?` as ${s}`:""}`,{cause:t}),Object.setPrototypeOf(this,H.prototype)}}function qe(r,e){const t={};for(const s in r){const n=r[s];if(!n)continue;let i,a;if(typeof n=="function"||"parse"in n)i=s,a=typeof n=="function"?n:n.parse.bind(n);else{const{type:p}=n;i=n.from||s,a=typeof p=="function"?p:p.parse.bind(p)}let c;const u=e(i);try{c=a(u)}catch(p){throw p instanceof W?new H(i,{type:p.type,cause:p}):new H(i,{cause:p})}c!==void 0&&(t[s]=c)}return t}function I(){return new TypeError("Value has unexpected type")}function ie(r){let e=r;if(typeof e=="string"&&(e=JSON.parse(e)),typeof e!="object"||e===null||Array.isArray(e))throw I();return e}class Q{constructor(e,t,s){this.parser=e,this.isOptional=t,this.type=s}parse(e){if(!(this.isOptional&&e===void 0))try{return this.parser(e)}catch(t){throw new W(e,{type:this.type,cause:t})}}optional(){return this.isOptional=!0,this}}function f(r,e){return new Q(t=>{const s=ie(t);return qe(r,n=>s[n])},!1,e)}function L(r,e){return()=>new Q(r,!1,e)}const h=L(r=>{if(typeof r=="string"||typeof r=="number")return r.toString();throw I()},"string");function Ae(r){return f({eventType:h(),eventData:e=>e}).parse(r)}function dt(r,e){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:r,eventData:e}),source:window.parent}))}function ft(){const r=window;"TelegramGameProxy_receiveEvent"in r||[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(e=>{let t=r;e.forEach((s,n,i)=>{if(n===i.length-1){t[s]=dt;return}s in t||(t[s]={}),t=t[s]})})}function gt(r){ft(),window.addEventListener("message",e=>{if(e.source===window.parent)try{const{eventType:t,eventData:s}=Ae(e.data);r(t,s)}catch{}})}function wt(){return f({req_id:h(),data:r=>r===null?r:h().optional().parse(r)})}function _t(){return f({req_id:h(),result:r=>r,error:h().optional()})}function bt(){return f({slug:h(),status:h()})}function mt(){return f({status:h()})}function yt(){return f({button_id:r=>r==null?void 0:h().parse(r)})}function Et(){return f({data:h().optional()})}function Z(r){return/^#[\da-f]{6}$/i.test(r)}function Ve(r){return/^#[\da-f]{3}$/i.test(r)}function oe(r){const e=r.replace(/\s/g,"").toLowerCase();if(Z(e))return e;if(Ve(e)){let s="#";for(let n=0;n<3;n+=1)s+=e[1+n].repeat(2);return s}const t=e.match(/^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/)||e.match(/^rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),\d{1,3}\)$/);if(t===null)throw new Error(`Value "${r}" does not satisfy any of known RGB formats.`);return t.slice(1).reduce((s,n)=>{const i=parseInt(n,10).toString(16);return s+(i.length===1?"0":"")+i},"#")}const ae=L(r=>oe(h().parse(r)),"rgb");function Ct(){return f({theme_params:r=>{const e=ae().optional();return Object.entries(ie(r)).reduce((t,[s,n])=>(t[s]=e.parse(n),t),{})}})}const C=L(r=>{if(typeof r=="boolean")return r;const e=String(r);if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw I()},"boolean"),k=L(r=>{if(typeof r=="number")return r;if(typeof r=="string"){const e=Number(r);if(!Number.isNaN(e))return e}throw I()},"number");function vt(){return f({height:k(),width:r=>r==null?window.innerWidth:k().parse(r),is_state_stable:C(),is_expanded:C()})}function Pt(){return f({status:h()})}class w{constructor(){o(this,"listeners",new Map);o(this,"subscribeListeners",[])}addListener(e,t,s){let n=this.listeners.get(e);return n||(n=[],this.listeners.set(e,n)),n.push([t,s]),()=>this.off(e,t)}emit(e,...t){this.subscribeListeners.forEach(n=>n(e,...t));const s=this.listeners.get(e);s&&s.forEach(([n,i],a)=>{n(...t),i&&s.splice(a,1)})}on(e,t){return this.addListener(e,t,!1)}once(e,t){return this.addListener(e,t,!0)}off(e,t){const s=this.listeners.get(e);if(s){for(let n=0;n<s.length;n+=1)if(t===s[n][0]){s.splice(n,1);return}}}subscribe(e){return this.subscribeListeners.push(e),()=>this.unsubscribe(e)}unsubscribe(e){for(let t=0;t<this.subscribeListeners.length;t+=1)if(this.subscribeListeners[t]===e){this.subscribeListeners.splice(t,1);return}}}function St(){const r=new w,e=(t,...s)=>{x.log("Emitting processed event:",t,...s),r.emit(t,...s)};return window.addEventListener("resize",()=>{e("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),gt((t,s)=>{x.log("Received raw event:",t,s);try{switch(t){case"viewport_changed":return e(t,vt().parse(s));case"theme_changed":return e(t,Ct().parse(s));case"popup_closed":return s==null?e(t,{}):e(t,yt().parse(s));case"set_custom_style":return e(t,h().parse(s));case"qr_text_received":return e(t,Et().parse(s));case"clipboard_text_received":return e(t,wt().parse(s));case"invoice_closed":return e(t,bt().parse(s));case"phone_requested":return e("phone_requested",mt().parse(s));case"custom_method_invoked":return e("custom_method_invoked",_t().parse(s));case"write_access_requested":return e("write_access_requested",Pt().parse(s));case"main_button_pressed":case"back_button_pressed":case"settings_button_pressed":case"scan_qr_popup_closed":case"reload_iframe":return e(t);default:return e(t,s)}}catch(n){x.error("Error processing event:",n)}}),r}const X="telegram-mini-apps-cached-emitter";function M(){const r=window;return r[X]===void 0&&(r[X]=St()),r[X]}function A(r,e){M().off(r,e)}function y(r,e){return M().on(r,e),()=>A(r,e)}class U extends Error{constructor(e){super(`Async call timeout exceeded. Timeout: ${e}`),Object.setPrototypeOf(this,U.prototype)}}function kt(r){return new Promise((e,t)=>{setTimeout(t,r,new U(r))})}function ce(r,e){return Promise.race([typeof r=="function"?r():r,kt(e)])}async function m(r,e,t){let s;const n=new Promise(b=>{s=b}),i=e?{...t,event:e,method:r}:r,{method:a,event:c,capture:u,postEvent:p=d,timeout:g}=i,_=(Array.isArray(c)?c:[c]).map(b=>y(b,l=>(!u||u(l))&&s(l)));try{return p(a,i.params),await(g?ce(n,g):n)}finally{_.forEach(b=>b())}}async function R(r,e,t,s={}){const{result:n,error:i}=await m("web_app_invoke_custom_method","custom_method_invoked",{...s,params:{method:r,params:e,req_id:t},capture:xe(t)});if(i)throw new Error(i);return n}function xt(r,e){return M().once(r,e),()=>A(r,e)}function Re(r){M().unsubscribe(r)}function qt(r){return M().subscribe(r),()=>Re(r)}function j(r,e){return r+(r.length&&e.length?` ${e}`:e)}function he(...r){return r.reduce((e,t)=>typeof t=="string"?j(e,t):T(t)?j(e,Object.entries(t).reduce((s,n)=>n[1]?j(s,n[0]):s,"")):Array.isArray(t)?j(e,he(...t)):e,"")}function At(...r){return r.reduce((e,t)=>(T(t)&&Object.entries(t).forEach(([s,n])=>{const i=he(e[s],n);i.length>0&&(e[s]=i)}),e),{})}function ue(r){const e=oe(r);return Math.sqrt([.299,.587,.114].reduce((s,n,i)=>{const a=parseInt(e.slice(1+i*2,1+(i+1)*2),16);return s+a*a*n},0))<120}class E{constructor(e,t){this.state=e,this.ee=t}internalSet(e,t){return this.state[e]===t||t===void 0?!1:(this.state[e]=t,this.ee.emit(`change:${e}`,t),!0)}clone(){return{...this.state}}set(e,t){let s=!1;if(typeof e=="string")s=this.internalSet(e,t);else for(const n in e)this.internalSet(n,e[n])&&(s=!0);s&&this.ee.emit("change")}get(e){return this.state[e]}}function P(r,e){return t=>q(e[t],r)}class Te{constructor(e,t,s=d){o(this,"ee",new w);o(this,"state");o(this,"on",(e,t)=>e==="click"?y("back_button_pressed",t):this.ee.on(e,t));o(this,"off",(e,t)=>e==="click"?A("back_button_pressed",t):this.ee.off(e,t));o(this,"supports");this.postEvent=s,this.state=new E({isVisible:e},this.ee),this.supports=P(t,{show:"web_app_setup_back_button",hide:"web_app_setup_back_button"})}set isVisible(e){this.state.set("isVisible",e),this.postEvent("web_app_setup_back_button",{is_visible:e})}get isVisible(){return this.state.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}class Ie{constructor(e,t=d){o(this,"ee",new w);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));this.postEvent=t,this.state=new E({isConfirmationNeeded:e},this.ee)}set isConfirmationNeeded(e){this.state.set("isConfirmationNeeded",e),this.postEvent("web_app_setup_closing_behavior",{need_confirmation:e})}get isConfirmationNeeded(){return this.state.get("isConfirmationNeeded")}disableConfirmation(){this.isConfirmationNeeded=!1}enableConfirmation(){this.isConfirmationNeeded=!0}}function Vt(r){if(Array.isArray(r))return r;if(typeof r=="string")try{const e=JSON.parse(r);if(Array.isArray(e))return e}catch{}throw I()}class Rt extends Q{constructor(t,s,n){super(Vt,s,n);o(this,"itemParser");this.itemParser=typeof t=="function"?t:t.parse.bind(t)}parse(t){const s=super.parse(t);return s===void 0?s:s.map(this.itemParser)}of(t){return this.itemParser=typeof t=="function"?t:t.parse.bind(t),this}}function Le(r){return new Rt(e=>e,!1,r)}function ye(r,e){return r.reduce((t,s)=>(t[s]=e,t),{})}class Be{constructor(e,t,s=d){o(this,"supports");this.createRequestId=t,this.postEvent=s,this.supports=P(e,{delete:"web_app_invoke_custom_method",get:"web_app_invoke_custom_method",getKeys:"web_app_invoke_custom_method",set:"web_app_invoke_custom_method"})}async delete(e,t={}){const s=Array.isArray(e)?e:[e];s.length!==0&&await R("deleteStorageValues",{keys:s},this.createRequestId(),{...t,postEvent:this.postEvent})}async getKeys(e={}){const t=await R("getStorageKeys",{},this.createRequestId(),{...e,postEvent:this.postEvent});return Le().of(h()).parse(t)}async get(e,t={}){const s=Array.isArray(e)?e:[e];if(s.length===0)return ye(s,"");const n=f(ye(s,h())),i=await R("getStorageValues",{keys:s},this.createRequestId(),{...t,postEvent:this.postEvent}).then(a=>n.parse(a));return Array.isArray(e)?i:i[e]}async set(e,t,s={}){await R("saveStorageValue",{key:e,value:t},this.createRequestId(),{...s,postEvent:this.postEvent})}}class $e{constructor(e,t=d){o(this,"supports");this.postEvent=t,this.supports=P(e,{impactOccurred:"web_app_trigger_haptic_feedback",notificationOccurred:"web_app_trigger_haptic_feedback",selectionChanged:"web_app_trigger_haptic_feedback"})}impactOccurred(e){this.postEvent("web_app_trigger_haptic_feedback",{type:"impact",impact_style:e})}notificationOccurred(e){this.postEvent("web_app_trigger_haptic_feedback",{type:"notification",notification_type:e})}selectionChanged(){this.postEvent("web_app_trigger_haptic_feedback",{type:"selection_change"})}}function De(){return f({id:k(),type:h(),title:h(),photoUrl:{type:h().optional(),from:"photo_url"},username:h().optional()},"Chat")}class Oe{constructor(e){this.initData=e}get authDate(){return this.initData.authDate}get canSendAfter(){return this.initData.canSendAfter}get canSendAfterDate(){const{canSendAfter:e}=this;return e===void 0?void 0:new Date(this.authDate.getTime()+e*1e3)}get chat(){return this.initData.chat}get chatType(){return this.initData.chatType}get chatInstance(){return this.initData.chatInstance}get hash(){return this.initData.hash}get queryId(){return this.initData.queryId}get receiver(){return this.initData.receiver}get startParam(){return this.initData.startParam}get user(){return this.initData.user}}function re(){return f({addedToAttachmentMenu:{type:C().optional(),from:"added_to_attachment_menu"},allowsWriteToPm:{type:C().optional(),from:"allows_write_to_pm"},firstName:{type:h(),from:"first_name"},id:k(),isBot:{type:C().optional(),from:"is_bot"},isPremium:{type:C().optional(),from:"is_premium"},languageCode:{type:h().optional(),from:"language_code"},lastName:{type:h().optional(),from:"last_name"},photoUrl:{type:h().optional(),from:"photo_url"},username:h().optional()},"User")}const pe=L(r=>r instanceof Date?r:new Date(k().parse(r)*1e3),"Date");function K(r,e){return new Q(t=>{if(typeof t!="string"&&!(t instanceof URLSearchParams))throw I();const s=typeof t=="string"?new URLSearchParams(t):t;return qe(r,n=>{const i=s.get(n);return i===null?void 0:i})},!1,e)}function le(){return K({authDate:{type:pe(),from:"auth_date"},canSendAfter:{type:k().optional(),from:"can_send_after"},chat:De().optional(),chatInstance:{type:h().optional(),from:"chat_instance"},chatType:{type:h().optional(),from:"chat_type"},hash:h(),queryId:{type:h().optional(),from:"query_id"},receiver:re().optional(),startParam:{type:h().optional(),from:"start_param"},user:re().optional()},"InitData")}function Tt(r){return le().parse(r)}function It(r){const{hostname:e,pathname:t}=new URL(r,window.location.href);if(e!=="t.me")throw new Error(`Incorrect hostname: ${e}`);const s=t.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/);if(s===null)throw new Error('Link pathname has incorrect format. Expected to receive "/invoice/{slug}" or "/${slug}"');return s[2]}class Ne{constructor(e,t=d){o(this,"ee",new w);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");this.postEvent=t,this.state=new E({isOpened:!1},this.ee),this.supports=P(e,{open:"web_app_open_invoice"})}set isOpened(e){this.state.set("isOpened",e)}get isOpened(){return this.state.get("isOpened")}async open(e,t){if(this.isOpened)throw new Error("Invoice is already opened");const s=t?It(e):e;this.isOpened=!0;try{return(await m("web_app_open_invoice","invoice_closed",{params:{slug:s},postEvent:this.postEvent,capture(i){return s===i.slug}})).status}finally{this.isOpened=!1}}}class He{constructor(e){o(this,"ee",new w);o(this,"state");o(this,"postEvent");o(this,"on",(e,t)=>e==="click"?y("main_button_pressed",t):this.ee.on(e,t));o(this,"off",(e,t)=>e==="click"?A("main_button_pressed",t):this.ee.off(e,t));const{postEvent:t=d,text:s,textColor:n,backgroundColor:i,isEnabled:a,isVisible:c,isLoaderVisible:u}=e;this.postEvent=t,this.state=new E({backgroundColor:i,isEnabled:a,isVisible:c,isLoaderVisible:u,text:s,textColor:n},this.ee)}commit(){this.text!==""&&this.postEvent("web_app_setup_main_button",{is_visible:this.isVisible,is_active:this.isEnabled,is_progress_visible:this.isLoaderVisible,text:this.text,color:this.backgroundColor,text_color:this.textColor})}set isEnabled(e){this.setParams({isEnabled:e})}get isEnabled(){return this.state.get("isEnabled")}set isLoaderVisible(e){this.setParams({isLoaderVisible:e})}get isLoaderVisible(){return this.state.get("isLoaderVisible")}set isVisible(e){this.setParams({isVisible:e})}get isVisible(){return this.state.get("isVisible")}get backgroundColor(){return this.state.get("backgroundColor")}get text(){return this.state.get("text")}get textColor(){return this.state.get("textColor")}disable(){return this.isEnabled=!1,this}enable(){return this.isEnabled=!0,this}hide(){return this.isVisible=!1,this}hideLoader(){return this.isLoaderVisible=!1,this}show(){return this.isVisible=!0,this}showLoader(){return this.isLoaderVisible=!0,this}setText(e){return this.setParams({text:e})}setTextColor(e){return this.setParams({textColor:e})}setBackgroundColor(e){return this.setParams({backgroundColor:e})}setParams(e){return this.state.set(e),this.commit(),this}}const Lt=K({contact:f({userId:{type:k(),from:"user_id"},phoneNumber:{type:h(),from:"phone_number"},firstName:{type:h(),from:"first_name"},lastName:{type:h().optional(),from:"last_name"}}),authDate:{type:pe(),from:"auth_date"},hash:h()});function We(r,e){return t=>{const[s,n]=e[t];return q(s,n,r)}}function Bt(r){return new Promise(e=>{setTimeout(e,r)})}class Me{constructor(e){o(this,"ee",new w);o(this,"state");o(this,"botInline");o(this,"postEvent");o(this,"createRequestId");o(this,"requestingPhoneAccess",!1);o(this,"requestingWriteAccess",!1);o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");o(this,"supportsParam");const{postEvent:t=d,headerColor:s,backgroundColor:n,version:i,botInline:a,createRequestId:c}=e,u=P(i,{requestPhoneAccess:"web_app_request_phone",requestWriteAccess:"web_app_request_write_access",switchInlineQuery:"web_app_switch_inline_query",setHeaderColor:"web_app_set_header_color",setBackgroundColor:"web_app_set_background_color"});this.postEvent=t,this.botInline=a,this.createRequestId=c,this.supports=p=>!(!u(p)||p==="switchInlineQuery"&&!a),this.state=new E({backgroundColor:n,headerColor:s},this.ee),this.supportsParam=We(i,{"setHeaderColor.color":["web_app_set_header_color","color"]})}async getRequestedContact(){return R("getRequestedContact",{},this.createRequestId(),{postEvent:this.postEvent,timeout:1e4}).then(e=>Lt.parse(e))}get backgroundColor(){return this.state.get("backgroundColor")}close(){this.postEvent("web_app_close")}get headerColor(){return this.state.get("headerColor")}get isBotInline(){return this.botInline}get isDark(){return ue(this.backgroundColor)}get isRequestingPhoneAccess(){return this.requestingPhoneAccess}get isRequestingWriteAccess(){return this.requestingWriteAccess}ready(){this.postEvent("web_app_ready")}async requestContact({timeout:e=5e3}={}){try{return await this.getRequestedContact()}catch{}if(await this.requestPhoneAccess()!=="sent")throw new Error("Access denied.");const s=Date.now()+e;let n=50;return ce(async()=>{for(;Date.now()<s;){try{return await this.getRequestedContact()}catch{}await Bt(n),n+=50}throw new Error("Unable to retrieve requested contact.")},e)}requestPhoneAccess(e={}){if(this.requestingPhoneAccess)throw new Error("Phone access is already being requested.");return this.requestingPhoneAccess=!0,m("web_app_request_phone","phone_requested",{...e,postEvent:this.postEvent}).then(t=>t.status).finally(()=>{this.requestingPhoneAccess=!1})}requestWriteAccess(e={}){if(this.requestingWriteAccess)throw new Error("Write access is already being requested.");return this.requestingWriteAccess=!0,m("web_app_request_write_access","write_access_requested",{...e,postEvent:this.postEvent}).then(t=>t.status).finally(()=>{this.requestingWriteAccess=!1})}sendData(e){const{size:t}=new Blob([e]);if(t===0||t>4096)throw new Error(`Passed data has incorrect size: ${t}`);this.postEvent("web_app_data_send",{data:e})}setHeaderColor(e){this.postEvent("web_app_set_header_color",Z(e)?{color:e}:{color_key:e}),this.state.set("headerColor",e)}setBackgroundColor(e){this.postEvent("web_app_set_background_color",{color:e}),this.state.set("backgroundColor",e)}switchInlineQuery(e,t=[]){if(!this.supports("switchInlineQuery")&&!this.isBotInline)throw new Error("Method is unsupported because Mini App should be launched in inline mode.");this.postEvent("web_app_switch_inline_query",{query:e,chat_types:t})}}function $t(r){const e=r.message.trim(),t=(r.title||"").trim(),s=r.buttons||[];let n;if(t.length>64)throw new Error(`Title has incorrect size: ${t.length}`);if(e.length===0||e.length>256)throw new Error(`Message has incorrect size: ${e.length}`);if(s.length>3)throw new Error(`Buttons have incorrect size: ${s.length}`);return s.length===0?n=[{type:"close",id:""}]:n=s.map(i=>{const{id:a=""}=i;if(a.length>64)throw new Error(`Button ID has incorrect size: ${a}`);if(i.type===void 0||i.type==="default"||i.type==="destructive"){const c=i.text.trim();if(c.length===0||c.length>64){const u=i.type||"default";throw new Error(`Button text with type "${u}" has incorrect size: ${i.text.length}`)}return{...i,text:c,id:a}}return{...i,id:a}}),{title:t,message:e,buttons:n}}class Ue{constructor(e,t=d){o(this,"ee",new w);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");this.postEvent=t,this.state=new E({isOpened:!1},this.ee),this.supports=P(e,{open:"web_app_open_popup"})}set isOpened(e){this.state.set("isOpened",e)}get isOpened(){return this.state.get("isOpened")}open(e){if(this.isOpened)throw new Error("Popup is already opened.");return this.isOpened=!0,m("web_app_open_popup","popup_closed",{postEvent:this.postEvent,params:$t(e)}).then(({button_id:t=null})=>t).finally(()=>{this.isOpened=!1})}}class Ge{constructor(e,t=d){o(this,"ee",new w);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");this.postEvent=t,this.state=new E({isOpened:!1},this.ee),this.supports=P(e,{close:"web_app_close_scan_qr_popup",open:"web_app_open_scan_qr_popup"})}close(){this.postEvent("web_app_close_scan_qr_popup"),this.isOpened=!1}set isOpened(e){this.state.set("isOpened",e)}get isOpened(){return this.state.get("isOpened")}async open(e){if(this.isOpened)throw new Error("QR scanner is already opened.");this.isOpened=!0;try{const t=await m("web_app_open_scan_qr_popup",["qr_text_received","scan_qr_popup_closed"],{postEvent:this.postEvent,params:{text:e}});return typeof t=="object"&&typeof t.data=="string"?t.data:null}finally{this.isOpened=!1}}}class je{constructor(e,t,s=d){o(this,"ee",new w);o(this,"state");o(this,"on",(e,t)=>e==="click"?y("settings_button_pressed",t):this.ee.on(e,t));o(this,"off",(e,t)=>e==="click"?A("settings_button_pressed",t):this.ee.off(e,t));o(this,"supports");this.postEvent=s,this.state=new E({isVisible:e},this.ee),this.supports=P(t,{show:"web_app_setup_settings_button",hide:"web_app_setup_settings_button"})}set isVisible(e){this.state.set("isVisible",e),this.postEvent("web_app_setup_settings_button",{is_visible:e})}get isVisible(){return this.state.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}function Dt(r){return r.replace(/(^|_)bg/,(e,t)=>`${t}background`).replace(/_([a-z])/g,(e,t)=>t.toUpperCase())}function Ot(r){return r.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`).replace(/(^|_)background/,(e,t)=>`${t}bg`)}const de=L(r=>{const e=ae().optional();return Object.entries(ie(r)).reduce((t,[s,n])=>(t[Dt(s)]=e.parse(n),t),{})},"ThemeParams");function fe(r){return de().parse(r)}function Nt(r){return m("web_app_request_theme","theme_changed",r).then(fe)}function Fe(r){return JSON.stringify(Object.entries(r).reduce((e,[t,s])=>(s&&(e[Ot(t)]=s),e),{}))}class ze{constructor(e){o(this,"ee",new w);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));this.state=new E(e,this.ee)}get accentTextColor(){return this.get("accentTextColor")}get backgroundColor(){return this.get("backgroundColor")}get buttonColor(){return this.get("buttonColor")}get buttonTextColor(){return this.get("buttonTextColor")}get destructiveTextColor(){return this.get("destructiveTextColor")}get(e){return this.state.get(e)}getState(){return this.state.clone()}get headerBackgroundColor(){return this.get("headerBackgroundColor")}get hintColor(){return this.get("hintColor")}get isDark(){return!this.backgroundColor||ue(this.backgroundColor)}get linkColor(){return this.get("linkColor")}get secondaryBackgroundColor(){return this.get("secondaryBackgroundColor")}get sectionBackgroundColor(){return this.get("sectionBackgroundColor")}get sectionHeaderTextColor(){return this.get("sectionHeaderTextColor")}listen(){return y("theme_changed",e=>{this.state.set(fe(e.theme_params))})}get subtitleTextColor(){return this.get("subtitleTextColor")}get textColor(){return this.get("textColor")}}class Je{constructor(e,t,s=d){o(this,"supports");o(this,"supportsParam");this.version=e,this.createRequestId=t,this.postEvent=s,this.supports=P(e,{readTextFromClipboard:"web_app_read_text_from_clipboard"}),this.supportsParam=We(e,{"openLink.tryInstantView":["web_app_open_link","try_instant_view"]})}openLink(e,t){const s=new URL(e,window.location.href).toString();if(!q("web_app_open_link",this.version)){window.open(s,"_blank");return}this.postEvent("web_app_open_link",{url:s,...typeof t=="boolean"?{try_instant_view:t}:{}})}openTelegramLink(e){const{hostname:t,pathname:s,search:n}=new URL(e,window.location.href);if(t!=="t.me")throw new Error(`URL has not allowed hostname: ${t}. Only "t.me" is allowed`);if(!q("web_app_open_tg_link",this.version)){window.location.href=e;return}this.postEvent("web_app_open_tg_link",{path_full:s+n})}async readTextFromClipboard(){const e=this.createRequestId(),{data:t=null}=await m("web_app_read_text_from_clipboard","clipboard_text_received",{postEvent:this.postEvent,params:{req_id:e},capture:xe(e)});return t}}function Qe(r){return["macos","tdesktop","unigram","web","weba"].includes(r)}async function ge(r){const e=await m("web_app_request_viewport","viewport_changed",r);return{height:e.height,width:e.width,isExpanded:e.is_expanded,isStateStable:e.is_state_stable}}function D(r){return r<0?0:r}class Ze{constructor(e){o(this,"ee",new w);o(this,"state");o(this,"postEvent");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));const{height:t,isExpanded:s,width:n,stableHeight:i,postEvent:a=d}=e;this.postEvent=a,this.state=new E({height:D(t),isExpanded:s,stableHeight:D(i),width:D(n)},this.ee)}sync(e){return ge(e).then(({height:t,isExpanded:s,width:n,isStateStable:i})=>{this.state.set({height:t,width:n,isExpanded:s,stableHeight:i?t:this.state.get("stableHeight")})})}get height(){return this.state.get("height")}get stableHeight(){return this.state.get("stableHeight")}listen(){return y("viewport_changed",e=>{const{height:t,width:s,is_expanded:n,is_state_stable:i}=e,a={height:D(t),isExpanded:n,width:D(s)};i&&(a.stableHeight=a.height),this.state.set(a)})}get isExpanded(){return this.state.get("isExpanded")}get width(){return this.state.get("width")}expand(){this.postEvent("web_app_expand"),this.state.set("isExpanded",!0)}get isStable(){return this.stableHeight===this.height}}function v(r,e){document.documentElement.style.setProperty(r,e)}function Ke(r,e){const t=()=>{v("--tg-background-color",r.backgroundColor)},s=()=>{const{backgroundColor:n,secondaryBackgroundColor:i}=e;if(Z(r.headerColor)){v("--tg-header-color",r.headerColor);return}if(r.headerColor==="bg_color"&&n){v("--tg-header-color",n);return}r.headerColor==="secondary_bg_color"&&i&&v("--tg-header-color",i)};e.on("change",s),r.on("change:backgroundColor",t),r.on("change:headerColor",s),t(),s()}function Ye(r){const e=()=>{const t=r.getState();Object.entries(t).forEach(([s,n])=>{if(n){const i=s.replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`);v(`--tg-theme-${i}`,n)}})};r.on("change",e),e()}function se(r){const e=()=>v("--tg-viewport-height",`${r.height}px`),t=()=>v("--tg-viewport-width",`${r.width}px`),s=()=>v("--tg-viewport-stable-height",`${r.stableHeight}px`);r.on("change:height",e),r.on("change:width",t),r.on("change:stableHeight",s),e(),t(),s()}function Ht(){const r=document.createElement("style");r.id="telegram-custom-styles",document.head.appendChild(r),y("set_custom_style",e=>{r.innerHTML=e})}function Xe(r){return`telegram-mini-apps-${r}`}function B(r,e){sessionStorage.setItem(Xe(r),JSON.stringify(e))}function $(r){const e=sessionStorage.getItem(Xe(r));return e?JSON.parse(e):null}function Wt(r,e,t){const{isVisible:s=!1}=r?$("back-button")||{}:{},n=new Te(s,e,t);return n.on("change",()=>{B("back-button",{isVisible:n.isVisible})}),n}function Mt(r,e){const{isConfirmationNeeded:t=!1}=r?$("closing-behavior")||{}:{},s=new Ie(t,e);return s.on("change",()=>B("closing-behavior",{isConfirmationNeeded:s.isConfirmationNeeded})),s}function Ut(r,e,t,s){const{backgroundColor:n=e,isEnabled:i=!1,isVisible:a=!1,isLoaderVisible:c=!1,textColor:u=t,text:p=""}=r?$("main-button")||{}:{},g=new He({backgroundColor:n,isEnabled:i,isLoaderVisible:c,isVisible:a,postEvent:s,text:p,textColor:u}),_=()=>B("main-button",{backgroundColor:g.backgroundColor,isEnabled:g.isEnabled,isLoaderVisible:g.isLoaderVisible,isVisible:g.isVisible,text:g.text,textColor:g.textColor});return g.on("change",_),g}function Gt(r,e,t,s,n,i){const{backgroundColor:a=e,headerColor:c="bg_color"}=r?$("mini-app")||{}:{},u=new Me({headerColor:c,backgroundColor:a,version:t,botInline:s,createRequestId:n,postEvent:i}),p=()=>B("mini-app",{backgroundColor:u.backgroundColor,headerColor:u.headerColor});return u.on("change",p),u}function jt(){let r=0;return()=>(r+=1,r.toString())}function Ft(r,e,t){const{isVisible:s=!1}=r?$("settings-button")||{}:{},n=new je(s,e,t);return n.on("change",()=>{B("settings-button",{isVisible:n.isVisible})}),n}function zt(r){const e=new ze(r);return e.listen(),e}function F(r){const e=new Ze(r);return e.on("change",()=>B("viewport",{height:e.height,isExpanded:e.isExpanded,stableHeight:e.stableHeight,width:e.width})),e.listen(),e}function Jt(r,e,t,s){const n=r?$("viewport"):null;if(n)return F({...n,postEvent:t});if(Qe(e))return F({height:window.innerHeight,isExpanded:!0,postEvent:t,stableHeight:window.innerHeight,width:window.innerWidth});if(s)return ge({postEvent:t,timeout:5e3}).then(({height:a,isStateStable:c,...u})=>F({...u,height:a,stableHeight:c?a:0}));const i=F({width:0,height:0,isExpanded:!1,postEvent:t,stableHeight:0});return i.sync({postEvent:t,timeout:5e3}).catch(a=>{console.error("Unable to actualize viewport state",a)}),i}function Qt(r){return typeof r=="object"?r:r?{themeParams:!0,viewport:!0,miniApp:!0}:{}}function Ee(r,e,t,s){const n=Qt(r);n.miniApp&&Ke(e,t),n.themeParams&&Ye(t),n.viewport&&(s instanceof Promise?s.then(se):se(s))}function et(){return K({botInline:{type:C().optional(),from:"tgWebAppBotInline"},initData:{type:le().optional(),from:"tgWebAppData"},initDataRaw:{type:h().optional(),from:"tgWebAppData"},platform:{type:h(),from:"tgWebAppPlatform"},showSettings:{type:C().optional(),from:"tgWebAppShowSettings"},startParam:{type:h().optional(),from:"tgWebAppStartParam"},themeParams:{type:de(),from:"tgWebAppThemeParams"},version:{type:h(),from:"tgWebAppVersion"}},"LaunchParams")}function we(r){return et().parse(r)}function tt(r){return we(r.replace(/^[^?#]*[?#]/,"").replace(/[?#]/g,"&"))}function Zt(){return tt(window.location.href)}function rt(){return performance.getEntriesByType("navigation")[0]}function Kt(){const r=rt();if(!r)throw new Error("Unable to get first navigation entry.");return tt(r.name)}function st(r){const{initDataRaw:e,themeParams:t,platform:s,version:n,showSettings:i,startParam:a,botInline:c}=r,u=new URLSearchParams;return e&&u.set("tgWebAppData",e),u.set("tgWebAppPlatform",s),u.set("tgWebAppThemeParams",Fe(t)),u.set("tgWebAppVersion",n),a&&u.set("tgWebAppStartParam",a),typeof i=="boolean"&&u.set("tgWebAppShowSettings",i?"1":"0"),typeof c=="boolean"&&u.set("tgWebAppBotInline",c?"1":"0"),u.toString()}const nt="telegram-mini-apps-launch-params";function Yt(){return we(sessionStorage.getItem(nt)||"")}function Xt(r){sessionStorage.setItem(nt,st(r))}function Y(){const r=[];for(const e of[Zt,Kt,Yt])try{const t=e();return Xt(t),t}catch(t){r.push(t)}throw x.error("Unable to extract launch parameters. Received errors:",r),new Error("Unable to retrieve launch parameters from any known source.")}function _e(){var r;return((r=rt())==null?void 0:r.type)==="reload"}function er(r={}){const{async:e=!1,complete:t=e,cssVars:s=!1,acceptCustomStyles:n=!1}=r;try{const{initData:i,initDataRaw:a,version:c,platform:u,themeParams:p,botInline:g=!1}=Y(),_=_e(),b=jt(),l=ke(c);ne()&&(n&&Ht(),l("iframe_ready",{reload_supported:!0}),y("reload_iframe",()=>{l("iframe_will_reload"),window.location.reload()}));const V={backButton:Wt(_,c,l),closingBehavior:Mt(_,l),cloudStorage:new Be(c,b,l),createRequestId:b,hapticFeedback:new $e(c,l),invoice:new Ne(c,l),mainButton:Ut(_,p.buttonColor||"#000000",p.buttonTextColor||"#ffffff",l),miniApp:Gt(_,p.backgroundColor||"#ffffff",c,g,b,l),popup:new Ue(c,l),postEvent:l,qrScanner:new Ge(c,l),settingsButton:Ft(_,c,l),themeParams:zt(p),utils:new Je(c,b,l),...i?{initData:new Oe(i),initDataRaw:a}:{}},G=Jt(_,u,l,t);return G instanceof Promise||t?Promise.resolve(G).then(me=>(Ee(s,V.miniApp,V.themeParams,me),{...V,viewport:me})):(Ee(s,V.miniApp,V.themeParams,G),{...V,viewport:G})}catch(i){if(t)return Promise.reject(i);throw i}}function tr(){return{launchParams:Y(),isPageReload:_e()}}function rr(){try{return Y(),!0}catch{return!1}}function sr(r){const e=r.match(/#(.+)/);return e?e[1]:null}async function N(r){return r===0?!0:Promise.race([new Promise(e=>{window.addEventListener("popstate",function t(){window.removeEventListener("popstate",t),e(!0)}),window.history.go(r)}),new Promise(e=>{setTimeout(e,50,!1)})])}async function nr(){if(window.history.length<=1||(window.history.pushState(null,""),await N(1-window.history.length)))return;let e=await N(-1);for(;e;)e=await N(-1)}function O(r,e){return r.startsWith(e)?r:`${e}${r}`}class it{constructor(e,t,{debug:s=!1,loggerPrefix:n="Navigator"}){o(this,"logger");o(this,"entries");if(this.entriesCursor=t,e.length===0)throw new Error("Entries list should not be empty.");if(t>=e.length)throw new Error("Cursor should be less than entries count.");this.entries=e.map(({pathname:i="",search:a,hash:c})=>{if(!i.startsWith("/")&&i.length>0)throw new Error('Pathname should start with "/"');return{pathname:O(i,"/"),search:a?O(a,"?"):"",hash:c?O(c,"#"):""}}),this.logger=new ve(`[${n}]`,s)}formatEntry(e){let t;if(typeof e=="string")t=e;else{const{pathname:a="",search:c,hash:u}=e;t=a+(c?O(c,"?"):"")+(u?O(u,"#"):"")}const{pathname:s,search:n,hash:i}=new URL(t,`https://localhost${this.path}`);return{pathname:s,search:n,hash:i}}get entry(){return this.entries[this.entriesCursor]}back(){return this.go(-1)}get cursor(){return this.entriesCursor}get canGoBack(){return this.entriesCursor>0}get canGoForward(){return this.entriesCursor!==this.entries.length-1}forward(){return this.go(1)}go(e){this.logger.log(`called go(${e})`);const t=Math.min(this.entries.length-1,Math.max(this.entriesCursor+e,0));if(this.entriesCursor===t)return this.performGo({updated:!1,delta:e});const s=this.entry;this.entriesCursor=t;const n=this.entry;return this.logger.log("State changed",{before:s,after:n}),this.performGo({updated:!0,delta:e,before:s,after:n})}getEntries(){return this.entries.map(e=>({...e}))}get hash(){return this.entry.hash}push(e){this.entriesCursor!==this.entries.length-1&&this.entries.splice(this.entriesCursor+1);const t=this.formatEntry(e),s=this.entry;this.entriesCursor+=1,this.entries[this.entriesCursor]=t;const n=this.entry;return this.logger.log("State changed",{before:s,after:n}),this.performPush({before:s,after:n})}get path(){return`${this.pathname}${this.search}${this.hash}`}get pathname(){return this.entry.pathname}replace(e){const t=this.formatEntry(e);if(this.search===t.search&&this.pathname===t.pathname&&this.hash===t.hash)return this.performReplace({updated:!1,entry:t});const s=this.entry;this.entries[this.entriesCursor]=t;const n=this.entry;return this.logger.log("State changed",{before:s,after:n}),this.performReplace({updated:!0,before:s,after:n})}get search(){return this.entry.search}}const Ce=0,ee=1,te=2;class be extends it{constructor(t,s,n={}){super(t,s,{...n,loggerPrefix:"HashNavigator"});o(this,"ee",new w);o(this,"attached",!1);o(this,"onPopState",async({state:t})=>{if(this.logger.log('"popstate" event received. State:',t),t===null)return this.push(window.location.hash.slice(1));if(t===Ce){this.logger.log("Void reached. Moving history forward"),window.history.forward();return}if(t===ee)return this.back();if(t===te)return this.forward()});o(this,"back",()=>super.back());o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee))}static fromLocation(t){const{search:s,pathname:n,hash:i}=new URL(window.location.hash.slice(1),window.location.href);return new be([{search:s,pathname:n,hash:i}],0,t)}async performGo(t){t.updated&&(this.attached&&await this.syncHistory(),this.emitChanged(t.before,t.after))}async performPush({before:t,after:s}){this.attached&&await this.syncHistory(),this.emitChanged(t,s)}async performReplace(t){t.updated&&(this.attached&&window.history.replaceState(null,"",`#${this.path}`),this.emitChanged(t.before,t.after))}async syncHistory(){window.removeEventListener("popstate",this.onPopState);const t=`#${this.path}`;await nr(),d("web_app_setup_back_button",{is_visible:this.canGoBack}),this.canGoBack&&this.canGoForward?(this.logger.log("Setting up history: [<-, *, ->]"),window.history.replaceState(ee,""),window.history.pushState(null,"",t),window.history.pushState(te,""),await N(-1)):this.canGoBack?(this.logger.log("Setting up history: [<-, *]"),window.history.replaceState(ee,""),window.history.pushState(null,"",t)):this.canGoForward?(this.logger.log("Setting up history: [*, ->]"),window.history.replaceState(null,t),window.history.pushState(te,""),await N(-1)):(this.logger.log("Setting up history: [~, *]"),window.history.replaceState(Ce,""),window.history.pushState(null,"",t)),window.addEventListener("popstate",this.onPopState)}emitChanged(t,s){this.ee.emit("change",{navigator:this,from:t,to:s})}async attach(){if(!this.attached)return this.logger.log("Attaching",this),this.attached=!0,y("back_button_pressed",this.back),this.syncHistory()}detach(){this.attached&&(this.logger.log("Detaching",this),this.attached=!1,window.removeEventListener("popstate",this.onPopState),A("back_button_pressed",this.back))}}function ir(r){return r instanceof U}exports.BackButton=Te;exports.ClosingBehavior=Ie;exports.CloudStorage=Be;exports.HapticFeedback=$e;exports.HashNavigator=be;exports.InitData=Oe;exports.Invoice=Ne;exports.MainButton=He;exports.MethodUnsupportedError=z;exports.MiniApp=Me;exports.Navigator=it;exports.ParameterUnsupportedError=J;exports.ParseError=W;exports.ParseSchemaFieldError=H;exports.Popup=Ue;exports.QRScanner=Ge;exports.SettingsButton=je;exports.ThemeParams=ze;exports.TimeoutError=U;exports.Utils=Je;exports.Viewport=Ze;exports.array=Le;exports.bindMiniAppCSSVars=Ke;exports.bindThemeCSSVars=Ye;exports.bindViewportCSSVars=se;exports.boolean=C;exports.chatParser=De;exports.classNames=he;exports.compareVersions=Se;exports.createPostEvent=ke;exports.date=pe;exports.getHash=sr;exports.init=er;exports.initDataParser=le;exports.invokeCustomMethod=R;exports.isColorDark=ue;exports.isIframe=ne;exports.isPageReload=_e;exports.isRGB=Z;exports.isRGBShort=Ve;exports.isRecord=T;exports.isStableViewportPlatform=Qe;exports.isTMA=rr;exports.isTimeoutError=ir;exports.json=f;exports.launchParamsParser=et;exports.mergeClassNames=At;exports.number=k;exports.off=A;exports.on=y;exports.once=xt;exports.parseInitData=Tt;exports.parseLaunchParams=we;exports.parseMessage=Ae;exports.parseThemeParams=fe;exports.postEvent=d;exports.request=m;exports.requestThemeParams=Nt;exports.requestViewport=ge;exports.retrieveLaunchData=tr;exports.retrieveLaunchParams=Y;exports.rgb=ae;exports.searchParams=K;exports.serializeLaunchParams=st;exports.serializeThemeParams=Fe;exports.setCSSVar=v;exports.setDebug=ct;exports.setTargetOrigin=ht;exports.string=h;exports.subscribe=qt;exports.supports=q;exports.themeParamsParser=de;exports.toRGB=oe;exports.unsubscribe=Re;exports.userParser=re;exports.withTimeout=ce;
1
+ "use strict";var Ee=Object.defineProperty;var ve=(e,t,s)=>t in e?Ee(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var c=(e,t,s)=>(ve(e,typeof t!="symbol"?t+"":t,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function St(e,t){let s;const n=()=>{s!==void 0&&t&&t(s),s=void 0};return[()=>s===void 0?s=e(n):s,n]}function X(e){const t=H(),{count:s}=t;t.unsubscribe(e),s&&!t.count&&Ve()}function Rt(e){return H().subscribe(e),()=>X(e)}class Se{constructor(t,s={}){this.scope=t,this.options=s}print(t,...s){const n=new Date,r=Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZone:"UTC"}).format(n),{textColor:i,bgColor:o}=this.options,a="font-weight: bold;padding: 0 5px;border-radius:5px";console[t](`%c${r}%c / %c${this.scope}`,`${a};background-color: lightblue;color:black`,"",`${a};${i?`color:${i};`:""}${o?`background-color:${o}`:""}`,...s)}error(...t){this.print("error",...t)}log(...t){this.print("log",...t)}}const O=new Se("SDK",{bgColor:"forestgreen",textColor:"white"});let Q=!1;const mt=({event:e,args:[t]})=>{O.log("Event received:",t===void 0?{name:e}:{name:e,data:t})};function Re(e){Q!==e&&(Q=e,e?Rt(mt):X(mt))}function Pe(...e){Q&&O.log(...e)}class q{constructor(){c(this,"listeners",new Map);c(this,"listenersCount",0);c(this,"subscribeListeners",[])}clear(){this.listeners.clear(),this.subscribeListeners=[]}get count(){return this.listenersCount+this.subscribeListeners.length}emit(t,...s){this.subscribeListeners.forEach(r=>r({event:t,args:s})),(this.listeners.get(t)||[]).forEach(([r,i])=>{r(...s),i&&this.off(t,r)})}on(t,s,n){let r=this.listeners.get(t);return r||this.listeners.set(t,r=[]),r.push([s,n]),this.listenersCount+=1,()=>this.off(t,s)}off(t,s){const n=this.listeners.get(t)||[];for(let r=0;r<n.length;r+=1)if(s===n[r][0]){n.splice(r,1),this.listenersCount-=1;return}}subscribe(t){return this.subscribeListeners.push(t),()=>this.unsubscribe(t)}unsubscribe(t){for(let s=0;s<this.subscribeListeners.length;s+=1)if(this.subscribeListeners[s]===t){this.subscribeListeners.splice(s,1);return}}}function Y(e,t,s){return window.addEventListener(e,t,s),()=>window.removeEventListener(e,t,s)}class k extends Error{constructor(t,s,n){super(s,{cause:n}),this.type=t,Object.setPrototypeOf(this,k.prototype)}}function d(e,t,s){return new k(e,t,s)}const Pt="ERR_METHOD_UNSUPPORTED",Tt="ERR_METHOD_PARAMETER_UNSUPPORTED",Ct="ERR_UNKNOWN_ENV",At="ERR_INVOKE_CUSTOM_METHOD_RESPONSE",It="ERR_TIMED_OUT",xt="ERR_UNEXPECTED_TYPE",Z="ERR_PARSE",Nt="ERR_NAVIGATION_LIST_EMPTY",qt="ERR_NAVIGATION_CURSOR_INVALID",Te="ERR_NAVIGATION_ITEM_INVALID",L="ERR_SSR_INIT",kt="ERR_SSR_POST_EVENT",Dt="ERR_INVALID_PATH_BASE";function P(){return d(xt,"Value has unexpected type")}class ${constructor(t,s,n){this.parser=t,this.isOptional=s,this.type=n}parse(t){if(!(this.isOptional&&t===void 0))try{return this.parser(t)}catch(s){throw d(Z,`Unable to parse value${this.type?` as ${this.type}`:""}`,s)}}optional(){return this.isOptional=!0,this}}function T(e,t){return()=>new $(e,!1,t)}const w=T(e=>{if(typeof e=="boolean")return e;const t=String(e);if(t==="1"||t==="true")return!0;if(t==="0"||t==="false")return!1;throw P()},"boolean");function Vt(e,t){const s={};for(const n in e){const r=e[n];if(!r)continue;let i,o;if(typeof r=="function"||"parse"in r)i=n,o=typeof r=="function"?r:r.parse.bind(r);else{const{type:a}=r;i=r.from||n,o=typeof a=="function"?a:a.parse.bind(a)}try{const a=o(t(i));a!==void 0&&(s[n]=a)}catch(a){throw d(Z,`Unable to parse field "${n}"`,a)}}return s}function tt(e){let t=e;if(typeof t=="string"&&(t=JSON.parse(t)),typeof t!="object"||t===null||Array.isArray(t))throw P();return t}function u(e,t){return new $(s=>{const n=tt(s);return Vt(e,r=>n[r])},!1,t)}const y=T(e=>{if(typeof e=="number")return e;if(typeof e=="string"){const t=Number(e);if(!Number.isNaN(t))return t}throw P()},"number");function U(e){return/^#[\da-f]{6}$/i.test(e)}function Mt(e){return/^#[\da-f]{3}$/i.test(e)}function et(e){const t=e.replace(/\s/g,"").toLowerCase();if(U(t))return t;if(Mt(t)){let n="#";for(let r=0;r<3;r+=1)n+=t[1+r].repeat(2);return n}const s=t.match(/^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/)||t.match(/^rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),\d{1,3}\)$/);if(!s)throw new Error(`Value "${e}" does not satisfy any of known RGB formats.`);return s.slice(1).reduce((n,r)=>{const i=parseInt(r,10).toString(16);return n+(i.length===1?"0":"")+i},"#")}const h=T(e=>{if(typeof e=="string"||typeof e=="number")return e.toString();throw P()},"string"),st=T(e=>et(h().parse(e)),"rgb");function Ce(e){return u({eventType:h(),eventData:t=>t}).parse(e)}function Ae(){["TelegramGameProxy_receiveEvent","TelegramGameProxy","Telegram"].forEach(e=>{delete window[e]})}function Ie(e,t){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:e,eventData:t}),source:window.parent}))}function xe(){[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(e=>{let t=window;e.forEach((s,n,r)=>{if(n===r.length-1){t[s]=Ie;return}s in t||(t[s]={}),t=t[s]})})}const Ne=u({button_id:e=>e==null?void 0:h().parse(e)}),qe={clipboard_text_received:u({req_id:h(),data:e=>e===null?e:h().optional().parse(e)}),custom_method_invoked:u({req_id:h(),result:e=>e,error:h().optional()}),invoice_closed:u({slug:h(),status:h()}),phone_requested:u({status:h()}),popup_closed:{parse:e=>Ne.parse(e??{})},qr_text_received:u({data:h().optional()}),theme_changed:u({theme_params:e=>{const t=st().optional();return Object.entries(tt(e)).reduce((s,[n,r])=>(s[n]=t.parse(r),s),{})}}),viewport_changed:u({height:y(),width:e=>e==null?window.innerWidth:y().parse(e),is_state_stable:w(),is_expanded:w()}),write_access_requested:u({status:h()})};function ke(){const e=new q;xe();let t=[Ae,Y("resize",()=>{e.emit("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),Y("message",s=>{if(s.source!==window.parent)return;let n;try{n=Ce(s.data)}catch{return}const{eventType:r,eventData:i}=n,o=qe[r];try{const a=o?o.parse(i):i;e.emit(...a?[r,a]:[r])}catch(a){O.error(`An error occurred processing the "${r}" event from the Telegram application. Please, file an issue here: https://github.com/Telegram-Mini-Apps/tma.js/issues/new/choose`,n,a)}}),()=>e.clear()];return[e,()=>{t.forEach(s=>s()),t=[]}]}const[De,Ve]=St(e=>{const[t,s]=ke(),n=t.off.bind(t);return t.off=(r,i)=>{const{count:o}=t;n(r,i),o&&!t.count&&e()},[t,s]},([,e])=>e());function H(){return De()[0]}function D(e,t){H().off(e,t)}function g(e,t,s){return H().on(e,t,s)}function V(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Bt(e,t){const s=e.split("."),n=t.split("."),r=Math.max(s.length,n.length);for(let i=0;i<r;i+=1){const o=parseInt(s[i]||"0",10),a=parseInt(n[i]||"0",10);if(o!==a)return o>a?1:-1}return 0}function b(e,t){return Bt(e,t)<=0}function E(e,t,s){if(typeof s=="string"){if(e==="web_app_open_link"&&t==="try_instant_view")return b("6.4",s);if(e==="web_app_set_header_color"&&t==="color")return b("6.9",s)}switch(e){case"web_app_open_tg_link":case"web_app_open_invoice":case"web_app_setup_back_button":case"web_app_set_background_color":case"web_app_set_header_color":case"web_app_trigger_haptic_feedback":return b("6.1",t);case"web_app_open_popup":return b("6.2",t);case"web_app_close_scan_qr_popup":case"web_app_open_scan_qr_popup":case"web_app_read_text_from_clipboard":return b("6.4",t);case"web_app_switch_inline_query":return b("6.7",t);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return b("6.9",t);case"web_app_setup_settings_button":return b("6.10",t);case"web_app_biometry_get_info":case"web_app_biometry_open_settings":case"web_app_biometry_request_access":case"web_app_biometry_request_auth":case"web_app_biometry_update_token":return b("7.2",t);default:return["iframe_ready","iframe_will_reload","web_app_close","web_app_data_send","web_app_expand","web_app_open_link","web_app_ready","web_app_request_theme","web_app_request_viewport","web_app_setup_main_button","web_app_setup_closing_behavior"].includes(e)}}function Me(e){return"external"in e&&V(e.external)&&"notify"in e.external&&typeof e.external.notify=="function"}function Ot(e){return"TelegramWebviewProxy"in e&&V(e.TelegramWebviewProxy)&&"postEvent"in e.TelegramWebviewProxy&&typeof e.TelegramWebviewProxy.postEvent=="function"}function Lt(){try{return window.self!==window.top}catch{return!0}}let $t="https://web.telegram.org";function Be(e){$t=e}function Ut(){return $t}function R(e,t,s){let n={},r;t===void 0&&s===void 0?n={}:t!==void 0&&s!==void 0?(n=s,r=t):t!==void 0&&("targetOrigin"in t?n=t:r=t);const{targetOrigin:i=Ut()}=n;if(Pe("Posting event:",r?{event:e,data:r}:{event:e}),Lt()){window.parent.postMessage(JSON.stringify({eventType:e,eventData:r}),i);return}if(Me(window)){window.external.notify(JSON.stringify({eventType:e,eventData:r}));return}if(Ot(window)){window.TelegramWebviewProxy.postEvent(e,JSON.stringify(r));return}throw d(Ct,"Unable to determine current environment and possible way to send event. You are probably trying to use Mini Apps method outside of Telegram application environment.")}function Ht(e){return(t,s)=>{if(!E(t,e))throw d(Pt,`Method "${t}" is unsupported in Mini Apps version ${e}`);if(V(s)){let n;if(t==="web_app_open_link"&&"try_instant_view"in s?n="try_instant_view":t==="web_app_set_header_color"&&"color"in s&&(n="color"),n&&!E(t,n,e))throw d(Tt,`Parameter "${n}" of "${t}" method is unsupported in Mini Apps version ${e}`)}return R(t,s)}}function nt(e){return({req_id:t})=>t===e}function Wt(e){return d(It,`Timeout reached: ${e}ms`)}function rt(e,t){return Promise.race([typeof e=="function"?e():e,new Promise((s,n)=>{setTimeout(()=>{n(Wt(t))},t)})])}async function l(e){let t;const s=new Promise(f=>{t=f}),{method:n,event:r,capture:i,postEvent:o=R,timeout:a}=e,p=(Array.isArray(r)?r:[r]).map(f=>g(f,wt=>(!i||i(wt))&&t(wt)));try{return o(n,e.params),await(a?rt(s,a):s)}finally{p.forEach(f=>f())}}async function S(e,t,s,n={}){const{result:r,error:i}=await l({...n,method:"web_app_invoke_custom_method",event:"custom_method_invoked",params:{method:e,params:t,req_id:s},capture:nt(s)});if(i)throw d(At,i);return r}function B(...e){return e.map(t=>{if(typeof t=="string")return t;if(V(t))return B(Object.entries(t).map(s=>s[1]&&s[0]));if(Array.isArray(t))return B(...t)}).filter(Boolean).join(" ")}function Oe(...e){return e.reduce((t,s)=>(V(s)&&Object.entries(s).forEach(([n,r])=>{const i=B(t[n],r);i.length&&(t[n]=i)}),t),{})}function it(e){const t=et(e);return Math.sqrt([.299,.587,.114].reduce((s,n,r)=>{const i=parseInt(t.slice(1+r*2,1+(r+1)*2),16);return s+i*i*n},0))<120}class Le{constructor(t){c(this,"ee",new q);c(this,"on",this.ee.on.bind(this.ee));c(this,"off",this.ee.off.bind(this.ee));this.state=t}clone(){return{...this.state}}set(t,s){Object.entries(typeof t=="string"?{[t]:s}:t).reduce((r,[i,o])=>this.state[i]===o||o===void 0?r:(this.state[i]=o,this.ee.emit(`change:${i}`,o),!0),!1)&&this.ee.emit("change",this.state)}get(t){return this.state[t]}}class ot{constructor(t){c(this,"state");c(this,"get");c(this,"set");c(this,"clone");this.state=new Le(t),this.set=this.state.set.bind(this.state),this.get=this.state.get.bind(this.state),this.clone=this.state.clone.bind(this.state)}}function Gt(e,t){return s=>E(t[s],e)}class at extends ot{constructor(s,n,r){super(s);c(this,"supports");this.supports=Gt(n,r)}}class jt extends at{constructor(s,n,r){super({isVisible:s},n,{show:"web_app_setup_back_button",hide:"web_app_setup_back_button"});c(this,"on",(s,n)=>s==="click"?g("back_button_pressed",n):this.state.on(s,n));c(this,"off",(s,n)=>s==="click"?D("back_button_pressed",n):this.state.off(s,n));this.postEvent=r}set isVisible(s){this.set("isVisible",s),this.postEvent("web_app_setup_back_button",{is_visible:s})}get isVisible(){return this.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}function v(){return typeof window>"u"}const ct=T(e=>e instanceof Date?e:new Date(y().parse(e)*1e3),"Date");function W(e,t){return new $(s=>{if(typeof s!="string"&&!(s instanceof URLSearchParams))throw P();const n=typeof s=="string"?new URLSearchParams(s):s;return Vt(e,r=>{const i=n.get(r);return i===null?void 0:i})},!1,t)}const $e=u({id:y(),type:h(),title:h(),photoUrl:{type:h().optional(),from:"photo_url"},username:h().optional()},"Chat").optional(),yt=u({addedToAttachmentMenu:{type:w().optional(),from:"added_to_attachment_menu"},allowsWriteToPm:{type:w().optional(),from:"allows_write_to_pm"},firstName:{type:h(),from:"first_name"},id:y(),isBot:{type:w().optional(),from:"is_bot"},isPremium:{type:w().optional(),from:"is_premium"},languageCode:{type:h().optional(),from:"language_code"},lastName:{type:h().optional(),from:"last_name"},photoUrl:{type:h().optional(),from:"photo_url"},username:h().optional()},"User").optional();function Ft(){return W({authDate:{type:ct(),from:"auth_date"},canSendAfter:{type:y().optional(),from:"can_send_after"},chat:$e,chatInstance:{type:h().optional(),from:"chat_instance"},chatType:{type:h().optional(),from:"chat_type"},hash:h(),queryId:{type:h().optional(),from:"query_id"},receiver:yt,startParam:{type:h().optional(),from:"start_param"},user:yt},"InitData")}function Ue(e){return e.replace(/_[a-z]/g,t=>t[1].toUpperCase())}function He(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}const zt=T(e=>{const t=st().optional();return Object.entries(tt(e)).reduce((s,[n,r])=>(s[Ue(n)]=t.parse(r),s),{})},"ThemeParams");function ht(e){return W({botInline:{type:w().optional(),from:"tgWebAppBotInline"},initData:{type:Ft().optional(),from:"tgWebAppData"},initDataRaw:{type:h().optional(),from:"tgWebAppData"},platform:{type:h(),from:"tgWebAppPlatform"},showSettings:{type:w().optional(),from:"tgWebAppShowSettings"},startParam:{type:h().optional(),from:"tgWebAppStartParam"},themeParams:{type:zt(),from:"tgWebAppThemeParams"},version:{type:h(),from:"tgWebAppVersion"}}).parse(e)}function Jt(e){return ht(e.replace(/^[^?#]*[?#]/,"").replace(/[?#]/g,"&"))}function We(){return Jt(window.location.href)}function Qt(){return performance.getEntriesByType("navigation")[0]}function Ge(){const e=Qt();if(!e)throw new Error("Unable to get first navigation entry.");return Jt(e.name)}function Yt(e){return`tma.js/${e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}`}function Kt(e,t){sessionStorage.setItem(Yt(e),JSON.stringify(t))}function Xt(e){const t=sessionStorage.getItem(Yt(e));try{return t?JSON.parse(t):void 0}catch{}}function je(){return ht(Xt("launchParams")||"")}function Zt(e){return JSON.stringify(Object.fromEntries(Object.entries(e).map(([t,s])=>[He(t),s])))}function te(e){const{initDataRaw:t,themeParams:s,platform:n,version:r,showSettings:i,startParam:o,botInline:a}=e,p=new URLSearchParams;return p.set("tgWebAppPlatform",n),p.set("tgWebAppThemeParams",Zt(s)),p.set("tgWebAppVersion",r),t&&p.set("tgWebAppData",t),o&&p.set("tgWebAppStartParam",o),typeof i=="boolean"&&p.set("tgWebAppShowSettings",i?"1":"0"),typeof a=="boolean"&&p.set("tgWebAppBotInline",a?"1":"0"),p.toString()}function Fe(e){Kt("launchParams",te(e))}function ee(){for(const e of[We,Ge,je])try{const t=e();return Fe(t),t}catch{}throw new Error("Unable to retrieve launch parameters from any known source.")}function pt(){const e=Qt();return!!(e&&e.type==="reload")}function ze(){let e=0;return()=>(e+=1).toString()}const[Je]=St(ze);function _(e,t){return({ssr:s}={})=>{let n;if(v()){if(!s)throw d(L,"ssr.options must be specified to initialize component on the server side");n=s}else n=ee();const r={...n,postEvent:"version"in n?Ht(n.version):()=>{throw d(kt,"postEvent function is forbidden to be called on the server side.")},createRequestId:Je()};if(v()||typeof e=="function")return typeof e=="function"?e(r):t(r);const i=t({...r,state:pt()?Xt(e):void 0}),o=a=>(a.on("change",p=>{Kt(e,p)}),a);return i instanceof Promise?i.then(o):o(i)}}const Qe=_("backButton",({postEvent:e,version:t,state:s={isVisible:!1}})=>new jt(s.isVisible,t,e));class M extends at{constructor(){super(...arguments);c(this,"on",this.state.on.bind(this.state));c(this,"off",this.state.off.bind(this.state))}}function se(e){const t=e.available?e:{available:!1,device_id:"",token_saved:!1,access_requested:!1,access_granted:!1,type:""};return{available:!0,type:t.type,deviceId:t.device_id,tokenSaved:t.token_saved,accessRequested:t.access_requested,accessGranted:t.access_granted}}class K extends M{constructor({postEvent:s,version:n,...r}){super(r,n,{auth:"web_app_biometry_request_auth",openSettings:"web_app_biometry_open_settings",requestAccess:"web_app_biometry_request_access",updateToken:"web_app_biometry_update_token"});c(this,"postEvent");c(this,"authPromise");c(this,"accessPromise");this.postEvent=s}get available(){return this.get("available")}get accessGranted(){return this.get("accessGranted")}get accessRequested(){return this.get("accessRequested")}async authenticate({reason:s,...n}){return this.authPromise||(this.authPromise=l({...n,method:"web_app_biometry_request_auth",event:"biometry_auth_requested",postEvent:this.postEvent,params:{reason:(s||"").trim()}}).then(({token:r})=>r).finally(()=>this.authPromise=void 0)),this.authPromise}get deviceId(){return this.get("deviceId")}openSettings(){this.postEvent("web_app_biometry_open_settings")}requestAccess({reason:s,...n}={}){return this.accessPromise||(this.accessPromise=l({...n,postEvent:this.postEvent,method:"web_app_biometry_request_access",event:"biometry_info_received",params:{reason:s||""}}).then(r=>{const i=se(r);return this.set(i),i.accessGranted}).finally(()=>this.accessPromise=void 0)),this.accessPromise}get biometryType(){return this.get("biometryType")}get tokenSaved(){return this.get("tokenSaved")}async updateToken({token:s,...n}={}){return["removed","updated"].includes((await l({...n,postEvent:this.postEvent,method:"web_app_biometry_update_token",event:"biometry_token_updated",params:{token:s||""}})).status)}}async function ne(e){return se(await l({...e||{},method:"web_app_biometry_get_info",event:"biometry_info_received"}))}const Ye=_("biometryManager",async({postEvent:e,version:t,state:s})=>{if(s)return new K({...s,version:t,postEvent:e});if(v())throw d(L,"BiometryManager cannot be instantiated on the server side without passing the ssr.state object.");return new K({...await ne({timeout:1e3}),version:t,postEvent:e})});class ut extends ot{constructor(){super(...arguments);c(this,"on",this.state.on.bind(this.state));c(this,"off",this.state.off.bind(this.state))}}class re extends ut{constructor(t,s){super({isConfirmationNeeded:t}),this.postEvent=s}set isConfirmationNeeded(t){this.set("isConfirmationNeeded",t),this.postEvent("web_app_setup_closing_behavior",{need_confirmation:t})}get isConfirmationNeeded(){return this.get("isConfirmationNeeded")}disableConfirmation(){this.isConfirmationNeeded=!1}enableConfirmation(){this.isConfirmationNeeded=!0}}const Ke=_("closingBehavior",({postEvent:e,state:t={isConfirmationNeeded:!1}})=>new re(t.isConfirmationNeeded,e));class lt{constructor(t,s){c(this,"supports");this.supports=Gt(t,s)}}function Xe(e){if(Array.isArray(e))return e;if(typeof e=="string")try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}throw P()}class Ze extends ${constructor(s,n,r){super(Xe,n,r);c(this,"itemParser");this.itemParser=typeof s=="function"?s:s.parse.bind(s)}parse(s){const n=super.parse(s);return n===void 0?n:n.map(this.itemParser)}of(s){return this.itemParser=typeof s=="function"?s:s.parse.bind(s),this}}function ie(e){return new Ze(t=>t,!1,e)}function Et(e,t){return Object.fromEntries(e.map(s=>[s,t]))}class oe extends lt{constructor(t,s,n){super(t,{delete:"web_app_invoke_custom_method",get:"web_app_invoke_custom_method",getKeys:"web_app_invoke_custom_method",set:"web_app_invoke_custom_method"}),this.createRequestId=s,this.postEvent=n}async delete(t,s={}){const n=Array.isArray(t)?t:[t];n.length&&await S("deleteStorageValues",{keys:n},this.createRequestId(),{...s,postEvent:this.postEvent})}async getKeys(t={}){return ie().of(h()).parse(await S("getStorageKeys",{},this.createRequestId(),{...t,postEvent:this.postEvent}))}async get(t,s={}){const n=Array.isArray(t)?t:[t];if(!n.length)return Et(n,"");const r=await S("getStorageValues",{keys:n},this.createRequestId(),{...s,postEvent:this.postEvent}),i=u(Et(n,h()),"CloudStorageData").parse(r);return Array.isArray(t)?i:i[t]}async set(t,s,n={}){await S("saveStorageValue",{key:t,value:s},this.createRequestId(),{...n,postEvent:this.postEvent})}}const ts=_(({createRequestId:e,postEvent:t,version:s})=>new oe(s,e,t));class ae extends lt{constructor(t,s){super(t,{impactOccurred:"web_app_trigger_haptic_feedback",notificationOccurred:"web_app_trigger_haptic_feedback",selectionChanged:"web_app_trigger_haptic_feedback"}),this.postEvent=s}impactOccurred(t){this.postEvent("web_app_trigger_haptic_feedback",{type:"impact",impact_style:t})}notificationOccurred(t){this.postEvent("web_app_trigger_haptic_feedback",{type:"notification",notification_type:t})}selectionChanged(){this.postEvent("web_app_trigger_haptic_feedback",{type:"selection_change"})}}const es=_(({version:e,postEvent:t})=>new ae(e,t));class ce{constructor(t){this.initData=t}get authDate(){return this.initData.authDate}get canSendAfter(){return this.initData.canSendAfter}get canSendAfterDate(){const{canSendAfter:t}=this;return t?new Date(this.authDate.getTime()+t*1e3):void 0}get chat(){return this.initData.chat}get chatType(){return this.initData.chatType}get chatInstance(){return this.initData.chatInstance}get hash(){return this.initData.hash}get queryId(){return this.initData.queryId}get receiver(){return this.initData.receiver}get startParam(){return this.initData.startParam}get user(){return this.initData.user}}const ss=_(({initData:e})=>e?new ce(e):void 0);function ns(e){return Ft().parse(e)}class he extends M{constructor(t,s,n){super({isOpened:t},s,{open:"web_app_open_invoice"}),this.postEvent=n}set isOpened(t){this.set("isOpened",t)}get isOpened(){return this.get("isOpened")}async open(t,s){if(this.isOpened)throw new Error("Invoice is already opened");let n;if(!s)n=t;else{const{hostname:r,pathname:i}=new URL(t,window.location.href);if(r!=="t.me")throw new Error(`Incorrect hostname: ${r}`);const o=i.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/);if(!o)throw new Error('Link pathname has incorrect format. Expected to receive "/invoice/{slug}" or "/${slug}"');[,,n]=o}this.isOpened=!0;try{return(await l({method:"web_app_open_invoice",event:"invoice_closed",params:{slug:n},postEvent:this.postEvent,capture(i){return n===i.slug}})).status}finally{this.isOpened=!1}}}const rs=_(({version:e,postEvent:t})=>new he(!1,e,t));class pe extends ot{constructor({postEvent:s,...n}){super(n);c(this,"postEvent");c(this,"on",(s,n)=>s==="click"?g("main_button_pressed",n):this.state.on(s,n));c(this,"off",(s,n)=>s==="click"?D("main_button_pressed",n):this.state.off(s,n));this.postEvent=s}commit(){this.text!==""&&this.postEvent("web_app_setup_main_button",{is_visible:this.isVisible,is_active:this.isEnabled,is_progress_visible:this.isLoaderVisible,text:this.text,color:this.backgroundColor,text_color:this.textColor})}set isEnabled(s){this.setParams({isEnabled:s})}get isEnabled(){return this.get("isEnabled")}set isLoaderVisible(s){this.setParams({isLoaderVisible:s})}get isLoaderVisible(){return this.get("isLoaderVisible")}set isVisible(s){this.setParams({isVisible:s})}get isVisible(){return this.get("isVisible")}get backgroundColor(){return this.get("backgroundColor")}get text(){return this.get("text")}get textColor(){return this.get("textColor")}disable(){return this.isEnabled=!1,this}enable(){return this.isEnabled=!0,this}hide(){return this.isVisible=!1,this}hideLoader(){return this.isLoaderVisible=!1,this}show(){return this.isVisible=!0,this}showLoader(){return this.isLoaderVisible=!0,this}setText(s){return this.setParams({text:s})}setTextColor(s){return this.setParams({textColor:s})}setBackgroundColor(s){return this.setParams({backgroundColor:s})}setParams(s){return this.set(s),this.commit(),this}}const is=_("mainButton",({postEvent:e,themeParams:t,state:s={isVisible:!1,isEnabled:!1,text:"",isLoaderVisible:!1,textColor:t.buttonTextColor||"#ffffff",backgroundColor:t.buttonColor||"#000000"}})=>new pe({...s,postEvent:e}));function os(){return W({contact:u({userId:{type:y(),from:"user_id"},phoneNumber:{type:h(),from:"phone_number"},firstName:{type:h(),from:"first_name"},lastName:{type:h().optional(),from:"last_name"}}),authDate:{type:ct(),from:"auth_date"},hash:h()},"RequestedContact")}function ue(e,t){return s=>{const[n,r]=t[s];return E(n,r,e)}}function as(e){return new Promise(t=>{setTimeout(t,e)})}class le extends M{constructor({postEvent:s,createRequestId:n,version:r,botInline:i,...o}){super(o,r,{requestPhoneAccess:"web_app_request_phone",requestWriteAccess:"web_app_request_write_access",switchInlineQuery:"web_app_switch_inline_query",setHeaderColor:"web_app_set_header_color",setBackgroundColor:"web_app_set_background_color"});c(this,"botInline");c(this,"postEvent");c(this,"createRequestId");c(this,"requestPhoneAccessPromise");c(this,"requestWriteAccessPromise");c(this,"supportsParam");this.createRequestId=n,this.postEvent=s,this.botInline=i;const a=this.supports.bind(this);this.supports=p=>a(p)?p!=="switchInlineQuery"||i:!1,this.supportsParam=ue(r,{"setHeaderColor.color":["web_app_set_header_color","color"]})}async getRequestedContact({timeout:s=1e4}={}){return os().parse(await S("getRequestedContact",{},this.createRequestId(),{postEvent:this.postEvent,timeout:s}))}get bgColor(){return this.get("bgColor")}close(){this.postEvent("web_app_close")}get headerColor(){return this.get("headerColor")}get isBotInline(){return this.botInline}get isDark(){return it(this.bgColor)}ready(){this.postEvent("web_app_ready")}async requestContact({timeout:s=5e3}={}){try{return await this.getRequestedContact()}catch{}if(await this.requestPhoneAccess()!=="sent")throw new Error("Access denied.");const r=Date.now()+s;let i=50;return rt(async()=>{for(;Date.now()<r;){try{return await this.getRequestedContact()}catch{}await as(i),i+=50}throw Wt(s)},s)}async requestPhoneAccess(s={}){return this.requestPhoneAccessPromise||(this.requestPhoneAccessPromise=l({...s,method:"web_app_request_phone",event:"phone_requested",postEvent:this.postEvent}).then(({status:n})=>n).finally(()=>this.requestPhoneAccessPromise=void 0)),this.requestPhoneAccessPromise}async requestWriteAccess(s={}){return this.requestWriteAccessPromise||(this.requestWriteAccessPromise=l({...s,method:"web_app_request_write_access",event:"write_access_requested",postEvent:this.postEvent}).then(({status:n})=>n).finally(()=>this.requestWriteAccessPromise=void 0)),this.requestWriteAccessPromise}sendData(s){const{size:n}=new Blob([s]);if(!n||n>4096)throw new Error(`Passed data has incorrect size: ${n}`);this.postEvent("web_app_data_send",{data:s})}setHeaderColor(s){this.postEvent("web_app_set_header_color",U(s)?{color:s}:{color_key:s}),this.set("headerColor",s)}setBgColor(s){this.postEvent("web_app_set_background_color",{color:s}),this.set("bgColor",s)}switchInlineQuery(s,n=[]){if(!this.supports("switchInlineQuery")&&!this.isBotInline)throw new Error("Method is unsupported because Mini App should be launched in inline mode.");this.postEvent("web_app_switch_inline_query",{query:s,chat_types:n})}}const cs=_("miniApp",({themeParams:e,botInline:t=!1,state:s={bgColor:e.bgColor||"#ffffff",headerColor:e.headerBgColor||"#000000"},...n})=>new le({...n,...s,botInline:t}));function hs(e){const t=e.message.trim(),s=(e.title||"").trim(),n=e.buttons||[];let r;if(s.length>64)throw new Error(`Title has incorrect size: ${s.length}`);if(!t.length||t.length>256)throw new Error(`Message has incorrect size: ${t.length}`);if(n.length>3)throw new Error(`Buttons have incorrect size: ${n.length}`);return n.length?r=n.map(i=>{const{id:o=""}=i;if(o.length>64)throw new Error(`Button ID has incorrect size: ${o}`);if(!i.type||i.type==="default"||i.type==="destructive"){const a=i.text.trim();if(!a.length||a.length>64){const p=i.type||"default";throw new Error(`Button text with type "${p}" has incorrect size: ${i.text.length}`)}return{...i,text:a,id:o}}return{...i,id:o}}):r=[{type:"close",id:""}],{title:s,message:t,buttons:r}}class de extends M{constructor(t,s,n){super({isOpened:t},s,{open:"web_app_open_popup"}),this.postEvent=n}set isOpened(t){this.set("isOpened",t)}get isOpened(){return this.get("isOpened")}async open(t){if(this.isOpened)throw new Error("Popup is already opened.");this.isOpened=!0;try{const{button_id:s=null}=await l({event:"popup_closed",method:"web_app_open_popup",postEvent:this.postEvent,params:hs(t)});return s}finally{this.isOpened=!1}}}const ps=_(({postEvent:e,version:t})=>new de(!1,t,e));class _e extends M{constructor(t,s,n){super({isOpened:t},s,{close:"web_app_close_scan_qr_popup",open:"web_app_open_scan_qr_popup"}),this.postEvent=n}close(){this.postEvent("web_app_close_scan_qr_popup"),this.isOpened=!1}set isOpened(t){this.set("isOpened",t)}get isOpened(){return this.get("isOpened")}async open(t){if(this.isOpened)throw new Error("QR scanner is already opened.");this.isOpened=!0;try{return(await l({method:"web_app_open_scan_qr_popup",event:["qr_text_received","scan_qr_popup_closed"],postEvent:this.postEvent,params:{text:t}})||{}).data||null}finally{this.isOpened=!1}}}const us=_(({version:e,postEvent:t})=>new _e(!1,e,t));class fe extends at{constructor(s,n,r){super({isVisible:s},n,{show:"web_app_setup_settings_button",hide:"web_app_setup_settings_button"});c(this,"on",(s,n)=>s==="click"?g("settings_button_pressed",n):this.state.on(s,n));c(this,"off",(s,n)=>s==="click"?D("settings_button_pressed",n):this.state.off(s,n));this.postEvent=r}set isVisible(s){this.set("isVisible",s),this.postEvent("web_app_setup_settings_button",{is_visible:s})}get isVisible(){return this.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}const ls=_("settingsButton",({version:e,postEvent:t,state:s={isVisible:!1}})=>new fe(s.isVisible,e,t));function dt(e){return zt().parse(e)}class ge extends ut{get accentTextColor(){return this.get("accentTextColor")}get bgColor(){return this.get("bgColor")}get buttonColor(){return this.get("buttonColor")}get buttonTextColor(){return this.get("buttonTextColor")}get destructiveTextColor(){return this.get("destructiveTextColor")}getState(){return this.clone()}get headerBgColor(){return this.get("headerBgColor")}get hintColor(){return this.get("hintColor")}get isDark(){return!this.bgColor||it(this.bgColor)}get linkColor(){return this.get("linkColor")}get secondaryBgColor(){return this.get("secondaryBgColor")}get sectionBgColor(){return this.get("sectionBgColor")}get sectionHeaderTextColor(){return this.get("sectionHeaderTextColor")}listen(){return g("theme_changed",t=>{this.set(dt(t.theme_params))})}get subtitleTextColor(){return this.get("subtitleTextColor")}get textColor(){return this.get("textColor")}}const ds=_("themeParams",({themeParams:e,state:t=e})=>{const s=new ge(t);return v()||s.listen(),s});function _s(e={}){return l({...e,method:"web_app_request_theme",event:"theme_changed"}).then(dt)}class be extends lt{constructor(s,n,r){super(s,{readTextFromClipboard:"web_app_read_text_from_clipboard"});c(this,"supportsParam");this.version=s,this.createRequestId=n,this.postEvent=r,this.supportsParam=ue(s,{"openLink.tryInstantView":["web_app_open_link","try_instant_view"]})}openLink(s,n){const r=new URL(s,window.location.href).toString();if(!E("web_app_open_link",this.version)){window.open(r,"_blank");return}this.postEvent("web_app_open_link",{url:r,...typeof n=="boolean"?{try_instant_view:n}:{}})}openTelegramLink(s){const{hostname:n,pathname:r,search:i}=new URL(s,window.location.href);if(n!=="t.me")throw new Error(`URL has not allowed hostname: ${n}. Only "t.me" is allowed`);if(!E("web_app_open_tg_link",this.version)){window.location.href=s;return}this.postEvent("web_app_open_tg_link",{path_full:r+i})}async readTextFromClipboard(){const s=this.createRequestId(),{data:n=null}=await l({method:"web_app_read_text_from_clipboard",event:"clipboard_text_received",postEvent:this.postEvent,params:{req_id:s},capture:nt(s)});return n}}const fs=_(({version:e,postEvent:t,createRequestId:s})=>new be(e,s,t));async function _t(e={}){const{is_expanded:t,is_state_stable:s,...n}=await l({...e,method:"web_app_request_viewport",event:"viewport_changed"});return{...n,isExpanded:t,isStateStable:s}}function C(e){return e<0?0:e}class ft extends ut{constructor({postEvent:s,stableHeight:n,height:r,width:i,isExpanded:o}){super({height:C(r),isExpanded:o,stableHeight:C(n),width:C(i)});c(this,"postEvent");this.postEvent=s}async sync(s){const{isStateStable:n,...r}=await _t(s);this.set({...r,stableHeight:n?r.height:this.get("stableHeight")})}get height(){return this.get("height")}get stableHeight(){return this.get("stableHeight")}listen(){return g("viewport_changed",s=>{const{height:n,width:r,is_expanded:i,is_state_stable:o}=s,a=C(n);this.set({height:a,isExpanded:i,width:C(r),...o?{stableHeight:a}:{}})})}get isExpanded(){return this.get("isExpanded")}get width(){return this.get("width")}expand(){this.postEvent("web_app_expand"),this.set("isExpanded",!0)}get isStable(){return this.stableHeight===this.height}}async function gs(e,t={}){const{height:s,width:n,isExpanded:r,isStateStable:i}=await _t({...t,postEvent:e});return new ft({postEvent:e,height:s,width:n,isExpanded:r,stableHeight:i?s:0})}function bs({state:e,platform:t,postEvent:s}){let n=!1,r=0,i=0,o=0;return e?(n=e.isExpanded,r=e.height,i=e.width,o=e.stableHeight):["macos","tdesktop","unigram","webk","weba","web"].includes(t)&&(n=!0,r=window.innerHeight,i=window.innerWidth,o=window.innerHeight),new ft({postEvent:s,height:r,width:i,stableHeight:o,isExpanded:n})}const ws=_("viewport",async e=>{if(v()&&!e.state)throw d(L,"Viewport cannot be instantiated on the server side without passing the ssr.state object.");let t=bs(e);return v()||(t.width===0&&await gs(e.postEvent,{timeout:1e3}).then(s=>t=s).catch(s=>O.error("Unable to sync viewport state",s)),t.listen()),t});function m(e,t){document.documentElement.style.setProperty(e,t)}function ms(e,t,s){s||(s=a=>`--tg-${a}-color`);const n=s("header"),r=s("bg"),i=()=>{const{headerColor:a}=e;if(U(a))m(n,a);else{const{bgColor:p,secondaryBgColor:f}=t;a==="bg_color"&&p?m(n,p):a==="secondary_bg_color"&&f&&m(n,f)}m(r,e.bgColor)},o=[t.on("change",i),e.on("change",i)];return i(),()=>o.forEach(a=>a())}function ys(e,t){t||(t=n=>`--tg-theme-${n.replace(/[A-Z]/g,r=>`-${r.toLowerCase()}`)}`);const s=()=>{Object.entries(e.getState()).forEach(([n,r])=>{r&&m(t(n),r)})};return s(),e.on("change",s)}function Es(e,t){t||(t=f=>`--tg-viewport-${f}`);const[s,n,r]=["height","width","stable-height"].map(f=>t(f)),i=()=>m(s,`${e.height}px`),o=()=>m(n,`${e.width}px`),a=()=>m(r,`${e.stableHeight}px`),p=[e.on("change:height",i),e.on("change:width",o),e.on("change:stableHeight",a)];return i(),o(),a(),()=>p.forEach(f=>f())}function vs(e=!0){const t=[g("reload_iframe",()=>{R("iframe_will_reload"),window.location.reload()})],s=()=>t.forEach(n=>n());if(e){const n=document.createElement("style");n.id="telegram-custom-styles",document.head.appendChild(n),t.push(g("set_custom_style",r=>{n.innerHTML=r}),()=>document.head.removeChild(n))}return R("iframe_ready",{reload_supported:!0}),s}async function Ss(){if(Ot(window))return!0;try{return await l({method:"web_app_request_theme",event:"theme_changed",timeout:100}),!0}catch{return!1}}function we(e){return e instanceof k}function Rs(e,t){return we(e)&&e.type===t}function G(e,t){let s,n,r;return typeof e=="string"?s=e:(s=e.pathname===void 0?t:e.pathname,n=e.params,r=e.id),Object.freeze({id:r||(Math.random()*2**14|0).toString(16),pathname:s,params:n})}class me{constructor(t,s,n=R){c(this,"history");c(this,"ee",new q);c(this,"attached",!1);c(this,"back",()=>this.go(-1));c(this,"on",this.ee.on.bind(this.ee));c(this,"off",this.ee.off.bind(this.ee));if(this._index=s,this.postEvent=n,t.length===0)throw d(Nt,"History should not be empty.");if(s<0||s>=t.length)throw d(qt,"Index should not be zero and higher or equal than history size.");this.history=t.map(r=>G(r,""))}attach(){this.attached||(this.attached=!0,this.sync(),g("back_button_pressed",this.back))}get current(){return this.history[this.index]}detach(){this.attached=!1,D("back_button_pressed",this.back)}forward(){this.go(1)}go(t,s){const n=this.index+t,r=Math.min(Math.max(0,n),this.history.length-1);(n===r||s)&&this.replaceAndMove(r,this.history[r])}goTo(t,s){this.go(t-this.index,s)}get hasPrev(){return this.index>0}get hasNext(){return this.index!==this.history.length-1}get index(){return this._index}push(t){this.hasNext&&this.history.splice(this.index+1),this.replaceAndMove(this.index+1,G(t,this.current.pathname))}replace(t){this.replaceAndMove(this.index,G(t,this.current.pathname))}replaceAndMove(t,s){const n=t-this.index;if(!n&&this.current===s)return;const r=this.current;if(this.index!==t){const i=this._index;this._index=t,this.attached&&i>0!=t>0&&this.sync()}this.history[t]=s,this.ee.emit("change",{navigator:this,from:r,to:this.current,delta:n})}sync(){this.postEvent("web_app_setup_back_button",{is_visible:!!this.index})}}function j({params:e,...t}){return{...e||{hash:"",search:""},...t}}function I(e,t){return e.startsWith(t)?e:`${t}${e}`}function x(e){return new URL(typeof e=="string"?e:`${e.pathname||""}${I(e.search||"","?")}${I(e.hash||"","#")}`,"http://a")}function N(e){const t=typeof e=="string"?e.startsWith("/"):!!(e.pathname&&e.pathname.startsWith("/")),s=x(e);return`${t?s.pathname:s.pathname.slice(1)}${s.search}${s.hash}`}function F(e,t,s){let n,r;typeof e=="string"?n=e:(n=N(e),s=e.state,r=e.id);const{pathname:i,search:o,hash:a}=new URL(n,`http://a${I(t,"/")}`);return{id:r,pathname:i,params:{hash:a,search:o,state:s}}}async function A(e){return e===0?!0:Promise.race([new Promise(t=>{const s=Y("popstate",()=>{s(),t(!0)});window.history.go(e)}),new Promise(t=>{setTimeout(t,50,!1)})])}async function Ps(){if(window.history.length<=1||(window.history.pushState(null,""),await A(1-window.history.length)))return;let t=await A(-1);for(;t;)t=await A(-1)}function gt(e){return x(e).pathname}const vt=0,z=1,J=2;class bt{constructor(t,s,{postEvent:n,hashMode:r,base:i}={}){c(this,"navigator");c(this,"ee",new q);c(this,"hashMode");c(this,"base");c(this,"attached",!1);c(this,"onPopState",({state:t})=>{if(t===null)return this.push(this.parsePath(window.location.href));t===vt?window.history.forward():t===z&&this.back(),t===J&&this.forward()});c(this,"onNavigatorChange",async({to:t,from:s,delta:n})=>{this.attached&&await this.syncHistory(),this.ee.emit("change",{delta:n,from:j(s),to:j(t),navigator:this})});c(this,"on",this.ee.on.bind(this.ee));c(this,"off",this.ee.off.bind(this.ee));this.navigator=new me(t.map(o=>F(o,"/")),s,n),this.navigator.on("change",this.onNavigatorChange),this.hashMode=r,this.base=gt(i||"")}async attach(){this.attached||(this.attached=!0,this.navigator.attach(),window.addEventListener("popstate",this.onPopState),await this.syncHistory())}back(){this.navigator.back()}detach(){this.attached=!1,this.navigator.detach(),window.removeEventListener("popstate",this.onPopState)}forward(){return this.navigator.forward()}get index(){return this.navigator.index}get id(){return this.navigator.current.id}go(t,s){return this.navigator.go(t,s)}goTo(t,s){this.navigator.goTo(t,s)}get hash(){return(this.navigator.current.params||{}).hash||""}get hasPrev(){return this.navigator.hasPrev}get hasNext(){return this.navigator.hasNext}get history(){return this.navigator.history.map(j)}get path(){return N(this)}get pathname(){return this.navigator.current.pathname}parsePath(t){let s=x(t);return this.hashMode&&(s=x(s.hash.slice(1))),{pathname:s.pathname,search:s.search,hash:s.hash}}push(t,s){const n=F(t,this.path),{state:r=s}=n.params;this.navigator.push({...n,params:{...n.params,state:r}})}replace(t,s){const n=F(t,this.path),{state:r=s}=n.params;this.navigator.replace({...n,params:{...n.params,state:r}})}renderPath(t){const s=(this.base.length===1?"":this.base)+I(N(t),"/");return this.hashMode?I(s.slice(1),this.hashMode==="default"?"#":"#/"):s}async syncHistory(){window.removeEventListener("popstate",this.onPopState);const{state:t}=this,s=this.renderPath(this);await Ps(),this.hasPrev&&this.hasNext?(window.history.replaceState(z,""),window.history.pushState(t,"",s),window.history.pushState(J,""),await A(-1)):this.hasPrev?(window.history.replaceState(z,""),window.history.pushState(t,"",s)):this.hasNext?(window.history.replaceState(t,s),window.history.pushState(J,""),await A(-1)):(window.history.replaceState(vt,""),window.history.pushState(t,"",s)),window.addEventListener("popstate",this.onPopState)}get search(){return(this.navigator.current.params||{}).search||""}get state(){return(this.navigator.current.params||{}).state}}function ye(e){e||(e={});const{href:t,hash:s}=window.location;let n=N(e.hashMode?s.includes("?")?s.slice(1):`?${s.slice(1)}`:t);const r=e.base?gt(e.base):void 0;if(r){if(!n.startsWith(r))throw d(Dt,`Path "${n}" expected to be starting with "${r}"`);n=n.slice(r.length)}return new bt([n],0,e)}function Ts(e){const t=e.match(/#(.+)/);return t?t[1]:null}function Cs(e,t){if(pt()){const s=sessionStorage.getItem(e);if(s)try{const{index:n,history:r}=JSON.parse(s);return new bt(r,n,t)}catch(n){console.error("Unable to restore hash navigator state.",n)}}return ye(t)}function As(e,t){const s=Cs(e,t),n=()=>sessionStorage.setItem(e,JSON.stringify({index:s.index,history:s.history}));return s.on("change",n),n(),s}exports.BackButton=jt;exports.BasicNavigator=me;exports.BiometryManager=K;exports.BrowserNavigator=bt;exports.ClosingBehavior=re;exports.CloudStorage=oe;exports.ERR_INVALID_PATH_BASE=Dt;exports.ERR_INVOKE_CUSTOM_METHOD_RESPONSE=At;exports.ERR_METHOD_PARAMETER_UNSUPPORTED=Tt;exports.ERR_METHOD_UNSUPPORTED=Pt;exports.ERR_NAVIGATION_HISTORY_EMPTY=Nt;exports.ERR_NAVIGATION_INDEX_INVALID=qt;exports.ERR_NAVIGATION_ITEM_INVALID=Te;exports.ERR_PARSE=Z;exports.ERR_SSR_INIT=L;exports.ERR_SSR_POST_EVENT=kt;exports.ERR_TIMED_OUT=It;exports.ERR_UNEXPECTED_TYPE=xt;exports.ERR_UNKNOWN_ENV=Ct;exports.EventEmitter=q;exports.HapticFeedback=ae;exports.InitData=ce;exports.Invoice=he;exports.MainButton=pe;exports.MiniApp=le;exports.Popup=de;exports.QRScanner=_e;exports.SDKError=k;exports.SettingsButton=fe;exports.ThemeParams=ge;exports.Utils=be;exports.Viewport=ft;exports.array=ie;exports.bindMiniAppCSSVars=ms;exports.bindThemeParamsCSSVars=ys;exports.bindViewportCSSVars=Es;exports.boolean=w;exports.captureSameReq=nt;exports.classNames=B;exports.compareVersions=Bt;exports.createBrowserNavigatorFromLocation=ye;exports.createPostEvent=Ht;exports.createSafeURL=x;exports.date=ct;exports.getHash=Ts;exports.getPathname=gt;exports.initBackButton=Qe;exports.initBiometryManager=Ye;exports.initClosingBehavior=Ke;exports.initCloudStorage=ts;exports.initHapticFeedback=es;exports.initInitData=ss;exports.initInvoice=rs;exports.initMainButton=is;exports.initMiniApp=cs;exports.initNavigator=As;exports.initPopup=ps;exports.initQRScanner=us;exports.initSettingsButton=ls;exports.initThemeParams=ds;exports.initUtils=fs;exports.initViewport=ws;exports.initWeb=vs;exports.invokeCustomMethod=S;exports.isColorDark=it;exports.isIframe=Lt;exports.isPageReload=pt;exports.isRGB=U;exports.isRGBShort=Mt;exports.isSDKError=we;exports.isSDKErrorOfType=Rs;exports.isSSR=v;exports.isTMA=Ss;exports.json=u;exports.mergeClassNames=Oe;exports.number=y;exports.off=D;exports.on=g;exports.parseInitData=ns;exports.parseLaunchParams=ht;exports.parseThemeParams=dt;exports.postEvent=R;exports.request=l;exports.requestBiometryInfo=ne;exports.requestThemeParams=_s;exports.requestViewport=_t;exports.retrieveLaunchParams=ee;exports.rgb=st;exports.searchParams=W;exports.serializeLaunchParams=te;exports.serializeThemeParams=Zt;exports.setCSSVar=m;exports.setDebug=Re;exports.setTargetOrigin=Be;exports.string=h;exports.subscribe=Rt;exports.supports=E;exports.targetOrigin=Ut;exports.toRGB=et;exports.unsubscribe=X;exports.urlToPath=N;exports.withTimeout=rt;
2
+ //# sourceMappingURL=index.cjs.map