@tma.js/bridge 2.3.3 → 4.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +156 -35
  2. package/dist/dts/env.d.ts +69 -0
  3. package/dist/dts/errors.d.ts +55 -9
  4. package/dist/dts/events.d.ts +64 -0
  5. package/dist/dts/index.d.ts +14 -26
  6. package/dist/dts/invokeCustomMethod.d.ts +33 -0
  7. package/dist/dts/launch-params.d.ts +101 -19
  8. package/dist/dts/logger.d.ts +29 -0
  9. package/dist/dts/mockTelegramEnv.d.ts +55 -0
  10. package/dist/dts/post-event.d.ts +40 -0
  11. package/dist/dts/request.d.ts +98 -0
  12. package/dist/dts/result.d.ts +45 -0
  13. package/dist/dts/start-param.d.ts +34 -40
  14. package/dist/dts/theme-params.d.ts +10 -0
  15. package/dist/dts/types/common.d.ts +61 -0
  16. package/dist/dts/{events/types → types}/events.d.ts +75 -56
  17. package/dist/dts/types/index.d.ts +5 -0
  18. package/dist/dts/{methods/types → types}/methods.d.ts +200 -116
  19. package/dist/dts/versions.d.ts +83 -0
  20. package/dist/dts/window-hooks.d.ts +27 -0
  21. package/dist/index.cjs +2 -3
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.iife.js +2 -3
  24. package/dist/index.iife.js.map +1 -1
  25. package/dist/index.js +619 -601
  26. package/dist/index.js.map +1 -1
  27. package/package.json +11 -19
  28. package/dist/dts/applyPolyfills.d.ts +0 -5
  29. package/dist/dts/base64-url.d.ts +0 -24
  30. package/dist/dts/env/hasWebviewProxy.d.ts +0 -10
  31. package/dist/dts/env/isIframe.d.ts +0 -5
  32. package/dist/dts/env/isTMA.d.ts +0 -31
  33. package/dist/dts/env/mockTelegramEnv.d.ts +0 -60
  34. package/dist/dts/events/createEmitter.d.ts +0 -58
  35. package/dist/dts/events/emitEvent.d.ts +0 -33
  36. package/dist/dts/events/emitter.d.ts +0 -2
  37. package/dist/dts/events/types/index.d.ts +0 -3
  38. package/dist/dts/events/types/listening.d.ts +0 -5
  39. package/dist/dts/events/types/misc.d.ts +0 -16
  40. package/dist/dts/globals.d.ts +0 -53
  41. package/dist/dts/methods/captureSameReq.d.ts +0 -10
  42. package/dist/dts/methods/createPostEvent.d.ts +0 -30
  43. package/dist/dts/methods/getReleaseVersion.d.ts +0 -15
  44. package/dist/dts/methods/postEvent.d.ts +0 -35
  45. package/dist/dts/methods/postMessage.d.ts +0 -7
  46. package/dist/dts/methods/supports.d.ts +0 -15
  47. package/dist/dts/methods/types/custom-method.d.ts +0 -59
  48. package/dist/dts/methods/types/index.d.ts +0 -6
  49. package/dist/dts/methods/types/misc.d.ts +0 -27
  50. package/dist/dts/methods/types/utils.d.ts +0 -9
  51. package/dist/dts/obj-prop-helpers.d.ts +0 -39
  52. package/dist/dts/utils/compareVersions.d.ts +0 -10
  53. package/dist/dts/utils/invokeCustomMethod.d.ts +0 -34
  54. package/dist/dts/utils/request.d.ts +0 -102
  55. package/dist/dts/utils/request2.d.ts +0 -62
  56. /package/dist/dts/{methods/types → types}/haptic-feedback.d.ts +0 -0
  57. /package/dist/dts/{methods/types → types}/popup.d.ts +0 -0
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/env/hasWebviewProxy.ts","../src/env/isIframe.ts","../src/errors.ts","../src/launch-params.ts","../src/events/createEmitter.ts","../src/events/emitEvent.ts","../src/globals.ts","../src/obj-prop-helpers.ts","../src/events/emitter.ts","../src/methods/postMessage.ts","../src/methods/postEvent.ts","../src/utils/request2.ts","../src/env/isTMA.ts","../src/env/mockTelegramEnv.ts","../src/methods/captureSameReq.ts","../src/methods/getReleaseVersion.ts","../src/utils/compareVersions.ts","../src/methods/supports.ts","../src/methods/createPostEvent.ts","../src/utils/invokeCustomMethod.ts","../src/utils/request.ts","../src/applyPolyfills.ts","../src/base64-url.ts","../src/start-param.ts"],"sourcesContent":["import * as v from 'valibot';\n\n/**\n * Returns true in case, passed value contains path `TelegramWebviewProxy.postEvent` property and\n * `postEvent` is a function.\n * @param value - value to check.\n */\nexport function hasWebviewProxy<T>(value: T): value is T & {\n TelegramWebviewProxy: {\n postEvent: (...args: unknown[]) => unknown;\n };\n} {\n return typeof value === 'object' && !!value && !Array.isArray(value) && v.is(\n v.looseObject({ TelegramWebviewProxy: v.looseObject({ postEvent: v.function() }) }),\n { TelegramWebviewProxy: (value as Record<string, unknown>).TelegramWebviewProxy },\n );\n}\n","/**\n * @see https://stackoverflow.com/a/326076\n * @returns True, if current environment is iframe.\n */\nexport function isIframe(): boolean {\n try {\n return window.self !== window.top;\n } catch {\n return true;\n }\n}\n","import type { Version } from '@tma.js/types';\nimport { errorClass, errorClassWithData } from 'error-kid';\n\nexport class MethodUnsupportedError extends /* @__PURE__ */ errorClass<\n [method: string, version: Version]\n>({\n name: 'MethodUnsupportedError',\n super: (method, version) => [\n `Method \"${method}\" is unsupported in Mini Apps version ${version}`,\n ],\n}) {\n}\n\nexport class MethodParameterUnsupportedError extends /* @__PURE__ */ errorClass<\n [method: string, param: string, version: Version]\n>({\n name: 'MethodParameterUnsupportedError',\n super: (method, param, version) => [\n `Parameter \"${param}\" of \"${method}\" method is unsupported in Mini Apps version ${version}`,\n ],\n}) {\n}\n\nexport class LaunchParamsRetrieveError extends /* @__PURE__ */ errorClassWithData<\n { errors: { source: string; error: unknown }[] },\n [{ source: string; error: unknown }[]]\n>({\n name: 'LaunchParamsRetrieveError',\n data: errors => ({ errors }),\n super: errors => [\n [\n 'Unable to retrieve launch parameters from any known source. Perhaps, you have opened your app outside Telegram?',\n '📖 Refer to docs for more information:',\n 'https://docs.telegram-mini-apps.com/packages/tma-js-bridge/environment',\n '',\n 'Collected errors:',\n ...errors.map(({ source, error }) => {\n return `Source: ${source} / ${error instanceof Error ? error.message : String(error)}`;\n }),\n ].join('\\n'),\n ],\n}) {\n}\n\nexport class InvalidLaunchParamsError extends /* @__PURE__ */ errorClass<\n [launchParams: string, cause: unknown]\n>({\n name: 'InvalidLaunchParamsError',\n super: (launchParams, cause) => [\n `Invalid value for launch params: ${launchParams}`,\n { cause },\n ],\n}) {\n}\n\nexport class UnknownEnvError extends /* @__PURE__ */ errorClass({ name: 'UnknownEnvError' }) {\n}\n\nexport class InvokeCustomMethodFailedError extends /* @__PURE__ */ errorClass<[error: string]>({\n name: 'InvokeCustomMethodError',\n super: error => [`Server returned error: ${error}`],\n}) {\n}\n","import { throwifyFpFn, getStorageValue, setStorageValue } from '@tma.js/toolkit';\nimport {\n parseLaunchParamsQueryFp,\n type LaunchParamsGenType,\n type ParseLaunchParamsQueryError,\n} from '@tma.js/transformers';\nimport { either as E, function as fn, option as O } from 'fp-ts';\n\nimport { LaunchParamsRetrieveError } from '@/errors.js';\n\nconst SESSION_STORAGE_KEY = 'launchParams';\n\nexport type RetrieveRawInitDataError = RetrieveRawLaunchParamsError;\nexport type RetrieveRawLaunchParamsError = LaunchParamsRetrieveError;\nexport type RetrieveLaunchParamsError = RetrieveRawLaunchParamsError | ParseLaunchParamsQueryError;\nexport type RetrieveLaunchParamsResult = LaunchParamsGenType;\n\n/**\n * @param urlString - URL to extract launch parameters from.\n * @returns Launch parameters from the specified URL.\n * @throws Error if function was unable to extract launch parameters from the\n * passed URL.\n */\nfunction retrieveLpFromUrl(urlString: string): string {\n return urlString\n // Replace everything before this first hashtag or question sign.\n .replace(/^[^?#]*[?#]/, '')\n // Replace all hashtags and question signs to make it look like some search\n // params.\n .replace(/[?#]/g, '&');\n}\n\n/**\n * @returns Launch parameters from any known source.\n */\nexport function retrieveLaunchParamsFp(): E.Either<\n RetrieveLaunchParamsError,\n RetrieveLaunchParamsResult\n> {\n return fn.pipe(\n retrieveRawLaunchParamsFp(),\n E.chainW(parseLaunchParamsQueryFp),\n );\n}\n\n/**\n * @see retrieveLaunchParamsFp\n */\nexport const retrieveLaunchParams: () => RetrieveLaunchParamsResult =\n throwifyFpFn(retrieveLaunchParamsFp);\n\n/**\n * @returns Raw init data from any known source.\n */\nexport function retrieveRawInitDataFp(): E.Either<RetrieveRawInitDataError, O.Option<string>> {\n return fn.pipe(\n retrieveRawLaunchParamsFp(),\n E.map(raw => {\n const v = new URLSearchParams(raw).get('tgWebAppData');\n return v ? O.some(v) : O.none;\n }),\n );\n}\n\n/**\n * @see retrieveRawInitDataFp\n */\nexport function retrieveRawInitData(): string | undefined {\n return fn.pipe(\n retrieveRawInitDataFp(),\n E.fold(err => {\n throw err;\n }, v => v),\n O.match(() => undefined, v => v),\n );\n}\n\n/**\n * @returns Launch parameters in a raw format from any known source.\n */\nexport function retrieveRawLaunchParamsFp(): E.Either<RetrieveRawLaunchParamsError, string> {\n const errors: { source: string; error: unknown }[] = [];\n\n for (const [retrieve, source] of [\n // Try to retrieve launch parameters from the current location. This method\n // can return nothing in case, location was changed, and then the page was\n // reloaded.\n [() => retrieveLpFromUrl(window.location.href), 'window.location.href'],\n // Then, try using the lower level API - window.performance.\n [() => {\n const navigationEntry = performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming | undefined;\n return navigationEntry && retrieveLpFromUrl(navigationEntry.name);\n }, 'performance navigation entries'],\n // Finally, try using the session storage.\n [() => getStorageValue<string>(SESSION_STORAGE_KEY), 'local storage'],\n ] as const) {\n const v = retrieve();\n if (!v) {\n errors.push({ source, error: new Error('Source is empty') });\n continue;\n }\n const maybeError = fn.pipe(\n parseLaunchParamsQueryFp(v),\n E.foldW(err => err, () => true as const),\n );\n if (typeof maybeError !== 'boolean') {\n errors.push({ source, error: maybeError });\n continue;\n }\n setStorageValue(SESSION_STORAGE_KEY, v);\n return E.right(v);\n }\n return E.left(new LaunchParamsRetrieveError(errors));\n}\n\n/**\n * @see retrieveRawLaunchParamsFp\n */\nexport const retrieveRawLaunchParams = throwifyFpFn(retrieveRawLaunchParamsFp);\n","import type { If, IsNever, IsUndefined, Or } from '@tma.js/toolkit';\nimport mitt, {\n type Emitter,\n type EventHandlerMap,\n type EventType,\n type Handler,\n} from 'mitt';\n\nexport type WildcardHandler<E> = Handler<{\n [K in keyof E]: {\n name: K;\n payload: If<Or<IsNever<E[K]>, IsUndefined<E[K]>>, never, E[K]>;\n };\n}[keyof E]>;\n\nexport interface OnFn<E> {\n /**\n * Adds a new listener for the specified event.\n * @param type - event name.\n * @param handler - event listener.\n * @param once - should this listener be called only once.\n * @returns Function to remove bound event listener.\n */\n <K extends keyof E>(type: K, handler: Handler<E[K]>, once?: boolean): VoidFunction;\n /**\n * Adds a listener to the wildcard event.\n * @param type - event name.\n * @param handler - event listener.\n * @param once - should this listener be called only once.\n * @returns Function to remove bound event listener.\n */\n (type: '*', handler: WildcardHandler<E>, once?: boolean): VoidFunction;\n}\n\nexport interface OffFn<E> {\n /**\n * Removes a listener from the specified event.\n * @param type - event to listen.\n * @param handler - event listener to remove.\n * @param once - had this listener to be called only once.\n */\n <K extends keyof E>(type: K, handler: Handler<E[K]>, once?: boolean): void;\n /**\n * Removes a listener from the wildcard event.\n * @param type - event to stop listening.\n * @param handler - event listener to remove.\n * @param once - should this listener be called only once.\n */\n (type: '*', handler: WildcardHandler<E>, once?: boolean): void;\n}\n\nexport interface EmitFn<E> {\n <K extends keyof E>(type: K, event: E[K]): void;\n <K extends keyof E>(type: undefined extends E[K] ? K : never): void;\n}\n\n/**\n * Creates a new enhanced event emitter.\n * @param onFirst - a function to call every time when the events map appeared to be empty during\n * the event listener creation.\n * @param onEmpty - a function to call every tume when the events map became empty.\n */\nexport function createEmitter<E extends object>(\n onFirst: VoidFunction,\n onEmpty: VoidFunction,\n): {\n on: OnFn<E>;\n off: OffFn<E>;\n emit: EmitFn<E>;\n clear: VoidFunction;\n} {\n // To understand the event handlers concept here, let's tell the underlying idea.\n //\n // We use a Map, where key is an event name, and the value is a Map we call HandlersMap.\n //\n // The HandlersMap is a Map, where the key is an event handler, added by the developer.\n // The corresponding value is a list of tuples, with an internally generated function and a\n // boolean value responsible for determining if the handler must be called only once. So, you\n // can imagine the following map as:\n //\n // HandlersMap {\n // { developer_handler }: Array<[ internally_created_handler, once ]>;\n // }\n //\n // The value for the key represents an array of tuples, as long as a single handler may be added\n // many times, and for each addition we add a new tuple entry.\n //\n // The handler may also be added to be called only once. Trying to remove such kind of handler\n // using a different value of the \"once\" argument will lead to nothing. The developer must\n // specify the same argument value to avoid confusions.\n //\n // Here is the final EventToHandlersMap definition:\n //\n // EventToHandlersMap {\n // { event_name }: HandlersMap {\n // { developer_handler }: Array<[ internally_created_handler, once ]>;\n // }\n // }\n type HandlersMap = Map<\n (...args: any) => void,\n [handler: (...args: any) => void, once: boolean][]\n >;\n\n const eventToHandlersMap = new Map<keyof E | '*', HandlersMap>();\n\n const emitter = (mitt as any as {\n <E extends Record<EventType, unknown>>(all?: EventHandlerMap<E>): Emitter<E>;\n })<E & Record<string | symbol, unknown>>();\n\n const off: OffFn<E> = (\n event: keyof E | '*',\n handler: (...args: any) => void,\n once = false,\n ) => {\n const handlersMap: HandlersMap = eventToHandlersMap.get(event) || new Map();\n eventToHandlersMap.set(event, handlersMap);\n\n const handlers = handlersMap.get(handler) || [];\n handlersMap.set(handler, handlers);\n\n const index = handlers.findIndex(item => item[1] === once);\n if (index >= 0) {\n // Remove the related handler.\n emitter.off(event, handlers[index][0]);\n\n // Remove the handler from the cache array.\n handlers.splice(index, 1);\n\n // If after removal, there are no handlers left, we should remove the entry from the cache.\n if (!handlers.length) {\n handlersMap.delete(handler);\n if (!handlersMap.size) {\n const prevSize = eventToHandlersMap.size;\n eventToHandlersMap.delete(event);\n prevSize && !eventToHandlersMap.size && onEmpty();\n }\n }\n }\n };\n\n return {\n on(event: keyof E | '*', handler: (...args: any[]) => any, once?: boolean) {\n // The events' map became non-empty. Call the onFirst callback.\n !eventToHandlersMap.size && onFirst();\n\n const cleanup = () => {\n off(event as any, handler, once);\n };\n\n const internalHandler = (...args: any[]) => {\n once && cleanup();\n if (event === '*') {\n handler({ name: args[0], payload: args[1] });\n } else {\n handler(...args);\n }\n };\n\n emitter.on(event, internalHandler);\n\n // Add this handler to the cache, so we could remove it using the passed listener.\n const handlersMap: HandlersMap = eventToHandlersMap.get(event) || new Map();\n eventToHandlersMap.set(event, handlersMap);\n\n const handlers = handlersMap.get(handler) || [];\n handlersMap.set(handler, handlers);\n handlers.push([internalHandler, once || false]);\n\n return cleanup;\n },\n off,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n emit: emitter.emit,\n clear() {\n const prevSize = eventToHandlersMap.size;\n emitter.all.clear();\n eventToHandlersMap.clear();\n prevSize && onEmpty();\n },\n };\n}\n","import type { EventPayload, EventWithoutPayload, EventWithPayload } from '@/events/types/index.js';\n\n/**\n * Emits an event without payload sent from the Telegram native application like it was sent in\n * a default web environment between two iframes.\n *\n * It dispatches a new MessageEvent and expects it to be handled via\n * the `window.addEventListener('message', ...)` call, as a developer would do it to handle\n * messages sent from the parent iframe.\n * @param eventType - event name.\n */\nexport function emitEvent<E extends EventWithoutPayload>(eventType: E): void;\n\n/**\n * Emits an event with payload sent from the Telegram native application like it was sent in\n * a default web environment between two iframes.\n *\n * It dispatches a new MessageEvent and expects it to be handled via\n * the `window.addEventListener('message', ...)` call, as a developer would do it to handle\n * messages sent from the parent iframe.\n * @param eventType - event name.\n * @param eventData - event payload.\n */\nexport function emitEvent<E extends EventWithPayload>(\n eventType: E,\n eventData: EventPayload<E>,\n): void;\n\n/**\n * Emits an unknown event sent from the Telegram native application like it was sent in a default\n * web environment between two iframes.\n *\n * It dispatches a new MessageEvent and expects it to be handled via\n * the `window.addEventListener('message', ...)` call, as a developer would do it to handle\n * messages sent from the parent iframe.\n * @param eventType - event name.\n * @param eventData - event payload.\n */\nexport function emitEvent<E extends string>(\n eventType: E,\n eventData: E extends EventWithoutPayload\n ? never\n : E extends EventWithPayload\n ? EventPayload<E>\n : unknown,\n): void;\n\n/**\n * Emits an event sent from the Telegram native application like it was sent in a default web\n * environment between two iframes.\n *\n * It dispatches a new MessageEvent and expects it to be handled via\n * the `window.addEventListener('message', ...)` call, as a developer would do it to handle\n * messages sent from the parent iframe.\n * @param eventType - event name.\n * @param eventData - event payload.\n */\nexport function emitEvent(eventType: string, eventData?: unknown): void {\n window.dispatchEvent(new MessageEvent('message', {\n data: JSON.stringify({ eventType, eventData }),\n // We specify this kind of source here in order to allow the package's \"on\" function to\n // capture it. The reason is this function always checks the event source and relies on\n // it to be the parent window.\n source: window.parent,\n }));\n}\n","import { signal, computed } from '@tma.js/signals';\nimport { createLogger, type Logger } from '@tma.js/toolkit';\n\nimport { off, offAll, on } from '@/events/emitter.js';\nimport type { SubscribeListener } from '@/events/types/index.js';\nimport type { PostMessage } from '@/methods/postMessage.js';\n\n/**\n * @internal\n */\nconst _debug = signal(false);\n/**\n * @internal\n */\nconst _targetOrigin = signal('https://web.telegram.org');\n\nconst onEventReceived: SubscribeListener = event => {\n logger().log('Event received:', event);\n};\n\n/**\n * The current debug mode state.\n *\n * To update the value, use the `setDebug` function.\n * @see setDebug\n */\nexport const debug = computed(_debug);\n\n/**\n * Sets the package debug mode.\n *\n * Enabling debug mode leads to printing additional messages in the console related to the\n * processes inside the package.\n * @param value - enable debug mode.\n */\nexport function setDebug(value: boolean): void {\n if (value !== _debug()) {\n _debug.set(value);\n (value ? on : off)('*', onEventReceived);\n }\n}\n\n/**\n * The current target origin used by the `postEvent` method.\n *\n * You don't need to override this value until you know what you are doing.\n * To update the value, use the `setTargetOrigin` function.\n * @default 'https://web.telegram.org'\n * @see setTargetOrigin\n */\nexport const targetOrigin = computed(_targetOrigin);\n\n/**\n * Sets a new target origin that is being used when calling the `postEvent` function in Telegram\n * web versions.\n *\n * You don't need to override this value until you know what you are doing.\n * @param origin - allowed target origin value.\n * @see _targetOrigin\n */\nexport function setTargetOrigin(origin: string) {\n _targetOrigin.set(origin);\n logger().log('New target origin set', origin);\n}\n\n/**\n * Signal containing a custom implementation of the method to post a message to the parent\n * window. We usually use it to send a message in web versions of Telegram.\n *\n * @default A function behaving like the `window.parent.postMessage` method.\n */\nexport const postMessageImpl = signal<PostMessage>((...args) => {\n window.parent.postMessage(...args as unknown as Parameters<PostMessage>);\n});\n\n/**\n * The package logger. You can override this value in order to use your own implementation.\n */\nexport const logger = signal<Logger>(createLogger('Bridge', {\n bgColor: '#9147ff',\n textColor: 'white',\n shouldLog: debug,\n}));\n\n/**\n * Resets the package global values. Normally, you don't use this function in your application.\n * We are using it only for test purposes.\n */\nexport function resetGlobals() {\n offAll();\n [postMessageImpl, _targetOrigin, targetOrigin, _debug, debug, logger].forEach(s => {\n s.unsubAll();\n 'reset' in s && s.reset();\n });\n}\n","/**\n * Defines a property, that is a functions compose. Trying to set a value in this property\n * will lead to adding it to a function's pool. The property value will always be equal to a\n * function, calling all collected functions in the pool.\n *\n * Returned function performs a cleanup. It does one of the following:\n * 1. Removes the property if no functions were to the pool added other than the initial one.\n * 2. Sets the value equal to the first added function to the pool after the initial one if\n * the only one additional function was added at all. In other words, if the pool length is equal\n * to 2, the second item will be selected as the property value.\n * 3. Leaves the value equal to a function calling all pool functions, but removes the initially\n * added one.\n * @param obj - object.\n * @param propertyName - object property.\n * @param initialFn - an initial function to set.\n */\nexport function defineFnComposer(\n obj: any,\n propertyName: string,\n initialFn: (...args: any) => any,\n): void {\n const assignedFunctions: any[] = [initialFn];\n\n const property = obj[propertyName];\n if (typeof property === 'function') {\n assignedFunctions.push(property);\n }\n\n const callAssignedFunctions = (...args: any) => {\n assignedFunctions.forEach(fn => fn(...args));\n };\n\n // Wrap the callPool function and add \"unwrap\" method to it.\n const unwrappableCallAssignedFunctions = Object.assign((...args: any) => {\n callAssignedFunctions(...args);\n }, {\n // Unwraps the composer.\n unwrap() {\n const { length: poolSize } = assignedFunctions;\n if (poolSize === 1) {\n // Only the initial handler is in the pool. In this case we just remove the property.\n delete obj[propertyName];\n return;\n }\n if (poolSize === 2) {\n // Only one additional handler was added. We set it as a value for the property.\n defineStaticProperty(obj, propertyName, assignedFunctions[1]);\n return;\n }\n // Many additional handlers were added. In this case we remove the initially added function\n // from the pool and leave the property value almost as is - only \"unwrap\" method will be\n // removed.\n assignedFunctions.unshift(1);\n defineStaticProperty(obj, propertyName, callAssignedFunctions);\n },\n });\n\n // This property should now always return our special function. Trying to set it to another\n // function should lead to just adding it to the pool of called functions.\n defineProxiedProperty(\n obj,\n propertyName,\n () => unwrappableCallAssignedFunctions,\n value => assignedFunctions.push(value),\n );\n}\n\n/**\n * Wires the specified property in the object preventing it from being overwritten. Instead, it\n * enhances the previous value by merging the current one with the passed one.\n * @param obj - object.\n * @param prop - object property to rewire.\n */\nexport function defineMergeableProperty(obj: any, prop: string): void {\n const value = obj[prop];\n defineProxiedProperty(obj, prop, () => value, v => {\n Object.entries(v).forEach(([objKey, objValue]) => {\n value[objKey] = objValue;\n });\n });\n}\n\n/**\n * Defines an enumerable and configurable property with a getter and setter.\n * @param obj - object.\n * @param prop - object property name.\n * @param get - getter to use.\n * @param set - setter to use.\n */\nexport function defineProxiedProperty(\n obj: any,\n prop: string,\n get: () => unknown,\n set: (v: any) => void,\n) {\n Object.defineProperty(obj, prop, {\n enumerable: true,\n configurable: true,\n get,\n set,\n });\n}\n\n/**\n * Defines an enumerable, configurable and writable property with the initial value.\n * @param obj - object.\n * @param prop - object property name.\n * @param value - value to set.\n */\nexport function defineStaticProperty(obj: any, prop: string, value: any): void {\n Object.defineProperty(obj, prop, {\n enumerable: true,\n configurable: true,\n writable: true,\n value,\n });\n}\n","import { miniAppsMessage, pipeJsonToSchema, themeParams } from '@tma.js/transformers';\nimport {\n boolean,\n looseObject,\n nullish,\n number,\n optional,\n parse,\n string,\n unknown,\n type BaseSchema,\n} from 'valibot';\n\nimport { createEmitter } from '@/events/createEmitter.js';\nimport { emitEvent } from '@/events/emitEvent.js';\nimport type { EventName, EventPayload, Events } from '@/events/types/index.js';\nimport { logger } from '@/globals.js';\nimport { defineFnComposer, defineMergeableProperty } from '@/obj-prop-helpers.js';\n\n/**\n * Transformers for problematic Mini Apps events.\n */\nconst transformers = {\n clipboard_text_received: looseObject({\n req_id: string(),\n data: nullish(string()),\n }),\n custom_method_invoked: looseObject({\n req_id: string(),\n result: optional(unknown()),\n error: optional(string()),\n }),\n popup_closed: nullish(\n looseObject({ button_id: nullish(string(), () => undefined) }),\n {},\n ),\n viewport_changed: nullish(\n looseObject({\n height: number(),\n width: nullish(number(), () => window.innerWidth),\n is_state_stable: boolean(),\n is_expanded: boolean(),\n }),\n // TODO: At the moment, macOS has a bug with the invalid event payload - it is always equal to\n // null. Leaving this default value until the bug is fixed.\n () => ({\n height: window.innerHeight,\n is_state_stable: true,\n is_expanded: true,\n }),\n ),\n theme_changed: looseObject({\n theme_params: themeParams(),\n }),\n} as const satisfies { [E in EventName]?: BaseSchema<unknown, EventPayload<E>, any> };\n\nfunction windowMessageListener(event: MessageEvent): void {\n // Ignore non-parent window messages.\n if (event.source !== window.parent) {\n return;\n }\n\n // Parse incoming event data.\n let message: { eventType: string; eventData?: unknown };\n try {\n message = parse(pipeJsonToSchema(miniAppsMessage()), event.data);\n } catch {\n // We ignore incorrect messages as they could be generated by any other code.\n return;\n }\n\n const { eventType, eventData } = message;\n const schema = transformers[eventType as keyof typeof transformers];\n\n let data: unknown;\n try {\n data = schema ? parse(schema, eventData) : eventData;\n } catch (cause) {\n return logger().forceError(\n [\n `An error occurred processing the \"${eventType}\" event from the Telegram application.`,\n 'Please, file an issue here:',\n 'https://github.com/Telegram-Mini-Apps/tma.js/issues/new/choose',\n ].join('\\n'),\n message,\n cause,\n );\n }\n emit(eventType as any, data);\n}\n\nexport const {\n on,\n off,\n emit,\n clear: offAll,\n} = createEmitter<Events>(\n () => {\n const wnd = window as any;\n\n // Define all functions responsible for receiving an event from the Telegram client.\n // All these \"ports\" should narrow the communication way to a single specific one - the way\n // accepted by the web version of Telegram between iframes.\n //\n // Here we consider 2 cases:\n // 1. When the Telegram SDK is already connected. In this case the Telegram SDK already\n // installed its own ports, and we should rewire them. The cleanup function should also work\n // properly in this context, removing @tma.js/bridge handler only, not\n // the Telegram SDK one.\n // 2. When the Telegram SDK is not connected, but probably will be. We know, that\n // the Telegram SDK is going to overwrite our own handlers. Due to this reason, we should\n // protect them from being overwritten, but still support handlers defined by the Telegram SDK.\n\n // TelegramGameProxy.receiveEvent\n !wnd.TelegramGameProxy && (wnd.TelegramGameProxy = {});\n defineFnComposer(wnd.TelegramGameProxy, 'receiveEvent', emitEvent);\n defineMergeableProperty(wnd, 'TelegramGameProxy');\n\n // Telegram.WebView.receiveEvent\n !wnd.Telegram && (wnd.Telegram = {});\n !wnd.Telegram.WebView && (wnd.Telegram.WebView = {});\n defineFnComposer(wnd.Telegram.WebView, 'receiveEvent', emitEvent);\n defineMergeableProperty(wnd.Telegram, 'WebView');\n\n // TelegramGameProxy_receiveEvent\n defineFnComposer(wnd, 'TelegramGameProxy_receiveEvent', emitEvent);\n\n // Add a listener handling events sent from the Telegram web application and also events\n // generated by the local emitEvent function.\n // This handler should emit a new event using the library event emitter.\n window.addEventListener('message', windowMessageListener);\n },\n () => {\n [\n ['TelegramGameProxy_receiveEvent'],\n ['TelegramGameProxy', 'receiveEvent'],\n ['Telegram', 'WebView', 'receiveEvent'],\n ].forEach(path => {\n const wnd = window as any;\n\n // A tuple, where the first value is the receiveEvent function owner, and the second\n // value is the receiveEvent itself.\n let cursor: [obj: any, receieveEvent: any] = [undefined, wnd];\n for (const item of path) {\n cursor = [cursor[1], cursor[1][item]];\n if (!cursor[1]) {\n return;\n }\n }\n const [receiveEventOwner, receiveEvent] = cursor;\n if ('unwrap' in receiveEvent) {\n receiveEvent.unwrap();\n if (\n receiveEventOwner\n && receiveEventOwner !== wnd\n && !Object.keys(receiveEventOwner).length\n ) {\n delete wnd[path[0]];\n }\n }\n });\n window.removeEventListener('message', windowMessageListener);\n },\n);\n","import { postMessageImpl } from '@/globals.js';\n\nexport type PostMessage = typeof window.parent.postMessage;\n\n/**\n * Posts a message to the parent window. We usually use it to send a message in web versions of\n * Telegram.\n * @param args - `window.parent.postMessage` arguments.\n */\nexport const postMessage: PostMessage = (...args) => {\n return postMessageImpl()(...args as unknown as Parameters<PostMessage>);\n};\n","import { either as E, function as fpFn } from 'fp-ts';\nimport { function as fn, is, looseObject } from 'valibot';\n\nimport { hasWebviewProxy } from '@/env/hasWebviewProxy.js';\nimport { isIframe } from '@/env/isIframe.js';\nimport { UnknownEnvError } from '@/errors.js';\nimport { logger, targetOrigin } from '@/globals.js';\nimport type {\n MethodName,\n MethodNameWithOptionalParams,\n MethodNameWithoutParams,\n MethodNameWithRequiredParams,\n MethodParams,\n} from '@/methods/types/index.js';\n\nimport { postMessage } from './postMessage.js';\n\nexport type PostEventError = UnknownEnvError;\nexport type PostEventFn = typeof postEvent;\nexport type PostEventFpFn = typeof postEventFp;\n\n/**\n * @see postEventFp\n */\nexport function postEvent<Method extends MethodNameWithRequiredParams>(\n method: Method,\n params: MethodParams<Method>,\n): void;\n/**\n * @see postEventFp\n */\nexport function postEvent(method: MethodNameWithoutParams): void;\n/**\n * @see postEventFp\n */\nexport function postEvent<Method extends MethodNameWithOptionalParams>(\n method: Method,\n params?: MethodParams<Method>,\n): void;\n\nexport function postEvent(\n eventType: MethodName,\n eventData?: MethodParams<MethodName>,\n): void {\n fpFn.pipe(\n postEventFp(\n // @ts-expect-error It's ok, TS can't determine a specific override.\n eventType,\n eventData,\n ),\n E.mapLeft(err => {\n throw err;\n }),\n );\n}\n\n/**\n * Calls Mini Apps methods requiring parameters.\n * @param method - method name.\n * @param params - options along with params.\n */\nexport function postEventFp<Method extends MethodNameWithRequiredParams>(\n method: Method,\n params: MethodParams<Method>,\n): E.Either<PostEventError, void>;\n\n/**\n * Calls Mini Apps methods accepting no parameters at all.\n * @param method - method name.\n */\nexport function postEventFp(method: MethodNameWithoutParams): E.Either<PostEventError, void>;\n\n/**\n * Calls Mini Apps methods accepting optional parameters.\n * @param method - method name.\n * @param params - options along with params.\n */\nexport function postEventFp<Method extends MethodNameWithOptionalParams>(\n method: Method,\n params?: MethodParams<Method>,\n): E.Either<PostEventError, void>;\n\nexport function postEventFp(\n eventType: MethodName,\n eventData?: MethodParams<MethodName>,\n): E.Either<PostEventError, void> {\n logger().log('Posting event:', eventData ? { eventType, eventData } : { eventType });\n\n const w = window;\n const message = JSON.stringify({ eventType, eventData });\n\n // Telegram Web.\n if (isIframe()) {\n postMessage(message, targetOrigin());\n return E.right(undefined);\n }\n\n // Telegram for iOS, macOS, Android and Telegram Desktop.\n if (hasWebviewProxy(w)) {\n w.TelegramWebviewProxy.postEvent(eventType, JSON.stringify(eventData));\n return E.right(undefined);\n }\n\n // Telegram for Windows Phone or Android.\n if (is(looseObject({ external: looseObject({ notify: fn() }) }), w)) {\n w.external.notify(message);\n return E.right(undefined);\n }\n\n // Otherwise, the current environment is unknown, and we are not able to send event.\n return E.left(new UnknownEnvError());\n}\n","import { signal } from '@tma.js/signals';\nimport {\n BetterTaskEither,\n type If,\n type IsNever,\n createCbCollector,\n throwifyAnyEither,\n} from '@tma.js/toolkit';\nimport { BetterPromise } from 'better-promises';\nimport { either as E, taskEither as TE, function as fn } from 'fp-ts';\n\nimport { on } from '@/events/emitter.js';\nimport type { EventName, EventPayload } from '@/events/types/index.js';\nimport { postEventFp } from '@/methods/postEvent.js';\nimport type {\n MethodName,\n MethodNameWithOptionalParams,\n MethodNameWithRequiredParams,\n MethodNameWithoutParams,\n MethodParams,\n} from '@/methods/types/index.js';\n\nimport type {\n RequestCaptureEventFn,\n RequestCaptureEventsFn,\n RequestCaptureFn,\n RequestError,\n RequestFpOptions,\n RequestOptions,\n RequestCaptureFnEventsPayload,\n} from './request.js';\n\ntype AnyEventName = EventName | EventName[];\n\nexport type Request2Error = RequestError;\nexport type Request2CaptureEventsFn<E extends EventName[]> = RequestCaptureEventsFn<E>;\nexport type Request2CaptureEventFn<E extends EventName> = RequestCaptureEventFn<E>;\nexport type Request2CaptureFn<E extends AnyEventName> = RequestCaptureFn<E>;\nexport type Request2Options<E extends AnyEventName> = RequestOptions<E>;\nexport type Request2FpOptions<E extends AnyEventName> = RequestFpOptions<E>;\nexport type Request2CaptureFnEventsPayload<E extends EventName[]> =\n RequestCaptureFnEventsPayload<E>;\nexport type Request2Result<E extends AnyEventName> =\n E extends (infer U extends EventName)[]\n ? U extends infer K extends EventName\n ? { event: K; payload: If<IsNever<EventPayload<K>>, undefined, EventPayload<K>> }\n : never\n : E extends EventName\n ? If<IsNever<EventPayload<E>>, undefined, EventPayload<E>>\n : never;\n\nexport type Request2Fn = typeof request2;\nexport type Request2FpFn = typeof request2Fp;\n\n/**\n * Calls a method waiting for the specified event(-s) to occur.\n * @param method - method name.\n * @param eventOrEvents - tracked event or events.\n * @param options - additional options.\n */\nexport function request2Fp<\n M extends MethodNameWithRequiredParams,\n E extends AnyEventName,\n AbortError = never,\n>(\n method: M,\n eventOrEvents: E,\n options: Request2FpOptions<E> & { params: MethodParams<M> },\n): TE.TaskEither<Request2Error | AbortError, Request2Result<E>>;\n\n/**\n * Calls a method waiting for the specified event(-s) to occur.\n * @param method - method name.\n * @param eventOrEvents - tracked event or events.\n * @param options - additional options.\n */\nexport function request2Fp<\n M extends MethodNameWithOptionalParams,\n E extends AnyEventName,\n AbortError = never,\n>(\n method: M,\n eventOrEvents: E,\n options?: Request2FpOptions<E> & { params?: MethodParams<M> },\n): TE.TaskEither<Request2Error | AbortError, Request2Result<E>>;\n\n/**\n * Calls a method waiting for the specified event(-s) to occur.\n * @param method - method name.\n * @param eventOrEvents - tracked event or events.\n * @param options - additional options.\n */\nexport function request2Fp<\n M extends MethodNameWithoutParams,\n E extends AnyEventName,\n AbortError = never,\n>(\n method: M,\n eventOrEvents: E,\n options?: Request2FpOptions<E>,\n): TE.TaskEither<Request2Error | AbortError, Request2Result<E>>;\n\nexport function request2Fp<\n M extends MethodName,\n E extends AnyEventName,\n AbortError = never,\n>(\n method: M,\n eventOrEvents: E,\n options: Request2FpOptions<E> & { params?: MethodParams<M> } = {},\n): TE.TaskEither<Request2Error | AbortError, Request2Result<E>> {\n const {\n // If no capture function was passed, we capture the first compatible event.\n capture = () => true,\n postEvent = postEventFp,\n } = options;\n\n // TODO: Maybe we want to rewrite it using a simple BetterPromise.\n\n const result = signal<undefined | [Request2Result<E>]>();\n const [addCleanup, cleanup] = createCbCollector();\n // Iterate over all the tracked events and add a listener, checking if the event should be\n // captured.\n (Array.isArray(eventOrEvents) ? eventOrEvents : [eventOrEvents]).forEach(event => {\n // Each event listener waits for the event to occur.\n // Then, if the capture function was passed, we should check if the event should\n // be captured. If the function is omitted, we instantly capture the event.\n addCleanup(\n on(event, payload => {\n const isEventsArray = Array.isArray(eventOrEvents);\n if (\n isEventsArray\n ? (capture as Request2CaptureEventsFn<EventName[]>)({ event, payload })\n : (capture as Request2CaptureEventFn<EventName>)(payload)\n ) {\n result.set([\n (isEventsArray ? { event, payload } : payload) as Request2Result<E>,\n ]);\n }\n }),\n );\n });\n const withCleanup = <T>(value: T): T => {\n cleanup();\n return value;\n };\n\n return fn.pipe(\n async () => postEvent(method as any, (options as any).params),\n TE.chainW(() => {\n return BetterTaskEither<AbortError, Request2Result<E>>((resolve, _, context) => {\n // When creating this BetterTaskEither, we could already have a value stored in\n // the result signal. For example, when tracked events were generated via emitEvent in\n // mockTelegramEnv.onEvent.\n const data = result();\n if (data) {\n return resolve(data[0]);\n }\n\n const listener = (data: [Request2Result<E>] | undefined) => {\n if (data) {\n resolve(data[0]);\n }\n };\n const unsub = () => {\n result.unsub(listener);\n };\n result.sub(listener);\n context.on('finalized', unsub);\n }, options);\n }),\n TE.mapBoth(withCleanup, withCleanup),\n );\n}\n\n/**\n * @see request2Fp\n */\nexport function request2<M extends MethodNameWithRequiredParams, E extends AnyEventName>(\n method: M,\n eventOrEvents: E,\n options: Request2Options<E> & { params: MethodParams<M> },\n): BetterPromise<Request2Result<E>>;\n\n/**\n * @see request2Fp\n */\nexport function request2<M extends MethodNameWithOptionalParams, E extends AnyEventName>(\n method: M,\n eventOrEvents: E,\n options?: Request2Options<E> & { params?: MethodParams<M> },\n): BetterPromise<Request2Result<E>>;\n\n/**\n * @see request2Fp\n */\nexport function request2<M extends MethodNameWithoutParams, E extends AnyEventName>(\n method: M,\n eventOrEvents: E,\n options?: Request2Options<E>,\n): BetterPromise<Request2Result<E>>;\n\nexport function request2<M extends MethodName, E extends AnyEventName>(\n method: M,\n eventOrEvents: E,\n options?: Request2Options<E> & { params?: MethodParams<M> },\n): BetterPromise<Request2Result<E>> {\n const { postEvent } = options || {};\n\n return throwifyAnyEither(\n // @ts-expect-error TypeScript will not be able to handle our overrides here.\n request2Fp(method, eventOrEvents, {\n ...options,\n postEvent: postEvent\n ? (...args: any[]) => {\n try {\n // @ts-expect-error TypeScript will not be able to handle our overrides here.\n postEvent(...args);\n return E.right(undefined);\n } catch (e) {\n return E.left(e);\n }\n }\n : postEventFp,\n }),\n );\n}\n","import { throwifyAnyEither } from '@tma.js/toolkit';\nimport {\n BetterPromise,\n type BetterPromiseOptions,\n TimeoutError,\n} from 'better-promises';\nimport { either as E, taskEither as TE, function as fn } from 'fp-ts';\n\nimport { hasWebviewProxy } from '@/env/hasWebviewProxy.js';\nimport { UnknownEnvError } from '@/errors.js';\nimport { retrieveRawLaunchParamsFp } from '@/launch-params.js';\nimport { type Request2Error, request2Fp } from '@/utils/request2.js';\n\nexport type isTMAError = Exclude<Request2Error, TimeoutError>;\n\n/**\n * @see isTMAFp\n */\nexport function isTMA(): boolean;\n/**\n * @see isTMAFp\n */\nexport function isTMA(type: 'complete', options?: BetterPromiseOptions): BetterPromise<boolean>;\nexport function isTMA(\n type?: 'complete',\n options?: BetterPromiseOptions,\n): boolean | BetterPromise<boolean> {\n const monad = isTMAFp(\n // @ts-expect-error TS doesn't get what override we are going to use.\n type,\n options,\n );\n return typeof monad === 'function'\n ? BetterPromise.fn(() => throwifyAnyEither(monad as TE.TaskEither<any, boolean>))\n : monad;\n}\n\n/**\n * Returns true if the current environment is Telegram Mini Apps.\n *\n * It uses the `retrieveLaunchParams` function to determine if the environment\n * contains launch parameters. In case it does, true will be returned.\n *\n * In case you need stricter checks, use async override of this function.\n */\nexport function isTMAFp(): boolean;\n/**\n * Returns promise with true if the current environment is Telegram Mini Apps.\n *\n * First of all, it checks if the current environment contains traits specific\n * to the Mini Apps environment. Then, it attempts to call a Mini Apps method\n * and waits for a response to be received.\n *\n * In case you need less strict checks, use sync override of this function.\n */\nexport function isTMAFp(\n type: 'complete',\n options?: BetterPromiseOptions,\n): TE.TaskEither<isTMAError, boolean>;\nexport function isTMAFp(\n type?: 'complete',\n options?: BetterPromiseOptions,\n): boolean | TE.TaskEither<isTMAError, boolean> {\n const hasProxy = hasWebviewProxy(window);\n if (!type) {\n return hasProxy || fn.pipe(retrieveRawLaunchParamsFp(), E.match(() => false, () => true));\n }\n if (hasProxy) {\n return TE.right(true);\n }\n const { timeout = 100 } = options || {};\n\n return fn.pipe(\n request2Fp('web_app_request_theme', 'theme_changed', { ...options, timeout }),\n TE.match(\n error => (\n TimeoutError.is(error) || UnknownEnvError.is(error)\n ? E.right(false)\n : E.left(error)\n ),\n () => E.right(true),\n ),\n );\n}\n","import { setStorageValue } from '@tma.js/toolkit';\nimport {\n miniAppsMessage,\n parseLaunchParamsQuery,\n pipeJsonToSchema,\n serializeLaunchParamsQuery,\n type LaunchParamsLike,\n} from '@tma.js/transformers';\nimport { parse } from 'valibot';\n\nimport { isIframe } from '@/env/isIframe.js';\nimport { InvalidLaunchParamsError } from '@/errors.js';\nimport { logger, postMessageImpl } from '@/globals.js';\nimport type { MethodName, MethodParams } from '@/methods/types/index.js';\n\n/**\n * Mocks the environment and imitates Telegram Mini Apps behavior.\n *\n * We usually use this function in the following cases:\n * 1. We are developing an application outside the Telegram environment and would like to imitate\n * the Telegram client in order to re-create the same communication behavior.\n * 2. We would like to intercept some Telegram Mini Apps methods' calls in order to enhance them\n * or write a custom behavior. It is extremely useful in some Telegram clients improperly handling\n * Mini Apps methods' calls and not even responding.\n *\n * Note that calling this function in Telegram web clients, the `postMessageImplementation` signal\n * value will be updated with a new one, enhancing previously set signal value to allow wrapping\n * the original `window.parent.postMessage` function. In other words, calling `mockTelegramEnv`\n * function N times, you will effectively wrap previously set implementation N times, so be\n * careful calling this function several times during a single lifecycle of the app. In case you\n * would like to avoid such kind of behavior, use the `resetPostMessage` option.\n */\nexport function mockTelegramEnv({ launchParams, onEvent, resetPostMessage }: {\n /**\n * Launch parameters to mock. They will be saved in the storage, so the SDK functions could\n * retrieve them.\n *\n * Note that this value must have `tgWebAppData` presented in a raw format as long as you will\n * need it when retrieving init data in this format. Otherwise, init data may be broken.\n */\n launchParams?:\n | (Omit<LaunchParamsLike, 'tgWebAppData'> & { tgWebAppData?: string | URLSearchParams })\n | string\n | URLSearchParams;\n /**\n * Function that will be called if a Mini Apps method call was requested by the mini app.\n *\n * It receives a Mini Apps method name along with the passed payload.\n *\n * Note that using the `next` function, in non-web environments it uses the\n * `window.TelegramWebviewProxy.postEvent` method.\n *\n * Talking about the web versions of Telegram, the value of `next` is a bit more complex - it\n * will be equal to the value stored in the `postMessageImpl` signal set previously. By default,\n * this value contains a function utilizing the `window.parent.postMessage` method.\n * @param event - event information.\n * @param next - function to call the original method used to call a Mini Apps method.\n */\n onEvent?: (\n event:\n | { [M in MethodName]: { name: M; params: MethodParams<M> } }[MethodName]\n | { name: string; params: unknown },\n next: () => void,\n ) => void;\n /**\n * Removes all previously set enhancements of the `window.parent.postMessage` function set\n * by other `mockTelegramEnv` calls.\n * @default false\n */\n resetPostMessage?: boolean;\n} = {}): void {\n if (launchParams) {\n // If launch parameters were passed, save them in the session storage, so\n // the retrieveLaunchParams function would return them.\n const launchParamsQuery =\n typeof launchParams === 'string' || launchParams instanceof URLSearchParams\n ? launchParams.toString()\n : (\n // Here we have to trick serializeLaunchParamsQuery into thinking, it serializes a valid\n // value. We are doing it because we are working with tgWebAppData presented as a\n // string, not an object as serializeLaunchParamsQuery requires.\n serializeLaunchParamsQuery({ ...launchParams, tgWebAppData: undefined })\n // Then, we just append init data.\n + (launchParams.tgWebAppData ? `&tgWebAppData=${encodeURIComponent(launchParams.tgWebAppData.toString())}` : '')\n );\n\n // Remember to check if launch params are valid.\n try {\n parseLaunchParamsQuery(launchParamsQuery);\n } catch (e) {\n throw new InvalidLaunchParamsError(launchParamsQuery, e);\n }\n setStorageValue('launchParams', launchParamsQuery);\n }\n\n // Original postEvent firstly checks if the current environment is iframe.\n // That's why we have a separate branch for this environment here too.\n if (isIframe()) {\n if (!onEvent) {\n return;\n }\n // As long as the postEvent function uses the postMessage method, we should rewire it.\n if (resetPostMessage) {\n postMessageImpl.reset();\n }\n\n const original = postMessageImpl();\n postMessageImpl.set((...args) => {\n const [message] = args;\n const next = () => {\n (original as any)(...args);\n };\n\n // Pass only Telegram Mini Apps events to the handler. All other calls should be passed\n // to the original handler (window.parent.postMessage likely).\n try {\n const data = parse(pipeJsonToSchema(miniAppsMessage()), message);\n onEvent({ name: data.eventType, params: data.eventData }, next);\n } catch {\n next();\n }\n });\n return;\n }\n\n // In all other environments, it is enough to define window.TelegramWebviewProxy.postEvent.\n const proxy = (window as any).TelegramWebviewProxy || {};\n const postEventDefaulted = proxy.postEvent || (() => undefined);\n (window as any).TelegramWebviewProxy = {\n ...proxy,\n postEvent(eventType: string, eventData: string) {\n const next = () => {\n postEventDefaulted(eventType, eventData);\n };\n onEvent\n ? onEvent({\n name: eventType,\n params: eventData ? JSON.parse(eventData) : undefined,\n }, next)\n : next();\n },\n };\n\n logger().log('Environment was mocked by the mockTelegramEnv function');\n}\n","type CaptureSameReqFn = (payload: { req_id: string }) => boolean;\n\n/**\n * Returns a function which can be used in `request` function `capture` property to capture\n * the event with the same request identifier.\n * @param reqId - request identifier.\n */\nexport function captureSameReq(reqId: string): CaptureSameReqFn {\n return ({ req_id }) => req_id === reqId;\n}\n","import { Version } from '@tma.js/types';\n\nimport {\n MethodName,\n MethodNameWithVersionedParams,\n MethodVersionedParams,\n} from '@/methods/types/index.js';\n\nconst releases = {\n '6.0': [\n 'iframe_ready',\n 'iframe_will_reload',\n 'web_app_close',\n 'web_app_data_send',\n 'web_app_expand',\n 'web_app_open_link',\n 'web_app_ready',\n 'web_app_request_theme',\n 'web_app_request_viewport',\n 'web_app_setup_main_button',\n 'web_app_setup_closing_behavior',\n ],\n 6.1: [\n 'web_app_open_tg_link',\n 'web_app_open_invoice',\n 'web_app_setup_back_button',\n 'web_app_set_background_color',\n 'web_app_set_header_color',\n 'web_app_trigger_haptic_feedback',\n ],\n 6.2: ['web_app_open_popup'],\n 6.4: [\n 'web_app_close_scan_qr_popup',\n 'web_app_open_scan_qr_popup',\n 'web_app_read_text_from_clipboard',\n { method: 'web_app_open_link', param: 'try_instant_view' },\n ],\n 6.7: ['web_app_switch_inline_query'],\n 6.9: [\n 'web_app_invoke_custom_method',\n 'web_app_request_write_access',\n 'web_app_request_phone',\n { method: 'web_app_set_header_color', param: 'color' },\n ],\n '6.10': ['web_app_setup_settings_button'],\n 7.2: [\n 'web_app_biometry_get_info',\n 'web_app_biometry_open_settings',\n 'web_app_biometry_request_access',\n 'web_app_biometry_request_auth',\n 'web_app_biometry_update_token',\n ],\n 7.6: [\n { method: 'web_app_open_link', param: 'try_browser' },\n { method: 'web_app_close', param: 'return_back' },\n ],\n 7.7: ['web_app_setup_swipe_behavior'],\n 7.8: ['web_app_share_to_story'],\n '7.10': [\n 'web_app_setup_secondary_button',\n 'web_app_set_bottom_bar_color',\n { method: 'web_app_setup_main_button', param: 'has_shine_effect' },\n ],\n '8.0': [\n 'web_app_request_safe_area',\n 'web_app_request_content_safe_area',\n 'web_app_request_fullscreen',\n 'web_app_exit_fullscreen',\n 'web_app_set_emoji_status',\n 'web_app_add_to_home_screen',\n 'web_app_check_home_screen',\n 'web_app_request_emoji_status_access',\n 'web_app_check_location',\n 'web_app_open_location_settings',\n 'web_app_request_file_download',\n 'web_app_request_location',\n 'web_app_send_prepared_message',\n 'web_app_start_accelerometer',\n 'web_app_start_device_orientation',\n 'web_app_start_gyroscope',\n 'web_app_stop_accelerometer',\n 'web_app_stop_device_orientation',\n 'web_app_stop_gyroscope',\n 'web_app_toggle_orientation_lock',\n ],\n '9.0': [\n 'web_app_device_storage_clear',\n 'web_app_device_storage_get_key',\n 'web_app_device_storage_save_key',\n 'web_app_secure_storage_clear',\n 'web_app_secure_storage_get_key',\n 'web_app_secure_storage_restore_key',\n 'web_app_secure_storage_save_key',\n ],\n 9.1: ['web_app_hide_keyboard'],\n 9.5: [\n { method: 'web_app_setup_main_button', param: 'icon_custom_emoji_id' },\n { method: 'web_app_setup_secondary_button', param: 'icon_custom_emoji_id' },\n ],\n};\n\n/**\n * @returns Version of the specified method parameter release. Returns `null`\n * if passed method or parameter are unknown.\n * @param method - method name\n * @param param - method parameter\n */\nexport function getReleaseVersion<M extends MethodNameWithVersionedParams>(\n method: M,\n param: MethodVersionedParams<M>,\n): Version | null;\n\n/**\n * @returns Version of the specified method release. Returns `null`\n * if passed method is unknown.\n * @param method - method name.\n */\nexport function getReleaseVersion(method: MethodName): Version | null;\nexport function getReleaseVersion(method: MethodName, param?: string): Version | null {\n const versions = Object.keys(releases) as (`${keyof typeof releases}`)[];\n return versions.find(version => {\n return releases[version].some(item => {\n if (param) {\n return typeof item === 'object'\n && item.method === method\n && item.param === param;\n }\n return item === method;\n });\n }) || null;\n}\n","import type { Version } from '@tma.js/types';\n\nfunction parts(a: Version): number[] {\n return a.split('.').map(Number);\n}\n\n/**\n * @param a - first version.\n * @param b - second version.\n * @returns\n * - `1` if the version \"a\" is greater than \"b\".\n * - `0` the version \"a\" is equal to \"b\".\n * - `-1` the version \"a\" is lower than \"b\".\n */\nexport function compareVersions(a: Version, b: Version): number {\n const aParts = parts(a);\n const bParts = parts(b);\n const len = Math.max(aParts.length, bParts.length);\n\n // Iterate over each part of versions and compare them. In case, part is\n // missing, assume its value is equal to 0.\n for (let i = 0; i < len; i += 1) {\n const aVal = aParts[i] || 0;\n const bVal = bParts[i] || 0;\n\n if (aVal === bVal) {\n continue;\n }\n return aVal > bVal ? 1 : -1;\n }\n return 0;\n}\n","import type { Version } from '@tma.js/types';\n\nimport { getReleaseVersion } from '@/methods/getReleaseVersion.js';\nimport type {\n MethodName,\n MethodNameWithVersionedParams,\n MethodVersionedParams,\n} from '@/methods/types/index.js';\nimport { compareVersions } from '@/utils/compareVersions.js';\n\n/**\n * Returns true in case, passed parameter in specified method is supported.\n * @param method - method name\n * @param param - method parameter\n * @param inVersion - platform version.\n */\nexport function supports<M extends MethodNameWithVersionedParams>(\n method: M,\n param: MethodVersionedParams<M>,\n inVersion: Version,\n): boolean;\n\n/**\n * Returns true in case, specified method is supported in a passed version.\n * @param method - method name.\n * @param inVersion - platform version.\n */\nexport function supports(method: MethodName, inVersion: Version): boolean;\n\nexport function supports(\n method: MethodName,\n paramOrVersion: Version | string,\n inVersion?: string,\n): boolean {\n const version = inVersion\n ? getReleaseVersion(\n method as MethodNameWithVersionedParams,\n paramOrVersion as MethodVersionedParams<MethodNameWithVersionedParams>,\n )\n : getReleaseVersion(method);\n return version\n ? compareVersions(version, inVersion || paramOrVersion) <= 0\n : false;\n}\n","import type { Version } from '@tma.js/types';\nimport { any, is, looseObject } from 'valibot';\n\nimport { MethodParameterUnsupportedError, MethodUnsupportedError } from '@/errors.js';\nimport { logger } from '@/globals.js';\nimport { type PostEventFn, postEvent } from '@/methods/postEvent.js';\nimport { supports } from '@/methods/supports.js';\nimport type {\n MethodName,\n MethodNameWithVersionedParams,\n MethodVersionedParams,\n} from '@/methods/types/index.js';\n\nexport type OnUnsupportedFn = (\n data: { version: Version } & (\n | { method: MethodName }\n | {\n [M in MethodNameWithVersionedParams]: {\n method: M;\n param: MethodVersionedParams<M>;\n };\n }[MethodNameWithVersionedParams]),\n) => void;\n\nexport type CreatePostEventMode = 'strict' | 'non-strict';\n\n/**\n * Creates a function that checks if the specified method and parameters are supported.\n *\n * If the method or parameters are unsupported, the `onUnsupported` function will be called.\n *\n * If `strict` or `non-strict` value was passed as the second argument, the function\n * will create its own `onUnsupported` function with behavior depending on the value passed.\n *\n * - Passing `strict` will make the function to throw a `MethodParameterUnsupportedError`\n * or a `MethodUnsupportedError` error.\n * - Passing `non-strict` will just warn you about something being unsupported.\n *\n * @param version - Telegram Mini Apps version.\n * @param onUnsupportedOrMode - function or strict mode. Default: `strict`\n */\nexport function createPostEvent(\n version: Version,\n onUnsupportedOrMode: OnUnsupportedFn | CreatePostEventMode = 'strict',\n): PostEventFn {\n const onUnsupported: OnUnsupportedFn = typeof onUnsupportedOrMode === 'function'\n ? onUnsupportedOrMode\n : data => {\n const { method, version } = data;\n const error = 'param' in data\n ? new MethodParameterUnsupportedError(method, data.param, version)\n : new MethodUnsupportedError(method, version);\n\n if (onUnsupportedOrMode === 'strict') {\n throw error;\n }\n return logger().forceWarn(error.message);\n };\n\n return ((method: any, params: any) => {\n // Firstly, check if the method is supported.\n if (!supports(method, version)) {\n return onUnsupported({ version, method });\n }\n\n // Method could use parameters, which are supported only in specific versions of Mini Apps.\n // We are validating only those parameters, which are not backward compatible.\n if (\n method === 'web_app_set_header_color'\n && is(looseObject({ color: any() }), params)\n && !supports(method, 'color', version)\n ) {\n return onUnsupported({ version, method, param: 'color' });\n }\n if (\n (method === 'web_app_setup_main_button' || method === 'web_app_setup_secondary_button')\n && is(looseObject({ icon_custom_emoji_id: any() }), params)\n && !supports(method, 'icon_custom_emoji_id', version)\n ) {\n return onUnsupported({ version, method, param: 'icon_custom_emoji_id' });\n }\n\n return postEvent(method, params);\n }) as PostEventFn;\n}\n","import { BetterPromise } from 'better-promises';\nimport { taskEither as TE, function as fn } from 'fp-ts';\n\nimport { InvokeCustomMethodFailedError } from '@/errors.js';\nimport { captureSameReq } from '@/methods/captureSameReq.js';\nimport type { CustomMethodName, CustomMethodParams } from '@/methods/types/index.js';\n\nimport {\n request2Fp,\n type Request2Error,\n type Request2FpOptions,\n type Request2Options,\n} from './request2.js';\n\nexport type InvokeCustomMethodError = Request2Error | InvokeCustomMethodFailedError;\n\nexport type InvokeCustomMethodOptions = Omit<Request2Options<'custom_method_invoked'>, 'capture'>;\nexport type InvokeCustomMethodFn = typeof invokeCustomMethod;\n\nexport type InvokeCustomMethodFpOptions = Omit<Request2FpOptions<'custom_method_invoked'>, 'capture'>;\nexport type InvokeCustomMethodFpFn = typeof invokeCustomMethodFp;\n\n/**\n * Invokes known custom method. Returns method execution result.\n * @param method - method name.\n * @param params - method parameters.\n * @param requestId - request identifier.\n * @param options - additional options.\n */\nexport function invokeCustomMethodFp<M extends CustomMethodName>(\n method: M,\n params: CustomMethodParams<M>,\n requestId: string,\n options?: InvokeCustomMethodFpOptions,\n): TE.TaskEither<InvokeCustomMethodError, unknown>;\n\n/**\n * Invokes unknown custom method. Returns method execution result.\n * @param method - method name.\n * @param params - method parameters.\n * @param requestId - request identifier.\n * @param options - additional options.\n */\nexport function invokeCustomMethodFp(\n method: string,\n params: object,\n requestId: string,\n options?: InvokeCustomMethodFpOptions,\n): TE.TaskEither<Request2Error, unknown>;\n\nexport function invokeCustomMethodFp(\n method: string,\n params: object,\n requestId: string,\n options?: InvokeCustomMethodFpOptions,\n): TE.TaskEither<InvokeCustomMethodError, unknown> {\n return fn.pipe(\n request2Fp('web_app_invoke_custom_method', 'custom_method_invoked', {\n ...options || {},\n params: { method, params, req_id: requestId },\n capture: captureSameReq(requestId),\n }),\n TE.chain(({ result, error }) => {\n return error\n ? TE.left(new InvokeCustomMethodFailedError(error))\n : TE.right(result);\n }),\n );\n}\n\n/**\n * @see invokeCustomMethodFp\n */\nexport function invokeCustomMethod<M extends CustomMethodName>(\n method: M,\n params: CustomMethodParams<M>,\n requestId: string,\n options?: InvokeCustomMethodOptions,\n): BetterPromise<unknown>;\n\n/**\n * @see invokeCustomMethodFp\n */\nexport function invokeCustomMethod(\n method: string,\n params: object,\n requestId: string,\n options?: InvokeCustomMethodOptions,\n): BetterPromise<unknown>;\n\nexport function invokeCustomMethod(\n method: string,\n params: object,\n requestId: string,\n options?: InvokeCustomMethodOptions,\n): BetterPromise<unknown> {\n return BetterPromise.fn(() => {\n return fn.pipe(\n // @ts-expect-error TypeScript is unable to determine required override.\n invokeCustomMethodFp(method, params, requestId, options),\n TE.match(\n error => {\n throw error;\n },\n result => result,\n ),\n )();\n });\n}\n","import { signal } from '@tma.js/signals';\nimport {\n createCbCollector,\n throwifyAnyEither,\n type If,\n type IsNever,\n BetterTaskEither,\n} from '@tma.js/toolkit';\nimport {\n BetterPromise,\n type BetterPromiseOptions,\n type TimeoutError,\n} from 'better-promises';\nimport { either as E, taskEither as TE, function as fn } from 'fp-ts';\n\nimport { on } from '@/events/emitter.js';\nimport type { EventName, EventPayload } from '@/events/types/index.js';\nimport {\n postEventFp,\n type PostEventError,\n type PostEventFn,\n type PostEventFpFn,\n} from '@/methods/postEvent.js';\nimport type {\n MethodName,\n MethodNameWithOptionalParams,\n MethodNameWithoutParams,\n MethodNameWithRequiredParams,\n MethodParams,\n} from '@/methods/types/index.js';\n\ntype AnyEventName = EventName | EventName[];\n\nexport type RequestError = PostEventError | TimeoutError;\n\n/**\n * @example\n * { event: 'scan_qr_closed' }\n * @example\n * {\n * event: 'popup_closed',\n * payload: { button_id: 'ok' }\n * }\n */\nexport type RequestCaptureFnEventsPayload<E extends EventName[]> =\n E extends (infer U extends EventName)[]\n ? {\n [K in U]: If<\n IsNever<EventPayload<K>>,\n { event: K },\n { event: K; payload: EventPayload<K> }\n >\n }[U]\n : never;\n\nexport type RequestCaptureEventsFn<E extends EventName[]> = (\n payload: RequestCaptureFnEventsPayload<E>,\n) => boolean;\n\nexport type RequestCaptureEventFn<E extends EventName> = If<\n IsNever<EventPayload<E>>,\n () => boolean,\n (payload: EventPayload<E>) => boolean\n>;\n\nexport type RequestCaptureFn<E extends AnyEventName> = E extends EventName[]\n ? RequestCaptureEventsFn<E>\n : E extends EventName\n ? RequestCaptureEventFn<E>\n : never;\n\nexport interface RequestOptions<E extends AnyEventName> extends Omit<RequestFpOptions<E>, 'postEvent'> {\n /**\n * Custom function to call mini apps methods.\n */\n postEvent?: PostEventFn;\n}\n\nexport type RequestResult<E extends AnyEventName> =\n E extends (infer U extends EventName)[]\n ? U extends infer K extends EventName\n ? If<IsNever<EventPayload<K>>, undefined, EventPayload<K>>\n : never\n : E extends EventName\n ? If<IsNever<EventPayload<E>>, undefined, EventPayload<E>>\n : never;\n\nexport interface RequestFpOptions<E extends AnyEventName> extends Pick<\n BetterPromiseOptions,\n 'abortSignal' | 'timeout'\n> {\n /**\n * A function that should return true if the event should be captured.\n * The first compatible request will be captured if this property is omitted.\n */\n capture?: RequestCaptureFn<E>;\n /**\n * A custom function to call mini apps methods.\n */\n postEvent?: PostEventFpFn;\n}\n\nexport type RequestFn = typeof request;\nexport type RequestFpFn = typeof requestFp;\n\n/**\n * Calls a method waiting for the specified event(-s) to occur.\n * @param method - method name.\n * @param eventOrEvents - tracked event or events.\n * @param options - additional options.\n * @deprecated To be removed in the next major update. Use `request2fp` instead, it provides\n * a proper way of handling multiple events.\n */\nexport function requestFp<\n M extends MethodNameWithRequiredParams,\n E extends AnyEventName,\n AbortError = never,\n>(\n method: M,\n eventOrEvents: E,\n options: RequestFpOptions<E> & { params: MethodParams<M> },\n): TE.TaskEither<RequestError | AbortError, RequestResult<E>>;\n\n/**\n * Calls a method waiting for the specified event(-s) to occur.\n * @param method - method name.\n * @param eventOrEvents - tracked event or events.\n * @param options - additional options.\n * @deprecated To be removed in the next major update. Use `request2fp` instead, it provides\n * a proper way of handling multiple events.\n */\nexport function requestFp<\n M extends MethodNameWithOptionalParams,\n E extends AnyEventName,\n AbortError = never,\n>(\n method: M,\n eventOrEvents: E,\n options?: RequestFpOptions<E> & { params?: MethodParams<M> },\n): TE.TaskEither<RequestError | AbortError, RequestResult<E>>;\n\n/**\n * Calls a method waiting for the specified event(-s) to occur.\n * @param method - method name.\n * @param eventOrEvents - tracked event or events.\n * @param options - additional options.\n * @deprecated To be removed in the next major update. Use `request2fp` instead, it provides\n * a proper way of handling multiple events.\n */\nexport function requestFp<\n M extends MethodNameWithoutParams,\n E extends AnyEventName,\n AbortError = never,\n>(\n method: M,\n eventOrEvents: E,\n options?: RequestFpOptions<E>,\n): TE.TaskEither<RequestError | AbortError, RequestResult<E>>;\n\nexport function requestFp<\n M extends MethodName,\n E extends AnyEventName,\n AbortError = never,\n>(\n method: M,\n eventOrEvents: E,\n options: RequestFpOptions<E> & { params?: MethodParams<M> } = {},\n): TE.TaskEither<RequestError | AbortError, RequestResult<E>> {\n const {\n // If no capture function was passed, we capture the first compatible event.\n capture = () => true,\n postEvent = postEventFp,\n } = options;\n\n const result = signal<undefined | [RequestResult<E>]>();\n const [addCleanup, cleanup] = createCbCollector();\n // Iterate over all the tracked events and add a listener, checking if the event should be\n // captured.\n (Array.isArray(eventOrEvents) ? eventOrEvents : [eventOrEvents]).forEach(event => {\n // Each event listener waits for the event to occur.\n // Then, if the capture function was passed, we should check if the event should\n // be captured. If the function is omitted, we instantly capture the event.\n addCleanup(\n on(event, payload => {\n if (\n Array.isArray(eventOrEvents)\n ? (capture as RequestCaptureEventsFn<EventName[]>)({ event, payload })\n : (capture as RequestCaptureEventFn<EventName>)(payload)\n ) {\n result.set([payload as RequestResult<E>]);\n }\n }),\n );\n });\n const withCleanup = <T>(value: T): T => {\n cleanup();\n return value;\n };\n\n return fn.pipe(\n async () => postEvent(method as any, (options as any).params),\n TE.chainW(() => {\n return BetterTaskEither<AbortError, RequestResult<E>>((resolve, _, context) => {\n // When creating this BetterTaskEither, we could already have a value stored in\n // the result signal. For example, when tracked events were generated via emitEvent in\n // mockTelegramEnv.onEvent.\n const data = result();\n if (data) {\n return resolve(data[0]);\n }\n\n const listener = (data: [RequestResult<E>] | undefined) => {\n if (data) {\n resolve(data[0]);\n }\n };\n const unsub = () => {\n result.unsub(listener);\n };\n result.sub(listener);\n context.on('finalized', unsub);\n }, options);\n }),\n TE.mapBoth(withCleanup, withCleanup),\n );\n}\n\n/**\n * @see requestFp\n * @deprecated To be removed in the next major update. Use `request2` instead, it provides\n * a proper way of handling multiple events.\n */\nexport function request<M extends MethodNameWithRequiredParams, E extends AnyEventName>(\n method: M,\n eventOrEvents: E,\n options: RequestOptions<E> & { params: MethodParams<M> },\n): BetterPromise<RequestResult<E>>;\n\n/**\n * @see requestFp\n * @deprecated To be removed in the next major update. Use `request2` instead, it provides\n * a proper way of handling multiple events.\n */\nexport function request<M extends MethodNameWithOptionalParams, E extends AnyEventName>(\n method: M,\n eventOrEvents: E,\n options?: RequestOptions<E> & { params?: MethodParams<M> },\n): BetterPromise<RequestResult<E>>;\n\n/**\n * @see requestFp\n * @deprecated To be removed in the next major update. Use `request2` instead, it provides\n * a proper way of handling multiple events.\n */\nexport function request<M extends MethodNameWithoutParams, E extends AnyEventName>(\n method: M,\n eventOrEvents: E,\n options?: RequestOptions<E>,\n): BetterPromise<RequestResult<E>>;\n\nexport function request<M extends MethodName, E extends AnyEventName>(\n method: M,\n eventOrEvents: E,\n options?: RequestOptions<E> & { params?: MethodParams<M> },\n): BetterPromise<RequestResult<E>> {\n const { postEvent } = options || {};\n\n return throwifyAnyEither(\n // @ts-expect-error TypeScript will not be able to handle our overrides here.\n requestFp(method, eventOrEvents, {\n ...options,\n postEvent: postEvent\n ? (...args: any[]) => {\n try {\n // @ts-expect-error TypeScript will not be able to handle our overrides here.\n postEvent(...args);\n return E.right(undefined);\n } catch (e) {\n return E.left(e);\n }\n }\n : postEventFp,\n }),\n );\n}\n","/**\n * Applies polyfills required for stable work of the package:\n * - `Object.hasOwn` - used by `valibot`\n */\nexport function applyPolyfills(): void {\n if (!Object.hasOwn) {\n Object.hasOwn = function(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n };\n }\n}\n","import { throwifyFpFn } from '@tma.js/toolkit';\nimport { either as E } from 'fp-ts';\n\nexport type DecodeBase64UrlError = DOMException;\n\n/**\n * Decodes a base-64-url ASCII string.\n * @param value - the value to decode.\n * @see Learn more about base64url:\n * https://herongyang.com/Encoding/Base64URL-Encoding-Algorithm.html\n * @see Source:\n * https://developer.mozilla.org/ru/docs/Glossary/Base64#solution_1_–_escaping_the_string_before_encoding_it\n */\nexport function decodeBase64UrlFp(value: string): E.Either<DecodeBase64UrlError, string> {\n return E.tryCatch(() => {\n return decodeURIComponent(\n atob(\n value\n .replace(/-/g, '+')\n .replace(/_/g, '/'),\n )\n .split('')\n .map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))\n .join(''),\n );\n }, e => e as DOMException);\n}\n\n/**\n * @see decodeBase64UrlFp\n */\nexport const decodeBase64Url = throwifyFpFn(decodeBase64UrlFp);\n\n/**\n * Creates a base-64-url encoded ASCII string from the passed value.\n * @param value - the value to encode.\n * @see Learn more about base64url:\n * https://herongyang.com/Encoding/Base64URL-Encoding-Algorithm.html\n * @see Source:\n * https://developer.mozilla.org/ru/docs/Glossary/Base64#solution_1_–_escaping_the_string_before_encoding_it\n */\nexport function encodeBase64Url(value: string): string {\n // first we use encodeURIComponent to get percent-encoded UTF-8,\n // then we convert the percent encodings into raw bytes which\n // can be fed into btoa.\n return btoa(\n encodeURIComponent(value).replace(/%([0-9A-F]{2})/g, (_, p1) => {\n return String.fromCharCode(parseInt(`0x${p1}`));\n }),\n )\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=/g, '');\n}\n","import { throwifyFpFn, throwifyAnyEither } from '@tma.js/toolkit';\nimport { either as E, function as fn, json as J } from 'fp-ts';\n\nimport { encodeBase64Url, type DecodeBase64UrlError, decodeBase64UrlFp } from '@/base64-url.js';\n\n/**\n * Creates a safe start parameter value. If the value is not a string, the\n * function applies JSON.stringify to it, so make sure you are not passing an\n * object with circular references.\n *\n * @param value - value to create start parameter from.\n * @see Learn more about start parameter:\n * https://docs.telegram-mini-apps.com/platform/start-parameter\n */\nexport function createStartParamFp(value: unknown): E.Either<Error, string> {\n const b64 = encodeBase64Url(typeof value === 'string' ? value : JSON.stringify(value));\n return b64.length > 512\n ? E.left(new Error('Value is too long for start parameter'))\n : E.right(b64);\n}\n\n/**\n * @see createStartParamFp\n */\nexport const createStartParam = throwifyFpFn(createStartParamFp);\n\n/**\n * @see decodeStartParamFp\n */\nexport function decodeStartParam<T>(value: string, parse: (value: string) => T): T;\n/**\n * @see decodeStartParamFp\n */\nexport function decodeStartParam(value: string, as: 'json'): J.Json;\n/**\n * @see decodeStartParamFp\n */\nexport function decodeStartParam(value: string): string;\nexport function decodeStartParam<T>(\n value: string,\n arg2?: 'json' | ((value: string) => T),\n): string | unknown | T {\n return throwifyAnyEither(\n decodeStartParamFp(\n value,\n // @ts-expect-error TypeScript is unable to detect a correct override.\n typeof arg2 === 'function'\n ? (value: string) => E.tryCatch(() => arg2(value), e => e)\n : arg2,\n ),\n );\n}\n\n/**\n * Decodes a start parameter using a custom parser.\n * @param value - a start parameter value.\n * @param parse - a custom value parser.\n */\nexport function decodeStartParamFp<L, R>(\n value: string,\n parse: (value: string) => E.Either<L, R>,\n): E.Either<L | DecodeBase64UrlError, R>;\n/**\n * Decodes a start parameter assuming that the result is a JSON value.\n * @param value - a start parameter value.\n * @param as - result kind.\n */\nexport function decodeStartParamFp(\n value: string,\n as: 'json',\n): E.Either<SyntaxError | DecodeBase64UrlError, J.Json>;\n/**\n * Decodes a start parameter and returns its decoded representation.\n * @param value - a value to decode.\n */\nexport function decodeStartParamFp(value: string): E.Either<DecodeBase64UrlError, string>;\nexport function decodeStartParamFp<L, R>(\n value: string,\n arg2?: 'json' | ((value: string) => E.Either<L, R>),\n): E.Either<DecodeBase64UrlError | SyntaxError | L, R | string | J.Json> {\n return fn.pipe(\n decodeBase64UrlFp(value),\n E.chain<DecodeBase64UrlError | SyntaxError | L, string, R | string | J.Json>(decoded => {\n if (!arg2) {\n return E.right(decoded);\n }\n if (typeof arg2 === 'function') {\n return arg2(decoded);\n }\n return J.parse(decoded) as E.Either<SyntaxError, J.Json>;\n }),\n );\n}\n\n/**\n * @returns True if the passed value is safe to be used to create a start parameter value from it.\n * If true is returned, the value can be safely passed to the `createStartParam` function.\n * @param value - value to check.\n * @see createStartParam\n */\nexport function isSafeToCreateStartParam(value: string): boolean {\n return encodeBase64Url(value).length <= 512;\n}\n"],"names":["hasWebviewProxy","value","v","isIframe","MethodUnsupportedError","errorClass","method","version","MethodParameterUnsupportedError","param","LaunchParamsRetrieveError","errorClassWithData","errors","source","error","InvalidLaunchParamsError","launchParams","cause","UnknownEnvError","InvokeCustomMethodFailedError","SESSION_STORAGE_KEY","retrieveLpFromUrl","urlString","retrieveLaunchParamsFp","fn","retrieveRawLaunchParamsFp","E","parseLaunchParamsQueryFp","retrieveLaunchParams","throwifyFpFn","retrieveRawInitDataFp","raw","O","retrieveRawInitData","err","retrieve","navigationEntry","getStorageValue","maybeError","setStorageValue","retrieveRawLaunchParams","createEmitter","onFirst","onEmpty","eventToHandlersMap","emitter","mitt","off","event","handler","once","handlersMap","handlers","index","item","prevSize","cleanup","internalHandler","args","emitEvent","eventType","eventData","_debug","signal","_targetOrigin","onEventReceived","logger","debug","computed","setDebug","on","targetOrigin","setTargetOrigin","origin","postMessageImpl","createLogger","resetGlobals","offAll","s","defineFnComposer","obj","propertyName","initialFn","assignedFunctions","property","callAssignedFunctions","unwrappableCallAssignedFunctions","poolSize","defineStaticProperty","defineProxiedProperty","defineMergeableProperty","prop","objKey","objValue","get","set","transformers","looseObject","string","nullish","optional","unknown","number","boolean","themeParams","windowMessageListener","message","parse","pipeJsonToSchema","miniAppsMessage","schema","data","emit","wnd","path","cursor","receiveEventOwner","receiveEvent","postMessage","postEvent","fpFn","postEventFp","w","is","request2Fp","eventOrEvents","options","capture","result","addCleanup","createCbCollector","payload","isEventsArray","withCleanup","TE","BetterTaskEither","resolve","_","context","listener","unsub","request2","throwifyAnyEither","e","isTMA","type","monad","isTMAFp","BetterPromise","hasProxy","timeout","TimeoutError","mockTelegramEnv","onEvent","resetPostMessage","launchParamsQuery","serializeLaunchParamsQuery","parseLaunchParamsQuery","original","next","proxy","postEventDefaulted","captureSameReq","reqId","req_id","releases","getReleaseVersion","parts","a","compareVersions","b","aParts","bParts","len","i","aVal","bVal","supports","paramOrVersion","inVersion","createPostEvent","onUnsupportedOrMode","onUnsupported","params","any","invokeCustomMethodFp","requestId","invokeCustomMethod","requestFp","request","applyPolyfills","decodeBase64UrlFp","c","decodeBase64Url","encodeBase64Url","p1","createStartParamFp","b64","createStartParam","decodeStartParam","arg2","decodeStartParamFp","decoded","J","isSafeToCreateStartParam"],"mappings":";;;;;;;;;;;AAOO,SAASA,GAAmBC,GAIjC;AACO,SAAA,OAAOA,KAAU,YAAY,CAAC,CAACA,KAAS,CAAC,MAAM,QAAQA,CAAK,KAAKC,EAAE;AAAA,IACxEA,EAAE,YAAY,EAAE,sBAAsBA,EAAE,YAAY,EAAE,WAAWA,EAAE,SAAW,EAAA,CAAC,GAAG;AAAA,IAClF,EAAE,sBAAuBD,EAAkC,qBAAqB;AAAA,EAClF;AACF;ACZO,SAASE,KAAoB;AAC9B,MAAA;AACK,WAAA,OAAO,SAAS,OAAO;AAAA,EAAA,QACxB;AACC,WAAA;AAAA,EAAA;AAEX;ACPO,MAAMC,YAEX,gBAAAC,EAAA;AAAA,EACA,MAAM;AAAA,EACN,OAAO,CAACC,GAAQC,MAAY;AAAA,IAC1B,WAAWD,CAAM,yCAAyCC,CAAO;AAAA,EAAA;AAErE,CAAC,GAAE;AACH;AAEO,MAAMC,YAEX,gBAAAH,EAAA;AAAA,EACA,MAAM;AAAA,EACN,OAAO,CAACC,GAAQG,GAAOF,MAAY;AAAA,IACjC,cAAcE,CAAK,SAASH,CAAM,gDAAgDC,CAAO;AAAA,EAAA;AAE7F,CAAC,GAAE;AACH;AAEO,MAAMG,YAGX,gBAAAC,GAAA;AAAA,EACA,MAAM;AAAA,EACN,MAAM,CAAWC,OAAA,EAAE,QAAAA;EACnB,OAAO,CAAUA,MAAA;AAAA,IACf;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,GAAGA,EAAO,IAAI,CAAC,EAAE,QAAAC,GAAQ,OAAAC,QAChB,WAAWD,CAAM,MAAMC,aAAiB,QAAQA,EAAM,UAAU,OAAOA,CAAK,CAAC,EACrF;AAAA,IACH,EAAE,KAAK;AAAA,CAAI;AAAA,EAAA;AAEf,CAAC,GAAE;AACH;AAEO,MAAMC,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AAOoM,EAAI,SAAS,MAChB3K,EAAE,KAAK,IAAI,MAAM,uCAAuC,CAAC,IACzDA,EAAE,MAAM2K,CAAG;AACjB;AAKa,MAAAC,KAAmBzK,EAAauK,EAAkB;AAc/C,SAAAG,GACdtM,GACAuM,GACsB;AACf,SAAA1D;AAAA,IACL2D;AAAA,MACExM;AAAA;AAAA,MAEA,OAAOuM,KAAS,aACZ,CAACvM,MAAkByB,EAAE,SAAS,MAAM8K,EAAKvM,CAAK,GAAG,CAAA8I,MAAKA,CAAC,IACvDyD;AAAA,IAAA;AAAA,EAER;AACF;AAyBgB,SAAAC,GACdxM,GACAuM,GACuE;AACvE,SAAOhL,EAAG;AAAA,IACRuK,GAAkB9L,CAAK;AAAA,IACvByB,EAAE,MAA2E,CAAWgL,MACjFF,IAGD,OAAOA,KAAS,aACXA,EAAKE,CAAO,IAEdC,GAAE,MAAMD,CAAO,IALbhL,EAAE,MAAMgL,CAAO,CAMzB;AAAA,EACH;AACF;AAQO,SAASE,GAAyB3M,GAAwB;AACxD,SAAAiM,GAAgBjM,CAAK,EAAE,UAAU;AAC1C;"}
1
+ {"version":3,"file":"index.js","sources":["../src/errors.ts","../src/result.ts","../src/theme-params.ts","../src/launch-params.ts","../src/logger.ts","../src/window-hooks.ts","../src/events.ts","../src/post-event.ts","../src/request.ts","../src/env.ts","../src/invokeCustomMethod.ts","../src/mockTelegramEnv.ts","../src/start-param.ts","../src/versions.ts"],"sourcesContent":["import { errorClass, errorClassWithData } from 'error-kid';\n\nimport type { Version } from './types/index.js';\n\n/**\n * Thrown when the current environment provides no known way to communicate with the Telegram\n * client. Usually, it means the app was opened outside Telegram.\n */\nexport class UnknownEnvError extends /* @__PURE__ */ errorClass({\n name: 'UnknownEnvError',\n message: 'Unable to determine the way to communicate with the Telegram client',\n}) {\n}\n\n/**\n * Thrown when a method is not supported in the current Mini Apps version.\n */\nexport class MethodUnsupportedError extends /* @__PURE__ */ errorClassWithData({\n name: 'MethodUnsupportedError',\n data: (method: string, version: Version) => ({ method, version }),\n message: (method: string, version: Version) => {\n return `Method \"${method}\" is unsupported in Mini Apps version ${version}`;\n },\n}) {\n}\n\n/**\n * Thrown when a method parameter is not supported in the current Mini Apps version.\n */\nexport class MethodParameterUnsupportedError extends /* @__PURE__ */ errorClassWithData({\n name: 'MethodParameterUnsupportedError',\n data: (method: string, param: string, version: Version) => ({ method, param, version }),\n message: (method: string, param: string, version: Version) => {\n return `Parameter \"${param}\" of \"${method}\" method is unsupported in Mini Apps version ${version}`;\n },\n}) {\n}\n\n/**\n * Thrown when launch parameters can't be found in any known source.\n */\nexport class LaunchParamsRetrieveError extends /* @__PURE__ */ errorClassWithData({\n name: 'LaunchParamsRetrieveError',\n data: (errors: { source: string; error: unknown }[]) => ({ errors }),\n message: (errors: { source: string; error: unknown }[]) => [\n 'Unable to retrieve launch parameters from any known source. Perhaps, you have opened your app outside Telegram?',\n '',\n 'Collected errors:',\n ...errors.map(({ source, error }) => {\n return `- ${source}: ${error instanceof Error ? error.message : String(error)}`;\n }),\n ].join('\\n'),\n}) {\n}\n\n/**\n * Thrown when a value doesn't represent valid launch parameters.\n */\nexport class InvalidLaunchParamsError extends /* @__PURE__ */ errorClassWithData({\n name: 'InvalidLaunchParamsError',\n message: (value: string) => `Invalid launch parameters: ${value}`,\n cause: (_value: string, cause?: unknown) => cause,\n data: (value: string) => ({ value }),\n}) {\n}\n\n/**\n * Thrown when a custom method invocation completed with an error.\n */\nexport class InvokeCustomMethodFailedError extends /* @__PURE__ */ errorClassWithData({\n name: 'InvokeCustomMethodFailedError',\n data: (error: string) => ({ error }),\n message: (error: string) => `Custom method invocation failed: ${error}`,\n}) {\n}\n\n/**\n * Thrown when an operation didn't complete in time.\n */\nexport class TimeoutError extends /* @__PURE__ */ errorClassWithData({\n name: 'TimeoutError',\n data: (timeout: number) => ({ timeout }),\n message: (timeout: number) => `Timeout reached: ${timeout}ms`,\n}) {\n}\n\n/**\n * Thrown when a value is too long to be used as a start parameter.\n */\nexport class StartParamTooLongError extends /* @__PURE__ */ errorClassWithData({\n name: 'StartParamTooLongError',\n data: (length: number) => ({ length }),\n message: (length: number) => {\n return `Encoded start parameter length is ${length}, but the maximum allowed is 512`;\n },\n}) {\n}\n","/**\n * Result of an operation which can fail with one of the known errors. Unlike a thrown error,\n * the error type here is checked by the compiler.\n */\nexport type Result<E, T> = { ok: false; error: E } | { ok: true; data: T };\n\n/**\n * @returns A successful result.\n * @param data - result data.\n */\nexport function ok<T>(data: T): { ok: true; data: T } {\n return { ok: true, data };\n}\n\n/**\n * @returns A failed result.\n * @param error - result error.\n */\nexport function err<E>(error: E): { ok: false; error: E } {\n return { ok: false, error };\n}\n\n/**\n * @returns Result data.\n * @param result - result to unwrap.\n * @throws The result error, if the result is failed.\n */\nexport function unwrap<E extends Error, T>(result: Result<E, T>): T {\n if (!result.ok) {\n throw result.error;\n }\n return result.data;\n}\n\n/**\n * Creates a throwing version of a function returning a result. The created function accepts\n * the same arguments and returns the result data, or throws the result error.\n *\n * Generic functions lose their type parameters when wrapped, so write their throwing versions\n * manually using `unwrap`.\n * @param fn - function returning a result, or a promise of it.\n * @example\n * export const createStartParam = throwing(safeCreateStartParam);\n */\nexport function throwing<A extends unknown[], E extends Error, T>(\n fn: (...args: A) => Promise<Result<E, T>>,\n): (...args: A) => Promise<T>;\nexport function throwing<A extends unknown[], E extends Error, T>(\n fn: (...args: A) => Result<E, T>,\n): (...args: A) => T;\nexport function throwing(\n fn: (...args: unknown[]) => Result<Error, unknown> | Promise<Result<Error, unknown>>,\n): (...args: unknown[]) => unknown {\n return (...args) => {\n const result = fn(...args);\n return result instanceof Promise ? result.then(unwrap) : unwrap(result);\n };\n}\n","import {\n check,\n type GenericSchema,\n number,\n parseJson,\n pipe,\n record,\n string,\n transform,\n union,\n} from 'valibot';\n\nimport type { RGB, ThemeParams } from './types/index.js';\n\n/**\n * Theme color. Some Telegram clients send colors as numbers, so they are converted to\n * the `#RRGGBB` format.\n */\nconst ColorSchema = pipe(\n union([string(), number()]),\n transform(value => (\n typeof value === 'number'\n ? `#${(value & 0xFFFFFF).toString(16).padStart(6, '0')}`\n : value\n ) as RGB),\n check(\n value => /^#([\\da-f]{3,4}|[\\da-f]{6}|[\\da-f]{8})$/i.test(value),\n issue => `Invalid color: ${String(issue.input)}`,\n ),\n);\n\n/**\n * Schema of a raw theme parameters object.\n */\nexport const ThemeParamsSchema: GenericSchema<unknown, ThemeParams> = record(string(), ColorSchema);\n\n/**\n * Schema of theme parameters in the JSON format.\n */\nexport const ThemeParamsJsonSchema: GenericSchema<unknown, ThemeParams> = pipe(\n string(),\n parseJson(),\n ThemeParamsSchema,\n);\n","import {\n nonEmpty,\n object,\n optional,\n pipe,\n safeParse,\n string,\n transform,\n ValiError,\n} from 'valibot';\n\nimport { InvalidLaunchParamsError, LaunchParamsRetrieveError } from './errors.js';\nimport { err, ok, type Result, throwing } from './result.js';\nimport { ThemeParamsJsonSchema } from './theme-params.js';\nimport type { Platform, ThemeParams, Version } from './types/index.js';\n\nconst STORAGE_KEY = 'tma.js/launch-params';\n\n/**\n * Launch parameters passed by the Telegram client to the mini app.\n * @see https://docs.telegram-mini-apps.com/platform/launch-parameters\n */\nexport interface LaunchParams {\n /**\n * True if the mini app was launched in inline mode.\n */\n tgWebAppBotInline?: boolean;\n /**\n * Init data in the raw format. Pass it to your server to authorize the user.\n * @see https://docs.telegram-mini-apps.com/platform/init-data\n */\n tgWebAppData?: string;\n /**\n * Default theme colors.\n */\n tgWebAppDefaultColors?: ThemeParams;\n /**\n * True if the mini app was launched in fullscreen mode.\n */\n tgWebAppFullscreen?: boolean;\n /**\n * Telegram client platform.\n */\n tgWebAppPlatform: Platform;\n /**\n * True if the Settings Button should be displayed.\n */\n tgWebAppShowSettings?: boolean;\n /**\n * Start parameter passed in the mini app link.\n * @see https://docs.telegram-mini-apps.com/platform/start-parameter\n */\n tgWebAppStartParam?: string;\n /**\n * Theme parameters.\n */\n tgWebAppThemeParams: ThemeParams;\n /**\n * Mini Apps version supported by the Telegram client.\n */\n tgWebAppVersion: Version;\n}\n\nconst OptionalBooleanSchema = optional(pipe(string(), transform(value => value === '1')));\n\nconst LaunchParamsSchema = object({\n tgWebAppBotInline: OptionalBooleanSchema,\n tgWebAppData: optional(string()),\n tgWebAppDefaultColors: optional(ThemeParamsJsonSchema),\n tgWebAppFullscreen: OptionalBooleanSchema,\n tgWebAppPlatform: pipe(string(), nonEmpty()),\n tgWebAppShowSettings: OptionalBooleanSchema,\n tgWebAppStartParam: optional(string()),\n tgWebAppThemeParams: optional(ThemeParamsJsonSchema, '{}'),\n tgWebAppVersion: pipe(string(), nonEmpty()),\n});\n\n/**\n * Parses launch parameters from their query representation.\n * @param value - launch parameters query.\n * @returns Launch parameters, or `InvalidLaunchParamsError` if the value doesn't represent\n * valid launch parameters.\n */\nexport function safeParseLaunchParams(\n value: string | URLSearchParams,\n): Result<InvalidLaunchParamsError, LaunchParams> {\n const query = new URLSearchParams(value);\n const input: Record<string, string> = {};\n query.forEach((item, key) => {\n // Like URLSearchParams.get, take the first value.\n key in input || (input[key] = item);\n });\n const result = safeParse(LaunchParamsSchema, input);\n return result.success\n ? ok(result.output)\n : err(new InvalidLaunchParamsError(query.toString(), new ValiError(result.issues)));\n}\n\n/**\n * Parses launch parameters from their query representation.\n *\n * Throwing version of `safeParseLaunchParams`.\n * @param value - launch parameters query.\n * @throws {InvalidLaunchParamsError} The value doesn't represent valid launch parameters.\n */\nexport const parseLaunchParams = /* @__PURE__ */ throwing(safeParseLaunchParams);\n\n/**\n * Converts launch parameters to their query representation.\n * @param value - launch parameters.\n */\nexport function serializeLaunchParams(value: LaunchParams): string {\n const query = new URLSearchParams();\n Object.entries(value).forEach(([key, item]) => {\n if (item === undefined) {\n return;\n }\n query.set(\n key,\n typeof item === 'boolean'\n ? item ? '1' : '0'\n : typeof item === 'object' ? JSON.stringify(item) : String(item),\n );\n });\n return query.toString();\n}\n\n/**\n * Converts a URL to a query containing both its search and hash parameters.\n */\nfunction urlToQuery(url: string): string {\n return url\n // Remove everything before the first \"?\" or \"#\".\n .replace(/^[^?#]*[?#]/, '')\n // Make the rest look like a single query.\n .replace(/[?#]/g, '&');\n}\n\nfunction readSessionStorage(key: string): string | null {\n try {\n return sessionStorage.getItem(key);\n } catch {\n return null;\n }\n}\n\n/**\n * Launch parameters sources ordered by priority.\n */\nconst sources: [name: string, retrieve: () => string | null | undefined][] = [\n // Launch parameters are passed in the URL hash. They can be missing in case the app changed\n // the location and then the page was reloaded.\n ['window.location.href', () => urlToQuery(window.location.href)],\n // The initial page URL.\n ['performance navigation entries', () => {\n const [entry] = performance.getEntriesByType('navigation') as PerformanceNavigationTiming[];\n return entry && urlToQuery(entry.name);\n }],\n // Value saved by this package previously.\n ['session storage', () => readSessionStorage(STORAGE_KEY)],\n // Value saved by the official SDK.\n ['official SDK session storage', () => {\n const raw = readSessionStorage('__telegram__initParams');\n if (!raw) {\n return;\n }\n const params = JSON.parse(raw) as Record<string, unknown> | null;\n return params\n ? new URLSearchParams(\n Object.entries(params).filter((entry): entry is [string, string] => {\n return typeof entry[1] === 'string';\n }),\n ).toString()\n : undefined;\n }],\n];\n\n/**\n * Saves launch parameters to the session storage, so they could be retrieved after the page\n * reload.\n * @param value - launch parameters query.\n */\nexport function saveLaunchParams(value: string): void {\n try {\n sessionStorage.setItem(STORAGE_KEY, value);\n } catch {\n // Session storage may be unavailable.\n }\n}\n\n/**\n * Retrieves launch parameters from any known source and saves them in the session storage.\n */\nfunction retrieve(): Result<LaunchParamsRetrieveError, { raw: string; parsed: LaunchParams }> {\n const errors: { source: string; error: unknown }[] = [];\n for (const [source, retrieveSource] of sources) {\n let raw: string | null | undefined;\n try {\n raw = retrieveSource();\n } catch (error) {\n errors.push({ source, error });\n continue;\n }\n if (!raw) {\n errors.push({ source, error: new Error('Source is empty') });\n continue;\n }\n const parsed = safeParseLaunchParams(raw);\n if (!parsed.ok) {\n errors.push({ source, error: parsed.error });\n continue;\n }\n saveLaunchParams(raw);\n return ok({ raw, parsed: parsed.data });\n }\n return err(new LaunchParamsRetrieveError(errors));\n}\n\n/**\n * Retrieves launch parameters in the raw format from any known source and saves them in\n * the session storage.\n * @returns Launch parameters, or `LaunchParamsRetrieveError` if they were not found.\n */\nexport function safeRetrieveRawLaunchParams(): Result<LaunchParamsRetrieveError, string> {\n const result = retrieve();\n return result.ok ? ok(result.data.raw) : result;\n}\n\n/**\n * Retrieves launch parameters in the raw format from any known source and saves them in\n * the session storage.\n *\n * Throwing version of `safeRetrieveRawLaunchParams`.\n * @throws {LaunchParamsRetrieveError} Launch parameters were not found.\n */\nexport const retrieveRawLaunchParams = /* @__PURE__ */ throwing(safeRetrieveRawLaunchParams);\n\n/**\n * Retrieves launch parameters from any known source.\n * @returns Launch parameters, or `LaunchParamsRetrieveError` if they were not found.\n */\nexport function safeRetrieveLaunchParams(): Result<LaunchParamsRetrieveError, LaunchParams> {\n const result = retrieve();\n return result.ok ? ok(result.data.parsed) : result;\n}\n\n/**\n * Retrieves launch parameters from any known source.\n *\n * Throwing version of `safeRetrieveLaunchParams`.\n * @throws {LaunchParamsRetrieveError} Launch parameters were not found.\n */\nexport const retrieveLaunchParams = /* @__PURE__ */ throwing(safeRetrieveLaunchParams);\n\n/**\n * Retrieves init data in the raw format. Pass it to your server to authorize the user.\n * @returns Init data (`undefined` if it is missing in launch parameters), or\n * `LaunchParamsRetrieveError` if launch parameters were not found.\n */\nexport function safeRetrieveRawInitData(): Result<LaunchParamsRetrieveError, string | undefined> {\n const result = retrieve();\n return result.ok ? ok(result.data.parsed.tgWebAppData) : result;\n}\n\n/**\n * Retrieves init data in the raw format. Pass it to your server to authorize the user.\n *\n * Throwing version of `safeRetrieveRawInitData`.\n * @returns Init data, or `undefined` if it is missing in launch parameters.\n * @throws {LaunchParamsRetrieveError} Launch parameters were not found.\n */\nexport const retrieveRawInitData = /* @__PURE__ */ throwing(safeRetrieveRawInitData);\n","export interface Logger {\n log: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n}\n\nconst PREFIX = [\n '%cBridge',\n 'background:#9147ff;color:white;font-weight:bold;padding:0 5px;border-radius:5px',\n];\n\nconst consoleLogger: Logger = {\n log: (...args) => console.log(...PREFIX, ...args),\n warn: (...args) => console.warn(...PREFIX, ...args),\n error: (...args) => console.error(...PREFIX, ...args),\n};\n\nlet debug = false;\nlet logger = consoleLogger;\n\n/**\n * Enables or disables debug mode. In debug mode, the package logs every outgoing method call\n * and every incoming event.\n * @param value - should the debug mode be enabled.\n */\nexport function setDebug(value: boolean): void {\n debug = value;\n}\n\n/**\n * @returns True if the debug mode is enabled.\n */\nexport function isDebug(): boolean {\n return debug;\n}\n\n/**\n * Replaces the package logger. Pass nothing to restore the default one.\n * @param value - logger to use.\n */\nexport function setLogger(value: Logger = consoleLogger): void {\n logger = value;\n}\n\n/**\n * @returns The current package logger.\n */\nexport function getLogger(): Logger {\n return logger;\n}\n\n/**\n * Logs a message only in debug mode.\n * @param args - values to log.\n */\nexport function debugLog(...args: unknown[]): void {\n debug && logger.log(...args);\n}\n","/**\n * Helpers allowing the package to receive events from Telegram clients together with other\n * libraries (usually, the official SDK) without overwriting each other's handlers.\n */\n\ntype AnyFn = (...args: any[]) => void;\ntype AnyObj = Record<string, any>;\nexport type Restore = () => void;\n\n/**\n * Makes `obj[key]` always return a function calling `fn` and then the function assigned to\n * `obj[key]` by someone else (before or after the call). Assigning a new function replaces only\n * the external one.\n * @returns Function restoring `obj[key]` to the external function.\n */\nexport function composeFn(obj: AnyObj, key: string, fn: AnyFn): Restore {\n let external: AnyFn | undefined = typeof obj[key] === 'function' ? obj[key] : undefined;\n const composed: AnyFn = (...args) => {\n fn(...args);\n external && external(...args);\n };\n Object.defineProperty(obj, key, {\n configurable: true,\n enumerable: true,\n get: () => composed,\n set(value) {\n external = typeof value === 'function' ? value : undefined;\n },\n });\n return () => {\n if (external) {\n Object.defineProperty(obj, key, {\n configurable: true,\n enumerable: true,\n writable: true,\n value: external,\n });\n } else {\n delete obj[key];\n }\n };\n}\n\n/**\n * Makes assignments to `obj[key]` merge the assigned object into the current one instead of\n * replacing it. It protects properties defined via `composeFn` from being overwritten together\n * with the owning object.\n * @returns Function restoring `obj[key]` to a plain property.\n */\nexport function mergeOnAssign(obj: AnyObj, key: string): Restore {\n const value: AnyObj = obj[key];\n Object.defineProperty(obj, key, {\n configurable: true,\n enumerable: true,\n get: () => value,\n set(next) {\n if (next && typeof next === 'object') {\n Object.assign(value, next);\n }\n },\n });\n return () => {\n Object.defineProperty(obj, key, {\n configurable: true,\n enumerable: true,\n writable: true,\n value,\n });\n };\n}\n\n/**\n * Creates an empty object in `obj[key]` if it is missing.\n * @returns Function removing the created object if it is still empty.\n */\nexport function ensureObject(obj: AnyObj, key: string): Restore {\n if (obj[key]) {\n return () => undefined;\n }\n obj[key] = {};\n return () => {\n const value: unknown = obj[key];\n if (value && typeof value === 'object' && !Object.keys(value).length) {\n delete obj[key];\n }\n };\n}\n","import {\n boolean,\n type GenericSchema,\n looseObject,\n nullish,\n number,\n optional,\n parse,\n parseJson,\n pipe,\n safeParse,\n string,\n transform,\n unknown,\n} from 'valibot';\n\nimport { isIframe, telegramWindow } from './env.js';\nimport { debugLog, getLogger } from './logger.js';\nimport { ThemeParamsSchema } from './theme-params.js';\nimport type {\n AnyEventListener,\n EventListener,\n EventListenerPayload,\n EventName,\n EventPayload,\n} from './types/index.js';\nimport { composeFn, ensureObject, mergeOnAssign, type Restore } from './window-hooks.js';\n\nexport interface OnOptions {\n /**\n * Remove the listener after the first call.\n */\n once?: boolean;\n /**\n * Signal removing the listener when aborted.\n */\n signal?: AbortSignal;\n}\n\n/**\n * Arguments following the event name when emitting the event.\n */\nexport type EmitEventArgs<E extends EventName> = [EventPayload<E>] extends [never]\n ? []\n : [payload: EventPayload<E>];\n\ntype Listener = (payload: any) => void;\n\n/**\n * Event name to its listeners. The value is a listener-to-once-flag map.\n */\nconst listeners = new Map<string, Map<Listener, boolean>>();\nconst anyListeners = new Map<AnyEventListener, boolean>();\nlet restoreWindow: Restore | undefined;\n\n/**\n * Schema of a message sent by Telegram Web clients via `window.postMessage`.\n */\nexport const MiniAppsMessageSchema = pipe(\n string(),\n parseJson(),\n looseObject({ eventType: string(), eventData: optional(unknown()) }),\n);\n\n/**\n * Validates event payloads and fixes known issues of the payloads sent by some Telegram clients.\n */\nconst payloadSchemas: { [E in EventName]?: GenericSchema<unknown, EventListenerPayload<E>> } = {\n clipboard_text_received: looseObject({\n req_id: string(),\n data: nullish(string()),\n }),\n custom_method_invoked: looseObject({\n req_id: string(),\n result: optional(unknown()),\n error: optional(string()),\n }),\n popup_closed: pipe(\n nullish(looseObject({ button_id: nullish(string()) })),\n transform(data => (data && typeof data.button_id === 'string' ? { button_id: data.button_id } : {})),\n ),\n theme_changed: looseObject({ theme_params: ThemeParamsSchema }),\n viewport_changed: nullish(\n looseObject({\n height: number(),\n width: nullish(number(), () => window.innerWidth),\n is_expanded: boolean(),\n is_state_stable: boolean(),\n }),\n // macOS client sends null instead of the payload.\n () => ({\n height: window.innerHeight,\n width: window.innerWidth,\n is_expanded: true,\n is_state_stable: true,\n }),\n ),\n};\n\nfunction callListener(listener: (value: any) => void, value: unknown): void {\n try {\n listener(value);\n } catch (e) {\n getLogger().error('An event listener threw an error:', e);\n }\n}\n\nfunction callListeners<L>(map: Map<L, boolean>, value: unknown): void {\n // Copying the entries, so listeners added or removed during the call don't affect it.\n [...map].forEach(([listener, once]) => {\n if (map.get(listener) === undefined) {\n return;\n }\n once && map.delete(listener);\n callListener(listener as (value: unknown) => void, value);\n });\n}\n\n/**\n * Processes an event received from the Telegram client.\n */\nfunction receiveEvent(name: string, data?: unknown): void {\n const schema = payloadSchemas[name as EventName];\n let payload: unknown;\n try {\n payload = schema ? parse(schema, data) : data;\n } catch (e) {\n getLogger().error(`Unable to process the \"${name}\" event payload:`, data, e);\n return;\n }\n debugLog('Event received:', name, payload);\n\n const eventListeners = listeners.get(name);\n if (eventListeners) {\n callListeners(eventListeners, payload);\n !eventListeners.size && listeners.delete(name);\n }\n callListeners(anyListeners, { name, payload });\n uninstallIfIdle();\n}\n\nfunction onMessage(event: MessageEvent): void {\n if (event.source !== window.parent) {\n return;\n }\n // Messages may be sent by any other code. We are ignoring unknown ones.\n const message = safeParse(MiniAppsMessageSchema, event.data);\n message.success && receiveEvent(message.output.eventType, message.output.eventData);\n}\n\n/**\n * Starts receiving events from the Telegram client.\n *\n * Native clients call one of `window.Telegram.WebView.receiveEvent`,\n * `window.TelegramGameProxy.receiveEvent` or `window.TelegramGameProxy_receiveEvent`. Web\n * clients post messages to the window. The official SDK defines the same functions, so they\n * are composed to keep both working regardless of which one was loaded first.\n */\nfunction install(): Restore {\n const w = telegramWindow() as unknown as Record<string, any>;\n const restores: Restore[] = [\n ensureObject(w, 'Telegram'),\n ensureObject(w.Telegram, 'WebView'),\n mergeOnAssign(w.Telegram, 'WebView'),\n composeFn(w.Telegram.WebView, 'receiveEvent', receiveEvent),\n ensureObject(w, 'TelegramGameProxy'),\n mergeOnAssign(w, 'TelegramGameProxy'),\n composeFn(w.TelegramGameProxy, 'receiveEvent', receiveEvent),\n composeFn(w, 'TelegramGameProxy_receiveEvent', receiveEvent),\n ];\n window.addEventListener('message', onMessage);\n\n return () => {\n window.removeEventListener('message', onMessage);\n restores.reverse().forEach(restore => restore());\n };\n}\n\nfunction installIfNeeded(): void {\n restoreWindow ||= install();\n}\n\nfunction uninstallIfIdle(): void {\n if (restoreWindow && !listeners.size && !anyListeners.size) {\n restoreWindow();\n restoreWindow = undefined;\n }\n}\n\nfunction subscribe(add: () => void, remove: () => void, options: OnOptions): VoidFunction {\n const { signal } = options;\n if (signal && signal.aborted) {\n return () => undefined;\n }\n installIfNeeded();\n add();\n\n const off = () => {\n remove();\n uninstallIfIdle();\n signal && signal.removeEventListener('abort', off);\n };\n signal && signal.addEventListener('abort', off);\n return off;\n}\n\n/**\n * Adds a listener of the specified Mini Apps event. Adding the same listener twice has no\n * effect.\n * @param event - event name.\n * @param listener - event listener.\n * @param options - additional options.\n * @returns Function removing the listener.\n * @see https://docs.telegram-mini-apps.com/platform/events\n */\nexport function onEvent<E extends EventName>(\n event: E,\n listener: EventListener<E>,\n options: OnOptions = {},\n): VoidFunction {\n return subscribe(\n () => {\n const map = listeners.get(event) || new Map<Listener, boolean>();\n listeners.set(event, map);\n map.set(listener as Listener, !!options.once);\n },\n () => offEvent(event, listener),\n options,\n );\n}\n\n/**\n * Removes a listener of the specified Mini Apps event.\n * @param event - event name.\n * @param listener - event listener.\n */\nexport function offEvent<E extends EventName>(event: E, listener: EventListener<E>): void {\n const map = listeners.get(event);\n if (map) {\n map.delete(listener as Listener);\n !map.size && listeners.delete(event);\n }\n uninstallIfIdle();\n}\n\n/**\n * Adds a listener of all Mini Apps events. Adding the same listener twice has no effect.\n * @param listener - events listener.\n * @param options - additional options.\n * @returns Function removing the listener.\n */\nexport function onAnyEvent(listener: AnyEventListener, options: OnOptions = {}): VoidFunction {\n return subscribe(\n () => anyListeners.set(listener, !!options.once),\n () => offAnyEvent(listener),\n options,\n );\n}\n\n/**\n * Removes a listener of all Mini Apps events.\n * @param listener - events listener.\n */\nexport function offAnyEvent(listener: AnyEventListener): void {\n anyListeners.delete(listener);\n uninstallIfIdle();\n}\n\n/**\n * Removes all event listeners and stops receiving events from the Telegram client.\n */\nexport function offAll(): void {\n listeners.clear();\n anyListeners.clear();\n uninstallIfIdle();\n}\n\n/**\n * Emits an event as if it was sent by the Telegram client. Use it to imitate the Telegram\n * client, for example, in the `mockTelegramEnv` function `onEvent` option.\n *\n * The event is delivered the same way a real Telegram client would deliver it, so other\n * libraries (e.g. the official SDK) receive it too.\n * @param event - event name.\n * @param args - event payload.\n */\nexport function emitEvent<E extends EventName>(event: E, ...args: EmitEventArgs<E>): void {\n const [eventData] = args as [unknown?];\n const receive = telegramWindow().Telegram?.WebView?.receiveEvent;\n if (!isIframe() && typeof receive === 'function') {\n receive(event, eventData);\n return;\n }\n window.dispatchEvent(new MessageEvent('message', {\n data: JSON.stringify({ eventType: event, eventData }),\n source: window.parent,\n }));\n}\n","import { isIframe, telegramWindow } from './env.js';\nimport { UnknownEnvError } from './errors.js';\nimport { debugLog } from './logger.js';\nimport type { MethodArgs, MethodName } from './types/index.js';\n\nlet targetOrigin = 'https://web.telegram.org';\n\n/**\n * Sets the target origin used to post messages to the parent window in Telegram Web clients.\n *\n * You don't need to change it until you know what you are doing.\n * @param origin - target origin. Default: `https://web.telegram.org`.\n */\nexport function setTargetOrigin(origin: string): void {\n targetOrigin = origin;\n}\n\n/**\n * @returns The target origin used to post messages to the parent window.\n */\nexport function getTargetOrigin(): string {\n return targetOrigin;\n}\n\nexport type PostMessageFn = (message: string, targetOrigin: string) => void;\n\nlet postMessage: PostMessageFn = (message, origin) => {\n window.parent.postMessage(message, origin);\n};\n\n/**\n * Replaces the function posting messages to the parent window in Telegram Web clients.\n * @param fn - function to use.\n * @returns Function restoring the previous implementation.\n * @internal\n */\nexport function setPostMessage(fn: PostMessageFn): VoidFunction {\n const previous = postMessage;\n postMessage = fn;\n return () => {\n postMessage = previous;\n };\n}\n\n/**\n * @returns The current function posting messages to the parent window.\n * @internal\n */\nexport function getPostMessage(): PostMessageFn {\n return postMessage;\n}\n\nexport type PostEventFn = <M extends MethodName>(method: M, ...args: MethodArgs<M>) => void;\n\n/**\n * Calls a Mini Apps method.\n *\n * Depending on the environment, the method is sent:\n * - via `window.parent.postMessage` in Telegram Web clients;\n * - via `window.TelegramWebviewProxy.postEvent` in Telegram for iOS, macOS, Android and Desktop;\n * - via `window.external.notify` in Telegram for Windows Phone.\n *\n * @param method - method name.\n * @param args - method parameters.\n * @throws {UnknownEnvError} The current environment is not a Telegram Mini App.\n * @see https://docs.telegram-mini-apps.com/platform/methods\n */\nexport const postEvent: PostEventFn = (method, ...args) => {\n const [params = ''] = args as [unknown?];\n debugLog('Posting method:', method, params);\n\n const message = JSON.stringify({ eventType: method, eventData: params });\n\n // Unlike the official SDK, the iframe check goes first. Telegram clients also define\n // TelegramWebviewProxy inside iframes embedded by a mini app, letting them bypass the mini app.\n // Calls must go through the top-level mini app only, so an iframe always posts to its parent.\n if (isIframe()) {\n postMessage(message, targetOrigin);\n return;\n }\n\n const w = telegramWindow();\n if (w.TelegramWebviewProxy && typeof w.TelegramWebviewProxy.postEvent === 'function') {\n w.TelegramWebviewProxy.postEvent(method, JSON.stringify(params));\n return;\n }\n if (w.external && typeof w.external.notify === 'function') {\n w.external.notify(message);\n return;\n }\n throw new UnknownEnvError();\n};\n","import { TimeoutError } from './errors.js';\nimport { onEvent } from './events.js';\nimport { postEvent as defaultPostEvent, type PostEventFn } from './post-event.js';\nimport { err, ok, type Result, unwrap } from './result.js';\nimport type {\n EventListenerPayload,\n EventName,\n MethodName,\n MethodNameWithRequiredParams,\n MethodParams,\n} from './types/index.js';\n\ntype AnyEventName = EventName | EventName[];\n\n/**\n * Value captured by the `request` function. For a list of tracked events, it also contains\n * the event name.\n */\nexport type RequestResult<E extends AnyEventName> = E extends (infer U extends EventName)[]\n ? { [K in U]: { event: K; payload: EventListenerPayload<K> } }[U]\n : E extends EventName ? EventListenerPayload<E> : never;\n\nexport interface RequestOptions<E extends AnyEventName> {\n /**\n * Function returning true if the received event should be captured. If omitted, the first\n * tracked event is captured.\n */\n capture?: (value: RequestResult<E>) => boolean;\n /**\n * Time in milliseconds to wait for the event. When reached, the request fails with\n * `TimeoutError`.\n */\n timeout?: number;\n /**\n * Signal to abort the request. When aborted, the request is rejected with `signal.reason`.\n */\n signal?: AbortSignal;\n /**\n * Custom function to call the method.\n */\n postEvent?: PostEventFn;\n}\n\n/**\n * Options of the `request` function. The `params` option is required only if the method\n * requires parameters.\n */\nexport type RequestFnOptions<M extends MethodName, E extends AnyEventName> =\n RequestOptions<E> & ([MethodParams<M>] extends [never]\n ? { params?: never }\n : M extends MethodNameWithRequiredParams\n ? { params: MethodParams<M> }\n : { params?: MethodParams<M> });\n\nexport type RequestFnArgs<M extends MethodName, E extends AnyEventName> =\n M extends MethodNameWithRequiredParams\n ? [options: RequestFnOptions<M, E>]\n : [options?: RequestFnOptions<M, E>];\n\n/**\n * Calls a Mini Apps method and waits for the specified event (or one of the events) to occur.\n *\n * Listeners are added before the method is called, so events emitted synchronously are\n * captured too.\n *\n * The request is rejected with `signal.reason` if it was aborted, and with the error thrown by\n * `postEvent` or the `capture` option.\n * @param method - method name.\n * @param events - event or events to wait for.\n * @param args - additional options.\n * @returns For a single event, its payload. For a list of events, an object with the captured\n * event name and payload. If the timeout was reached, `TimeoutError`.\n * @example\n * const result = await safeRequest('web_app_request_phone', 'phone_requested', { timeout: 5000 });\n * if (!result.ok) {\n * console.log('The user didn\\'t respond in time');\n * }\n */\nexport function safeRequest<M extends MethodName, E extends AnyEventName>(\n method: M,\n events: E,\n ...args: RequestFnArgs<M, E>\n): Promise<Result<TimeoutError, RequestResult<E>>> {\n const {\n capture = () => true,\n timeout,\n signal,\n params,\n postEvent = defaultPostEvent,\n } = (args[0] || {}) as RequestOptions<E> & { params?: unknown };\n\n return new Promise<Result<TimeoutError, RequestResult<E>>>((resolve, reject) => {\n if (signal && signal.aborted) {\n // Rejecting with the abort reason is the standard behavior of abortable APIs.\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n return reject(signal.reason);\n }\n\n const cleanups: VoidFunction[] = [];\n const settle = <T>(fn: (value: T) => void) => (value: T) => {\n cleanups.forEach(cleanup => cleanup());\n fn(value);\n };\n const onResolve = settle(resolve);\n const onReject = settle(reject);\n\n const isList = Array.isArray(events);\n (isList ? events : [events]).forEach(event => {\n cleanups.push(onEvent(event, payload => {\n const value = (isList ? { event, payload } : payload) as RequestResult<E>;\n try {\n capture(value) && onResolve(ok(value));\n } catch (e) {\n onReject(e);\n }\n }));\n });\n\n if (timeout) {\n const timeoutId = setTimeout(() => onResolve(err(new TimeoutError(timeout))), timeout);\n cleanups.push(() => clearTimeout(timeoutId));\n }\n if (signal) {\n const onAbort = () => onReject(signal.reason);\n signal.addEventListener('abort', onAbort);\n cleanups.push(() => signal.removeEventListener('abort', onAbort));\n }\n\n try {\n (postEvent as (method: string, params?: unknown) => void)(method, params);\n } catch (e) {\n onReject(e);\n }\n });\n}\n\n/**\n * Calls a Mini Apps method and waits for the specified event (or one of the events) to occur.\n *\n * Throwing version of `safeRequest`.\n * @param method - method name.\n * @param events - event or events to wait for.\n * @param args - additional options.\n * @returns For a single event, its payload. For a list of events, an object with the captured\n * event name and payload.\n * @throws {TimeoutError} The timeout was reached.\n * @example\n * const { button_id } = await request('web_app_open_popup', 'popup_closed', {\n * params: { title: 'Hello', message: 'World', buttons: [{ id: 'ok', type: 'ok' }] },\n * });\n * @example\n * const result = await request('web_app_request_phone', ['phone_requested'], { timeout: 5000 });\n */\nexport async function request<M extends MethodName, E extends AnyEventName>(\n method: M,\n events: E,\n ...args: RequestFnArgs<M, E>\n): Promise<RequestResult<E>> {\n return unwrap(await safeRequest(method, events, ...args));\n}\n\n/**\n * @returns A new unique request identifier. Use it for methods requiring the `req_id` parameter.\n */\nexport function createRequestId(): string {\n return typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'\n ? crypto.randomUUID()\n : `${Date.now().toString(36)}${Math.random().toString(36)\n .slice(2)}`;\n}\n\n/**\n * @returns Function to use in the `request` function `capture` option to capture the event\n * with the specified request identifier.\n * @param reqId - request identifier.\n */\nexport function captureSameReq(reqId: string): (payload: { req_id: string }) => boolean {\n return payload => payload.req_id === reqId;\n}\n","import { TimeoutError, UnknownEnvError } from './errors.js';\nimport { retrieveRawLaunchParams } from './launch-params.js';\nimport { request } from './request.js';\n\n/**\n * Window properties used by the Telegram clients and the official SDK to communicate with\n * a mini app.\n */\nexport interface TelegramWindow {\n /**\n * Telegram for iOS, macOS, Android and Telegram Desktop.\n */\n TelegramWebviewProxy?: {\n postEvent: (eventType: string, eventData: string) => void;\n };\n /**\n * Telegram for Windows Phone.\n */\n external?: {\n notify?: (message: string) => void;\n };\n Telegram?: {\n WebView?: {\n receiveEvent?: ReceiveEventFn;\n [key: string]: unknown;\n };\n [key: string]: unknown;\n };\n TelegramGameProxy?: {\n receiveEvent?: ReceiveEventFn;\n [key: string]: unknown;\n };\n TelegramGameProxy_receiveEvent?: ReceiveEventFn;\n}\n\nexport type ReceiveEventFn = (eventType: string, eventData?: unknown) => void;\n\n/**\n * @returns The current window with Telegram-specific properties typed.\n */\nexport function telegramWindow(): Window & TelegramWindow {\n return window;\n}\n\n/**\n * @returns True if the current environment is an iframe. Telegram Web clients open mini apps\n * in an iframe.\n * @see https://stackoverflow.com/a/326076\n */\nexport function isIframe(): boolean {\n try {\n return window.self !== window.top;\n } catch {\n return true;\n }\n}\n\n/**\n * @returns True if the `window.TelegramWebviewProxy.postEvent` function exists. Native Telegram\n * clients define it to receive method calls.\n */\nexport function hasWebviewProxy(): boolean {\n return typeof telegramWindow().TelegramWebviewProxy?.postEvent === 'function';\n}\n\n/**\n * @returns True if the current environment looks like a Telegram Mini App: the Telegram webview\n * proxy is defined, or launch parameters are available.\n *\n * Use `isTMAAsync` for a stricter check.\n */\nexport function isTMA(): boolean {\n if (hasWebviewProxy()) {\n return true;\n }\n try {\n retrieveRawLaunchParams();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Checks if the current environment is a Telegram Mini App by calling a method and waiting for\n * the Telegram client response.\n * @param options - additional options.\n */\nexport async function isTMAAsync(options: {\n /**\n * Time in milliseconds to wait for the response.\n * @default 100\n */\n timeout?: number;\n /**\n * Signal to abort the check.\n */\n signal?: AbortSignal;\n} = {}): Promise<boolean> {\n if (hasWebviewProxy()) {\n return true;\n }\n try {\n await request('web_app_request_theme', 'theme_changed', { timeout: 100, ...options });\n return true;\n } catch (e) {\n if (TimeoutError.is(e) || UnknownEnvError.is(e)) {\n return false;\n }\n throw e;\n }\n}\n","import { InvokeCustomMethodFailedError, type TimeoutError } from './errors.js';\nimport { captureSameReq, createRequestId, type RequestOptions, safeRequest } from './request.js';\nimport { err, ok, type Result, unwrap } from './result.js';\nimport type { CustomMethodName, CustomMethodParams } from './types/index.js';\n\nexport interface InvokeCustomMethodOptions\n extends Omit<RequestOptions<'custom_method_invoked'>, 'capture'> {\n /**\n * Request identifier. Generated automatically if omitted.\n */\n requestId?: string;\n}\n\n/**\n * Invokes a custom method and returns its result.\n * @param method - method name.\n * @param params - method parameters.\n * @param options - additional options.\n * @returns Method result, or one of the errors:\n * - `InvokeCustomMethodFailedError`: the method returned an error;\n * - `TimeoutError`: the timeout was reached.\n */\nexport function safeInvokeCustomMethod<M extends CustomMethodName>(\n method: M,\n params: CustomMethodParams<M>,\n options?: InvokeCustomMethodOptions,\n): Promise<Result<InvokeCustomMethodFailedError | TimeoutError, unknown>>;\nexport function safeInvokeCustomMethod(\n method: string,\n params: object,\n options?: InvokeCustomMethodOptions,\n): Promise<Result<InvokeCustomMethodFailedError | TimeoutError, unknown>>;\nexport async function safeInvokeCustomMethod(\n method: string,\n params: object,\n { requestId = createRequestId(), ...options }: InvokeCustomMethodOptions = {},\n): Promise<Result<InvokeCustomMethodFailedError | TimeoutError, unknown>> {\n const response = await safeRequest(\n 'web_app_invoke_custom_method',\n 'custom_method_invoked',\n {\n ...options,\n params: { method, params, req_id: requestId },\n capture: captureSameReq(requestId),\n },\n );\n if (!response.ok) {\n return response;\n }\n const { result, error } = response.data;\n return error ? err(new InvokeCustomMethodFailedError(error)) : ok(result);\n}\n\n/**\n * Invokes a custom method and returns its result.\n *\n * Throwing version of `safeInvokeCustomMethod`.\n * @param method - method name.\n * @param params - method parameters.\n * @param options - additional options.\n * @throws {InvokeCustomMethodFailedError} The method returned an error.\n * @throws {TimeoutError} The timeout was reached.\n */\nexport function invokeCustomMethod<M extends CustomMethodName>(\n method: M,\n params: CustomMethodParams<M>,\n options?: InvokeCustomMethodOptions,\n): Promise<unknown>;\nexport function invokeCustomMethod(\n method: string,\n params: object,\n options?: InvokeCustomMethodOptions,\n): Promise<unknown>;\nexport async function invokeCustomMethod(\n method: string,\n params: object,\n options?: InvokeCustomMethodOptions,\n): Promise<unknown> {\n return unwrap(await safeInvokeCustomMethod(method, params, options));\n}\n","import { safeParse } from 'valibot';\n\nimport { isIframe, telegramWindow, type TelegramWindow } from './env.js';\nimport { MiniAppsMessageSchema } from './events.js';\nimport {\n parseLaunchParams,\n saveLaunchParams,\n serializeLaunchParams,\n type LaunchParams,\n} from './launch-params.js';\nimport { debugLog } from './logger.js';\nimport { getPostMessage, setPostMessage } from './post-event.js';\nimport type { MethodName, MethodParams } from './types/index.js';\n\n/**\n * Mini Apps method call intercepted by `mockTelegramEnv`.\n */\nexport type MockedMethodCall =\n | {\n [M in MethodName]: {\n name: M;\n params: [MethodParams<M>] extends [never] ? undefined : MethodParams<M>;\n };\n }[MethodName]\n | { name: string & {}; params: unknown };\n\nexport interface MockTelegramEnvOptions {\n /**\n * Launch parameters to mock. They are saved in the session storage, so the launch parameters\n * retrieving functions return them.\n */\n launchParams?: string | URLSearchParams | LaunchParams;\n /**\n * Function called whenever the mini app calls a Mini Apps method. Use `emitEvent` to respond\n * to the call as the Telegram client would do.\n * @param call - called method name and its parameters.\n * @param next - function passing the call to the original transport, if there is one.\n */\n onMethod?: (call: MockedMethodCall, next: VoidFunction) => void;\n}\n\n/**\n * Mocks the environment to imitate the Telegram client.\n *\n * Use it to develop the app outside Telegram, or to intercept method calls in Telegram, for\n * example, to fix a client not responding to some method.\n *\n * Outside iframes, calls are intercepted by defining `window.TelegramWebviewProxy`, so method\n * calls performed by other libraries (e.g. the official SDK) are intercepted too. In Telegram Web\n * (iframe), only calls performed by this package are intercepted.\n * @param options - mock options.\n * @returns Function reverting the mocked method calls handling. Launch parameters stay saved.\n * When mocking several times, revert in the reverse order.\n * @example\n * mockTelegramEnv({\n * launchParams: {\n * tgWebAppPlatform: 'tdesktop',\n * tgWebAppVersion: '9.0',\n * tgWebAppThemeParams: { bg_color: '#ffffff' },\n * },\n * onMethod({ name }) {\n * if (name === 'web_app_request_theme') {\n * emitEvent('theme_changed', { theme_params: { bg_color: '#ffffff' } });\n * }\n * },\n * });\n */\nexport function mockTelegramEnv(\n { launchParams, onMethod }: MockTelegramEnvOptions = {},\n): VoidFunction {\n if (launchParams) {\n const query = typeof launchParams === 'string' || launchParams instanceof URLSearchParams\n ? launchParams.toString()\n : serializeLaunchParams(launchParams);\n // Throws if the launch parameters are invalid.\n parseLaunchParams(query);\n saveLaunchParams(query);\n }\n\n if (isIframe()) {\n // In Telegram Web, without a handler, there is nothing to intercept.\n if (!onMethod) {\n return () => undefined;\n }\n const original = getPostMessage();\n return setPostMessage((message, targetOrigin) => {\n const next = () => original(message, targetOrigin);\n const call = safeParse(MiniAppsMessageSchema, message);\n if (!call.success) {\n return next();\n }\n onMethod({\n name: call.output.eventType,\n params: normalizeParams(call.output.eventData),\n }, next);\n });\n }\n\n const w = telegramWindow();\n const original = w.TelegramWebviewProxy;\n const proxy: TelegramWindow['TelegramWebviewProxy'] = {\n postEvent(eventType, eventData) {\n const next = () => original && original.postEvent(eventType, eventData);\n onMethod\n ? onMethod({\n name: eventType,\n params: normalizeParams(eventData ? JSON.parse(eventData) : undefined),\n }, next)\n : next();\n },\n };\n w.TelegramWebviewProxy = proxy;\n debugLog('Environment was mocked');\n\n return () => {\n if (w.TelegramWebviewProxy === proxy) {\n original ? (w.TelegramWebviewProxy = original) : delete w.TelegramWebviewProxy;\n }\n };\n}\n\n/**\n * The official SDK and this package pass an empty string for methods without parameters.\n */\nfunction normalizeParams(value: unknown): unknown {\n return value === '' ? undefined : value;\n}\n","import { StartParamTooLongError } from './errors.js';\nimport { err, ok, type Result, throwing } from './result.js';\n\nconst MAX_LENGTH = 512;\n\n/**\n * Encodes a string to base64url.\n * @param value - value to encode.\n * @see https://datatracker.ietf.org/doc/html/rfc4648#section-5\n */\nexport function encodeBase64Url(value: string): string {\n let binary = '';\n new TextEncoder().encode(value)\n .forEach(byte => {\n binary += String.fromCharCode(byte);\n });\n return btoa(binary).replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n}\n\n/**\n * Decodes a base64url string.\n * @param value - value to decode.\n * @throws {DOMException} The value is not a valid base64url string.\n * @throws {TypeError} The decoded value is not a valid UTF-8 string.\n */\nexport function decodeBase64Url(value: string): string {\n const binary = atob(value.replace(/-/g, '+').replace(/_/g, '/'));\n return new TextDecoder('utf-8', { fatal: true }).decode(\n Uint8Array.from(binary, char => char.charCodeAt(0)),\n );\n}\n\n/**\n * @returns True if the value can be used to create a start parameter.\n * @param value - value to check.\n */\nexport function isSafeToCreateStartParam(value: string): boolean {\n return encodeBase64Url(value).length <= MAX_LENGTH;\n}\n\n/**\n * Creates a start parameter from the value. Non-string values are converted to JSON.\n * @param value - value to encode.\n * @returns Start parameter, or `StartParamTooLongError` if the encoded value exceeds 512\n * characters.\n * @see https://docs.telegram-mini-apps.com/platform/start-parameter\n */\nexport function safeCreateStartParam(value: unknown): Result<StartParamTooLongError, string> {\n const encoded = encodeBase64Url(typeof value === 'string' ? value : JSON.stringify(value));\n return encoded.length > MAX_LENGTH\n ? err(new StartParamTooLongError(encoded.length))\n : ok(encoded);\n}\n\n/**\n * Creates a start parameter from the value. Non-string values are converted to JSON.\n *\n * Throwing version of `safeCreateStartParam`.\n * @param value - value to encode.\n * @throws {StartParamTooLongError} The encoded value exceeds 512 characters.\n * @see https://docs.telegram-mini-apps.com/platform/start-parameter\n */\nexport const createStartParam = /* @__PURE__ */ throwing(safeCreateStartParam);\n\n/**\n * Decodes a start parameter created with `createStartParam`.\n * @param value - start parameter.\n * @param parse - `json` to parse the decoded value as JSON, or a custom parser.\n * @throws {DOMException} The value is not a valid base64url string.\n */\nexport function decodeStartParam(value: string): string;\nexport function decodeStartParam(value: string, parse: 'json'): unknown;\nexport function decodeStartParam<T>(value: string, parse: (value: string) => T): T;\nexport function decodeStartParam(\n value: string,\n parse?: 'json' | ((value: string) => unknown),\n): unknown {\n const decoded = decodeBase64Url(value);\n if (!parse) {\n return decoded;\n }\n return parse === 'json' ? JSON.parse(decoded) : parse(decoded);\n}\n","import { MethodParameterUnsupportedError, MethodUnsupportedError } from './errors.js';\nimport { getLogger } from './logger.js';\nimport { postEvent, type PostEventFn } from './post-event.js';\nimport type { MethodName, Version } from './types/index.js';\n\n/**\n * Mini Apps version to the methods and method parameters released in it.\n */\nconst releases = {\n '6.0': [\n 'iframe_ready',\n 'iframe_will_reload',\n 'web_app_close',\n 'web_app_data_send',\n 'web_app_expand',\n 'web_app_open_link',\n 'web_app_ready',\n 'web_app_request_theme',\n 'web_app_request_viewport',\n 'web_app_setup_main_button',\n 'web_app_setup_closing_behavior',\n ],\n 6.1: [\n 'web_app_open_tg_link',\n 'web_app_open_invoice',\n 'web_app_setup_back_button',\n 'web_app_set_background_color',\n 'web_app_set_header_color',\n 'web_app_trigger_haptic_feedback',\n ],\n 6.2: ['web_app_open_popup'],\n 6.4: [\n 'web_app_close_scan_qr_popup',\n 'web_app_open_scan_qr_popup',\n 'web_app_read_text_from_clipboard',\n ['web_app_open_link', 'try_instant_view'],\n ],\n 6.7: ['web_app_switch_inline_query'],\n 6.9: [\n 'web_app_invoke_custom_method',\n 'web_app_request_write_access',\n 'web_app_request_phone',\n ['web_app_set_header_color', 'color'],\n ],\n '6.10': ['web_app_setup_settings_button'],\n 7.2: [\n 'web_app_biometry_get_info',\n 'web_app_biometry_open_settings',\n 'web_app_biometry_request_access',\n 'web_app_biometry_request_auth',\n 'web_app_biometry_update_token',\n ],\n 7.6: [\n ['web_app_open_link', 'try_browser'],\n ['web_app_close', 'return_back'],\n ],\n 7.7: ['web_app_setup_swipe_behavior'],\n 7.8: ['web_app_share_to_story'],\n '7.10': [\n 'web_app_setup_secondary_button',\n 'web_app_set_bottom_bar_color',\n ['web_app_setup_main_button', 'has_shine_effect'],\n ],\n '8.0': [\n 'web_app_request_safe_area',\n 'web_app_request_content_safe_area',\n 'web_app_request_fullscreen',\n 'web_app_exit_fullscreen',\n 'web_app_set_emoji_status',\n 'web_app_add_to_home_screen',\n 'web_app_check_home_screen',\n 'web_app_request_emoji_status_access',\n 'web_app_check_location',\n 'web_app_open_location_settings',\n 'web_app_request_file_download',\n 'web_app_request_location',\n 'web_app_send_prepared_message',\n 'web_app_start_accelerometer',\n 'web_app_start_device_orientation',\n 'web_app_start_gyroscope',\n 'web_app_stop_accelerometer',\n 'web_app_stop_device_orientation',\n 'web_app_stop_gyroscope',\n 'web_app_toggle_orientation_lock',\n ],\n '9.0': [\n 'web_app_device_storage_clear',\n 'web_app_device_storage_get_key',\n 'web_app_device_storage_save_key',\n 'web_app_secure_storage_clear',\n 'web_app_secure_storage_get_key',\n 'web_app_secure_storage_restore_key',\n 'web_app_secure_storage_save_key',\n ],\n 9.1: ['web_app_hide_keyboard'],\n 9.5: [\n ['web_app_setup_main_button', 'icon_custom_emoji_id'],\n ['web_app_setup_secondary_button', 'icon_custom_emoji_id'],\n ],\n 9.6: ['web_app_request_chat'],\n} as const satisfies Record<Version, readonly (MethodName | readonly [MethodName, string])[]>;\n\ntype ReleaseItem = (typeof releases)[keyof typeof releases][number];\n\n/**\n * Methods having parameters released later than the method itself.\n */\nexport type MethodNameWithVersionedParams = Extract<ReleaseItem, readonly unknown[]>[0];\n\n/**\n * Method parameters released later than the method itself.\n */\nexport type MethodVersionedParam<M extends MethodNameWithVersionedParams> =\n Extract<ReleaseItem, readonly [M, string]>[1];\n\n/**\n * Compares two versions.\n * @param a - first version.\n * @param b - second version.\n * @returns `1` if `a` is greater than `b`, `-1` if `a` is lower than `b`, `0` if they are equal.\n */\nexport function compareVersions(a: Version, b: Version): -1 | 0 | 1 {\n const aParts = a.split('.').map(Number);\n const bParts = b.split('.').map(Number);\n for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) {\n const aPart = aParts[i] || 0;\n const bPart = bParts[i] || 0;\n if (aPart !== bPart) {\n return aPart > bPart ? 1 : -1;\n }\n }\n return 0;\n}\n\n/**\n * @returns Version the method parameter was released in, or `undefined` if it is unknown.\n * @param method - method name.\n * @param param - method parameter.\n */\nexport function getReleaseVersion<M extends MethodNameWithVersionedParams>(\n method: M,\n param: MethodVersionedParam<M>,\n): Version | undefined;\n/**\n * @returns Version the method was released in, or `undefined` if it is unknown.\n * @param method - method name.\n */\nexport function getReleaseVersion(method: MethodName): Version | undefined;\nexport function getReleaseVersion(method: string, param?: string): Version | undefined {\n return Object.keys(releases).find(version => {\n return (releases[version as keyof typeof releases] as readonly ReleaseItem[]).some(item => {\n return param\n ? typeof item === 'object' && item[0] === method && item[1] === param\n : item === method;\n });\n });\n}\n\n/**\n * @returns True if the method parameter is supported in the specified version.\n * @param method - method name.\n * @param param - method parameter.\n * @param version - Mini Apps version.\n */\nexport function supports<M extends MethodNameWithVersionedParams>(\n method: M,\n param: MethodVersionedParam<M>,\n version: Version,\n): boolean;\n/**\n * @returns True if the method is supported in the specified version.\n * @param method - method name.\n * @param version - Mini Apps version.\n */\nexport function supports(method: MethodName, version: Version): boolean;\nexport function supports(method: MethodName, paramOrVersion: string, version?: Version): boolean {\n const released = version\n ? getReleaseVersion(method as MethodNameWithVersionedParams, paramOrVersion as never)\n : getReleaseVersion(method);\n return !!released && compareVersions(released, version || paramOrVersion) <= 0;\n}\n\nexport type OnUnsupportedFn = (\n data:\n | { version: Version; method: MethodName }\n | { version: Version; method: MethodName; param: string },\n) => void;\n\n/**\n * Methods parameters which make older clients misbehave. Other versioned parameters are\n * ignored by older clients, so they are not checked.\n */\nconst checkedParams: [MethodName, string][] = [\n ['web_app_set_header_color', 'color'],\n ['web_app_setup_main_button', 'icon_custom_emoji_id'],\n ['web_app_setup_secondary_button', 'icon_custom_emoji_id'],\n];\n\n/**\n * Creates a `postEvent` function checking if the method and its parameters are supported in\n * the specified Mini Apps version.\n * @param version - Mini Apps version.\n * @param onUnsupported - what to do when something is unsupported:\n * - `strict` (default) - throw `MethodUnsupportedError` or `MethodParameterUnsupportedError`;\n * - `non-strict` - log a warning and don't call the method;\n * - a function to call instead of the method.\n */\nexport function createPostEvent(\n version: Version,\n onUnsupported: 'strict' | 'non-strict' | OnUnsupportedFn = 'strict',\n): PostEventFn {\n const handle: OnUnsupportedFn = typeof onUnsupported === 'function'\n ? onUnsupported\n : data => {\n const error = 'param' in data\n ? new MethodParameterUnsupportedError(data.method, data.param, data.version)\n : new MethodUnsupportedError(data.method, data.version);\n if (onUnsupported === 'strict') {\n throw error;\n }\n getLogger().warn(error.message);\n };\n\n return (method, ...args) => {\n if (!supports(method, version)) {\n return handle({ version, method });\n }\n const [params] = args as [unknown?];\n for (const [checkedMethod, param] of checkedParams) {\n if (\n method === checkedMethod\n && params\n && typeof params === 'object'\n && param in params\n && !supports(checkedMethod as MethodNameWithVersionedParams, param as never, version)\n ) {\n return handle({ version, method, param });\n }\n }\n postEvent(method, ...args);\n };\n}\n"],"names":["UnknownEnvError","errorClass","MethodUnsupportedError","errorClassWithData","method","version","MethodParameterUnsupportedError","param","LaunchParamsRetrieveError","errors","source","error","InvalidLaunchParamsError","value","_value","cause","InvokeCustomMethodFailedError","TimeoutError","timeout","StartParamTooLongError","length","ok","data","err","unwrap","result","throwing","fn","args","ColorSchema","pipe","union","string","number","transform","check","issue","ThemeParamsSchema","record","ThemeParamsJsonSchema","parseJson","STORAGE_KEY","OptionalBooleanSchema","optional","LaunchParamsSchema","object","nonEmpty","safeParseLaunchParams","query","input","item","key","safeParse","ValiError","parseLaunchParams","serializeLaunchParams","urlToQuery","url","readSessionStorage","sources","entry","raw","params","saveLaunchParams","retrieve","retrieveSource","parsed","safeRetrieveRawLaunchParams","retrieveRawLaunchParams","safeRetrieveLaunchParams","retrieveLaunchParams","safeRetrieveRawInitData","retrieveRawInitData","PREFIX","consoleLogger","debug","logger","setDebug","isDebug","setLogger","getLogger","debugLog","composeFn","obj","external","composed","mergeOnAssign","next","ensureObject","listeners","anyListeners","restoreWindow","MiniAppsMessageSchema","looseObject","unknown","payloadSchemas","nullish","boolean","callListener","listener","e","callListeners","map","once","receiveEvent","name","schema","payload","parse","eventListeners","uninstallIfIdle","onMessage","event","message","install","w","telegramWindow","restores","restore","installIfNeeded","subscribe","add","remove","options","signal","off","onEvent","offEvent","onAnyEvent","offAnyEvent","offAll","emitEvent","eventData","receive","_b","_a","isIframe","targetOrigin","setTargetOrigin","origin","getTargetOrigin","postMessage","setPostMessage","previous","getPostMessage","postEvent","safeRequest","events","capture","defaultPostEvent","resolve","reject","cleanups","settle","cleanup","onResolve","onReject","isList","timeoutId","onAbort","request","createRequestId","captureSameReq","reqId","hasWebviewProxy","isTMA","isTMAAsync","safeInvokeCustomMethod","requestId","response","invokeCustomMethod","mockTelegramEnv","launchParams","onMethod","original","call","normalizeParams","proxy","eventType","MAX_LENGTH","encodeBase64Url","binary","byte","decodeBase64Url","char","isSafeToCreateStartParam","safeCreateStartParam","encoded","createStartParam","decodeStartParam","decoded","releases","compareVersions","a","b","aParts","bParts","i","aPart","bPart","getReleaseVersion","supports","paramOrVersion","released","checkedParams","createPostEvent","onUnsupported","handle","checkedMethod"],"mappings":";;;AAQO,MAAMA,YAAmD,gBAAAC,GAAA;AAAA,EAC9D,MAAM;AAAA,EACN,SAAS;AACX,CAAC,GAAE;AACH;AAKO,MAAMC,YAAkE,gBAAAC,EAAA;AAAA,EAC7E,MAAM;AAAA,EACN,MAAM,CAACC,GAAgBC,OAAsB,EAAE,QAAAD,GAAQ,SAAAC,EAAQ;AAAA,EAC/D,SAAS,CAACD,GAAgBC,MACjB,WAAWD,CAAM,yCAAyCC,CAAO;AAE5E,CAAC,GAAE;AACH;AAKO,MAAMC,YAA2E,gBAAAH,EAAA;AAAA,EACtF,MAAM;AAAA,EACN,MAAM,CAACC,GAAgBG,GAAeF,OAAsB,EAAE,QAAAD,GAAQ,OAAAG,GAAO,SAAAF;EAC7E,SAAS,CAACD,GAAgBG,GAAeF,MAChC,cAAcE,CAAK,SAASH,CAAM,gDAAgDC,CAAO;AAEpG,CAAC,GAAE;AACH;AAKO,MAAMG,YAAqE,gBAAAL,EAAA;AAAA,EAChF,MAAM;AAAA,EACN,MAAM,CAACM,OAAkD,EAAE,QAAAA;EAC3D,SAAS,CAACA,MAAiD;AAAA,IACzD;AAAA,IACA;AAAA,IACA;AAAA,I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AD,GAAQ,OAAAG,GAAO;AAGlC,IAAA0I,GAAA7I,GAAQ,GAAGwB,CAAI;AAAA,EAC3B;AACF;"}
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@tma.js/bridge",
3
- "version": "2.3.3",
4
- "description": "TypeScript package to provide communication layer between Mini App and Telegram application.",
3
+ "version": "4.0.0-rc.0",
4
+ "description": "Communication layer between a Telegram Mini App and the Telegram client.",
5
5
  "author": "Vladislav Kibenko <wolfram.deus@gmail.com>",
6
6
  "homepage": "https://github.com/Telegram-Mini-Apps/tma.js#readme",
7
7
  "repository": {
8
8
  "type": "git",
9
- "url": "git@github.com:Telegram-Mini-Apps/tma.js.git",
9
+ "url": "git+https://github.com/Telegram-Mini-Apps/tma.js.git",
10
10
  "directory": "packages/bridge"
11
11
  },
12
12
  "bugs": {
@@ -28,37 +28,29 @@
28
28
  "types": "./dist/dts/index.d.ts",
29
29
  "exports": {
30
30
  ".": {
31
+ "@tma.js/source": "./src/index.ts",
31
32
  "types": "./dist/dts/index.d.ts",
32
33
  "import": "./dist/index.js",
33
34
  "require": "./dist/index.cjs",
34
35
  "default": "./dist/index.cjs"
35
36
  }
36
37
  },
37
- "dependencies": {
38
- "better-promises": "^1.0.0",
39
- "error-kid": "^2.0.0",
40
- "fp-ts": "^2.16.11",
41
- "mitt": "^3.0.1",
42
- "valibot": "^1.1.0",
43
- "@tma.js/signals": "^1.0.1",
44
- "@tma.js/toolkit": "^1.0.4",
45
- "@tma.js/transformers": "^1.2.0",
46
- "@tma.js/types": "^1.0.2"
47
- },
48
38
  "devDependencies": {
49
- "test-utils": "0.0.1",
39
+ "happy-dom": "^20.0.5",
50
40
  "tsconfig": "0.0.2"
51
41
  },
52
42
  "publishConfig": {
53
43
  "access": "public"
54
44
  },
45
+ "dependencies": {
46
+ "error-kid": "^3.1.0",
47
+ "valibot": "^1.5.0"
48
+ },
55
49
  "scripts": {
56
50
  "test": "vitest --run",
57
51
  "lint": "eslint src",
58
52
  "lint:fix": "pnpm run lint --fix",
59
- "typecheck": "tsc --noEmit -p tsconfig.build.json",
60
- "build": "rimraf dist && pnpm run build:default && pnpm run build:iife",
61
- "build:default": "vite build -c vite.config.ts",
62
- "build:iife": "vite build -c vite.iife.config.ts"
53
+ "typecheck": "tsc --noEmit",
54
+ "build": "rimraf dist && vite build && vite build --mode iife"
63
55
  }
64
56
  }
@@ -1,5 +0,0 @@
1
- /**
2
- * Applies polyfills required for stable work of the package:
3
- * - `Object.hasOwn` - used by `valibot`
4
- */
5
- export declare function applyPolyfills(): void;
@@ -1,24 +0,0 @@
1
- import { either as E } from 'fp-ts';
2
- export type DecodeBase64UrlError = DOMException;
3
- /**
4
- * Decodes a base-64-url ASCII string.
5
- * @param value - the value to decode.
6
- * @see Learn more about base64url:
7
- * https://herongyang.com/Encoding/Base64URL-Encoding-Algorithm.html
8
- * @see Source:
9
- * https://developer.mozilla.org/ru/docs/Glossary/Base64#solution_1_–_escaping_the_string_before_encoding_it
10
- */
11
- export declare function decodeBase64UrlFp(value: string): E.Either<DecodeBase64UrlError, string>;
12
- /**
13
- * @see decodeBase64UrlFp
14
- */
15
- export declare const decodeBase64Url: ((value: string) => string) & {};
16
- /**
17
- * Creates a base-64-url encoded ASCII string from the passed value.
18
- * @param value - the value to encode.
19
- * @see Learn more about base64url:
20
- * https://herongyang.com/Encoding/Base64URL-Encoding-Algorithm.html
21
- * @see Source:
22
- * https://developer.mozilla.org/ru/docs/Glossary/Base64#solution_1_–_escaping_the_string_before_encoding_it
23
- */
24
- export declare function encodeBase64Url(value: string): string;
@@ -1,10 +0,0 @@
1
- /**
2
- * Returns true in case, passed value contains path `TelegramWebviewProxy.postEvent` property and
3
- * `postEvent` is a function.
4
- * @param value - value to check.
5
- */
6
- export declare function hasWebviewProxy<T>(value: T): value is T & {
7
- TelegramWebviewProxy: {
8
- postEvent: (...args: unknown[]) => unknown;
9
- };
10
- };
@@ -1,5 +0,0 @@
1
- /**
2
- * @see https://stackoverflow.com/a/326076
3
- * @returns True, if current environment is iframe.
4
- */
5
- export declare function isIframe(): boolean;
@@ -1,31 +0,0 @@
1
- import { BetterPromise, BetterPromiseOptions, TimeoutError } from 'better-promises';
2
- import { taskEither as TE } from 'fp-ts';
3
- import { Request2Error } from '../utils/request2.js';
4
- export type isTMAError = Exclude<Request2Error, TimeoutError>;
5
- /**
6
- * @see isTMAFp
7
- */
8
- export declare function isTMA(): boolean;
9
- /**
10
- * @see isTMAFp
11
- */
12
- export declare function isTMA(type: 'complete', options?: BetterPromiseOptions): BetterPromise<boolean>;
13
- /**
14
- * Returns true if the current environment is Telegram Mini Apps.
15
- *
16
- * It uses the `retrieveLaunchParams` function to determine if the environment
17
- * contains launch parameters. In case it does, true will be returned.
18
- *
19
- * In case you need stricter checks, use async override of this function.
20
- */
21
- export declare function isTMAFp(): boolean;
22
- /**
23
- * Returns promise with true if the current environment is Telegram Mini Apps.
24
- *
25
- * First of all, it checks if the current environment contains traits specific
26
- * to the Mini Apps environment. Then, it attempts to call a Mini Apps method
27
- * and waits for a response to be received.
28
- *
29
- * In case you need less strict checks, use sync override of this function.
30
- */
31
- export declare function isTMAFp(type: 'complete', options?: BetterPromiseOptions): TE.TaskEither<isTMAError, boolean>;