@tma.js/bridge 1.3.8 → 1.3.10

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.
@@ -1,4 +1,5 @@
1
- import { log as utilLog } from '@tma.js/logger';
1
+ import { Logger } from '@tma.js/logger';
2
+ export declare const logger: Logger;
2
3
  /**
3
4
  * Sets new debug mode. Enabling debug mode leads to printing
4
5
  * additional messages in console, related to the processes
@@ -19,9 +20,3 @@ export declare function setTargetOrigin(value: string): void;
19
20
  * Returns current global target origin.
20
21
  */
21
22
  export declare function targetOrigin(): string;
22
- /**
23
- * Logs message in case, debug mode is enabled.
24
- * @param level - log level
25
- * @param args - values to print.
26
- */
27
- export declare const log: typeof utilLog;
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("@tma.js/utils"),C=require("@tma.js/logger"),I=require("@tma.js/event-emitter"),o=require("@tma.js/parsing");let x=!1,q="https://web.telegram.org";function J(e){x=e}function M(e){q=e}function G(){return q}const g=(e,...t)=>{x&&C.log(e,"[Bridge]",...t)};function H(e){return e==null}const c=o.rgb().optional(),L=o.number(),U=o.createValueParserGen(e=>e==null?window.innerWidth:L.parse(e)),$=o.json({theme_params:o.json({bg_color:c,text_color:c,hint_color:c,link_color:c,button_color:c,button_text_color:c,secondary_bg_color:c})}),z=o.json({height:o.number(),width:U(),is_state_stable:o.boolean(),is_expanded:o.boolean()}),B=o.json({button_id:o.string({isEmpty:H}).optional()}),F=o.json({data:o.string().optional()}),K=o.json({slug:o.string(),status:o.string()}),Q=o.json({req_id:o.string(),data:e=>e===null?e:o.string().optional().parse(e)}),X=o.json({status:o.string()}),Y=o.json({status:o.string()}),Z=o.json({req_id:o.string(),result:e=>e,error:o.string().optional()}),D=o.json({eventType:o.string(),eventData:e=>e});function V(e,t){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:e,eventData:t})}))}function O(){const e=window;"TelegramGameProxy_receiveEvent"in e||[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(t=>{let r=e;t.forEach((n,i,s)=>{if(i===s.length-1){r[n]=V;return}n in r||(r[n]={}),r=r[n]})})}function ee(e){O(),window.addEventListener("message",t=>{try{const{eventType:r,eventData:n}=D.parse(t.data);e(r,n)}catch{}})}const w="__telegram-cached-emitter__";function te(){const e=new I.EventEmitter,t=(r,...n)=>{g("log","Emitting processed event:",r,...n),e.emit(r,...n)};return window.addEventListener("resize",()=>{t("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),ee((r,n)=>{g("log","Received raw event:",r,n);try{switch(r){case"viewport_changed":return t(r,z.parse(n));case"theme_changed":return t(r,$.parse(n));case"popup_closed":return n==null?t(r,{}):t(r,B.parse(n));case"set_custom_style":return t(r,o.string().parse(n));case"qr_text_received":return t(r,F.parse(n));case"clipboard_text_received":return t(r,Q.parse(n));case"invoice_closed":return t(r,K.parse(n));case"phone_requested":return t("phone_requested",Y.parse(n));case"custom_method_invoked":return t("custom_method_invoked",Z.parse(n));case"write_access_requested":return t("write_access_requested",X.parse(n));case"main_button_pressed":case"back_button_pressed":case"settings_button_pressed":case"scan_qr_popup_closed":return t(r);default:return t(r,n)}}catch(i){g("error","Error processing event:",i)}}),e}function d(){const e=window;return e[w]===void 0&&(e[w]=te()),e[w]}function b(e,t){d().off(e,t)}function v(e,t){return d().on(e,t),()=>b(e,t)}function re(e,t){return d().once(e,t),()=>b(e,t)}function P(e){d().unsubscribe(e)}function ne(e){return d().subscribe(e),()=>P(e)}function j(e){return"external"in e&&a.isRecord(e.external)&&"notify"in e.external&&typeof e.external.notify=="function"}function k(e){return"TelegramWebviewProxy"in e&&a.isRecord(e.TelegramWebviewProxy)&&"postEvent"in e.TelegramWebviewProxy&&typeof e.TelegramWebviewProxy.postEvent=="function"}function W(){try{return window.self!==window.top}catch{return!0}}function R(e,t,r){let n={},i;t===void 0&&r===void 0?n={}:t!==void 0&&r!==void 0?(n=r,i=t):t!==void 0&&("targetOrigin"in t?n=t:i=t);const{targetOrigin:s=G()}=n;if(W()){window.parent.postMessage(JSON.stringify({eventType:e,eventData:i}),s);return}if(j(window)){window.external.notify(JSON.stringify({eventType:e,eventData:i}));return}if(k(window)){window.TelegramWebviewProxy.postEvent(e,JSON.stringify(i));return}throw new Error("Unable to determine current environment and possible way to send event.")}function oe(e,t,r,n){let i,s,l,f;typeof t=="string"||Array.isArray(t)?(l=Array.isArray(t)?t:[t],i=r):(s=t,l=Array.isArray(r)?r:[r],i=n),a.isRecord(s)&&typeof s.req_id=="string"&&(f=s.req_id);const{postEvent:A=R,timeout:h}=i||{},y=i&&"capture"in i?i.capture:null,m=new Promise((S,T)=>{const N=l.map(_=>v(_,p=>{typeof f=="string"&&(!a.isRecord(p)||p.req_id!==f)||typeof y=="function"&&!y(p)||(E(),S(p))})),E=()=>N.forEach(_=>_());try{A(e,s)}catch(_){E(),T(_)}});return typeof h=="number"?a.withTimeout(m,h):m}function u(e,t){return a.compareVersions(e,t)<=0}function ie(e,t){return e==="web_app_open_link"&&"try_instant_view"in t?["try_instant_view"]:e==="web_app_set_header_color"&&"color"in t?["color"]:[]}function se(e,t,r){if(typeof r=="string"){if(e==="web_app_open_link"&&t==="try_instant_view")return u("6.4",r);if(e==="web_app_set_header_color"&&t==="color")return u("6.9",r)}switch(e){case"web_app_open_tg_link":case"web_app_open_invoice":case"web_app_setup_back_button":case"web_app_set_background_color":case"web_app_set_header_color":case"web_app_trigger_haptic_feedback":return u("6.1",t);case"web_app_open_popup":return u("6.2",t);case"web_app_close_scan_qr_popup":case"web_app_open_scan_qr_popup":case"web_app_read_text_from_clipboard":return u("6.4",t);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return u("6.9",t);case"web_app_setup_settings_button":return u("6.10",t);default:return!0}}exports.detectSupportParams=ie;exports.hasExternalNotify=j;exports.hasWebviewProxy=k;exports.isIframe=W;exports.off=b;exports.on=v;exports.once=re;exports.postEvent=R;exports.request=oe;exports.setDebug=J;exports.setTargetOrigin=M;exports.subscribe=ne;exports.supports=se;exports.unsubscribe=P;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("@tma.js/utils"),N=require("@tma.js/logger"),C=require("@tma.js/event-emitter"),o=require("@tma.js/parsing");let x="https://web.telegram.org";const d=new N.Logger("[Bridge]",!1);function I(e){if(e){d.enable();return}d.disable()}function J(e){x=e}function M(){return x}function G(e){return e==null}const c=o.rgb().optional(),L=o.number(),H=o.createValueParserGen(e=>e==null?window.innerWidth:L.parse(e)),$=o.json({theme_params:o.json({bg_color:c,text_color:c,hint_color:c,link_color:c,button_color:c,button_text_color:c,secondary_bg_color:c})}),U=o.json({height:o.number(),width:H(),is_state_stable:o.boolean(),is_expanded:o.boolean()}),z=o.json({button_id:o.string({isEmpty:G}).optional()}),B=o.json({data:o.string().optional()}),F=o.json({slug:o.string(),status:o.string()}),K=o.json({req_id:o.string(),data:e=>e===null?e:o.string().optional().parse(e)}),Q=o.json({status:o.string()}),X=o.json({status:o.string()}),Y=o.json({req_id:o.string(),result:e=>e,error:o.string().optional()}),Z=o.json({eventType:o.string(),eventData:e=>e});function V(e,t){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:e,eventData:t})}))}function D(){const e=window;"TelegramGameProxy_receiveEvent"in e||[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(t=>{let r=e;t.forEach((n,i,s)=>{if(i===s.length-1){r[n]=V;return}n in r||(r[n]={}),r=r[n]})})}function O(e){D(),window.addEventListener("message",t=>{try{const{eventType:r,eventData:n}=Z.parse(t.data);e(r,n)}catch{}})}const w="__telegram-cached-emitter__";function ee(){const e=new C.EventEmitter,t=(r,...n)=>{d.log("Emitting processed event:",r,...n),e.emit(r,...n)};return window.addEventListener("resize",()=>{t("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),O((r,n)=>{d.log("Received raw event:",r,n);try{switch(r){case"viewport_changed":return t(r,U.parse(n));case"theme_changed":return t(r,$.parse(n));case"popup_closed":return n==null?t(r,{}):t(r,z.parse(n));case"set_custom_style":return t(r,o.string().parse(n));case"qr_text_received":return t(r,B.parse(n));case"clipboard_text_received":return t(r,K.parse(n));case"invoice_closed":return t(r,F.parse(n));case"phone_requested":return t("phone_requested",X.parse(n));case"custom_method_invoked":return t("custom_method_invoked",Y.parse(n));case"write_access_requested":return t("write_access_requested",Q.parse(n));case"main_button_pressed":case"back_button_pressed":case"settings_button_pressed":case"scan_qr_popup_closed":return t(r);default:return t(r,n)}}catch(i){d.error("Error processing event:",i)}}),e}function p(){const e=window;return e[w]===void 0&&(e[w]=ee()),e[w]}function b(e,t){p().off(e,t)}function q(e,t){return p().on(e,t),()=>b(e,t)}function te(e,t){return p().once(e,t),()=>b(e,t)}function v(e){p().unsubscribe(e)}function re(e){return p().subscribe(e),()=>v(e)}function P(e){return"external"in e&&u.isRecord(e.external)&&"notify"in e.external&&typeof e.external.notify=="function"}function j(e){return"TelegramWebviewProxy"in e&&u.isRecord(e.TelegramWebviewProxy)&&"postEvent"in e.TelegramWebviewProxy&&typeof e.TelegramWebviewProxy.postEvent=="function"}function k(){try{return window.self!==window.top}catch{return!0}}function W(e,t,r){let n={},i;t===void 0&&r===void 0?n={}:t!==void 0&&r!==void 0?(n=r,i=t):t!==void 0&&("targetOrigin"in t?n=t:i=t);const{targetOrigin:s=M()}=n;if(k()){window.parent.postMessage(JSON.stringify({eventType:e,eventData:i}),s);return}if(P(window)){window.external.notify(JSON.stringify({eventType:e,eventData:i}));return}if(j(window)){window.TelegramWebviewProxy.postEvent(e,JSON.stringify(i));return}throw new Error("Unable to determine current environment and possible way to send event.")}function ne(e,t,r,n){let i,s,g,f;typeof t=="string"||Array.isArray(t)?(g=Array.isArray(t)?t:[t],i=r):(s=t,g=Array.isArray(r)?r:[r],i=n),u.isRecord(s)&&typeof s.req_id=="string"&&(f=s.req_id);const{postEvent:R=W,timeout:h}=i||{},y=i&&"capture"in i?i.capture:null,m=new Promise((A,S)=>{const T=g.map(_=>q(_,l=>{typeof f=="string"&&(!u.isRecord(l)||l.req_id!==f)||typeof y=="function"&&!y(l)||(E(),A(l))})),E=()=>T.forEach(_=>_());try{R(e,s)}catch(_){E(),S(_)}});return typeof h=="number"?u.withTimeout(m,h):m}function a(e,t){return u.compareVersions(e,t)<=0}function oe(e,t){return e==="web_app_open_link"&&"try_instant_view"in t?["try_instant_view"]:e==="web_app_set_header_color"&&"color"in t?["color"]:[]}function ie(e,t,r){if(typeof r=="string"){if(e==="web_app_open_link"&&t==="try_instant_view")return a("6.4",r);if(e==="web_app_set_header_color"&&t==="color")return a("6.9",r)}switch(e){case"web_app_open_tg_link":case"web_app_open_invoice":case"web_app_setup_back_button":case"web_app_set_background_color":case"web_app_set_header_color":case"web_app_trigger_haptic_feedback":return a("6.1",t);case"web_app_open_popup":return a("6.2",t);case"web_app_close_scan_qr_popup":case"web_app_open_scan_qr_popup":case"web_app_read_text_from_clipboard":return a("6.4",t);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return a("6.9",t);case"web_app_setup_settings_button":return a("6.10",t);default:return!0}}exports.detectSupportParams=oe;exports.hasExternalNotify=P;exports.hasWebviewProxy=j;exports.isIframe=k;exports.off=b;exports.on=q;exports.once=te;exports.postEvent=W;exports.request=ne;exports.setDebug=I;exports.setTargetOrigin=J;exports.subscribe=re;exports.supports=ie;exports.unsubscribe=v;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../src/globals.ts","../src/events/parsing.ts","../src/events/onTelegramEvent.ts","../src/events/emitter.ts","../src/events/off.ts","../src/events/on.ts","../src/events/once.ts","../src/events/unsubscribe.ts","../src/events/subscribe.ts","../src/env.ts","../src/methods/postEvent.ts","../src/request.ts","../src/supports.ts"],"sourcesContent":["import { log as utilLog } from '@tma.js/logger';\n\nlet currentDebug = false;\nlet currentTargetOrigin = 'https://web.telegram.org';\n\n/**\n * Sets new debug mode. Enabling debug mode leads to printing\n * additional messages in console, related to the processes\n * inside the package.\n * @param value - should debug mode be enabled.\n */\nexport function setDebug(value: boolean): void {\n currentDebug = value;\n}\n\n/**\n * Sets new global targetOrigin, used by `postEvent` method.\n * Default value is \"https://web.telegram.org\". You don't need to\n * use this method until you know what you are doing.\n *\n * This method could be used for test purposes.\n * @param value - new target origin.\n */\nexport function setTargetOrigin(value: string): void {\n currentTargetOrigin = value;\n}\n\n/**\n * Returns current global target origin.\n */\nexport function targetOrigin(): string {\n return currentTargetOrigin;\n}\n\n/**\n * Logs message in case, debug mode is enabled.\n * @param level - log level\n * @param args - values to print.\n */\nexport const log: typeof utilLog = (level, ...args) => {\n if (currentDebug) {\n utilLog(level, '[Bridge]', ...args);\n }\n};\n","import {\n number,\n string,\n boolean,\n json,\n rgb,\n createValueParserGen,\n} from '@tma.js/parsing';\n\nimport type {\n ClipboardTextReceivedPayload, CustomMethodInvokedPayload,\n InvoiceClosedPayload, PhoneRequestedPayload,\n PopupClosedPayload, QrTextReceivedPayload,\n ThemeChangedPayload,\n ViewportChangedPayload, WriteAccessRequestedPayload,\n} from './payloads.js';\n\nfunction isNullOrUndefined(value: unknown): boolean {\n return value === null || value === undefined;\n}\n\nconst rgbOptional = rgb().optional();\nconst num = number();\n\nconst windowWidthParser = createValueParserGen((value) => (value === null || value === undefined\n ? window.innerWidth\n : num.parse(value)));\n\n/**\n * Parses incoming value as ThemeChangedPayload.\n */\nexport const themeChangedPayload = json<ThemeChangedPayload>({\n theme_params: json({\n bg_color: rgbOptional,\n text_color: rgbOptional,\n hint_color: rgbOptional,\n link_color: rgbOptional,\n button_color: rgbOptional,\n button_text_color: rgbOptional,\n secondary_bg_color: rgbOptional,\n }),\n});\n\n/**\n * Parses incoming value as ViewportChangedPayload.\n * @param value - value to parse.\n */\nexport const viewportChangedPayload = json<ViewportChangedPayload>({\n height: number(),\n width: windowWidthParser(),\n is_state_stable: boolean(),\n is_expanded: boolean(),\n});\n\n/**\n * Parses incoming value as PopupClosedPayload.\n */\nexport const popupClosedPayload = json<PopupClosedPayload>({\n button_id: string({ isEmpty: isNullOrUndefined }).optional(),\n});\n\n/**\n * Parses incoming value as QrTextReceivedPayload.\n */\nexport const qrTextReceivedPayload = json<QrTextReceivedPayload>({\n data: string().optional(),\n});\n\n/**\n * Parses incoming value as InvoiceClosedPayload.\n */\nexport const invoiceClosedPayload = json<InvoiceClosedPayload>({\n slug: string(),\n status: string(),\n});\n\n/**\n * Parses incoming value as clipboard text received payload.\n */\nexport const clipboardTextReceivedPayload = json<ClipboardTextReceivedPayload>({\n req_id: string(),\n data: (value) => (value === null ? value : string().optional().parse(value)),\n});\n\n/**\n * Parses incoming value as WriteAccessRequestedPayload.\n */\nexport const writeAccessRequestedPayload = json<WriteAccessRequestedPayload>({ status: string() });\n\n/**\n * Parses incoming value as PhoneRequestedPayload.\n */\nexport const phoneRequestedPayload = json<PhoneRequestedPayload>({ status: string() });\n\n/**\n * Parses incoming value as CustomMethodInvokedPayload.\n */\nexport const customMethodInvokedPayload = json<CustomMethodInvokedPayload>({\n req_id: string(),\n result: (value) => value,\n error: string().optional(),\n});\n","import { json, string } from '@tma.js/parsing';\n\n/**\n * Extracts event data from native application event.\n */\nconst eventDataJson = json<{ eventType: string; eventData?: unknown }>({\n eventType: string(),\n eventData: (value) => value,\n});\n\n/**\n * Emits event sent from Telegram native application like it was sent in\n * default web environment between 2 iframes. It dispatches new MessageEvent\n * and expects it to be handled via `window.addEventListener('message', ...)`\n * as developer would do it to handle messages sent from parent iframe.\n * @param eventType - event name.\n * @param eventData - event payload.\n */\nfunction emitEvent(eventType: string, eventData: unknown): void {\n window.dispatchEvent(new MessageEvent('message', {\n data: JSON.stringify({ eventType, eventData }),\n }));\n}\n\n/**\n * Defines special handlers by known paths, which are recognized by\n * Telegram as ports to receive events. This function also sets special\n * function in global window object to prevent duplicate declaration.\n */\nfunction defineEventHandlers(): void {\n const wnd: any = window;\n\n // Prevent from duplicate event handlers definition.\n if ('TelegramGameProxy_receiveEvent' in wnd) {\n return;\n }\n\n // Iterate over each path, where \"receiveEvent\" function should be\n // defined. This function is called by external environment in case,\n // it wants to emit some event.\n [\n ['TelegramGameProxy_receiveEvent'], // Windows Phone.\n ['TelegramGameProxy', 'receiveEvent'], // Desktop.\n ['Telegram', 'WebView', 'receiveEvent'], // Android and iOS.\n ].forEach((path) => {\n // Path starts from \"window\" object.\n let pointer = wnd;\n\n path.forEach((item, idx, arr) => {\n // We are on the last iteration, where function property name is passed.\n if (idx === arr.length - 1) {\n pointer[item] = emitEvent;\n return;\n }\n\n if (!(item in pointer)) {\n pointer[item] = {};\n }\n pointer = pointer[item];\n });\n });\n}\n\n/**\n * Adds listener to window \"message\" event assuming, that this event could\n * be sent by Telegram native application. Calls passed callback with event\n * type and data.\n * @param cb - callback to call.\n */\nexport function onTelegramEvent(cb: (eventType: string, eventData: unknown) => void): void {\n // Define event handlers to make sure, message handler will work correctly.\n defineEventHandlers();\n\n // We expect Telegram to send us new event through \"message\" event.\n window.addEventListener('message', (event) => {\n try {\n const { eventType, eventData } = eventDataJson.parse(event.data);\n cb(eventType, eventData);\n } catch {\n // We ignore incorrect messages as they could be generated by any other code.\n }\n });\n}\n","import { EventEmitter as UtilEventEmitter } from '@tma.js/event-emitter';\nimport { string } from '@tma.js/parsing';\n\nimport { log } from '../globals.js';\nimport {\n clipboardTextReceivedPayload,\n customMethodInvokedPayload,\n invoiceClosedPayload,\n phoneRequestedPayload,\n popupClosedPayload,\n qrTextReceivedPayload,\n themeChangedPayload,\n viewportChangedPayload,\n writeAccessRequestedPayload,\n} from './parsing.js';\nimport { onTelegramEvent } from './onTelegramEvent.js';\n\nimport type { EventEmitter, EventName } from './events.js';\n\nconst CACHED_EMITTER = '__telegram-cached-emitter__';\n\n/**\n * Returns event emitter which could be safely used, to process events from\n * Telegram native application.\n */\nexport function createEmitter(): EventEmitter {\n const emitter: EventEmitter = new UtilEventEmitter();\n const emit: EventEmitter['emit'] = (event: any, ...data: any[]) => {\n log('log', 'Emitting processed event:', event, ...data);\n emitter.emit(event, ...data);\n };\n\n // Desktop version of Telegram is sometimes not sending the viewport_changed\n // event. For example, when main button is shown. That's why we should\n // add our own listener to make sure, viewport information is always fresh.\n // Issue: https://github.com/Telegram-Mini-Apps/tma.js/issues/10\n window.addEventListener('resize', () => {\n emit('viewport_changed', {\n width: window.innerWidth,\n height: window.innerHeight,\n is_state_stable: true,\n is_expanded: true,\n });\n });\n\n // In case, any Telegram event was received, we should prepare data before\n // passing it to emitter.\n onTelegramEvent((eventType: EventName | string, eventData): void => {\n log('log', 'Received raw event:', eventType, eventData);\n\n try {\n switch (eventType) {\n case 'viewport_changed':\n return emit(eventType, viewportChangedPayload.parse(eventData));\n\n case 'theme_changed':\n return emit(eventType, themeChangedPayload.parse(eventData));\n\n case 'popup_closed':\n // FIXME: Payloads are different on different platforms.\n // Issue: https://github.com/Telegram-Mini-Apps/tma.js/issues/2\n if (\n // Sent on desktop.\n eventData === undefined\n // Sent on iOS.\n || eventData === null\n ) {\n return emit(eventType, {});\n }\n return emit(eventType, popupClosedPayload.parse(eventData));\n\n case 'set_custom_style':\n return emit(eventType, string().parse(eventData));\n\n case 'qr_text_received':\n return emit(eventType, qrTextReceivedPayload.parse(eventData));\n\n case 'clipboard_text_received':\n return emit(eventType, clipboardTextReceivedPayload.parse(eventData));\n\n case 'invoice_closed':\n return emit(eventType, invoiceClosedPayload.parse(eventData));\n\n case 'phone_requested':\n return emit('phone_requested', phoneRequestedPayload.parse(eventData));\n\n case 'custom_method_invoked':\n return emit('custom_method_invoked', customMethodInvokedPayload.parse(eventData));\n\n case 'write_access_requested':\n return emit('write_access_requested', writeAccessRequestedPayload.parse(eventData));\n\n // Events which have no parameters.\n case 'main_button_pressed':\n case 'back_button_pressed':\n case 'settings_button_pressed':\n case 'scan_qr_popup_closed':\n return emit(eventType);\n\n // All other event listeners will receive unknown type of data.\n default:\n return emit(eventType as any, eventData);\n }\n } catch (cause) {\n log('error', 'Error processing event:', cause);\n }\n });\n\n return emitter;\n}\n\n/**\n * Returns singleton instance of bridge EventEmitter. Also, defines\n * Telegram event handlers.\n */\nexport function singletonEmitter(): EventEmitter {\n const wnd: any = window;\n const cachedEmitter = wnd[CACHED_EMITTER];\n\n if (cachedEmitter === undefined) {\n wnd[CACHED_EMITTER] = createEmitter();\n }\n\n return wnd[CACHED_EMITTER];\n}\n","import { singletonEmitter } from './emitter.js';\n\nimport type { EventName, EventListener } from './events.js';\n\n/**\n * Removes listener from specified event.\n * @param event - event to listen.\n * @param listener - event listener.\n */\nexport function off<E extends EventName>(event: E, listener: EventListener<E>): void {\n singletonEmitter().off(event, listener);\n}\n","import { singletonEmitter } from './emitter.js';\nimport { off } from './off.js';\n\nimport type { EventName, EventListener } from './events.js';\n\ntype StopListening = () => void;\n\n/**\n * Adds new listener to the specified event. Returns handler\n * which allows to stop listening to event.\n * @param event - event name.\n * @param listener - event listener.\n */\nexport function on<E extends EventName>(event: E, listener: EventListener<E>): StopListening {\n singletonEmitter().on(event, listener);\n return () => off(event, listener);\n}\n","import { singletonEmitter } from './emitter.js';\nimport { off } from './off.js';\n\nimport type { EventName, EventListener } from './events.js';\n\ntype StopListening = () => void;\n\n/**\n * Works the same as \"on\" method, but after catching the event, will remove event listener.\n * @param event - event name.\n * @param listener - event listener.\n */\nexport function once<E extends EventName>(event: E, listener: EventListener<E>): StopListening {\n singletonEmitter().once(event, listener);\n return () => off(event, listener);\n}\n","import { singletonEmitter } from './emitter.js';\n\nimport type { GlobalEventListener } from './events.js';\n\n/**\n * Removes global event listener.\n * @param listener - event listener.\n */\nexport function unsubscribe(listener: GlobalEventListener): void {\n singletonEmitter().unsubscribe(listener);\n}\n","import { singletonEmitter } from './emitter.js';\nimport { unsubscribe } from './unsubscribe.js';\n\nimport type { GlobalEventListener } from './events.js';\n\ntype StopListening = () => void;\n\n/**\n * Subscribes to all events sent from the native Telegram application.\n * Returns function used to remove added event listener.\n * @param listener - event listener.\n */\nexport function subscribe(listener: GlobalEventListener): StopListening {\n singletonEmitter().subscribe(listener);\n return () => unsubscribe(listener);\n}\n","import { isRecord } from '@tma.js/utils';\n\ntype AnyFunc = (...args: unknown[]) => unknown;\n\ntype WithExternalNotify<T> = T & {\n external: { notify: AnyFunc }\n};\n\ntype WithWebviewProxy<T> = T & {\n TelegramWebviewProxy: {\n postEvent: AnyFunc;\n }\n};\n\n/**\n * Returns true in case, passed value contains path `external.notify` property and `notify` is a\n * function.\n * @param value - value to check.\n */\nexport function hasExternalNotify<T extends {}>(value: T): value is WithExternalNotify<T> {\n return 'external' in value\n && isRecord(value.external)\n && 'notify' in value.external\n && typeof value.external.notify === 'function';\n}\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 extends {}>(value: T): value is WithWebviewProxy<T> {\n return 'TelegramWebviewProxy' in value\n && isRecord(value.TelegramWebviewProxy)\n && 'postEvent' in value.TelegramWebviewProxy\n && typeof value.TelegramWebviewProxy.postEvent === 'function';\n}\n\n/**\n * Returns true in case, current environment is iframe.\n * @see https://stackoverflow.com/a/326076\n */\nexport function isIframe(): boolean {\n try {\n return window.self !== window.top;\n } catch (e) {\n return true;\n }\n}\n","import {\n isIframe,\n hasExternalNotify,\n hasWebviewProxy,\n} from '../env.js';\nimport { targetOrigin as globalTargetOrigin } from '../globals.js';\n\nimport type {\n EmptyMethodName,\n MethodName,\n MethodParams,\n NonEmptyMethodName,\n} from './params.js';\n\ninterface PostEventOptions {\n /**\n * Origin used while posting message. This option is only used in case,\n * current environment is browser (Web version of Telegram) and could\n * be used for test purposes.\n * @default 'https://web.telegram.org'\n */\n targetOrigin?: string;\n}\n\nexport type PostEvent = typeof postEvent;\n\n/**\n * Sends event to native application which launched Web App. This function\n * accepts only events, which require arguments.\n * @param eventType - event name.\n * @param params - event parameters.\n * @param options - posting options.\n * @throws {Error} Bridge could not determine current\n * environment and possible way to send event.\n */\nexport function postEvent<E extends NonEmptyMethodName>(\n eventType: E,\n params: MethodParams<E>,\n options?: PostEventOptions,\n): void;\n\n/**\n * Sends event to native application which launched Web App. This function\n * accepts only events, which require arguments.\n * @param eventType - event name.\n * @param options - posting options.\n * @throws {Error} Bridge could not determine current\n * environment and possible way to send event.\n */\nexport function postEvent(eventType: EmptyMethodName, options?: PostEventOptions): void;\n\nexport function postEvent(\n eventType: MethodName,\n paramsOrOptions?: MethodParams<MethodName> | PostEventOptions,\n options?: PostEventOptions,\n): void {\n let postOptions: PostEventOptions = {};\n let eventData: any;\n\n if (paramsOrOptions === undefined && options === undefined) {\n // Parameters and options were not passed.\n postOptions = {};\n } else if (paramsOrOptions !== undefined && options !== undefined) {\n // Both parameters and options passed.\n postOptions = options;\n eventData = paramsOrOptions;\n } else if (paramsOrOptions !== undefined) {\n // Only parameters were passed.\n if ('targetOrigin' in paramsOrOptions) {\n postOptions = paramsOrOptions;\n } else {\n eventData = paramsOrOptions;\n }\n }\n const { targetOrigin = globalTargetOrigin() } = postOptions;\n\n // Telegram Web.\n if (isIframe()) {\n window.parent.postMessage(JSON.stringify({\n eventType,\n eventData,\n }), targetOrigin);\n return;\n }\n\n // Telegram for Windows Phone or Android.\n if (hasExternalNotify(window)) {\n window.external.notify(JSON.stringify({ eventType, eventData }));\n return;\n }\n\n // Telegram for iOS and macOS.\n if (hasWebviewProxy(window)) {\n window.TelegramWebviewProxy.postEvent(eventType, JSON.stringify(eventData));\n return;\n }\n\n // Otherwise current environment is unknown, and we are not able to send\n // event.\n throw new Error(\n 'Unable to determine current environment and possible way to send event.',\n );\n}\n","import { withTimeout, isRecord } from '@tma.js/utils';\n\nimport type { And, If, IsNever } from '@tma.js/util-types';\n\nimport { postEvent as defaultPostEvent, type PostEvent } from './methods/postEvent.js';\nimport { on, type EventName, type EventParams, type EventHasParams } from './events/index.js';\n\nimport type {\n EmptyMethodName, MethodHasParams,\n MethodName,\n MethodParams,\n NonEmptyMethodName,\n} from './methods/params.js';\n\n/**\n * Names of methods, which require passing \"req_id\" parameter.\n */\ntype MethodNameWithRequestId = {\n [Method in MethodName]: If<\n And<MethodHasParams<Method>, MethodParams<Method> extends { req_id: string } ? true : false>,\n Method,\n never\n >;\n}[MethodName];\n\n/**\n * Names of events, which contain \"req_id\" parameter.\n */\ntype EventNameWithRequestId = {\n [Event in EventName]: If<\n And<EventHasParams<Event>, EventParams<Event> extends { req_id: string } ? true : false>,\n Event,\n never\n >;\n}[EventName];\n\nexport interface RequestOptions {\n /**\n * Bridge postEvent method.\n * @default Global postEvent method.\n */\n postEvent?: PostEvent;\n\n /**\n * Execution timeout.\n */\n timeout?: number;\n}\n\nexport interface RequestOptionsAdvanced<EventPayload> extends RequestOptions {\n /**\n * Should return true in case, this event should be captured. If not specified,\n * request is not skipping captured events.\n */\n capture?: If<IsNever<EventPayload>, () => boolean, (payload: EventPayload) => boolean>;\n}\n\n/**\n * Calls specified TWA method and captures one of the specified events. Returns promise\n * which will be resolved in case, event with specified in method request identifier\n * was captured.\n * @param method - method to execute.\n * @param params - method parameters.\n * @param event - event or events to listen.\n * @param options - additional execution options.\n */\nexport function request<\n Method extends MethodNameWithRequestId,\n Event extends EventNameWithRequestId,\n>(\n method: Method,\n params: MethodParams<Method>,\n event: Event | Event[],\n options?: RequestOptions,\n): Promise<EventParams<Event>>;\n\n/**\n * Calls specified TWA method and captures one of the specified events. Returns promise\n * which will be resolved in case, specified event was captured.\n * @param method - method to execute.\n * @param event - event or events to listen.\n * @param options - additional execution options.\n */\nexport function request<Method extends EmptyMethodName, Event extends EventName>(\n method: Method,\n event: Event | Event[],\n options?: RequestOptionsAdvanced<EventParams<Event>>,\n): Promise<EventParams<Event>>;\n\n/**\n * Calls specified TWA method and captures one of the specified events. Returns promise\n * which will be resolved in case, specified event was captured.\n * @param method - method to execute\n * @param params - method parameters.\n * @param event - event or events to listen\n * @param options - additional execution options.\n */\nexport function request<Method extends NonEmptyMethodName, Event extends EventName>(\n method: Method,\n params: MethodParams<Method>,\n event: Event | Event[],\n options?: RequestOptionsAdvanced<EventParams<Event>>,\n): Promise<EventParams<Event>>;\n\nexport function request(\n method: MethodName,\n eventOrParams: EventName | EventName[] | EventParams<any>,\n eventOrOptions?: EventName | EventName[] | RequestOptions | RequestOptionsAdvanced<any>,\n options?: RequestOptions | RequestOptionsAdvanced<any>,\n): Promise<any> {\n let executionOptions: RequestOptions | RequestOptionsAdvanced<any> | undefined;\n let methodParams: EventParams<any> | undefined;\n let events: EventName[];\n let requestId: string | undefined;\n\n if (typeof eventOrParams === 'string' || Array.isArray(eventOrParams)) {\n // Override: [method, event, options?]\n events = Array.isArray(eventOrParams) ? eventOrParams : [eventOrParams] as EventName[];\n executionOptions = eventOrOptions as (RequestOptionsAdvanced<any> | undefined);\n } else {\n // Override: [method, params, event, options?]\n methodParams = eventOrParams as EventParams<any>;\n events = Array.isArray(eventOrOptions) ? eventOrOptions : [eventOrOptions] as EventName[];\n executionOptions = options;\n }\n\n // In case, method parameters were passed, and they contained request identifier, we should store\n // it and wait for the event with this identifier to occur.\n if (isRecord(methodParams) && typeof methodParams.req_id === 'string') {\n requestId = methodParams.req_id;\n }\n\n const { postEvent = defaultPostEvent, timeout } = executionOptions || {};\n const capture = executionOptions && 'capture' in executionOptions\n ? executionOptions.capture\n : null;\n\n const promise = new Promise((res, rej) => {\n // Iterate over each event and create event listener.\n const stoppers = events.map((ev) => on(ev, (data?) => {\n // If request identifier was specified, we are waiting for event with the same value\n // to occur.\n if (typeof requestId === 'string' && (!isRecord(data) || data.req_id !== requestId)) {\n return;\n }\n\n if (typeof capture === 'function' && !capture(data)) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n stopListening();\n res(data);\n }));\n\n // Function which removes all event listeners.\n const stopListening = () => stoppers.forEach((stop) => stop());\n\n try {\n // We are wrapping this call in try catch, because it can throw errors in case,\n // compatibility check was enabled. We want an error to be captured by promise, not by\n // another one external try catch.\n postEvent(method as any, methodParams);\n } catch (e) {\n stopListening();\n rej(e);\n }\n });\n\n return typeof timeout === 'number' ? withTimeout(promise, timeout) : promise;\n}\n","import { compareVersions, type Version } from '@tma.js/utils';\n\nimport type {\n HasCheckSupportMethodParam,\n HasCheckSupportMethodName,\n MethodName,\n MethodParams,\n NonEmptyMethodName,\n} from './methods/index.js';\n\nfunction lessOrEqual(a: Version, b: Version): boolean {\n return compareVersions(a, b) <= 0;\n}\n\n/**\n * By specified method and parameters extracts properties which could be used by\n * supports function as TWA method parameter.\n * @param method - TWA method.\n * @param params - method parameters.\n */\nexport function detectSupportParams<M extends NonEmptyMethodName>(\n method: M,\n params: MethodParams<M>,\n): HasCheckSupportMethodParam<HasCheckSupportMethodName>[] {\n if (method === 'web_app_open_link') {\n if ('try_instant_view' in params) {\n return ['try_instant_view'];\n }\n }\n\n if (method === 'web_app_set_header_color') {\n if ('color' in params) {\n return ['color'];\n }\n }\n\n return [];\n}\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 HasCheckSupportMethodName>(\n method: M,\n param: HasCheckSupportMethodParam<M>,\n inVersion: Version,\n): boolean;\n/**\n * Returns true in case, specified method is supported in passed version.\n * @param method - method name.\n * @param inVersion - platform version.\n */\nexport function supports(method: MethodName, inVersion: Version): boolean;\nexport function supports(\n method: MethodName,\n paramOrVersion: Version | string,\n inVersion?: string,\n): boolean {\n // Method name, parameter, target version.\n if (typeof inVersion === 'string') {\n if (method === 'web_app_open_link') {\n if (paramOrVersion === 'try_instant_view') {\n return lessOrEqual('6.4', inVersion);\n }\n }\n\n if (method === 'web_app_set_header_color') {\n if (paramOrVersion === 'color') {\n return lessOrEqual('6.9', inVersion);\n }\n }\n }\n\n // Method name, target version.\n switch (method) {\n case 'web_app_open_tg_link':\n case 'web_app_open_invoice':\n case 'web_app_setup_back_button':\n case 'web_app_set_background_color':\n case 'web_app_set_header_color':\n case 'web_app_trigger_haptic_feedback':\n return lessOrEqual('6.1', paramOrVersion);\n case 'web_app_open_popup':\n return lessOrEqual('6.2', paramOrVersion);\n case 'web_app_close_scan_qr_popup':\n case 'web_app_open_scan_qr_popup':\n case 'web_app_read_text_from_clipboard':\n return lessOrEqual('6.4', paramOrVersion);\n case 'web_app_invoke_custom_method':\n case 'web_app_request_write_access':\n case 'web_app_request_phone':\n return lessOrEqual('6.9', paramOrVersion);\n case 'web_app_setup_settings_button':\n return lessOrEqual('6.10', paramOrVersion);\n default:\n return true;\n }\n}\n"],"names":["currentDebug","currentTargetOrigin","setDebug","value","setTargetOrigin","targetOrigin","log","level","args","utilLog","isNullOrUndefined","rgbOptional","rgb","num","number","windowWidthParser","createValueParserGen","themeChangedPayload","json","viewportChangedPayload","boolean","popupClosedPayload","string","qrTextReceivedPayload","invoiceClosedPayload","clipboardTextReceivedPayload","writeAccessRequestedPayload","phoneRequestedPayload","customMethodInvokedPayload","eventDataJson","emitEvent","eventType","eventData","defineEventHandlers","wnd","path","pointer","item","idx","arr","onTelegramEvent","cb","event","CACHED_EMITTER","createEmitter","emitter","UtilEventEmitter","emit","data","cause","singletonEmitter","off","listener","on","once","unsubscribe","subscribe","hasExternalNotify","isRecord","hasWebviewProxy","isIframe","postEvent","paramsOrOptions","options","postOptions","globalTargetOrigin","request","method","eventOrParams","eventOrOptions","executionOptions","methodParams","events","requestId","defaultPostEvent","timeout","capture","promise","res","rej","stoppers","ev","stopListening","stop","e","withTimeout","lessOrEqual","a","b","compareVersions","detectSupportParams","params","supports","paramOrVersion","inVersion"],"mappings":"6MAEA,IAAIA,EAAe,GACfC,EAAsB,2BAQnB,SAASC,EAASC,EAAsB,CAC9BH,EAAAG,CACjB,CAUO,SAASC,EAAgBD,EAAqB,CAC7BF,EAAAE,CACxB,CAKO,SAASE,GAAuB,CAC9B,OAAAJ,CACT,CAOa,MAAAK,EAAsB,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IK,CAAC,CACP,CAAA,CACD,EAED,OAAO,OAAOT,GAAY,SAAWU,EAAAA,YAAYR,EAASF,CAAO,EAAIE,CACvE,CChKA,SAASS,EAAYC,EAAYC,EAAqB,CAC7C,OAAAC,kBAAgBF,EAAGC,CAAC,GAAK,CAClC,CAQgB,SAAAE,GACdvB,EACAwB,EACyD,CACzD,OAAIxB,IAAW,qBACT,qBAAsBwB,EACjB,CAAC,kBAAkB,EAI1BxB,IAAW,4BACT,UAAWwB,EACN,CAAC,OAAO,EAIZ,EACT,CAmBgB,SAAAC,GACdzB,EACA0B,EACAC,EACS,CAEL,GAAA,OAAOA,GAAc,SAAU,CACjC,GAAI3B,IAAW,qBACT0B,IAAmB,mBACd,OAAAP,EAAY,MAAOQ,CAAS,EAIvC,GAAI3B,IAAW,4BACT0B,IAAmB,QACd,OAAAP,EAAY,MAAOQ,CAAS,CAGzC,CAGA,OAAQ3B,EAAQ,CACd,IAAK,uBACL,IAAK,uBACL,IAAK,4BACL,IAAK,+BACL,IAAK,2BACL,IAAK,kCACI,OAAAmB,EAAY,MAAOO,CAAc,EAC1C,IAAK,qBACI,OAAAP,EAAY,MAAOO,CAAc,EAC1C,IAAK,8BACL,IAAK,6BACL,IAAK,mCACI,OAAAP,EAAY,MAAOO,CAAc,EAC1C,IAAK,+BACL,IAAK,+BACL,IAAK,wBACI,OAAAP,EAAY,MAAOO,CAAc,EAC1C,IAAK,gCACI,OAAAP,EAAY,OAAQO,CAAc,EAC3C,QACS,MAAA,EACX,CACF"}
1
+ {"version":3,"file":"index.cjs","sources":["../src/globals.ts","../src/events/parsing.ts","../src/events/onTelegramEvent.ts","../src/events/emitter.ts","../src/events/off.ts","../src/events/on.ts","../src/events/once.ts","../src/events/unsubscribe.ts","../src/events/subscribe.ts","../src/env.ts","../src/methods/postEvent.ts","../src/request.ts","../src/supports.ts"],"sourcesContent":["import { Logger } from '@tma.js/logger';\n\nlet currentTargetOrigin = 'https://web.telegram.org';\n\nexport const logger = new Logger('[Bridge]', false);\n\n/**\n * Sets new debug mode. Enabling debug mode leads to printing\n * additional messages in console, related to the processes\n * inside the package.\n * @param value - should debug mode be enabled.\n */\nexport function setDebug(value: boolean): void {\n if (value) {\n logger.enable();\n return;\n }\n logger.disable();\n}\n\n/**\n * Sets new global targetOrigin, used by `postEvent` method.\n * Default value is \"https://web.telegram.org\". You don't need to\n * use this method until you know what you are doing.\n *\n * This method could be used for test purposes.\n * @param value - new target origin.\n */\nexport function setTargetOrigin(value: string): void {\n currentTargetOrigin = value;\n}\n\n/**\n * Returns current global target origin.\n */\nexport function targetOrigin(): string {\n return currentTargetOrigin;\n}\n","import {\n number,\n string,\n boolean,\n json,\n rgb,\n createValueParserGen,\n} from '@tma.js/parsing';\n\nimport type {\n ClipboardTextReceivedPayload, CustomMethodInvokedPayload,\n InvoiceClosedPayload, PhoneRequestedPayload,\n PopupClosedPayload, QrTextReceivedPayload,\n ThemeChangedPayload,\n ViewportChangedPayload, WriteAccessRequestedPayload,\n} from './payloads.js';\n\nfunction isNullOrUndefined(value: unknown): boolean {\n return value === null || value === undefined;\n}\n\nconst rgbOptional = rgb().optional();\nconst num = number();\n\nconst windowWidthParser = createValueParserGen((value) => (value === null || value === undefined\n ? window.innerWidth\n : num.parse(value)));\n\n/**\n * Parses incoming value as ThemeChangedPayload.\n */\nexport const themeChangedPayload = json<ThemeChangedPayload>({\n theme_params: json({\n bg_color: rgbOptional,\n text_color: rgbOptional,\n hint_color: rgbOptional,\n link_color: rgbOptional,\n button_color: rgbOptional,\n button_text_color: rgbOptional,\n secondary_bg_color: rgbOptional,\n }),\n});\n\n/**\n * Parses incoming value as ViewportChangedPayload.\n * @param value - value to parse.\n */\nexport const viewportChangedPayload = json<ViewportChangedPayload>({\n height: number(),\n width: windowWidthParser(),\n is_state_stable: boolean(),\n is_expanded: boolean(),\n});\n\n/**\n * Parses incoming value as PopupClosedPayload.\n */\nexport const popupClosedPayload = json<PopupClosedPayload>({\n button_id: string({ isEmpty: isNullOrUndefined }).optional(),\n});\n\n/**\n * Parses incoming value as QrTextReceivedPayload.\n */\nexport const qrTextReceivedPayload = json<QrTextReceivedPayload>({\n data: string().optional(),\n});\n\n/**\n * Parses incoming value as InvoiceClosedPayload.\n */\nexport const invoiceClosedPayload = json<InvoiceClosedPayload>({\n slug: string(),\n status: string(),\n});\n\n/**\n * Parses incoming value as clipboard text received payload.\n */\nexport const clipboardTextReceivedPayload = json<ClipboardTextReceivedPayload>({\n req_id: string(),\n data: (value) => (value === null ? value : string().optional().parse(value)),\n});\n\n/**\n * Parses incoming value as WriteAccessRequestedPayload.\n */\nexport const writeAccessRequestedPayload = json<WriteAccessRequestedPayload>({ status: string() });\n\n/**\n * Parses incoming value as PhoneRequestedPayload.\n */\nexport const phoneRequestedPayload = json<PhoneRequestedPayload>({ status: string() });\n\n/**\n * Parses incoming value as CustomMethodInvokedPayload.\n */\nexport const customMethodInvokedPayload = json<CustomMethodInvokedPayload>({\n req_id: string(),\n result: (value) => value,\n error: string().optional(),\n});\n","import { json, string } from '@tma.js/parsing';\n\n/**\n * Extracts event data from native application event.\n */\nconst eventDataJson = json<{ eventType: string; eventData?: unknown }>({\n eventType: string(),\n eventData: (value) => value,\n});\n\n/**\n * Emits event sent from Telegram native application like it was sent in\n * default web environment between 2 iframes. It dispatches new MessageEvent\n * and expects it to be handled via `window.addEventListener('message', ...)`\n * as developer would do it to handle messages sent from parent iframe.\n * @param eventType - event name.\n * @param eventData - event payload.\n */\nfunction emitEvent(eventType: string, eventData: unknown): void {\n window.dispatchEvent(new MessageEvent('message', {\n data: JSON.stringify({ eventType, eventData }),\n }));\n}\n\n/**\n * Defines special handlers by known paths, which are recognized by\n * Telegram as ports to receive events. This function also sets special\n * function in global window object to prevent duplicate declaration.\n */\nfunction defineEventHandlers(): void {\n const wnd: any = window;\n\n // Prevent from duplicate event handlers definition.\n if ('TelegramGameProxy_receiveEvent' in wnd) {\n return;\n }\n\n // Iterate over each path, where \"receiveEvent\" function should be\n // defined. This function is called by external environment in case,\n // it wants to emit some event.\n [\n ['TelegramGameProxy_receiveEvent'], // Windows Phone.\n ['TelegramGameProxy', 'receiveEvent'], // Desktop.\n ['Telegram', 'WebView', 'receiveEvent'], // Android and iOS.\n ].forEach((path) => {\n // Path starts from \"window\" object.\n let pointer = wnd;\n\n path.forEach((item, idx, arr) => {\n // We are on the last iteration, where function property name is passed.\n if (idx === arr.length - 1) {\n pointer[item] = emitEvent;\n return;\n }\n\n if (!(item in pointer)) {\n pointer[item] = {};\n }\n pointer = pointer[item];\n });\n });\n}\n\n/**\n * Adds listener to window \"message\" event assuming, that this event could\n * be sent by Telegram native application. Calls passed callback with event\n * type and data.\n * @param cb - callback to call.\n */\nexport function onTelegramEvent(cb: (eventType: string, eventData: unknown) => void): void {\n // Define event handlers to make sure, message handler will work correctly.\n defineEventHandlers();\n\n // We expect Telegram to send us new event through \"message\" event.\n window.addEventListener('message', (event) => {\n try {\n const { eventType, eventData } = eventDataJson.parse(event.data);\n cb(eventType, eventData);\n } catch {\n // We ignore incorrect messages as they could be generated by any other code.\n }\n });\n}\n","import { EventEmitter as UtilEventEmitter } from '@tma.js/event-emitter';\nimport { string } from '@tma.js/parsing';\n\nimport { logger } from '../globals.js';\nimport {\n clipboardTextReceivedPayload,\n customMethodInvokedPayload,\n invoiceClosedPayload,\n phoneRequestedPayload,\n popupClosedPayload,\n qrTextReceivedPayload,\n themeChangedPayload,\n viewportChangedPayload,\n writeAccessRequestedPayload,\n} from './parsing.js';\nimport { onTelegramEvent } from './onTelegramEvent.js';\n\nimport type { EventEmitter, EventName } from './events.js';\n\nconst CACHED_EMITTER = '__telegram-cached-emitter__';\n\n/**\n * Returns event emitter which could be safely used, to process events from\n * Telegram native application.\n */\nexport function createEmitter(): EventEmitter {\n const emitter: EventEmitter = new UtilEventEmitter();\n const emit: EventEmitter['emit'] = (event: any, ...data: any[]) => {\n logger.log('Emitting processed event:', event, ...data);\n emitter.emit(event, ...data);\n };\n\n // Desktop version of Telegram is sometimes not sending the viewport_changed\n // event. For example, when main button is shown. That's why we should\n // add our own listener to make sure, viewport information is always fresh.\n // Issue: https://github.com/Telegram-Mini-Apps/tma.js/issues/10\n window.addEventListener('resize', () => {\n emit('viewport_changed', {\n width: window.innerWidth,\n height: window.innerHeight,\n is_state_stable: true,\n is_expanded: true,\n });\n });\n\n // In case, any Telegram event was received, we should prepare data before\n // passing it to emitter.\n onTelegramEvent((eventType: EventName | string, eventData): void => {\n logger.log('Received raw event:', eventType, eventData);\n\n try {\n switch (eventType) {\n case 'viewport_changed':\n return emit(eventType, viewportChangedPayload.parse(eventData));\n\n case 'theme_changed':\n return emit(eventType, themeChangedPayload.parse(eventData));\n\n case 'popup_closed':\n // FIXME: Payloads are different on different platforms.\n // Issue: https://github.com/Telegram-Mini-Apps/tma.js/issues/2\n if (\n // Sent on desktop.\n eventData === undefined\n // Sent on iOS.\n || eventData === null\n ) {\n return emit(eventType, {});\n }\n return emit(eventType, popupClosedPayload.parse(eventData));\n\n case 'set_custom_style':\n return emit(eventType, string().parse(eventData));\n\n case 'qr_text_received':\n return emit(eventType, qrTextReceivedPayload.parse(eventData));\n\n case 'clipboard_text_received':\n return emit(eventType, clipboardTextReceivedPayload.parse(eventData));\n\n case 'invoice_closed':\n return emit(eventType, invoiceClosedPayload.parse(eventData));\n\n case 'phone_requested':\n return emit('phone_requested', phoneRequestedPayload.parse(eventData));\n\n case 'custom_method_invoked':\n return emit('custom_method_invoked', customMethodInvokedPayload.parse(eventData));\n\n case 'write_access_requested':\n return emit('write_access_requested', writeAccessRequestedPayload.parse(eventData));\n\n // Events which have no parameters.\n case 'main_button_pressed':\n case 'back_button_pressed':\n case 'settings_button_pressed':\n case 'scan_qr_popup_closed':\n return emit(eventType);\n\n // All other event listeners will receive unknown type of data.\n default:\n return emit(eventType as any, eventData);\n }\n } catch (cause) {\n logger.error('Error processing event:', cause);\n }\n });\n\n return emitter;\n}\n\n/**\n * Returns singleton instance of bridge EventEmitter. Also, defines\n * Telegram event handlers.\n */\nexport function singletonEmitter(): EventEmitter {\n const wnd: any = window;\n const cachedEmitter = wnd[CACHED_EMITTER];\n\n if (cachedEmitter === undefined) {\n wnd[CACHED_EMITTER] = createEmitter();\n }\n\n return wnd[CACHED_EMITTER];\n}\n","import { singletonEmitter } from './emitter.js';\n\nimport type { EventName, EventListener } from './events.js';\n\n/**\n * Removes listener from specified event.\n * @param event - event to listen.\n * @param listener - event listener.\n */\nexport function off<E extends EventName>(event: E, listener: EventListener<E>): void {\n singletonEmitter().off(event, listener);\n}\n","import { singletonEmitter } from './emitter.js';\nimport { off } from './off.js';\n\nimport type { EventName, EventListener } from './events.js';\n\ntype StopListening = () => void;\n\n/**\n * Adds new listener to the specified event. Returns handler\n * which allows to stop listening to event.\n * @param event - event name.\n * @param listener - event listener.\n */\nexport function on<E extends EventName>(event: E, listener: EventListener<E>): StopListening {\n singletonEmitter().on(event, listener);\n return () => off(event, listener);\n}\n","import { singletonEmitter } from './emitter.js';\nimport { off } from './off.js';\n\nimport type { EventName, EventListener } from './events.js';\n\ntype StopListening = () => void;\n\n/**\n * Works the same as \"on\" method, but after catching the event, will remove event listener.\n * @param event - event name.\n * @param listener - event listener.\n */\nexport function once<E extends EventName>(event: E, listener: EventListener<E>): StopListening {\n singletonEmitter().once(event, listener);\n return () => off(event, listener);\n}\n","import { singletonEmitter } from './emitter.js';\n\nimport type { GlobalEventListener } from './events.js';\n\n/**\n * Removes global event listener.\n * @param listener - event listener.\n */\nexport function unsubscribe(listener: GlobalEventListener): void {\n singletonEmitter().unsubscribe(listener);\n}\n","import { singletonEmitter } from './emitter.js';\nimport { unsubscribe } from './unsubscribe.js';\n\nimport type { GlobalEventListener } from './events.js';\n\ntype StopListening = () => void;\n\n/**\n * Subscribes to all events sent from the native Telegram application.\n * Returns function used to remove added event listener.\n * @param listener - event listener.\n */\nexport function subscribe(listener: GlobalEventListener): StopListening {\n singletonEmitter().subscribe(listener);\n return () => unsubscribe(listener);\n}\n","import { isRecord } from '@tma.js/utils';\n\ntype AnyFunc = (...args: unknown[]) => unknown;\n\ntype WithExternalNotify<T> = T & {\n external: { notify: AnyFunc }\n};\n\ntype WithWebviewProxy<T> = T & {\n TelegramWebviewProxy: {\n postEvent: AnyFunc;\n }\n};\n\n/**\n * Returns true in case, passed value contains path `external.notify` property and `notify` is a\n * function.\n * @param value - value to check.\n */\nexport function hasExternalNotify<T extends {}>(value: T): value is WithExternalNotify<T> {\n return 'external' in value\n && isRecord(value.external)\n && 'notify' in value.external\n && typeof value.external.notify === 'function';\n}\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 extends {}>(value: T): value is WithWebviewProxy<T> {\n return 'TelegramWebviewProxy' in value\n && isRecord(value.TelegramWebviewProxy)\n && 'postEvent' in value.TelegramWebviewProxy\n && typeof value.TelegramWebviewProxy.postEvent === 'function';\n}\n\n/**\n * Returns true in case, current environment is iframe.\n * @see https://stackoverflow.com/a/326076\n */\nexport function isIframe(): boolean {\n try {\n return window.self !== window.top;\n } catch (e) {\n return true;\n }\n}\n","import {\n isIframe,\n hasExternalNotify,\n hasWebviewProxy,\n} from '../env.js';\nimport { targetOrigin as globalTargetOrigin } from '../globals.js';\n\nimport type {\n EmptyMethodName,\n MethodName,\n MethodParams,\n NonEmptyMethodName,\n} from './params.js';\n\ninterface PostEventOptions {\n /**\n * Origin used while posting message. This option is only used in case,\n * current environment is browser (Web version of Telegram) and could\n * be used for test purposes.\n * @default 'https://web.telegram.org'\n */\n targetOrigin?: string;\n}\n\nexport type PostEvent = typeof postEvent;\n\n/**\n * Sends event to native application which launched Web App. This function\n * accepts only events, which require arguments.\n * @param eventType - event name.\n * @param params - event parameters.\n * @param options - posting options.\n * @throws {Error} Bridge could not determine current\n * environment and possible way to send event.\n */\nexport function postEvent<E extends NonEmptyMethodName>(\n eventType: E,\n params: MethodParams<E>,\n options?: PostEventOptions,\n): void;\n\n/**\n * Sends event to native application which launched Web App. This function\n * accepts only events, which require arguments.\n * @param eventType - event name.\n * @param options - posting options.\n * @throws {Error} Bridge could not determine current\n * environment and possible way to send event.\n */\nexport function postEvent(eventType: EmptyMethodName, options?: PostEventOptions): void;\n\nexport function postEvent(\n eventType: MethodName,\n paramsOrOptions?: MethodParams<MethodName> | PostEventOptions,\n options?: PostEventOptions,\n): void {\n let postOptions: PostEventOptions = {};\n let eventData: any;\n\n if (paramsOrOptions === undefined && options === undefined) {\n // Parameters and options were not passed.\n postOptions = {};\n } else if (paramsOrOptions !== undefined && options !== undefined) {\n // Both parameters and options passed.\n postOptions = options;\n eventData = paramsOrOptions;\n } else if (paramsOrOptions !== undefined) {\n // Only parameters were passed.\n if ('targetOrigin' in paramsOrOptions) {\n postOptions = paramsOrOptions;\n } else {\n eventData = paramsOrOptions;\n }\n }\n const { targetOrigin = globalTargetOrigin() } = postOptions;\n\n // Telegram Web.\n if (isIframe()) {\n window.parent.postMessage(JSON.stringify({\n eventType,\n eventData,\n }), targetOrigin);\n return;\n }\n\n // Telegram for Windows Phone or Android.\n if (hasExternalNotify(window)) {\n window.external.notify(JSON.stringify({ eventType, eventData }));\n return;\n }\n\n // Telegram for iOS and macOS.\n if (hasWebviewProxy(window)) {\n window.TelegramWebviewProxy.postEvent(eventType, JSON.stringify(eventData));\n return;\n }\n\n // Otherwise current environment is unknown, and we are not able to send\n // event.\n throw new Error(\n 'Unable to determine current environment and possible way to send event.',\n );\n}\n","import { withTimeout, isRecord } from '@tma.js/utils';\n\nimport type { And, If, IsNever } from '@tma.js/util-types';\n\nimport { postEvent as defaultPostEvent, type PostEvent } from './methods/postEvent.js';\nimport { on, type EventName, type EventParams, type EventHasParams } from './events/index.js';\n\nimport type {\n EmptyMethodName, MethodHasParams,\n MethodName,\n MethodParams,\n NonEmptyMethodName,\n} from './methods/params.js';\n\n/**\n * Names of methods, which require passing \"req_id\" parameter.\n */\ntype MethodNameWithRequestId = {\n [Method in MethodName]: If<\n And<MethodHasParams<Method>, MethodParams<Method> extends { req_id: string } ? true : false>,\n Method,\n never\n >;\n}[MethodName];\n\n/**\n * Names of events, which contain \"req_id\" parameter.\n */\ntype EventNameWithRequestId = {\n [Event in EventName]: If<\n And<EventHasParams<Event>, EventParams<Event> extends { req_id: string } ? true : false>,\n Event,\n never\n >;\n}[EventName];\n\nexport interface RequestOptions {\n /**\n * Bridge postEvent method.\n * @default Global postEvent method.\n */\n postEvent?: PostEvent;\n\n /**\n * Execution timeout.\n */\n timeout?: number;\n}\n\nexport interface RequestOptionsAdvanced<EventPayload> extends RequestOptions {\n /**\n * Should return true in case, this event should be captured. If not specified,\n * request is not skipping captured events.\n */\n capture?: If<IsNever<EventPayload>, () => boolean, (payload: EventPayload) => boolean>;\n}\n\n/**\n * Calls specified TWA method and captures one of the specified events. Returns promise\n * which will be resolved in case, event with specified in method request identifier\n * was captured.\n * @param method - method to execute.\n * @param params - method parameters.\n * @param event - event or events to listen.\n * @param options - additional execution options.\n */\nexport function request<\n Method extends MethodNameWithRequestId,\n Event extends EventNameWithRequestId,\n>(\n method: Method,\n params: MethodParams<Method>,\n event: Event | Event[],\n options?: RequestOptions,\n): Promise<EventParams<Event>>;\n\n/**\n * Calls specified TWA method and captures one of the specified events. Returns promise\n * which will be resolved in case, specified event was captured.\n * @param method - method to execute.\n * @param event - event or events to listen.\n * @param options - additional execution options.\n */\nexport function request<Method extends EmptyMethodName, Event extends EventName>(\n method: Method,\n event: Event | Event[],\n options?: RequestOptionsAdvanced<EventParams<Event>>,\n): Promise<EventParams<Event>>;\n\n/**\n * Calls specified TWA method and captures one of the specified events. Returns promise\n * which will be resolved in case, specified event was captured.\n * @param method - method to execute\n * @param params - method parameters.\n * @param event - event or events to listen\n * @param options - additional execution options.\n */\nexport function request<Method extends NonEmptyMethodName, Event extends EventName>(\n method: Method,\n params: MethodParams<Method>,\n event: Event | Event[],\n options?: RequestOptionsAdvanced<EventParams<Event>>,\n): Promise<EventParams<Event>>;\n\nexport function request(\n method: MethodName,\n eventOrParams: EventName | EventName[] | EventParams<any>,\n eventOrOptions?: EventName | EventName[] | RequestOptions | RequestOptionsAdvanced<any>,\n options?: RequestOptions | RequestOptionsAdvanced<any>,\n): Promise<any> {\n let executionOptions: RequestOptions | RequestOptionsAdvanced<any> | undefined;\n let methodParams: EventParams<any> | undefined;\n let events: EventName[];\n let requestId: string | undefined;\n\n if (typeof eventOrParams === 'string' || Array.isArray(eventOrParams)) {\n // Override: [method, event, options?]\n events = Array.isArray(eventOrParams) ? eventOrParams : [eventOrParams] as EventName[];\n executionOptions = eventOrOptions as (RequestOptionsAdvanced<any> | undefined);\n } else {\n // Override: [method, params, event, options?]\n methodParams = eventOrParams as EventParams<any>;\n events = Array.isArray(eventOrOptions) ? eventOrOptions : [eventOrOptions] as EventName[];\n executionOptions = options;\n }\n\n // In case, method parameters were passed, and they contained request identifier, we should store\n // it and wait for the event with this identifier to occur.\n if (isRecord(methodParams) && typeof methodParams.req_id === 'string') {\n requestId = methodParams.req_id;\n }\n\n const { postEvent = defaultPostEvent, timeout } = executionOptions || {};\n const capture = executionOptions && 'capture' in executionOptions\n ? executionOptions.capture\n : null;\n\n const promise = new Promise((res, rej) => {\n // Iterate over each event and create event listener.\n const stoppers = events.map((ev) => on(ev, (data?) => {\n // If request identifier was specified, we are waiting for event with the same value\n // to occur.\n if (typeof requestId === 'string' && (!isRecord(data) || data.req_id !== requestId)) {\n return;\n }\n\n if (typeof capture === 'function' && !capture(data)) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n stopListening();\n res(data);\n }));\n\n // Function which removes all event listeners.\n const stopListening = () => stoppers.forEach((stop) => stop());\n\n try {\n // We are wrapping this call in try catch, because it can throw errors in case,\n // compatibility check was enabled. We want an error to be captured by promise, not by\n // another one external try catch.\n postEvent(method as any, methodParams);\n } catch (e) {\n stopListening();\n rej(e);\n }\n });\n\n return typeof timeout === 'number' ? withTimeout(promise, timeout) : promise;\n}\n","import { compareVersions, type Version } from '@tma.js/utils';\n\nimport type {\n HasCheckSupportMethodParam,\n HasCheckSupportMethodName,\n MethodName,\n MethodParams,\n NonEmptyMethodName,\n} from './methods/index.js';\n\nfunction lessOrEqual(a: Version, b: Version): boolean {\n return compareVersions(a, b) <= 0;\n}\n\n/**\n * By specified method and parameters extracts properties which could be used by\n * supports function as TWA method parameter.\n * @param method - TWA method.\n * @param params - method parameters.\n */\nexport function detectSupportParams<M extends NonEmptyMethodName>(\n method: M,\n params: MethodParams<M>,\n): HasCheckSupportMethodParam<HasCheckSupportMethodName>[] {\n if (method === 'web_app_open_link') {\n if ('try_instant_view' in params) {\n return ['try_instant_view'];\n }\n }\n\n if (method === 'web_app_set_header_color') {\n if ('color' in params) {\n return ['color'];\n }\n }\n\n return [];\n}\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 HasCheckSupportMethodName>(\n method: M,\n param: HasCheckSupportMethodParam<M>,\n inVersion: Version,\n): boolean;\n/**\n * Returns true in case, specified method is supported in passed version.\n * @param method - method name.\n * @param inVersion - platform version.\n */\nexport function supports(method: MethodName, inVersion: Version): boolean;\nexport function supports(\n method: MethodName,\n paramOrVersion: Version | string,\n inVersion?: string,\n): boolean {\n // Method name, parameter, target version.\n if (typeof inVersion === 'string') {\n if (method === 'web_app_open_link') {\n if (paramOrVersion === 'try_instant_view') {\n return lessOrEqual('6.4', inVersion);\n }\n }\n\n if (method === 'web_app_set_header_color') {\n if (paramOrVersion === 'color') {\n return lessOrEqual('6.9', inVersion);\n }\n }\n }\n\n // Method name, target version.\n switch (method) {\n case 'web_app_open_tg_link':\n case 'web_app_open_invoice':\n case 'web_app_setup_back_button':\n case 'web_app_set_background_color':\n case 'web_app_set_header_color':\n case 'web_app_trigger_haptic_feedback':\n return lessOrEqual('6.1', paramOrVersion);\n case 'web_app_open_popup':\n return lessOrEqual('6.2', paramOrVersion);\n case 'web_app_close_scan_qr_popup':\n case 'web_app_open_scan_qr_popup':\n case 'web_app_read_text_from_clipboard':\n return lessOrEqual('6.4', paramOrVersion);\n case 'web_app_invoke_custom_method':\n case 'web_app_request_write_access':\n case 'web_app_request_phone':\n return lessOrEqual('6.9', paramOrVersion);\n case 'web_app_setup_settings_button':\n return lessOrEqual('6.10', paramOrVersion);\n default:\n return true;\n }\n}\n"],"names":["currentTargetOrigin","logger","Logger","setDebug","value","setTargetOrigin","targetOrigin","isNullOrUndefined","rgbOptional","rgb","num","number","windowWidthParser","createValueParserGen","themeChangedPayload","json","viewportChangedPayload","boolean","popupClosedPayload","string","qrTextReceivedPayload","invoiceClosedPayload","clipboardTextReceivedPayload","writeAccessRequestedPayload","phoneRequestedPayload","customMethodInvokedPayload","eventDataJson","emitEvent","eventType","eventData","defineEventHandlers","wnd","path","pointer","item","idx","arr","onTelegramEvent","cb","event","CACHED_EMITTER","createEmitter","emitter","UtilEventEmitter","emit","data","cause","singletonEmitter","off","listener","on","once","unsubscribe","subscribe","hasExternalNotify","isRecord","hasWebviewProxy","isIframe","postEvent","paramsOrOptions","options","postOptions","globalTargetOrigin","request","method","eventOrParams","eventOrOptions","executionOptions","methodParams","events","requestId","defaultPostEvent","timeout","capture","promise","res","rej","stoppers","ev","stopListening","stop","e","withTimeout","lessOrEqual","a","b","compareVersions","detectSupportParams","params","supports","paramOrVersion","inVersion"],"mappings":"6MAEA,IAAIA,EAAsB,2BAEnB,MAAMC,EAAS,IAAIC,EAAAA,OAAO,WAAY,EAAK,EAQ3C,SAASC,EAASC,EAAsB,CAC7C,GAAIA,EAAO,CACTH,EAAO,OAAO,EACd,MACF,CACAA,EAAO,QAAQ,CACjB,CAUO,SAASI,EAAgBD,EAAqB,CAC7BJ,EAAAI,CACxB,CAKO,SAASE,GAAuB,CAC9B,OAAAN,CACT,CCpBA,SAASO,EAAkBH,EAAyB,CAC3C,OAAAA,GAAU,IACnB,CAEA,MAAMI,EAAcC,EAAAA,MAAM,WACpBC,EAAMC,EAAO,OAAA,EAEbC,EAAoBC,EAAA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,IAAW,qBACT,qBAAsBwB,EACjB,CAAC,kBAAkB,EAI1BxB,IAAW,4BACT,UAAWwB,EACN,CAAC,OAAO,EAIZ,EACT,CAmBgB,SAAAC,GACdzB,EACA0B,EACAC,EACS,CAEL,GAAA,OAAOA,GAAc,SAAU,CACjC,GAAI3B,IAAW,qBACT0B,IAAmB,mBACd,OAAAP,EAAY,MAAOQ,CAAS,EAIvC,GAAI3B,IAAW,4BACT0B,IAAmB,QACd,OAAAP,EAAY,MAAOQ,CAAS,CAGzC,CAGA,OAAQ3B,EAAQ,CACd,IAAK,uBACL,IAAK,uBACL,IAAK,4BACL,IAAK,+BACL,IAAK,2BACL,IAAK,kCACI,OAAAmB,EAAY,MAAOO,CAAc,EAC1C,IAAK,qBACI,OAAAP,EAAY,MAAOO,CAAc,EAC1C,IAAK,8BACL,IAAK,6BACL,IAAK,mCACI,OAAAP,EAAY,MAAOO,CAAc,EAC1C,IAAK,+BACL,IAAK,+BACL,IAAK,wBACI,OAAAP,EAAY,MAAOO,CAAc,EAC1C,IAAK,gCACI,OAAAP,EAAY,OAAQO,CAAc,EAC3C,QACS,MAAA,EACX,CACF"}
@@ -1,2 +1,2 @@
1
- this.tmajs=this.tmajs||{};this.tmajs.bridge=function(c){"use strict";var z=Object.defineProperty,F=(e,t,r)=>t in e?z(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,A=(e,t,r)=>(F(e,typeof t!="symbol"?t+"":t,r),r);let Z=class{constructor(){A(this,"listeners",{}),A(this,"subscribeListeners",[])}emit(t,...r){this.subscribeListeners.forEach(i=>i(t,...r));const n=this.listeners[t];if(n===void 0)return;const o=[];n.forEach(i=>{if(typeof i=="function"){i(...r);return}i.once&&o.push(i.listener),i.listener(...r)}),o.forEach(i=>this.off(t,i))}on(t,r){const n=this.listeners[t];n===void 0?this.listeners[t]=[r]:n.push(r)}once(t,r){const n=this.listeners[t],o={listener:r,once:!0};n===void 0?this.listeners[t]=[o]:n.push(o)}off(t,r){const n=this.listeners[t];if(n!==void 0)for(let o=0;o<n.length;o+=1){const i=n[o],s=typeof i=="function"?i:i.listener;r===s&&(n.splice(o,1),o-=1)}}subscribe(t){this.subscribeListeners.push(t)}unsubscribe(t){const r=this.subscribeListeners.indexOf(t);r>=0&&this.subscribeListeners.splice(r,1)}};function K(e){return/^#[\da-f]{3}$/i.test(e)}function Q(e){return/^#[\da-f]{6}$/i.test(e)}function X(e){const t=e.replace(/\s/g,"").toLowerCase();if(Q(t))return t;if(K(t)){let n="#";for(let o=0;o<3;o+=1)n+=t[1+o].repeat(2);return n}const r=t.match(/^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/)||t.match(/^rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),\d{1,3}\)$/);if(r===null)throw new Error(`Value "${e}" does not satisfy any of known RGB formats.`);return r.slice(1).reduce((n,o)=>{const i=parseInt(o,10).toString(16);return n+(i.length===1?"0":"")+i},"#")}let p=class H extends Error{constructor(t,{type:r,error:n,field:o}={}){super(`Unable to parse ${o?`field "${o}"`:"value"} as ${r}`,{cause:{value:t,error:n}}),Object.setPrototypeOf(this,H.prototype)}};class S{constructor(t,r,n){this.parser=t,this.isOptional=r,this.isEmpty=n}parse(t){return this.isOptional&&this.isEmpty(t)?void 0:this.parser(t)}optional(){return this.isOptional=!0,this}}function N(e){return e===void 0}function m(){return new TypeError("Does not have any of expected types")}function w(e,{isEmpty:t=N}={}){return function({isEmpty:r=t}={}){return new S(e,!1,r)}}function Y(e,t,r){const n={};for(const o in e){const i=e[o];if(!i)continue;let s,f;if("type"in i){const{type:l}=i;s=i.from||o,f=typeof l=="function"?l:l.parse.bind(l)}else s=o,f=typeof i=="function"?i:i.parse.bind(i);let b;const y=t(s);try{b=f(y)}catch(l){throw new p(y,{field:s,type:r,error:l})}b!==void 0&&(n[o]=b)}return n}const T=w(e=>{if(typeof e=="boolean")return e;throw new p(e,{type:"boolean",error:m()})}),P=w(e=>{if(typeof e=="number")return e;if(typeof e=="string"){const t=Number(e);if(!Number.isNaN(t))return t}throw new p(e,{type:"number",error:m()})});P();function a(e,t={}){const{type:r,isEmpty:n=N}=t;return new S(o=>{let i=o;if(typeof i=="string")try{i=JSON.parse(i)}catch(s){throw new p(o,{type:r,error:s})}if(typeof i!="object"||i===null||Array.isArray(i))throw new p(o,{type:r,error:m()});return Y(e,s=>i[s])},!1,n)}const u=w(e=>{if(typeof e=="string"||typeof e=="number")return e.toString();throw new p(e,{type:"string",error:m()})}),D=u(),O=w(e=>{try{return X(D.parse(e))}catch(t){throw new p(e,{type:"RGB",error:t})}});function V(e,...t){const r=new Date,n=Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZone:"UTC"}).format(r);console[e](`[${n}]`,...t)}let W=!1,j="https://web.telegram.org";function ee(e){W=e}function te(e){j=e}function re(){return j}const q=(e,...t)=>{W&&V(e,"[Bridge]",...t)};function ne(e){return e==null}const d=O().optional(),oe=P(),ie=w(e=>e==null?window.innerWidth:oe.parse(e)),se=a({theme_params:a({bg_color:d,text_color:d,hint_color:d,link_color:d,button_color:d,button_text_color:d,secondary_bg_color:d})}),ce=a({height:P(),width:ie(),is_state_stable:T(),is_expanded:T()}),ue=a({button_id:u({isEmpty:ne}).optional()}),ae=a({data:u().optional()}),fe=a({slug:u(),status:u()}),le=a({req_id:u(),data:e=>e===null?e:u().optional().parse(e)}),pe=a({status:u()}),de=a({status:u()}),_e=a({req_id:u(),result:e=>e,error:u().optional()}),we=a({eventType:u(),eventData:e=>e});function he(e,t){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:e,eventData:t})}))}function be(){const e=window;"TelegramGameProxy_receiveEvent"in e||[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(t=>{let r=e;t.forEach((n,o,i)=>{if(o===i.length-1){r[n]=he;return}n in r||(r[n]={}),r=r[n]})})}function ye(e){be(),window.addEventListener("message",t=>{try{const{eventType:r,eventData:n}=we.parse(t.data);e(r,n)}catch{}})}const $="__telegram-cached-emitter__";function ge(){const e=new Z,t=(r,...n)=>{q("log","Emitting processed event:",r,...n),e.emit(r,...n)};return window.addEventListener("resize",()=>{t("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),ye((r,n)=>{q("log","Received raw event:",r,n);try{switch(r){case"viewport_changed":return t(r,ce.parse(n));case"theme_changed":return t(r,se.parse(n));case"popup_closed":return n==null?t(r,{}):t(r,ue.parse(n));case"set_custom_style":return t(r,u().parse(n));case"qr_text_received":return t(r,ae.parse(n));case"clipboard_text_received":return t(r,le.parse(n));case"invoice_closed":return t(r,fe.parse(n));case"phone_requested":return t("phone_requested",de.parse(n));case"custom_method_invoked":return t("custom_method_invoked",_e.parse(n));case"write_access_requested":return t("write_access_requested",pe.parse(n));case"main_button_pressed":case"back_button_pressed":case"settings_button_pressed":case"scan_qr_popup_closed":return t(r);default:return t(r,n)}}catch(o){q("error","Error processing event:",o)}}),e}function h(){const e=window;return e[$]===void 0&&(e[$]=ge()),e[$]}function x(e,t){h().off(e,t)}function I(e,t){return h().on(e,t),()=>x(e,t)}function me(e,t){return h().once(e,t),()=>x(e,t)}function L(e){h().unsubscribe(e)}function Ee(e){return h().subscribe(e),()=>L(e)}function E(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ve(e,t){const r=e.split("."),n=t.split("."),o=Math.max(r.length,n.length);for(let i=0;i<o;i+=1){const s=parseInt(r[i]||"0",10),f=parseInt(n[i]||"0",10);if(s!==f)return s>f?1:-1}return 0}class k extends Error{constructor(t){super(`Async call timeout exceeded. Timeout: ${t}`),Object.setPrototypeOf(this,k.prototype)}}function C(e){return new Promise((t,r)=>{setTimeout(r,e,new k(e))})}function Pe(e,t){return typeof e=="function"?(...r)=>Promise.race([e(...r),C(t)]):Promise.race([e,C(t)])}function R(e){return"external"in e&&E(e.external)&&"notify"in e.external&&typeof e.external.notify=="function"}function G(e){return"TelegramWebviewProxy"in e&&E(e.TelegramWebviewProxy)&&"postEvent"in e.TelegramWebviewProxy&&typeof e.TelegramWebviewProxy.postEvent=="function"}function J(){try{return window.self!==window.top}catch{return!0}}function M(e,t,r){let n={},o;t===void 0&&r===void 0?n={}:t!==void 0&&r!==void 0?(n=r,o=t):t!==void 0&&("targetOrigin"in t?n=t:o=t);const{targetOrigin:i=re()}=n;if(J()){window.parent.postMessage(JSON.stringify({eventType:e,eventData:o}),i);return}if(R(window)){window.external.notify(JSON.stringify({eventType:e,eventData:o}));return}if(G(window)){window.TelegramWebviewProxy.postEvent(e,JSON.stringify(o));return}throw new Error("Unable to determine current environment and possible way to send event.")}function qe(e,t,r,n){let o,i,s,f;typeof t=="string"||Array.isArray(t)?(s=Array.isArray(t)?t:[t],o=r):(i=t,s=Array.isArray(r)?r:[r],o=n),E(i)&&typeof i.req_id=="string"&&(f=i.req_id);const{postEvent:b=M,timeout:y}=o||{},l=o&&"capture"in o?o.capture:null,B=new Promise((ke,Ae)=>{const Se=s.map(g=>I(g,v=>{typeof f=="string"&&(!E(v)||v.req_id!==f)||typeof l=="function"&&!l(v)||(U(),ke(v))})),U=()=>Se.forEach(g=>g());try{b(e,i)}catch(g){U(),Ae(g)}});return typeof y=="number"?Pe(B,y):B}function _(e,t){return ve(e,t)<=0}function $e(e,t){return e==="web_app_open_link"&&"try_instant_view"in t?["try_instant_view"]:e==="web_app_set_header_color"&&"color"in t?["color"]:[]}function xe(e,t,r){if(typeof r=="string"){if(e==="web_app_open_link"&&t==="try_instant_view")return _("6.4",r);if(e==="web_app_set_header_color"&&t==="color")return _("6.9",r)}switch(e){case"web_app_open_tg_link":case"web_app_open_invoice":case"web_app_setup_back_button":case"web_app_set_background_color":case"web_app_set_header_color":case"web_app_trigger_haptic_feedback":return _("6.1",t);case"web_app_open_popup":return _("6.2",t);case"web_app_close_scan_qr_popup":case"web_app_open_scan_qr_popup":case"web_app_read_text_from_clipboard":return _("6.4",t);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return _("6.9",t);case"web_app_setup_settings_button":return _("6.10",t);default:return!0}}return c.detectSupportParams=$e,c.hasExternalNotify=R,c.hasWebviewProxy=G,c.isIframe=J,c.off=x,c.on=I,c.once=me,c.postEvent=M,c.request=qe,c.setDebug=ee,c.setTargetOrigin=te,c.subscribe=Ee,c.supports=xe,c.unsubscribe=L,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"}),c}({});
1
+ this.tmajs=this.tmajs||{};this.tmajs.bridge=function(c){"use strict";var U=Object.defineProperty,H=(e,t,r)=>t in e?U(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,A=(e,t,r)=>(H(e,typeof t!="symbol"?t+"":t,r),r);let z=class{constructor(){A(this,"listeners",new Map),A(this,"subscribeListeners",[])}addListener(t,r,n){let i=this.listeners.get(t);return i||(i=[],this.listeners.set(t,i)),i.push([r,n]),()=>this.off(t,r)}emit(t,...r){this.subscribeListeners.forEach(i=>i(t,...r));const n=this.listeners.get(t);n&&n.forEach(([i,o],s)=>{i(...r),o&&n.splice(s,1)})}on(t,r){return this.addListener(t,r,!1)}once(t,r){return this.addListener(t,r,!0)}off(t,r){const n=this.listeners.get(t);if(n){for(let i=0;i<n.length;i+=1)if(r===n[i][0]){n.splice(i,1);return}}}subscribe(t){return this.subscribeListeners.push(t),()=>this.unsubscribe(t)}unsubscribe(t){for(let r=0;r<this.subscribeListeners.length;r+=1)if(this.subscribeListeners[r]===t){this.subscribeListeners.splice(r,1);return}}};function F(e){return/^#[\da-f]{3}$/i.test(e)}function Z(e){return/^#[\da-f]{6}$/i.test(e)}function K(e){const t=e.replace(/\s/g,"").toLowerCase();if(Z(t))return t;if(F(t)){let n="#";for(let i=0;i<3;i+=1)n+=t[1+i].repeat(2);return n}const r=t.match(/^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/)||t.match(/^rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),\d{1,3}\)$/);if(r===null)throw new Error(`Value "${e}" does not satisfy any of known RGB formats.`);return r.slice(1).reduce((n,i)=>{const o=parseInt(i,10).toString(16);return n+(o.length===1?"0":"")+o},"#")}class l extends Error{constructor(t,{type:r,error:n,field:i}={}){super(`Unable to parse ${i?`field "${i}"`:"value"} as ${r}`,{cause:{value:t,error:n}}),Object.setPrototypeOf(this,l.prototype)}}class L{constructor(t,r,n){this.parser=t,this.isOptional=r,this.isEmpty=n}parse(t){return this.isOptional&&this.isEmpty(t)?void 0:this.parser(t)}optional(){return this.isOptional=!0,this}}function S(e){return e===void 0}function E(){return new TypeError("Does not have any of expected types")}function b(e,{isEmpty:t=S}={}){return function({isEmpty:r=t}={}){return new L(e,!1,r)}}function Q(e,t,r){const n={};for(const i in e){const o=e[i];if(!o)continue;let s,f;if("type"in o){const{type:p}=o;s=o.from||i,f=typeof p=="function"?p:p.parse.bind(p)}else s=i,f=typeof o=="function"?o:o.parse.bind(o);let g;const y=t(s);try{g=f(y)}catch(p){throw new l(y,{field:s,type:r,error:p})}g!==void 0&&(n[i]=g)}return n}const N=b(e=>{if(typeof e=="boolean")return e;throw new l(e,{type:"boolean",error:E()})}),q=b(e=>{if(typeof e=="number")return e;if(typeof e=="string"){const t=Number(e);if(!Number.isNaN(t))return t}throw new l(e,{type:"number",error:E()})});q();function a(e,t={}){const{type:r,isEmpty:n=S}=t;return new L(i=>{let o=i;if(typeof o=="string")try{o=JSON.parse(o)}catch(s){throw new l(i,{type:r,error:s})}if(typeof o!="object"||o===null||Array.isArray(o))throw new l(i,{type:r,error:E()});return Q(e,s=>o[s])},!1,n)}const u=b(e=>{if(typeof e=="string"||typeof e=="number")return e.toString();throw new l(e,{type:"string",error:E()})}),X=u(),Y=b(e=>{try{return K(X.parse(e))}catch(t){throw new l(e,{type:"RGB",error:t})}});class D{constructor(t,r){this.prefix=t,this.enabled=r}print(t,...r){if(!this.enabled)return;const n=new Date,i=Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZone:"UTC"}).format(n);console[t](`[${i}]`,this.prefix,...r)}disable(){this.enabled=!1}error(...t){this.print("error",...t)}enable(){this.enabled=!0}log(...t){this.print("log",...t)}warn(...t){this.print("warn",...t)}}let T="https://web.telegram.org";const h=new D("[Bridge]",!1);function O(e){if(e){h.enable();return}h.disable()}function V(e){T=e}function ee(){return T}function te(e){return e==null}const d=Y().optional(),re=q(),ne=b(e=>e==null?window.innerWidth:re.parse(e)),ie=a({theme_params:a({bg_color:d,text_color:d,hint_color:d,link_color:d,button_color:d,button_text_color:d,secondary_bg_color:d})}),oe=a({height:q(),width:ne(),is_state_stable:N(),is_expanded:N()}),se=a({button_id:u({isEmpty:te}).optional()}),ce=a({data:u().optional()}),ue=a({slug:u(),status:u()}),ae=a({req_id:u(),data:e=>e===null?e:u().optional().parse(e)}),fe=a({status:u()}),le=a({status:u()}),pe=a({req_id:u(),result:e=>e,error:u().optional()}),de=a({eventType:u(),eventData:e=>e});function _e(e,t){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:e,eventData:t})}))}function be(){const e=window;"TelegramGameProxy_receiveEvent"in e||[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(t=>{let r=e;t.forEach((n,i,o)=>{if(i===o.length-1){r[n]=_e;return}n in r||(r[n]={}),r=r[n]})})}function he(e){be(),window.addEventListener("message",t=>{try{const{eventType:r,eventData:n}=de.parse(t.data);e(r,n)}catch{}})}const x="__telegram-cached-emitter__";function we(){const e=new z,t=(r,...n)=>{h.log("Emitting processed event:",r,...n),e.emit(r,...n)};return window.addEventListener("resize",()=>{t("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),he((r,n)=>{h.log("Received raw event:",r,n);try{switch(r){case"viewport_changed":return t(r,oe.parse(n));case"theme_changed":return t(r,ie.parse(n));case"popup_closed":return n==null?t(r,{}):t(r,se.parse(n));case"set_custom_style":return t(r,u().parse(n));case"qr_text_received":return t(r,ce.parse(n));case"clipboard_text_received":return t(r,ae.parse(n));case"invoice_closed":return t(r,ue.parse(n));case"phone_requested":return t("phone_requested",le.parse(n));case"custom_method_invoked":return t("custom_method_invoked",pe.parse(n));case"write_access_requested":return t("write_access_requested",fe.parse(n));case"main_button_pressed":case"back_button_pressed":case"settings_button_pressed":case"scan_qr_popup_closed":return t(r);default:return t(r,n)}}catch(i){h.error("Error processing event:",i)}}),e}function w(){const e=window;return e[x]===void 0&&(e[x]=we()),e[x]}function $(e,t){w().off(e,t)}function W(e,t){return w().on(e,t),()=>$(e,t)}function ge(e,t){return w().once(e,t),()=>$(e,t)}function j(e){w().unsubscribe(e)}function ye(e){return w().subscribe(e),()=>j(e)}function v(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function me(e,t){const r=e.split("."),n=t.split("."),i=Math.max(r.length,n.length);for(let o=0;o<i;o+=1){const s=parseInt(r[o]||"0",10),f=parseInt(n[o]||"0",10);if(s!==f)return s>f?1:-1}return 0}class k extends Error{constructor(t){super(`Async call timeout exceeded. Timeout: ${t}`),Object.setPrototypeOf(this,k.prototype)}}function I(e){return new Promise((t,r)=>{setTimeout(r,e,new k(e))})}function Ee(e,t){return typeof e=="function"?(...r)=>Promise.race([e(...r),I(t)]):Promise.race([e,I(t)])}function C(e){return"external"in e&&v(e.external)&&"notify"in e.external&&typeof e.external.notify=="function"}function R(e){return"TelegramWebviewProxy"in e&&v(e.TelegramWebviewProxy)&&"postEvent"in e.TelegramWebviewProxy&&typeof e.TelegramWebviewProxy.postEvent=="function"}function G(){try{return window.self!==window.top}catch{return!0}}function M(e,t,r){let n={},i;t===void 0&&r===void 0?n={}:t!==void 0&&r!==void 0?(n=r,i=t):t!==void 0&&("targetOrigin"in t?n=t:i=t);const{targetOrigin:o=ee()}=n;if(G()){window.parent.postMessage(JSON.stringify({eventType:e,eventData:i}),o);return}if(C(window)){window.external.notify(JSON.stringify({eventType:e,eventData:i}));return}if(R(window)){window.TelegramWebviewProxy.postEvent(e,JSON.stringify(i));return}throw new Error("Unable to determine current environment and possible way to send event.")}function ve(e,t,r,n){let i,o,s,f;typeof t=="string"||Array.isArray(t)?(s=Array.isArray(t)?t:[t],i=r):(o=t,s=Array.isArray(r)?r:[r],i=n),v(o)&&typeof o.req_id=="string"&&(f=o.req_id);const{postEvent:g=M,timeout:y}=i||{},p=i&&"capture"in i?i.capture:null,J=new Promise((xe,$e)=>{const ke=s.map(m=>W(m,P=>{typeof f=="string"&&(!v(P)||P.req_id!==f)||typeof p=="function"&&!p(P)||(B(),xe(P))})),B=()=>ke.forEach(m=>m());try{g(e,o)}catch(m){B(),$e(m)}});return typeof y=="number"?Ee(J,y):J}function _(e,t){return me(e,t)<=0}function Pe(e,t){return e==="web_app_open_link"&&"try_instant_view"in t?["try_instant_view"]:e==="web_app_set_header_color"&&"color"in t?["color"]:[]}function qe(e,t,r){if(typeof r=="string"){if(e==="web_app_open_link"&&t==="try_instant_view")return _("6.4",r);if(e==="web_app_set_header_color"&&t==="color")return _("6.9",r)}switch(e){case"web_app_open_tg_link":case"web_app_open_invoice":case"web_app_setup_back_button":case"web_app_set_background_color":case"web_app_set_header_color":case"web_app_trigger_haptic_feedback":return _("6.1",t);case"web_app_open_popup":return _("6.2",t);case"web_app_close_scan_qr_popup":case"web_app_open_scan_qr_popup":case"web_app_read_text_from_clipboard":return _("6.4",t);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return _("6.9",t);case"web_app_setup_settings_button":return _("6.10",t);default:return!0}}return c.detectSupportParams=Pe,c.hasExternalNotify=C,c.hasWebviewProxy=R,c.isIframe=G,c.off=$,c.on=W,c.once=ge,c.postEvent=M,c.request=ve,c.setDebug=O,c.setTargetOrigin=V,c.subscribe=ye,c.supports=qe,c.unsubscribe=j,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"}),c}({});
2
2
  //# sourceMappingURL=index.iife.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.iife.js","sources":["../../event-emitter/dist/index.mjs","../../colors/dist/index.mjs","../../parsing/dist/index.mjs","../../logger/dist/index.mjs","../src/globals.ts","../src/events/parsing.ts","../src/events/onTelegramEvent.ts","../src/events/emitter.ts","../src/events/off.ts","../src/events/on.ts","../src/events/once.ts","../src/events/unsubscribe.ts","../src/events/subscribe.ts","../../utils/dist/index.mjs","../src/env.ts","../src/methods/postEvent.ts","../src/request.ts","../src/supports.ts"],"sourcesContent":["var f = Object.defineProperty;\nvar h = (r, s, e) => s in r ? f(r, s, { enumerable: !0, configurable: !0, writable: !0, value: e }) : r[s] = e;\nvar o = (r, s, e) => (h(r, typeof s != \"symbol\" ? s + \"\" : s, e), e);\nclass l {\n constructor() {\n o(this, \"listeners\", {});\n o(this, \"subscribeListeners\", []);\n }\n emit(s, ...e) {\n this.subscribeListeners.forEach((t) => t(s, ...e));\n const i = this.listeners[s];\n if (i === void 0)\n return;\n const n = [];\n i.forEach((t) => {\n if (typeof t == \"function\") {\n t(...e);\n return;\n }\n t.once && n.push(t.listener), t.listener(...e);\n }), n.forEach((t) => this.off(s, t));\n }\n /**\n * Adds event listener.\n * @param event - event name.\n * @param listener - event listener.\n */\n on(s, e) {\n const i = this.listeners[s];\n i === void 0 ? this.listeners[s] = [e] : i.push(e);\n }\n /**\n * Adds event listener which will be called only once.\n * @param event - event name.\n * @param listener - event listener.\n */\n once(s, e) {\n const i = this.listeners[s], n = { listener: e, once: !0 };\n i === void 0 ? this.listeners[s] = [n] : i.push(n);\n }\n /**\n * Removes event listener.\n * @param event - event name.\n * @param listener - event listener.\n */\n off(s, e) {\n const i = this.listeners[s];\n if (i !== void 0)\n for (let n = 0; n < i.length; n += 1) {\n const t = i[n], c = typeof t == \"function\" ? t : t.listener;\n e === c && (i.splice(n, 1), n -= 1);\n }\n }\n /**\n * Subscribes to any events appearing.\n * @param listener - events listener.\n */\n subscribe(s) {\n this.subscribeListeners.push(s);\n }\n /**\n * Removes listener from global listeners.\n * @param listener - events listener.\n */\n unsubscribe(s) {\n const e = this.subscribeListeners.indexOf(s);\n e >= 0 && this.subscribeListeners.splice(e, 1);\n }\n}\nexport {\n l as EventEmitter\n};\n//# sourceMappingURL=index.mjs.map\n","function a(t) {\n return /^#[\\da-f]{3}$/i.test(t);\n}\nfunction i(t) {\n return /^#[\\da-f]{6}$/i.test(t);\n}\nfunction u(t) {\n const r = t.replace(/\\s/g, \"\").toLowerCase();\n if (i(r))\n return r;\n if (a(r)) {\n let n = \"#\";\n for (let e = 0; e < 3; e += 1)\n n += r[1 + e].repeat(2);\n return n;\n }\n const s = r.match(/^rgb\\((\\d{1,3}),(\\d{1,3}),(\\d{1,3})\\)$/) || r.match(/^rgba\\((\\d{1,3}),(\\d{1,3}),(\\d{1,3}),\\d{1,3}\\)$/);\n if (s === null)\n throw new Error(`Value \"${t}\" does not satisfy any of known RGB formats.`);\n return s.slice(1).reduce((n, e) => {\n const o = parseInt(e, 10).toString(16);\n return n + (o.length === 1 ? \"0\" : \"\") + o;\n }, \"#\");\n}\nfunction f(t) {\n const r = u(t);\n return Math.sqrt(\n [0.299, 0.587, 0.114].reduce((n, e, o) => {\n const c = parseInt(r.slice(1 + o * 2, 1 + (o + 1) * 2), 16);\n return n + c * c * e;\n }, 0)\n ) < 120;\n}\nexport {\n f as isColorDark,\n i as isRGB,\n a as isRGBShort,\n u as toRGB\n};\n//# sourceMappingURL=index.mjs.map\n","var g = Object.defineProperty;\nvar l = (r, t, e) => t in r ? g(r, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : r[t] = e;\nvar d = (r, t, e) => (l(r, typeof t != \"symbol\" ? t + \"\" : t, e), e);\nimport { toRGB as A } from \"@tma.js/colors\";\nclass i extends Error {\n constructor(t, { type: e, error: o, field: n } = {}) {\n super(`Unable to parse ${n ? `field \"${n}\"` : \"value\"} as ${e}`, {\n cause: { value: t, error: o }\n }), Object.setPrototypeOf(this, i.prototype);\n }\n}\nclass u {\n constructor(t, e, o) {\n this.parser = t, this.isOptional = e, this.isEmpty = o;\n }\n parse(t) {\n return this.isOptional && this.isEmpty(t) ? void 0 : this.parser(t);\n }\n optional() {\n return this.isOptional = !0, this;\n }\n}\nfunction E(r) {\n if (Array.isArray(r))\n return r;\n if (typeof r == \"string\")\n try {\n const t = JSON.parse(r);\n if (Array.isArray(t))\n return t;\n } catch {\n }\n throw new i(r, { type: \"array\" });\n}\nclass O extends u {\n constructor(e, o, n) {\n super(E, o, n);\n d(this, \"itemParser\");\n this.itemParser = typeof e == \"function\" ? e : e.parse.bind(e);\n }\n parse(e) {\n const o = super.parse(e);\n return o === void 0 ? o : o.map(this.itemParser);\n }\n of(e) {\n return this.itemParser = typeof e == \"function\" ? e : e.parse.bind(e), this;\n }\n}\nfunction h(r) {\n return r === void 0;\n}\nfunction D() {\n return new O((r) => r, !1, h);\n}\nfunction f() {\n return new TypeError(\"Does not have any of expected types\");\n}\nfunction y(r, { isEmpty: t = h } = {}) {\n return function({ isEmpty: o = t } = {}) {\n return new u(r, !1, o);\n };\n}\nfunction b(r, t, e) {\n const o = {};\n for (const n in r) {\n const s = r[n];\n if (!s)\n continue;\n let a, p;\n if (\"type\" in s) {\n const { type: c } = s;\n a = s.from || n, p = typeof c == \"function\" ? c : c.parse.bind(c);\n } else\n a = n, p = typeof s == \"function\" ? s : s.parse.bind(s);\n let w;\n const m = t(a);\n try {\n w = p(m);\n } catch (c) {\n throw new i(m, {\n field: a,\n type: e,\n error: c\n });\n }\n w !== void 0 && (o[n] = w);\n }\n return o;\n}\nconst G = y((r) => {\n if (typeof r == \"boolean\")\n return r;\n throw new i(r, { type: \"boolean\", error: f() });\n}), V = y((r) => {\n if (typeof r == \"number\")\n return r;\n if (typeof r == \"string\") {\n const t = Number(r);\n if (!Number.isNaN(t))\n return t;\n }\n throw new i(r, { type: \"number\", error: f() });\n}), N = V(), R = y((r) => {\n if (r instanceof Date)\n return r;\n try {\n return new Date(N.parse(r) * 1e3);\n } catch (t) {\n throw new i(r, { type: \"Date\", error: t });\n }\n});\nfunction U(r, t = {}) {\n const {\n type: e,\n isEmpty: o = h\n } = t;\n return new u((n) => {\n let s = n;\n if (typeof s == \"string\")\n try {\n s = JSON.parse(s);\n } catch (a) {\n throw new i(n, { type: e, error: a });\n }\n if (typeof s != \"object\" || s === null || Array.isArray(s))\n throw new i(n, { type: e, error: f() });\n return b(r, (a) => s[a]);\n }, !1, o);\n}\nconst P = y((r) => {\n if (typeof r == \"string\" || typeof r == \"number\")\n return r.toString();\n throw new i(r, { type: \"string\", error: f() });\n}), S = P(), B = y((r) => {\n try {\n return A(S.parse(r));\n } catch (t) {\n throw new i(r, { type: \"RGB\", error: t });\n }\n});\nfunction $(r, t = {}) {\n const {\n type: e,\n isEmpty: o = h\n } = t;\n return new u((n) => {\n if (typeof n != \"string\" && !(n instanceof URLSearchParams))\n throw new i(n, { type: e, error: f() });\n const s = typeof n == \"string\" ? new URLSearchParams(n) : n;\n return b(r, (a) => {\n const p = s.get(a);\n return p === null ? void 0 : p;\n });\n }, !1, o);\n}\nexport {\n O as ArrayValueParser,\n i as ParsingError,\n u as ValueParser,\n D as array,\n G as boolean,\n y as createValueParserGen,\n R as date,\n U as json,\n V as number,\n B as rgb,\n $ as searchParams,\n P as string\n};\n//# sourceMappingURL=index.mjs.map\n","function i(t, ...o) {\n const n = /* @__PURE__ */ new Date(), e = Intl.DateTimeFormat(\"en-GB\", {\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n fractionalSecondDigits: 3,\n timeZone: \"UTC\"\n }).format(n);\n console[t](`[${e}]`, ...o);\n}\nexport {\n i as log\n};\n//# sourceMappingURL=index.mjs.map\n","import { log as utilLog } from '@tma.js/logger';\n\nlet currentDebug = false;\nlet currentTargetOrigin = 'https://web.telegram.org';\n\n/**\n * Sets new debug mode. Enabling debug mode leads to printing\n * additional messages in console, related to the processes\n * inside the package.\n * @param value - should debug mode be enabled.\n */\nexport function setDebug(value: boolean): void {\n currentDebug = value;\n}\n\n/**\n * Sets new global targetOrigin, used by `postEvent` method.\n * Default value is \"https://web.telegram.org\". You don't need to\n * use this method until you know what you are doing.\n *\n * This method could be used for test purposes.\n * @param value - new target origin.\n */\nexport function setTargetOrigin(value: string): void {\n currentTargetOrigin = value;\n}\n\n/**\n * Returns current global target origin.\n */\nexport function targetOrigin(): string {\n return currentTargetOrigin;\n}\n\n/**\n * Logs message in case, debug mode is enabled.\n * @param level - log level\n * @param args - values to print.\n */\nexport const log: typeof utilLog = (level, ...args) => {\n if (currentDebug) {\n utilLog(level, '[Bridge]', ...args);\n }\n};\n","import {\n number,\n string,\n boolean,\n json,\n rgb,\n createValueParserGen,\n} from '@tma.js/parsing';\n\nimport type {\n ClipboardTextReceivedPayload, CustomMethodInvokedPayload,\n InvoiceClosedPayload, PhoneRequestedPayload,\n PopupClosedPayload, QrTextReceivedPayload,\n ThemeChangedPayload,\n ViewportChangedPayload, WriteAccessRequestedPayload,\n} from './payloads.js';\n\nfunction isNullOrUndefined(value: unknown): boolean {\n return value === null || value === undefined;\n}\n\nconst rgbOptional = rgb().optional();\nconst num = number();\n\nconst windowWidthParser = createValueParserGen((value) => (value === null || value === undefined\n ? window.innerWidth\n : num.parse(value)));\n\n/**\n * Parses incoming value as ThemeChangedPayload.\n */\nexport const themeChangedPayload = json<ThemeChangedPayload>({\n theme_params: json({\n bg_color: rgbOptional,\n text_color: rgbOptional,\n hint_color: rgbOptional,\n link_color: rgbOptional,\n button_color: rgbOptional,\n button_text_color: rgbOptional,\n secondary_bg_color: rgbOptional,\n }),\n});\n\n/**\n * Parses incoming value as ViewportChangedPayload.\n * @param value - value to parse.\n */\nexport const viewportChangedPayload = json<ViewportChangedPayload>({\n height: number(),\n width: windowWidthParser(),\n is_state_stable: boolean(),\n is_expanded: boolean(),\n});\n\n/**\n * Parses incoming value as PopupClosedPayload.\n */\nexport const popupClosedPayload = json<PopupClosedPayload>({\n button_id: string({ isEmpty: isNullOrUndefined }).optional(),\n});\n\n/**\n * Parses incoming value as QrTextReceivedPayload.\n */\nexport const qrTextReceivedPayload = json<QrTextReceivedPayload>({\n data: string().optional(),\n});\n\n/**\n * Parses incoming value as InvoiceClosedPayload.\n */\nexport const invoiceClosedPayload = json<InvoiceClosedPayload>({\n slug: string(),\n status: string(),\n});\n\n/**\n * Parses incoming value as clipboard text received payload.\n */\nexport const clipboardTextReceivedPayload = json<ClipboardTextReceivedPayload>({\n req_id: string(),\n data: (value) => (value === null ? value : string().optional().parse(value)),\n});\n\n/**\n * Parses incoming value as WriteAccessRequestedPayload.\n */\nexport const writeAccessRequestedPayload = json<WriteAccessRequestedPayload>({ status: string() });\n\n/**\n * Parses incoming value as PhoneRequestedPayload.\n */\nexport const phoneRequestedPayload = json<PhoneRequestedPayload>({ status: string() });\n\n/**\n * Parses incoming value as CustomMethodInvokedPayload.\n */\nexport const customMethodInvokedPayload = json<CustomMethodInvokedPayload>({\n req_id: string(),\n result: (value) => value,\n error: string().optional(),\n});\n","import { json, string } from '@tma.js/parsing';\n\n/**\n * Extracts event data from native application event.\n */\nconst eventDataJson = json<{ eventType: string; eventData?: unknown }>({\n eventType: string(),\n eventData: (value) => value,\n});\n\n/**\n * Emits event sent from Telegram native application like it was sent in\n * default web environment between 2 iframes. It dispatches new MessageEvent\n * and expects it to be handled via `window.addEventListener('message', ...)`\n * as developer would do it to handle messages sent from parent iframe.\n * @param eventType - event name.\n * @param eventData - event payload.\n */\nfunction emitEvent(eventType: string, eventData: unknown): void {\n window.dispatchEvent(new MessageEvent('message', {\n data: JSON.stringify({ eventType, eventData }),\n }));\n}\n\n/**\n * Defines special handlers by known paths, which are recognized by\n * Telegram as ports to receive events. This function also sets special\n * function in global window object to prevent duplicate declaration.\n */\nfunction defineEventHandlers(): void {\n const wnd: any = window;\n\n // Prevent from duplicate event handlers definition.\n if ('TelegramGameProxy_receiveEvent' in wnd) {\n return;\n }\n\n // Iterate over each path, where \"receiveEvent\" function should be\n // defined. This function is called by external environment in case,\n // it wants to emit some event.\n [\n ['TelegramGameProxy_receiveEvent'], // Windows Phone.\n ['TelegramGameProxy', 'receiveEvent'], // Desktop.\n ['Telegram', 'WebView', 'receiveEvent'], // Android and iOS.\n ].forEach((path) => {\n // Path starts from \"window\" object.\n let pointer = wnd;\n\n path.forEach((item, idx, arr) => {\n // We are on the last iteration, where function property name is passed.\n if (idx === arr.length - 1) {\n pointer[item] = emitEvent;\n return;\n }\n\n if (!(item in pointer)) {\n pointer[item] = {};\n }\n pointer = pointer[item];\n });\n });\n}\n\n/**\n * Adds listener to window \"message\" event assuming, that this event could\n * be sent by Telegram native application. Calls passed callback with event\n * type and data.\n * @param cb - callback to call.\n */\nexport function onTelegramEvent(cb: (eventType: string, eventData: unknown) => void): void {\n // Define event handlers to make sure, message handler will work correctly.\n defineEventHandlers();\n\n // We expect Telegram to send us new event through \"message\" event.\n window.addEventListener('message', (event) => {\n try {\n const { eventType, eventData } = eventDataJson.parse(event.data);\n cb(eventType, eventData);\n } catch {\n // We ignore incorrect messages as they could be generated by any other code.\n }\n });\n}\n","import { EventEmitter as UtilEventEmitter } from '@tma.js/event-emitter';\nimport { string } from '@tma.js/parsing';\n\nimport { log } from '../globals.js';\nimport {\n clipboardTextReceivedPayload,\n customMethodInvokedPayload,\n invoiceClosedPayload,\n phoneRequestedPayload,\n popupClosedPayload,\n qrTextReceivedPayload,\n themeChangedPayload,\n viewportChangedPayload,\n writeAccessRequestedPayload,\n} from './parsing.js';\nimport { onTelegramEvent } from './onTelegramEvent.js';\n\nimport type { EventEmitter, EventName } from './events.js';\n\nconst CACHED_EMITTER = '__telegram-cached-emitter__';\n\n/**\n * Returns event emitter which could be safely used, to process events from\n * Telegram native application.\n */\nexport function createEmitter(): EventEmitter {\n const emitter: EventEmitter = new UtilEventEmitter();\n const emit: EventEmitter['emit'] = (event: any, ...data: any[]) => {\n log('log', 'Emitting processed event:', event, ...data);\n emitter.emit(event, ...data);\n };\n\n // Desktop version of Telegram is sometimes not sending the viewport_changed\n // event. For example, when main button is shown. That's why we should\n // add our own listener to make sure, viewport information is always fresh.\n // Issue: https://github.com/Telegram-Mini-Apps/tma.js/issues/10\n window.addEventListener('resize', () => {\n emit('viewport_changed', {\n width: window.innerWidth,\n height: window.innerHeight,\n is_state_stable: true,\n is_expanded: true,\n });\n });\n\n // In case, any Telegram event was received, we should prepare data before\n // passing it to emitter.\n onTelegramEvent((eventType: EventName | string, eventData): void => {\n log('log', 'Received raw event:', eventType, eventData);\n\n try {\n switch (eventType) {\n case 'viewport_changed':\n return emit(eventType, viewportChangedPayload.parse(eventData));\n\n case 'theme_changed':\n return emit(eventType, themeChangedPayload.parse(eventData));\n\n case 'popup_closed':\n // FIXME: Payloads are different on different platforms.\n // Issue: https://github.com/Telegram-Mini-Apps/tma.js/issues/2\n if (\n // Sent on desktop.\n eventData === undefined\n // Sent on iOS.\n || eventData === null\n ) {\n return emit(eventType, {});\n }\n return emit(eventType, popupClosedPayload.parse(eventData));\n\n case 'set_custom_style':\n return emit(eventType, string().parse(eventData));\n\n case 'qr_text_received':\n return emit(eventType, qrTextReceivedPayload.parse(eventData));\n\n case 'clipboard_text_received':\n return emit(eventType, clipboardTextReceivedPayload.parse(eventData));\n\n case 'invoice_closed':\n return emit(eventType, invoiceClosedPayload.parse(eventData));\n\n case 'phone_requested':\n return emit('phone_requested', phoneRequestedPayload.parse(eventData));\n\n case 'custom_method_invoked':\n return emit('custom_method_invoked', customMethodInvokedPayload.parse(eventData));\n\n case 'write_access_requested':\n return emit('write_access_requested', writeAccessRequestedPayload.parse(eventData));\n\n // Events which have no parameters.\n case 'main_button_pressed':\n case 'back_button_pressed':\n case 'settings_button_pressed':\n case 'scan_qr_popup_closed':\n return emit(eventType);\n\n // All other event listeners will receive unknown type of data.\n default:\n return emit(eventType as any, eventData);\n }\n } catch (cause) {\n log('error', 'Error processing event:', cause);\n }\n });\n\n return emitter;\n}\n\n/**\n * Returns singleton instance of bridge EventEmitter. Also, defines\n * Telegram event handlers.\n */\nexport function singletonEmitter(): EventEmitter {\n const wnd: any = window;\n const cachedEmitter = wnd[CACHED_EMITTER];\n\n if (cachedEmitter === undefined) {\n wnd[CACHED_EMITTER] = createEmitter();\n }\n\n return wnd[CACHED_EMITTER];\n}\n","import { singletonEmitter } from './emitter.js';\n\nimport type { EventName, EventListener } from './events.js';\n\n/**\n * Removes listener from specified event.\n * @param event - event to listen.\n * @param listener - event listener.\n */\nexport function off<E extends EventName>(event: E, listener: EventListener<E>): void {\n singletonEmitter().off(event, listener);\n}\n","import { singletonEmitter } from './emitter.js';\nimport { off } from './off.js';\n\nimport type { EventName, EventListener } from './events.js';\n\ntype StopListening = () => void;\n\n/**\n * Adds new listener to the specified event. Returns handler\n * which allows to stop listening to event.\n * @param event - event name.\n * @param listener - event listener.\n */\nexport function on<E extends EventName>(event: E, listener: EventListener<E>): StopListening {\n singletonEmitter().on(event, listener);\n return () => off(event, listener);\n}\n","import { singletonEmitter } from './emitter.js';\nimport { off } from './off.js';\n\nimport type { EventName, EventListener } from './events.js';\n\ntype StopListening = () => void;\n\n/**\n * Works the same as \"on\" method, but after catching the event, will remove event listener.\n * @param event - event name.\n * @param listener - event listener.\n */\nexport function once<E extends EventName>(event: E, listener: EventListener<E>): StopListening {\n singletonEmitter().once(event, listener);\n return () => off(event, listener);\n}\n","import { singletonEmitter } from './emitter.js';\n\nimport type { GlobalEventListener } from './events.js';\n\n/**\n * Removes global event listener.\n * @param listener - event listener.\n */\nexport function unsubscribe(listener: GlobalEventListener): void {\n singletonEmitter().unsubscribe(listener);\n}\n","import { singletonEmitter } from './emitter.js';\nimport { unsubscribe } from './unsubscribe.js';\n\nimport type { GlobalEventListener } from './events.js';\n\ntype StopListening = () => void;\n\n/**\n * Subscribes to all events sent from the native Telegram application.\n * Returns function used to remove added event listener.\n * @param listener - event listener.\n */\nexport function subscribe(listener: GlobalEventListener): StopListening {\n singletonEmitter().subscribe(listener);\n return () => unsubscribe(listener);\n}\n","function f(t, e) {\n return t + (t.length > 0 && e.length > 0 ? ` ${e}` : e);\n}\nfunction a(...t) {\n return t.reduce((e, r) => {\n let n = \"\";\n return typeof r == \"string\" ? n = r : typeof r == \"object\" && r !== null && (n = Object.entries(r).reduce((s, [o, i]) => i ? f(s, o) : s, \"\")), f(e, n);\n }, \"\");\n}\nfunction p(t) {\n return typeof t == \"object\" && t !== null && !Array.isArray(null);\n}\nfunction m(...t) {\n return t.reduce((e, r) => (p(r) && Object.entries(r).forEach(([n, s]) => {\n const o = a(e[n], s);\n o.length > 0 && (e[n] = o);\n }), e), {});\n}\nfunction y(t) {\n return typeof t == \"object\" && t !== null && !Array.isArray(t);\n}\nfunction h(t, e) {\n const r = t.split(\".\"), n = e.split(\".\"), s = Math.max(r.length, n.length);\n for (let o = 0; o < s; o += 1) {\n const i = parseInt(r[o] || \"0\", 10), u = parseInt(n[o] || \"0\", 10);\n if (i !== u)\n return i > u ? 1 : -1;\n }\n return 0;\n}\nclass c extends Error {\n constructor(e) {\n super(`Async call timeout exceeded. Timeout: ${e}`), Object.setPrototypeOf(this, c.prototype);\n }\n}\nfunction l(t) {\n return new Promise((e, r) => {\n setTimeout(r, t, new c(t));\n });\n}\nfunction d(t, e) {\n return typeof t == \"function\" ? (...r) => Promise.race([\n t(...r),\n l(e)\n ]) : Promise.race([t, l(e)]);\n}\nfunction b(t) {\n return t instanceof c;\n}\nexport {\n c as TimeoutError,\n a as classNames,\n h as compareVersions,\n y as isRecord,\n b as isTimeoutError,\n m as mergeClassNames,\n d as withTimeout\n};\n//# sourceMappingURL=index.mjs.map\n","import { isRecord } from '@tma.js/utils';\n\ntype AnyFunc = (...args: unknown[]) => unknown;\n\ntype WithExternalNotify<T> = T & {\n external: { notify: AnyFunc }\n};\n\ntype WithWebviewProxy<T> = T & {\n TelegramWebviewProxy: {\n postEvent: AnyFunc;\n }\n};\n\n/**\n * Returns true in case, passed value contains path `external.notify` property and `notify` is a\n * function.\n * @param value - value to check.\n */\nexport function hasExternalNotify<T extends {}>(value: T): value is WithExternalNotify<T> {\n return 'external' in value\n && isRecord(value.external)\n && 'notify' in value.external\n && typeof value.external.notify === 'function';\n}\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 extends {}>(value: T): value is WithWebviewProxy<T> {\n return 'TelegramWebviewProxy' in value\n && isRecord(value.TelegramWebviewProxy)\n && 'postEvent' in value.TelegramWebviewProxy\n && typeof value.TelegramWebviewProxy.postEvent === 'function';\n}\n\n/**\n * Returns true in case, current environment is iframe.\n * @see https://stackoverflow.com/a/326076\n */\nexport function isIframe(): boolean {\n try {\n return window.self !== window.top;\n } catch (e) {\n return true;\n }\n}\n","import {\n isIframe,\n hasExternalNotify,\n hasWebviewProxy,\n} from '../env.js';\nimport { targetOrigin as globalTargetOrigin } from '../globals.js';\n\nimport type {\n EmptyMethodName,\n MethodName,\n MethodParams,\n NonEmptyMethodName,\n} from './params.js';\n\ninterface PostEventOptions {\n /**\n * Origin used while posting message. This option is only used in case,\n * current environment is browser (Web version of Telegram) and could\n * be used for test purposes.\n * @default 'https://web.telegram.org'\n */\n targetOrigin?: string;\n}\n\nexport type PostEvent = typeof postEvent;\n\n/**\n * Sends event to native application which launched Web App. This function\n * accepts only events, which require arguments.\n * @param eventType - event name.\n * @param params - event parameters.\n * @param options - posting options.\n * @throws {Error} Bridge could not determine current\n * environment and possible way to send event.\n */\nexport function postEvent<E extends NonEmptyMethodName>(\n eventType: E,\n params: MethodParams<E>,\n options?: PostEventOptions,\n): void;\n\n/**\n * Sends event to native application which launched Web App. This function\n * accepts only events, which require arguments.\n * @param eventType - event name.\n * @param options - posting options.\n * @throws {Error} Bridge could not determine current\n * environment and possible way to send event.\n */\nexport function postEvent(eventType: EmptyMethodName, options?: PostEventOptions): void;\n\nexport function postEvent(\n eventType: MethodName,\n paramsOrOptions?: MethodParams<MethodName> | PostEventOptions,\n options?: PostEventOptions,\n): void {\n let postOptions: PostEventOptions = {};\n let eventData: any;\n\n if (paramsOrOptions === undefined && options === undefined) {\n // Parameters and options were not passed.\n postOptions = {};\n } else if (paramsOrOptions !== undefined && options !== undefined) {\n // Both parameters and options passed.\n postOptions = options;\n eventData = paramsOrOptions;\n } else if (paramsOrOptions !== undefined) {\n // Only parameters were passed.\n if ('targetOrigin' in paramsOrOptions) {\n postOptions = paramsOrOptions;\n } else {\n eventData = paramsOrOptions;\n }\n }\n const { targetOrigin = globalTargetOrigin() } = postOptions;\n\n // Telegram Web.\n if (isIframe()) {\n window.parent.postMessage(JSON.stringify({\n eventType,\n eventData,\n }), targetOrigin);\n return;\n }\n\n // Telegram for Windows Phone or Android.\n if (hasExternalNotify(window)) {\n window.external.notify(JSON.stringify({ eventType, eventData }));\n return;\n }\n\n // Telegram for iOS and macOS.\n if (hasWebviewProxy(window)) {\n window.TelegramWebviewProxy.postEvent(eventType, JSON.stringify(eventData));\n return;\n }\n\n // Otherwise current environment is unknown, and we are not able to send\n // event.\n throw new Error(\n 'Unable to determine current environment and possible way to send event.',\n );\n}\n","import { withTimeout, isRecord } from '@tma.js/utils';\n\nimport type { And, If, IsNever } from '@tma.js/util-types';\n\nimport { postEvent as defaultPostEvent, type PostEvent } from './methods/postEvent.js';\nimport { on, type EventName, type EventParams, type EventHasParams } from './events/index.js';\n\nimport type {\n EmptyMethodName, MethodHasParams,\n MethodName,\n MethodParams,\n NonEmptyMethodName,\n} from './methods/params.js';\n\n/**\n * Names of methods, which require passing \"req_id\" parameter.\n */\ntype MethodNameWithRequestId = {\n [Method in MethodName]: If<\n And<MethodHasParams<Method>, MethodParams<Method> extends { req_id: string } ? true : false>,\n Method,\n never\n >;\n}[MethodName];\n\n/**\n * Names of events, which contain \"req_id\" parameter.\n */\ntype EventNameWithRequestId = {\n [Event in EventName]: If<\n And<EventHasParams<Event>, EventParams<Event> extends { req_id: string } ? true : false>,\n Event,\n never\n >;\n}[EventName];\n\nexport interface RequestOptions {\n /**\n * Bridge postEvent method.\n * @default Global postEvent method.\n */\n postEvent?: PostEvent;\n\n /**\n * Execution timeout.\n */\n timeout?: number;\n}\n\nexport interface RequestOptionsAdvanced<EventPayload> extends RequestOptions {\n /**\n * Should return true in case, this event should be captured. If not specified,\n * request is not skipping captured events.\n */\n capture?: If<IsNever<EventPayload>, () => boolean, (payload: EventPayload) => boolean>;\n}\n\n/**\n * Calls specified TWA method and captures one of the specified events. Returns promise\n * which will be resolved in case, event with specified in method request identifier\n * was captured.\n * @param method - method to execute.\n * @param params - method parameters.\n * @param event - event or events to listen.\n * @param options - additional execution options.\n */\nexport function request<\n Method extends MethodNameWithRequestId,\n Event extends EventNameWithRequestId,\n>(\n method: Method,\n params: MethodParams<Method>,\n event: Event | Event[],\n options?: RequestOptions,\n): Promise<EventParams<Event>>;\n\n/**\n * Calls specified TWA method and captures one of the specified events. Returns promise\n * which will be resolved in case, specified event was captured.\n * @param method - method to execute.\n * @param event - event or events to listen.\n * @param options - additional execution options.\n */\nexport function request<Method extends EmptyMethodName, Event extends EventName>(\n method: Method,\n event: Event | Event[],\n options?: RequestOptionsAdvanced<EventParams<Event>>,\n): Promise<EventParams<Event>>;\n\n/**\n * Calls specified TWA method and captures one of the specified events. Returns promise\n * which will be resolved in case, specified event was captured.\n * @param method - method to execute\n * @param params - method parameters.\n * @param event - event or events to listen\n * @param options - additional execution options.\n */\nexport function request<Method extends NonEmptyMethodName, Event extends EventName>(\n method: Method,\n params: MethodParams<Method>,\n event: Event | Event[],\n options?: RequestOptionsAdvanced<EventParams<Event>>,\n): Promise<EventParams<Event>>;\n\nexport function request(\n method: MethodName,\n eventOrParams: EventName | EventName[] | EventParams<any>,\n eventOrOptions?: EventName | EventName[] | RequestOptions | RequestOptionsAdvanced<any>,\n options?: RequestOptions | RequestOptionsAdvanced<any>,\n): Promise<any> {\n let executionOptions: RequestOptions | RequestOptionsAdvanced<any> | undefined;\n let methodParams: EventParams<any> | undefined;\n let events: EventName[];\n let requestId: string | undefined;\n\n if (typeof eventOrParams === 'string' || Array.isArray(eventOrParams)) {\n // Override: [method, event, options?]\n events = Array.isArray(eventOrParams) ? eventOrParams : [eventOrParams] as EventName[];\n executionOptions = eventOrOptions as (RequestOptionsAdvanced<any> | undefined);\n } else {\n // Override: [method, params, event, options?]\n methodParams = eventOrParams as EventParams<any>;\n events = Array.isArray(eventOrOptions) ? eventOrOptions : [eventOrOptions] as EventName[];\n executionOptions = options;\n }\n\n // In case, method parameters were passed, and they contained request identifier, we should store\n // it and wait for the event with this identifier to occur.\n if (isRecord(methodParams) && typeof methodParams.req_id === 'string') {\n requestId = methodParams.req_id;\n }\n\n const { postEvent = defaultPostEvent, timeout } = executionOptions || {};\n const capture = executionOptions && 'capture' in executionOptions\n ? executionOptions.capture\n : null;\n\n const promise = new Promise((res, rej) => {\n // Iterate over each event and create event listener.\n const stoppers = events.map((ev) => on(ev, (data?) => {\n // If request identifier was specified, we are waiting for event with the same value\n // to occur.\n if (typeof requestId === 'string' && (!isRecord(data) || data.req_id !== requestId)) {\n return;\n }\n\n if (typeof capture === 'function' && !capture(data)) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n stopListening();\n res(data);\n }));\n\n // Function which removes all event listeners.\n const stopListening = () => stoppers.forEach((stop) => stop());\n\n try {\n // We are wrapping this call in try catch, because it can throw errors in case,\n // compatibility check was enabled. We want an error to be captured by promise, not by\n // another one external try catch.\n postEvent(method as any, methodParams);\n } catch (e) {\n stopListening();\n rej(e);\n }\n });\n\n return typeof timeout === 'number' ? withTimeout(promise, timeout) : promise;\n}\n","import { compareVersions, type Version } from '@tma.js/utils';\n\nimport type {\n HasCheckSupportMethodParam,\n HasCheckSupportMethodName,\n MethodName,\n MethodParams,\n NonEmptyMethodName,\n} from './methods/index.js';\n\nfunction lessOrEqual(a: Version, b: Version): boolean {\n return compareVersions(a, b) <= 0;\n}\n\n/**\n * By specified method and parameters extracts properties which could be used by\n * supports function as TWA method parameter.\n * @param method - TWA method.\n * @param params - method parameters.\n */\nexport function detectSupportParams<M extends NonEmptyMethodName>(\n method: M,\n params: MethodParams<M>,\n): HasCheckSupportMethodParam<HasCheckSupportMethodName>[] {\n if (method === 'web_app_open_link') {\n if ('try_instant_view' in params) {\n return ['try_instant_view'];\n }\n }\n\n if (method === 'web_app_set_header_color') {\n if ('color' in params) {\n return ['color'];\n }\n }\n\n return [];\n}\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 HasCheckSupportMethodName>(\n method: M,\n param: HasCheckSupportMethodParam<M>,\n inVersion: Version,\n): boolean;\n/**\n * Returns true in case, specified method is supported in passed version.\n * @param method - method name.\n * @param inVersion - platform version.\n */\nexport function supports(method: MethodName, inVersion: Version): boolean;\nexport function supports(\n method: MethodName,\n paramOrVersion: Version | string,\n inVersion?: string,\n): boolean {\n // Method name, parameter, target version.\n if (typeof inVersion === 'string') {\n if (method === 'web_app_open_link') {\n if (paramOrVersion === 'try_instant_view') {\n return lessOrEqual('6.4', inVersion);\n }\n }\n\n if (method === 'web_app_set_header_color') {\n if (paramOrVersion === 'color') {\n return lessOrEqual('6.9', inVersion);\n }\n }\n }\n\n // Method name, target version.\n switch (method) {\n case 'web_app_open_tg_link':\n case 'web_app_open_invoice':\n case 'web_app_setup_back_button':\n case 'web_app_set_background_color':\n case 'web_app_set_header_color':\n case 'web_app_trigger_haptic_feedback':\n return lessOrEqual('6.1', paramOrVersion);\n case 'web_app_open_popup':\n return lessOrEqual('6.2', paramOrVersion);\n case 'web_app_close_scan_qr_popup':\n case 'web_app_open_scan_qr_popup':\n case 'web_app_read_text_from_clipboard':\n return lessOrEqual('6.4', paramOrVersion);\n case 'web_app_invoke_custom_method':\n case 'web_app_request_write_access':\n case 'web_app_request_phone':\n return lessOrEqual('6.9', paramOrVersion);\n case 'web_app_setup_settings_button':\n return lessOrEqual('6.10', paramOrVersion);\n default:\n return true;\n }\n}\n"],"names":["f","h","r","s","e","o","l$1","t","i","n","c","a","u","y","b","p","w","m","G","V","U","P","S","B","A","currentDebug","currentTargetOrigin","setDebug","value","setTargetOrigin","targetOrigin","log","level","args","utilLog","isNullOrUndefined","rgbOptional","rgb","num","number","windowWidthParser","createValueParserGen","themeChangedPayload","json","viewportChangedPayload","boolean","popupClosedPayload","string","qrTextReceivedPayload","invoiceClosedPayload","clipboardTextReceivedPayload","writeAccessRequestedPayload","phoneRequestedPayload","customMethodInvokedPayload","eventDataJson","emitEvent","eventType","eventData","defineEventHandlers","wnd","path","pointer","item","idx","arr","onTelegramEvent","cb","event","CACHED_EMITTER","createEmitter","emitter","UtilEventEmitter","emit","data","cause","singletonEmitter","off","listener","on","once","unsubscribe","subscribe","l","d","hasExternalNotify","isRecord","hasWebviewProxy","isIframe","postEvent","paramsOrOptions","options","postOptions","globalTargetOrigin","request","method","eventOrParams","eventOrOptions","executionOptions","methodParams","events","requestId","defaultPostEvent","timeout","capture","promise","res","rej","stoppers","ev","stopListening","stop","withTimeout","lessOrEqual","compareVersions","detectSupportParams","params","supports","paramOrVersion","inVersion"],"mappings":"qEAAA,IAAIA,EAAI,OAAO,eACXC,EAAI,CAACC,EAAGC,EAAGC,IAAMD,KAAKD,EAAIF,EAAEE,EAAGC,EAAG,CAAE,WAAY,GAAI,aAAc,GAAI,SAAU,GAAI,MAAOC,CAAC,CAAE,EAAIF,EAAEC,CAAC,EAAIC,EACzGC,EAAI,CAACH,EAAGC,EAAGC,KAAOH,EAAEC,EAAG,OAAOC,GAAK,SAAWA,EAAI,GAAKA,EAAGC,CAAC,EAAGA,GAClE,IAAAE,EAAA,KAAQ,CACN,aAAc,CACZD,EAAE,KAAM,YAAa,CAAA,CAAE,EACvBA,EAAE,KAAM,qBAAsB,CAAA,CAAE,CACjC,CACD,KAAKF,KAAMC,EAAG,CACZ,KAAK,mBAAmB,QAASG,GAAMA,EAAEJ,EAAG,GAAGC,CAAC,CAAC,EACjD,MAAMI,EAAI,KAAK,UAAUL,CAAC,EAC1B,GAAIK,IAAM,OACR,OACF,MAAMC,EAAI,CAAA,EACVD,EAAE,QAASD,GAAM,C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CAEL,GAAA,OAAOA,GAAc,SAAU,CACjC,GAAIxB,IAAW,qBACTuB,IAAmB,mBACd,OAAAL,EAAY,MAAOM,CAAS,EAIvC,GAAIxB,IAAW,4BACTuB,IAAmB,QACd,OAAAL,EAAY,MAAOM,CAAS,CAGzC,CAGA,OAAQxB,EAAQ,CACd,IAAK,uBACL,IAAK,uBACL,IAAK,4BACL,IAAK,+BACL,IAAK,2BACL,IAAK,kCACI,OAAAkB,EAAY,MAAOK,CAAc,EAC1C,IAAK,qBACI,OAAAL,EAAY,MAAOK,CAAc,EAC1C,IAAK,8BACL,IAAK,6BACL,IAAK,mCACI,OAAAL,EAAY,MAAOK,CAAc,EAC1C,IAAK,+BACL,IAAK,+BACL,IAAK,wBACI,OAAAL,EAAY,MAAOK,CAAc,EAC1C,IAAK,gCACI,OAAAL,EAAY,OAAQK,CAAc,EAC3C,QACS,MAAA,EACX,CACF"}
1
+ {"version":3,"file":"index.iife.js","sources":["../../event-emitter/dist/index.mjs","../../colors/dist/index.mjs","../../parsing/dist/index.mjs","../../logger/dist/index.mjs","../src/globals.ts","../src/events/parsing.ts","../src/events/onTelegramEvent.ts","../src/events/emitter.ts","../src/events/off.ts","../src/events/on.ts","../src/events/once.ts","../src/events/unsubscribe.ts","../src/events/subscribe.ts","../../utils/dist/index.mjs","../src/env.ts","../src/methods/postEvent.ts","../src/request.ts","../src/supports.ts"],"sourcesContent":["var b = Object.defineProperty;\nvar c = (r, s, e) => s in r ? b(r, s, { enumerable: !0, configurable: !0, writable: !0, value: e }) : r[s] = e;\nvar n = (r, s, e) => (c(r, typeof s != \"symbol\" ? s + \"\" : s, e), e);\nclass f {\n constructor() {\n n(this, \"listeners\", /* @__PURE__ */ new Map());\n n(this, \"subscribeListeners\", []);\n }\n /**\n * Adds specified event listener.\n * @param event - event name.\n * @param listener - event listener.\n * @param once - should listener called only once.\n */\n addListener(s, e, t) {\n let i = this.listeners.get(s);\n return i || (i = [], this.listeners.set(s, i)), i.push([e, t]), () => this.off(s, e);\n }\n emit(s, ...e) {\n this.subscribeListeners.forEach((i) => i(s, ...e));\n const t = this.listeners.get(s);\n t && t.forEach(([i, u], h) => {\n i(...e), u && t.splice(h, 1);\n });\n }\n /**\n * Adds event listener.\n * @param event - event name.\n * @param listener - event listener.\n * @returns Function to remove event listener.\n */\n on(s, e) {\n return this.addListener(s, e, !1);\n }\n /**\n * Adds event listener following the logic, described in `on` method, but calls specified\n * listener only once, removing it after.\n * @param event - event name.\n * @param listener - event listener.\n * @returns Function to remove event listener.\n * @see on\n */\n once(s, e) {\n return this.addListener(s, e, !0);\n }\n /**\n * Removes event listener. In case, specified listener was bound several times, it removes\n * only a single one.\n * @param event - event name.\n * @param listener - event listener.\n */\n off(s, e) {\n const t = this.listeners.get(s);\n if (t) {\n for (let i = 0; i < t.length; i += 1)\n if (e === t[i][0]) {\n t.splice(i, 1);\n return;\n }\n }\n }\n /**\n * Adds event listener to all events.\n * @param listener - events listener.\n * @returns Function to remove event listener.\n * @see on\n * @see once\n */\n subscribe(s) {\n return this.subscribeListeners.push(s), () => this.unsubscribe(s);\n }\n /**\n * Removes global event listener. In case, specified listener was bound several times, it removes\n * only a single one.\n * @param listener - events listener.\n * @returns Function to remove event listener.\n */\n unsubscribe(s) {\n for (let e = 0; e < this.subscribeListeners.length; e += 1)\n if (this.subscribeListeners[e] === s) {\n this.subscribeListeners.splice(e, 1);\n return;\n }\n }\n}\nexport {\n f as EventEmitter\n};\n//# sourceMappingURL=index.mjs.map\n","function a(t) {\n return /^#[\\da-f]{3}$/i.test(t);\n}\nfunction i(t) {\n return /^#[\\da-f]{6}$/i.test(t);\n}\nfunction u(t) {\n const r = t.replace(/\\s/g, \"\").toLowerCase();\n if (i(r))\n return r;\n if (a(r)) {\n let n = \"#\";\n for (let e = 0; e < 3; e += 1)\n n += r[1 + e].repeat(2);\n return n;\n }\n const s = r.match(/^rgb\\((\\d{1,3}),(\\d{1,3}),(\\d{1,3})\\)$/) || r.match(/^rgba\\((\\d{1,3}),(\\d{1,3}),(\\d{1,3}),\\d{1,3}\\)$/);\n if (s === null)\n throw new Error(`Value \"${t}\" does not satisfy any of known RGB formats.`);\n return s.slice(1).reduce((n, e) => {\n const o = parseInt(e, 10).toString(16);\n return n + (o.length === 1 ? \"0\" : \"\") + o;\n }, \"#\");\n}\nfunction f(t) {\n const r = u(t);\n return Math.sqrt(\n [0.299, 0.587, 0.114].reduce((n, e, o) => {\n const c = parseInt(r.slice(1 + o * 2, 1 + (o + 1) * 2), 16);\n return n + c * c * e;\n }, 0)\n ) < 120;\n}\nexport {\n f as isColorDark,\n i as isRGB,\n a as isRGBShort,\n u as toRGB\n};\n//# sourceMappingURL=index.mjs.map\n","var g = Object.defineProperty;\nvar l = (r, t, e) => t in r ? g(r, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : r[t] = e;\nvar d = (r, t, e) => (l(r, typeof t != \"symbol\" ? t + \"\" : t, e), e);\nimport { toRGB as A } from \"@tma.js/colors\";\nclass i extends Error {\n constructor(t, { type: e, error: o, field: n } = {}) {\n super(`Unable to parse ${n ? `field \"${n}\"` : \"value\"} as ${e}`, {\n cause: { value: t, error: o }\n }), Object.setPrototypeOf(this, i.prototype);\n }\n}\nclass u {\n constructor(t, e, o) {\n this.parser = t, this.isOptional = e, this.isEmpty = o;\n }\n parse(t) {\n return this.isOptional && this.isEmpty(t) ? void 0 : this.parser(t);\n }\n optional() {\n return this.isOptional = !0, this;\n }\n}\nfunction E(r) {\n if (Array.isArray(r))\n return r;\n if (typeof r == \"string\")\n try {\n const t = JSON.parse(r);\n if (Array.isArray(t))\n return t;\n } catch {\n }\n throw new i(r, { type: \"array\" });\n}\nclass O extends u {\n constructor(e, o, n) {\n super(E, o, n);\n d(this, \"itemParser\");\n this.itemParser = typeof e == \"function\" ? e : e.parse.bind(e);\n }\n parse(e) {\n const o = super.parse(e);\n return o === void 0 ? o : o.map(this.itemParser);\n }\n of(e) {\n return this.itemParser = typeof e == \"function\" ? e : e.parse.bind(e), this;\n }\n}\nfunction h(r) {\n return r === void 0;\n}\nfunction D() {\n return new O((r) => r, !1, h);\n}\nfunction f() {\n return new TypeError(\"Does not have any of expected types\");\n}\nfunction y(r, { isEmpty: t = h } = {}) {\n return function({ isEmpty: o = t } = {}) {\n return new u(r, !1, o);\n };\n}\nfunction b(r, t, e) {\n const o = {};\n for (const n in r) {\n const s = r[n];\n if (!s)\n continue;\n let a, p;\n if (\"type\" in s) {\n const { type: c } = s;\n a = s.from || n, p = typeof c == \"function\" ? c : c.parse.bind(c);\n } else\n a = n, p = typeof s == \"function\" ? s : s.parse.bind(s);\n let w;\n const m = t(a);\n try {\n w = p(m);\n } catch (c) {\n throw new i(m, {\n field: a,\n type: e,\n error: c\n });\n }\n w !== void 0 && (o[n] = w);\n }\n return o;\n}\nconst G = y((r) => {\n if (typeof r == \"boolean\")\n return r;\n throw new i(r, { type: \"boolean\", error: f() });\n}), V = y((r) => {\n if (typeof r == \"number\")\n return r;\n if (typeof r == \"string\") {\n const t = Number(r);\n if (!Number.isNaN(t))\n return t;\n }\n throw new i(r, { type: \"number\", error: f() });\n}), N = V(), R = y((r) => {\n if (r instanceof Date)\n return r;\n try {\n return new Date(N.parse(r) * 1e3);\n } catch (t) {\n throw new i(r, { type: \"Date\", error: t });\n }\n});\nfunction U(r, t = {}) {\n const {\n type: e,\n isEmpty: o = h\n } = t;\n return new u((n) => {\n let s = n;\n if (typeof s == \"string\")\n try {\n s = JSON.parse(s);\n } catch (a) {\n throw new i(n, { type: e, error: a });\n }\n if (typeof s != \"object\" || s === null || Array.isArray(s))\n throw new i(n, { type: e, error: f() });\n return b(r, (a) => s[a]);\n }, !1, o);\n}\nconst P = y((r) => {\n if (typeof r == \"string\" || typeof r == \"number\")\n return r.toString();\n throw new i(r, { type: \"string\", error: f() });\n}), S = P(), B = y((r) => {\n try {\n return A(S.parse(r));\n } catch (t) {\n throw new i(r, { type: \"RGB\", error: t });\n }\n});\nfunction $(r, t = {}) {\n const {\n type: e,\n isEmpty: o = h\n } = t;\n return new u((n) => {\n if (typeof n != \"string\" && !(n instanceof URLSearchParams))\n throw new i(n, { type: e, error: f() });\n const s = typeof n == \"string\" ? new URLSearchParams(n) : n;\n return b(r, (a) => {\n const p = s.get(a);\n return p === null ? void 0 : p;\n });\n }, !1, o);\n}\nexport {\n O as ArrayValueParser,\n i as ParsingError,\n u as ValueParser,\n D as array,\n G as boolean,\n y as createValueParserGen,\n R as date,\n U as json,\n V as number,\n B as rgb,\n $ as searchParams,\n P as string\n};\n//# sourceMappingURL=index.mjs.map\n","class o {\n constructor(t, e) {\n this.prefix = t, this.enabled = e;\n }\n /**\n * Prints message into a console in case, logger is currently enabled.\n * @param level - log level.\n * @param args - arguments.\n */\n print(t, ...e) {\n if (!this.enabled)\n return;\n const i = /* @__PURE__ */ new Date(), n = Intl.DateTimeFormat(\"en-GB\", {\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n fractionalSecondDigits: 3,\n timeZone: \"UTC\"\n }).format(i);\n console[t](`[${n}]`, this.prefix, ...e);\n }\n /**\n * Disables the logger.\n */\n disable() {\n this.enabled = !1;\n }\n /**\n * Prints error message into a console.\n * @param args\n */\n error(...t) {\n this.print(\"error\", ...t);\n }\n /**\n * Enables the logger.\n */\n enable() {\n this.enabled = !0;\n }\n /**\n * Prints log message into a console.\n * @param args\n */\n log(...t) {\n this.print(\"log\", ...t);\n }\n /**\n * Prints warning message into a console.\n * @param args\n */\n warn(...t) {\n this.print(\"warn\", ...t);\n }\n}\nexport {\n o as Logger\n};\n//# sourceMappingURL=index.mjs.map\n","import { Logger } from '@tma.js/logger';\n\nlet currentTargetOrigin = 'https://web.telegram.org';\n\nexport const logger = new Logger('[Bridge]', false);\n\n/**\n * Sets new debug mode. Enabling debug mode leads to printing\n * additional messages in console, related to the processes\n * inside the package.\n * @param value - should debug mode be enabled.\n */\nexport function setDebug(value: boolean): void {\n if (value) {\n logger.enable();\n return;\n }\n logger.disable();\n}\n\n/**\n * Sets new global targetOrigin, used by `postEvent` method.\n * Default value is \"https://web.telegram.org\". You don't need to\n * use this method until you know what you are doing.\n *\n * This method could be used for test purposes.\n * @param value - new target origin.\n */\nexport function setTargetOrigin(value: string): void {\n currentTargetOrigin = value;\n}\n\n/**\n * Returns current global target origin.\n */\nexport function targetOrigin(): string {\n return currentTargetOrigin;\n}\n","import {\n number,\n string,\n boolean,\n json,\n rgb,\n createValueParserGen,\n} from '@tma.js/parsing';\n\nimport type {\n ClipboardTextReceivedPayload, CustomMethodInvokedPayload,\n InvoiceClosedPayload, PhoneRequestedPayload,\n PopupClosedPayload, QrTextReceivedPayload,\n ThemeChangedPayload,\n ViewportChangedPayload, WriteAccessRequestedPayload,\n} from './payloads.js';\n\nfunction isNullOrUndefined(value: unknown): boolean {\n return value === null || value === undefined;\n}\n\nconst rgbOptional = rgb().optional();\nconst num = number();\n\nconst windowWidthParser = createValueParserGen((value) => (value === null || value === undefined\n ? window.innerWidth\n : num.parse(value)));\n\n/**\n * Parses incoming value as ThemeChangedPayload.\n */\nexport const themeChangedPayload = json<ThemeChangedPayload>({\n theme_params: json({\n bg_color: rgbOptional,\n text_color: rgbOptional,\n hint_color: rgbOptional,\n link_color: rgbOptional,\n button_color: rgbOptional,\n button_text_color: rgbOptional,\n secondary_bg_color: rgbOptional,\n }),\n});\n\n/**\n * Parses incoming value as ViewportChangedPayload.\n * @param value - value to parse.\n */\nexport const viewportChangedPayload = json<ViewportChangedPayload>({\n height: number(),\n width: windowWidthParser(),\n is_state_stable: boolean(),\n is_expanded: boolean(),\n});\n\n/**\n * Parses incoming value as PopupClosedPayload.\n */\nexport const popupClosedPayload = json<PopupClosedPayload>({\n button_id: string({ isEmpty: isNullOrUndefined }).optional(),\n});\n\n/**\n * Parses incoming value as QrTextReceivedPayload.\n */\nexport const qrTextReceivedPayload = json<QrTextReceivedPayload>({\n data: string().optional(),\n});\n\n/**\n * Parses incoming value as InvoiceClosedPayload.\n */\nexport const invoiceClosedPayload = json<InvoiceClosedPayload>({\n slug: string(),\n status: string(),\n});\n\n/**\n * Parses incoming value as clipboard text received payload.\n */\nexport const clipboardTextReceivedPayload = json<ClipboardTextReceivedPayload>({\n req_id: string(),\n data: (value) => (value === null ? value : string().optional().parse(value)),\n});\n\n/**\n * Parses incoming value as WriteAccessRequestedPayload.\n */\nexport const writeAccessRequestedPayload = json<WriteAccessRequestedPayload>({ status: string() });\n\n/**\n * Parses incoming value as PhoneRequestedPayload.\n */\nexport const phoneRequestedPayload = json<PhoneRequestedPayload>({ status: string() });\n\n/**\n * Parses incoming value as CustomMethodInvokedPayload.\n */\nexport const customMethodInvokedPayload = json<CustomMethodInvokedPayload>({\n req_id: string(),\n result: (value) => value,\n error: string().optional(),\n});\n","import { json, string } from '@tma.js/parsing';\n\n/**\n * Extracts event data from native application event.\n */\nconst eventDataJson = json<{ eventType: string; eventData?: unknown }>({\n eventType: string(),\n eventData: (value) => value,\n});\n\n/**\n * Emits event sent from Telegram native application like it was sent in\n * default web environment between 2 iframes. It dispatches new MessageEvent\n * and expects it to be handled via `window.addEventListener('message', ...)`\n * as developer would do it to handle messages sent from parent iframe.\n * @param eventType - event name.\n * @param eventData - event payload.\n */\nfunction emitEvent(eventType: string, eventData: unknown): void {\n window.dispatchEvent(new MessageEvent('message', {\n data: JSON.stringify({ eventType, eventData }),\n }));\n}\n\n/**\n * Defines special handlers by known paths, which are recognized by\n * Telegram as ports to receive events. This function also sets special\n * function in global window object to prevent duplicate declaration.\n */\nfunction defineEventHandlers(): void {\n const wnd: any = window;\n\n // Prevent from duplicate event handlers definition.\n if ('TelegramGameProxy_receiveEvent' in wnd) {\n return;\n }\n\n // Iterate over each path, where \"receiveEvent\" function should be\n // defined. This function is called by external environment in case,\n // it wants to emit some event.\n [\n ['TelegramGameProxy_receiveEvent'], // Windows Phone.\n ['TelegramGameProxy', 'receiveEvent'], // Desktop.\n ['Telegram', 'WebView', 'receiveEvent'], // Android and iOS.\n ].forEach((path) => {\n // Path starts from \"window\" object.\n let pointer = wnd;\n\n path.forEach((item, idx, arr) => {\n // We are on the last iteration, where function property name is passed.\n if (idx === arr.length - 1) {\n pointer[item] = emitEvent;\n return;\n }\n\n if (!(item in pointer)) {\n pointer[item] = {};\n }\n pointer = pointer[item];\n });\n });\n}\n\n/**\n * Adds listener to window \"message\" event assuming, that this event could\n * be sent by Telegram native application. Calls passed callback with event\n * type and data.\n * @param cb - callback to call.\n */\nexport function onTelegramEvent(cb: (eventType: string, eventData: unknown) => void): void {\n // Define event handlers to make sure, message handler will work correctly.\n defineEventHandlers();\n\n // We expect Telegram to send us new event through \"message\" event.\n window.addEventListener('message', (event) => {\n try {\n const { eventType, eventData } = eventDataJson.parse(event.data);\n cb(eventType, eventData);\n } catch {\n // We ignore incorrect messages as they could be generated by any other code.\n }\n });\n}\n","import { EventEmitter as UtilEventEmitter } from '@tma.js/event-emitter';\nimport { string } from '@tma.js/parsing';\n\nimport { logger } from '../globals.js';\nimport {\n clipboardTextReceivedPayload,\n customMethodInvokedPayload,\n invoiceClosedPayload,\n phoneRequestedPayload,\n popupClosedPayload,\n qrTextReceivedPayload,\n themeChangedPayload,\n viewportChangedPayload,\n writeAccessRequestedPayload,\n} from './parsing.js';\nimport { onTelegramEvent } from './onTelegramEvent.js';\n\nimport type { EventEmitter, EventName } from './events.js';\n\nconst CACHED_EMITTER = '__telegram-cached-emitter__';\n\n/**\n * Returns event emitter which could be safely used, to process events from\n * Telegram native application.\n */\nexport function createEmitter(): EventEmitter {\n const emitter: EventEmitter = new UtilEventEmitter();\n const emit: EventEmitter['emit'] = (event: any, ...data: any[]) => {\n logger.log('Emitting processed event:', event, ...data);\n emitter.emit(event, ...data);\n };\n\n // Desktop version of Telegram is sometimes not sending the viewport_changed\n // event. For example, when main button is shown. That's why we should\n // add our own listener to make sure, viewport information is always fresh.\n // Issue: https://github.com/Telegram-Mini-Apps/tma.js/issues/10\n window.addEventListener('resize', () => {\n emit('viewport_changed', {\n width: window.innerWidth,\n height: window.innerHeight,\n is_state_stable: true,\n is_expanded: true,\n });\n });\n\n // In case, any Telegram event was received, we should prepare data before\n // passing it to emitter.\n onTelegramEvent((eventType: EventName | string, eventData): void => {\n logger.log('Received raw event:', eventType, eventData);\n\n try {\n switch (eventType) {\n case 'viewport_changed':\n return emit(eventType, viewportChangedPayload.parse(eventData));\n\n case 'theme_changed':\n return emit(eventType, themeChangedPayload.parse(eventData));\n\n case 'popup_closed':\n // FIXME: Payloads are different on different platforms.\n // Issue: https://github.com/Telegram-Mini-Apps/tma.js/issues/2\n if (\n // Sent on desktop.\n eventData === undefined\n // Sent on iOS.\n || eventData === null\n ) {\n return emit(eventType, {});\n }\n return emit(eventType, popupClosedPayload.parse(eventData));\n\n case 'set_custom_style':\n return emit(eventType, string().parse(eventData));\n\n case 'qr_text_received':\n return emit(eventType, qrTextReceivedPayload.parse(eventData));\n\n case 'clipboard_text_received':\n return emit(eventType, clipboardTextReceivedPayload.parse(eventData));\n\n case 'invoice_closed':\n return emit(eventType, invoiceClosedPayload.parse(eventData));\n\n case 'phone_requested':\n return emit('phone_requested', phoneRequestedPayload.parse(eventData));\n\n case 'custom_method_invoked':\n return emit('custom_method_invoked', customMethodInvokedPayload.parse(eventData));\n\n case 'write_access_requested':\n return emit('write_access_requested', writeAccessRequestedPayload.parse(eventData));\n\n // Events which have no parameters.\n case 'main_button_pressed':\n case 'back_button_pressed':\n case 'settings_button_pressed':\n case 'scan_qr_popup_closed':\n return emit(eventType);\n\n // All other event listeners will receive unknown type of data.\n default:\n return emit(eventType as any, eventData);\n }\n } catch (cause) {\n logger.error('Error processing event:', cause);\n }\n });\n\n return emitter;\n}\n\n/**\n * Returns singleton instance of bridge EventEmitter. Also, defines\n * Telegram event handlers.\n */\nexport function singletonEmitter(): EventEmitter {\n const wnd: any = window;\n const cachedEmitter = wnd[CACHED_EMITTER];\n\n if (cachedEmitter === undefined) {\n wnd[CACHED_EMITTER] = createEmitter();\n }\n\n return wnd[CACHED_EMITTER];\n}\n","import { singletonEmitter } from './emitter.js';\n\nimport type { EventName, EventListener } from './events.js';\n\n/**\n * Removes listener from specified event.\n * @param event - event to listen.\n * @param listener - event listener.\n */\nexport function off<E extends EventName>(event: E, listener: EventListener<E>): void {\n singletonEmitter().off(event, listener);\n}\n","import { singletonEmitter } from './emitter.js';\nimport { off } from './off.js';\n\nimport type { EventName, EventListener } from './events.js';\n\ntype StopListening = () => void;\n\n/**\n * Adds new listener to the specified event. Returns handler\n * which allows to stop listening to event.\n * @param event - event name.\n * @param listener - event listener.\n */\nexport function on<E extends EventName>(event: E, listener: EventListener<E>): StopListening {\n singletonEmitter().on(event, listener);\n return () => off(event, listener);\n}\n","import { singletonEmitter } from './emitter.js';\nimport { off } from './off.js';\n\nimport type { EventName, EventListener } from './events.js';\n\ntype StopListening = () => void;\n\n/**\n * Works the same as \"on\" method, but after catching the event, will remove event listener.\n * @param event - event name.\n * @param listener - event listener.\n */\nexport function once<E extends EventName>(event: E, listener: EventListener<E>): StopListening {\n singletonEmitter().once(event, listener);\n return () => off(event, listener);\n}\n","import { singletonEmitter } from './emitter.js';\n\nimport type { GlobalEventListener } from './events.js';\n\n/**\n * Removes global event listener.\n * @param listener - event listener.\n */\nexport function unsubscribe(listener: GlobalEventListener): void {\n singletonEmitter().unsubscribe(listener);\n}\n","import { singletonEmitter } from './emitter.js';\nimport { unsubscribe } from './unsubscribe.js';\n\nimport type { GlobalEventListener } from './events.js';\n\ntype StopListening = () => void;\n\n/**\n * Subscribes to all events sent from the native Telegram application.\n * Returns function used to remove added event listener.\n * @param listener - event listener.\n */\nexport function subscribe(listener: GlobalEventListener): StopListening {\n singletonEmitter().subscribe(listener);\n return () => unsubscribe(listener);\n}\n","function f(t, e) {\n return t + (t.length > 0 && e.length > 0 ? ` ${e}` : e);\n}\nfunction a(...t) {\n return t.reduce((e, r) => {\n let n = \"\";\n return typeof r == \"string\" ? n = r : typeof r == \"object\" && r !== null && (n = Object.entries(r).reduce((s, [o, i]) => i ? f(s, o) : s, \"\")), f(e, n);\n }, \"\");\n}\nfunction p(t) {\n return typeof t == \"object\" && t !== null && !Array.isArray(null);\n}\nfunction m(...t) {\n return t.reduce((e, r) => (p(r) && Object.entries(r).forEach(([n, s]) => {\n const o = a(e[n], s);\n o.length > 0 && (e[n] = o);\n }), e), {});\n}\nfunction y(t) {\n return typeof t == \"object\" && t !== null && !Array.isArray(t);\n}\nfunction h(t, e) {\n const r = t.split(\".\"), n = e.split(\".\"), s = Math.max(r.length, n.length);\n for (let o = 0; o < s; o += 1) {\n const i = parseInt(r[o] || \"0\", 10), u = parseInt(n[o] || \"0\", 10);\n if (i !== u)\n return i > u ? 1 : -1;\n }\n return 0;\n}\nclass c extends Error {\n constructor(e) {\n super(`Async call timeout exceeded. Timeout: ${e}`), Object.setPrototypeOf(this, c.prototype);\n }\n}\nfunction l(t) {\n return new Promise((e, r) => {\n setTimeout(r, t, new c(t));\n });\n}\nfunction d(t, e) {\n return typeof t == \"function\" ? (...r) => Promise.race([\n t(...r),\n l(e)\n ]) : Promise.race([t, l(e)]);\n}\nfunction b(t) {\n return t instanceof c;\n}\nexport {\n c as TimeoutError,\n a as classNames,\n h as compareVersions,\n y as isRecord,\n b as isTimeoutError,\n m as mergeClassNames,\n d as withTimeout\n};\n//# sourceMappingURL=index.mjs.map\n","import { isRecord } from '@tma.js/utils';\n\ntype AnyFunc = (...args: unknown[]) => unknown;\n\ntype WithExternalNotify<T> = T & {\n external: { notify: AnyFunc }\n};\n\ntype WithWebviewProxy<T> = T & {\n TelegramWebviewProxy: {\n postEvent: AnyFunc;\n }\n};\n\n/**\n * Returns true in case, passed value contains path `external.notify` property and `notify` is a\n * function.\n * @param value - value to check.\n */\nexport function hasExternalNotify<T extends {}>(value: T): value is WithExternalNotify<T> {\n return 'external' in value\n && isRecord(value.external)\n && 'notify' in value.external\n && typeof value.external.notify === 'function';\n}\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 extends {}>(value: T): value is WithWebviewProxy<T> {\n return 'TelegramWebviewProxy' in value\n && isRecord(value.TelegramWebviewProxy)\n && 'postEvent' in value.TelegramWebviewProxy\n && typeof value.TelegramWebviewProxy.postEvent === 'function';\n}\n\n/**\n * Returns true in case, current environment is iframe.\n * @see https://stackoverflow.com/a/326076\n */\nexport function isIframe(): boolean {\n try {\n return window.self !== window.top;\n } catch (e) {\n return true;\n }\n}\n","import {\n isIframe,\n hasExternalNotify,\n hasWebviewProxy,\n} from '../env.js';\nimport { targetOrigin as globalTargetOrigin } from '../globals.js';\n\nimport type {\n EmptyMethodName,\n MethodName,\n MethodParams,\n NonEmptyMethodName,\n} from './params.js';\n\ninterface PostEventOptions {\n /**\n * Origin used while posting message. This option is only used in case,\n * current environment is browser (Web version of Telegram) and could\n * be used for test purposes.\n * @default 'https://web.telegram.org'\n */\n targetOrigin?: string;\n}\n\nexport type PostEvent = typeof postEvent;\n\n/**\n * Sends event to native application which launched Web App. This function\n * accepts only events, which require arguments.\n * @param eventType - event name.\n * @param params - event parameters.\n * @param options - posting options.\n * @throws {Error} Bridge could not determine current\n * environment and possible way to send event.\n */\nexport function postEvent<E extends NonEmptyMethodName>(\n eventType: E,\n params: MethodParams<E>,\n options?: PostEventOptions,\n): void;\n\n/**\n * Sends event to native application which launched Web App. This function\n * accepts only events, which require arguments.\n * @param eventType - event name.\n * @param options - posting options.\n * @throws {Error} Bridge could not determine current\n * environment and possible way to send event.\n */\nexport function postEvent(eventType: EmptyMethodName, options?: PostEventOptions): void;\n\nexport function postEvent(\n eventType: MethodName,\n paramsOrOptions?: MethodParams<MethodName> | PostEventOptions,\n options?: PostEventOptions,\n): void {\n let postOptions: PostEventOptions = {};\n let eventData: any;\n\n if (paramsOrOptions === undefined && options === undefined) {\n // Parameters and options were not passed.\n postOptions = {};\n } else if (paramsOrOptions !== undefined && options !== undefined) {\n // Both parameters and options passed.\n postOptions = options;\n eventData = paramsOrOptions;\n } else if (paramsOrOptions !== undefined) {\n // Only parameters were passed.\n if ('targetOrigin' in paramsOrOptions) {\n postOptions = paramsOrOptions;\n } else {\n eventData = paramsOrOptions;\n }\n }\n const { targetOrigin = globalTargetOrigin() } = postOptions;\n\n // Telegram Web.\n if (isIframe()) {\n window.parent.postMessage(JSON.stringify({\n eventType,\n eventData,\n }), targetOrigin);\n return;\n }\n\n // Telegram for Windows Phone or Android.\n if (hasExternalNotify(window)) {\n window.external.notify(JSON.stringify({ eventType, eventData }));\n return;\n }\n\n // Telegram for iOS and macOS.\n if (hasWebviewProxy(window)) {\n window.TelegramWebviewProxy.postEvent(eventType, JSON.stringify(eventData));\n return;\n }\n\n // Otherwise current environment is unknown, and we are not able to send\n // event.\n throw new Error(\n 'Unable to determine current environment and possible way to send event.',\n );\n}\n","import { withTimeout, isRecord } from '@tma.js/utils';\n\nimport type { And, If, IsNever } from '@tma.js/util-types';\n\nimport { postEvent as defaultPostEvent, type PostEvent } from './methods/postEvent.js';\nimport { on, type EventName, type EventParams, type EventHasParams } from './events/index.js';\n\nimport type {\n EmptyMethodName, MethodHasParams,\n MethodName,\n MethodParams,\n NonEmptyMethodName,\n} from './methods/params.js';\n\n/**\n * Names of methods, which require passing \"req_id\" parameter.\n */\ntype MethodNameWithRequestId = {\n [Method in MethodName]: If<\n And<MethodHasParams<Method>, MethodParams<Method> extends { req_id: string } ? true : false>,\n Method,\n never\n >;\n}[MethodName];\n\n/**\n * Names of events, which contain \"req_id\" parameter.\n */\ntype EventNameWithRequestId = {\n [Event in EventName]: If<\n And<EventHasParams<Event>, EventParams<Event> extends { req_id: string } ? true : false>,\n Event,\n never\n >;\n}[EventName];\n\nexport interface RequestOptions {\n /**\n * Bridge postEvent method.\n * @default Global postEvent method.\n */\n postEvent?: PostEvent;\n\n /**\n * Execution timeout.\n */\n timeout?: number;\n}\n\nexport interface RequestOptionsAdvanced<EventPayload> extends RequestOptions {\n /**\n * Should return true in case, this event should be captured. If not specified,\n * request is not skipping captured events.\n */\n capture?: If<IsNever<EventPayload>, () => boolean, (payload: EventPayload) => boolean>;\n}\n\n/**\n * Calls specified TWA method and captures one of the specified events. Returns promise\n * which will be resolved in case, event with specified in method request identifier\n * was captured.\n * @param method - method to execute.\n * @param params - method parameters.\n * @param event - event or events to listen.\n * @param options - additional execution options.\n */\nexport function request<\n Method extends MethodNameWithRequestId,\n Event extends EventNameWithRequestId,\n>(\n method: Method,\n params: MethodParams<Method>,\n event: Event | Event[],\n options?: RequestOptions,\n): Promise<EventParams<Event>>;\n\n/**\n * Calls specified TWA method and captures one of the specified events. Returns promise\n * which will be resolved in case, specified event was captured.\n * @param method - method to execute.\n * @param event - event or events to listen.\n * @param options - additional execution options.\n */\nexport function request<Method extends EmptyMethodName, Event extends EventName>(\n method: Method,\n event: Event | Event[],\n options?: RequestOptionsAdvanced<EventParams<Event>>,\n): Promise<EventParams<Event>>;\n\n/**\n * Calls specified TWA method and captures one of the specified events. Returns promise\n * which will be resolved in case, specified event was captured.\n * @param method - method to execute\n * @param params - method parameters.\n * @param event - event or events to listen\n * @param options - additional execution options.\n */\nexport function request<Method extends NonEmptyMethodName, Event extends EventName>(\n method: Method,\n params: MethodParams<Method>,\n event: Event | Event[],\n options?: RequestOptionsAdvanced<EventParams<Event>>,\n): Promise<EventParams<Event>>;\n\nexport function request(\n method: MethodName,\n eventOrParams: EventName | EventName[] | EventParams<any>,\n eventOrOptions?: EventName | EventName[] | RequestOptions | RequestOptionsAdvanced<any>,\n options?: RequestOptions | RequestOptionsAdvanced<any>,\n): Promise<any> {\n let executionOptions: RequestOptions | RequestOptionsAdvanced<any> | undefined;\n let methodParams: EventParams<any> | undefined;\n let events: EventName[];\n let requestId: string | undefined;\n\n if (typeof eventOrParams === 'string' || Array.isArray(eventOrParams)) {\n // Override: [method, event, options?]\n events = Array.isArray(eventOrParams) ? eventOrParams : [eventOrParams] as EventName[];\n executionOptions = eventOrOptions as (RequestOptionsAdvanced<any> | undefined);\n } else {\n // Override: [method, params, event, options?]\n methodParams = eventOrParams as EventParams<any>;\n events = Array.isArray(eventOrOptions) ? eventOrOptions : [eventOrOptions] as EventName[];\n executionOptions = options;\n }\n\n // In case, method parameters were passed, and they contained request identifier, we should store\n // it and wait for the event with this identifier to occur.\n if (isRecord(methodParams) && typeof methodParams.req_id === 'string') {\n requestId = methodParams.req_id;\n }\n\n const { postEvent = defaultPostEvent, timeout } = executionOptions || {};\n const capture = executionOptions && 'capture' in executionOptions\n ? executionOptions.capture\n : null;\n\n const promise = new Promise((res, rej) => {\n // Iterate over each event and create event listener.\n const stoppers = events.map((ev) => on(ev, (data?) => {\n // If request identifier was specified, we are waiting for event with the same value\n // to occur.\n if (typeof requestId === 'string' && (!isRecord(data) || data.req_id !== requestId)) {\n return;\n }\n\n if (typeof capture === 'function' && !capture(data)) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n stopListening();\n res(data);\n }));\n\n // Function which removes all event listeners.\n const stopListening = () => stoppers.forEach((stop) => stop());\n\n try {\n // We are wrapping this call in try catch, because it can throw errors in case,\n // compatibility check was enabled. We want an error to be captured by promise, not by\n // another one external try catch.\n postEvent(method as any, methodParams);\n } catch (e) {\n stopListening();\n rej(e);\n }\n });\n\n return typeof timeout === 'number' ? withTimeout(promise, timeout) : promise;\n}\n","import { compareVersions, type Version } from '@tma.js/utils';\n\nimport type {\n HasCheckSupportMethodParam,\n HasCheckSupportMethodName,\n MethodName,\n MethodParams,\n NonEmptyMethodName,\n} from './methods/index.js';\n\nfunction lessOrEqual(a: Version, b: Version): boolean {\n return compareVersions(a, b) <= 0;\n}\n\n/**\n * By specified method and parameters extracts properties which could be used by\n * supports function as TWA method parameter.\n * @param method - TWA method.\n * @param params - method parameters.\n */\nexport function detectSupportParams<M extends NonEmptyMethodName>(\n method: M,\n params: MethodParams<M>,\n): HasCheckSupportMethodParam<HasCheckSupportMethodName>[] {\n if (method === 'web_app_open_link') {\n if ('try_instant_view' in params) {\n return ['try_instant_view'];\n }\n }\n\n if (method === 'web_app_set_header_color') {\n if ('color' in params) {\n return ['color'];\n }\n }\n\n return [];\n}\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 HasCheckSupportMethodName>(\n method: M,\n param: HasCheckSupportMethodParam<M>,\n inVersion: Version,\n): boolean;\n/**\n * Returns true in case, specified method is supported in passed version.\n * @param method - method name.\n * @param inVersion - platform version.\n */\nexport function supports(method: MethodName, inVersion: Version): boolean;\nexport function supports(\n method: MethodName,\n paramOrVersion: Version | string,\n inVersion?: string,\n): boolean {\n // Method name, parameter, target version.\n if (typeof inVersion === 'string') {\n if (method === 'web_app_open_link') {\n if (paramOrVersion === 'try_instant_view') {\n return lessOrEqual('6.4', inVersion);\n }\n }\n\n if (method === 'web_app_set_header_color') {\n if (paramOrVersion === 'color') {\n return lessOrEqual('6.9', inVersion);\n }\n }\n }\n\n // Method name, target version.\n switch (method) {\n case 'web_app_open_tg_link':\n case 'web_app_open_invoice':\n case 'web_app_setup_back_button':\n case 'web_app_set_background_color':\n case 'web_app_set_header_color':\n case 'web_app_trigger_haptic_feedback':\n return lessOrEqual('6.1', paramOrVersion);\n case 'web_app_open_popup':\n return lessOrEqual('6.2', paramOrVersion);\n case 'web_app_close_scan_qr_popup':\n case 'web_app_open_scan_qr_popup':\n case 'web_app_read_text_from_clipboard':\n return lessOrEqual('6.4', paramOrVersion);\n case 'web_app_invoke_custom_method':\n case 'web_app_request_write_access':\n case 'web_app_request_phone':\n return lessOrEqual('6.9', paramOrVersion);\n case 'web_app_setup_settings_button':\n return lessOrEqual('6.10', paramOrVersion);\n default:\n return true;\n }\n}\n"],"names":["b","c","r","s","e","n","f$1","t","u","h","a","i","o","f","y","p","w","m","G","V","U","P","S","B","A","currentTargetOrigin","logger","Logger","setDebug","value","setTargetOrigin","targetOrigin","isNullOrUndefined","rgbOptional","rgb","num","number","windowWidthParser","createValueParserGen","themeChangedPayload","json","viewportChangedPayload","boolean","popupClosedPayload","string","qrTextReceivedPayload","invoiceClosedPayload","clipboardTextReceivedPayload","writeAccessRequestedPayload","phoneRequestedPayload","customMethodInvokedPayload","eventDataJson","emitEvent","eventType","eventData","defineEventHandlers","wnd","path","pointer","item","idx","arr","onTelegramEvent","cb","event","CACHED_EMITTER","createEmitter","emitter","UtilEventEmitter","emit","data","cause","singletonEmitter","off","listener","on","once","unsubscribe","subscribe","l","d","hasExternalNotify","isRecord","hasWebviewProxy","isIframe","postEvent","paramsOrOptions","options","postOptions","globalTargetOrigin","request","method","eventOrParams","eventOrOptions","executionOptions","methodParams","events","requestId","defaultPostEvent","timeout","capture","promise","res","rej","stoppers","ev","stopListening","stop","withTimeout","lessOrEqual","compareVersions","detectSupportParams","params","supports","paramOrVersion","inVersion"],"mappings":"qEAAA,IAAIA,EAAI,OAAO,eACXC,EAAI,CAACC,EAAGC,EAAGC,IAAMD,KAAKD,EAAIF,EAAEE,EAAGC,EAAG,CAAE,WAAY,GAAI,aAAc,GAAI,SAAU,GAAI,MAAOC,CAAC,CAAE,EAAIF,EAAEC,CAAC,EAAIC,EACzGC,EAAI,CAACH,EAAGC,EAAGC,KAAOH,EAAEC,EAAG,OAAOC,GAAK,SAAWA,EAAI,GAAKA,EAAGC,CAAC,EAAGA,GAClE,IAAAE,EAAA,KAAQ,CACN,aAAc,CACZD,EAAE,KAAM,YAA6B,IAAI,GAAK,EAC9CA,EAAE,KAAM,qBAAsB,CAAA,CAAE,CACjC,CAOD,YAAYF,EAAGC,EAAGG,EAAG,CACnB,IAAI,EAAI,KAAK,UAAU,IAAIJ,CAAC,EAC5B,OAAO,IAAM,EAAI,GAAI,KAAK,UAAU,IAAIA,EAAG,CAAC,GAAI,EAAE,KAAK,CAACC,EAAGG,CAAC,CAAC,EAAG,IAAM,KAAK,IAAIJ,EAAGC,CAAC,CACpF,CACD,KAAKD,KAAMC,EAAG,CACZ,KAAK,mBAAmB,QAAS,GAAM,EAAED,EAAG,GAAGC,CAAC,CAAC,EACjD,MAAMG,EAAI,KAAK,UAAU,I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AAsBqB,EACjB,CAAC,kBAAkB,EAI1BrB,IAAW,4BACT,UAAWqB,EACN,CAAC,OAAO,EAIZ,EACT,CAmBgB,SAAAC,GACdtB,EACAuB,EACAC,EACS,CAEL,GAAA,OAAOA,GAAc,SAAU,CACjC,GAAIxB,IAAW,qBACTuB,IAAmB,mBACd,OAAAL,EAAY,MAAOM,CAAS,EAIvC,GAAIxB,IAAW,4BACTuB,IAAmB,QACd,OAAAL,EAAY,MAAOM,CAAS,CAGzC,CAGA,OAAQxB,EAAQ,CACd,IAAK,uBACL,IAAK,uBACL,IAAK,4BACL,IAAK,+BACL,IAAK,2BACL,IAAK,kCACI,OAAAkB,EAAY,MAAOK,CAAc,EAC1C,IAAK,qBACI,OAAAL,EAAY,MAAOK,CAAc,EAC1C,IAAK,8BACL,IAAK,6BACL,IAAK,mCACI,OAAAL,EAAY,MAAOK,CAAc,EAC1C,IAAK,+BACL,IAAK,+BACL,IAAK,wBACI,OAAAL,EAAY,MAAOK,CAAc,EAC1C,IAAK,gCACI,OAAAL,EAAY,OAAQK,CAAc,EAC3C,QACS,MAAA,EACX,CACF"}
package/dist/index.mjs CHANGED
@@ -1,24 +1,26 @@
1
- import { isRecord as l, withTimeout as N, compareVersions as T } from "@tma.js/utils";
2
- import { log as J } from "@tma.js/logger";
3
- import { EventEmitter as S } from "@tma.js/event-emitter";
4
- import { rgb as G, number as q, createValueParserGen as I, json as s, boolean as x, string as i } from "@tma.js/parsing";
5
- let v = !1, P = "https://web.telegram.org";
1
+ import { isRecord as f, withTimeout as C, compareVersions as N } from "@tma.js/utils";
2
+ import { Logger as T } from "@tma.js/logger";
3
+ import { EventEmitter as J } from "@tma.js/event-emitter";
4
+ import { rgb as S, number as q, createValueParserGen as G, json as s, boolean as x, string as i } from "@tma.js/parsing";
5
+ let v = "https://web.telegram.org";
6
+ const d = new T("[Bridge]", !1);
7
+ function ue(e) {
8
+ if (e) {
9
+ d.enable();
10
+ return;
11
+ }
12
+ d.disable();
13
+ }
6
14
  function de(e) {
7
15
  v = e;
8
16
  }
9
- function pe(e) {
10
- P = e;
17
+ function I() {
18
+ return v;
11
19
  }
12
- function M() {
13
- return P;
14
- }
15
- const g = (e, ...t) => {
16
- v && J(e, "[Bridge]", ...t);
17
- };
18
- function H(e) {
20
+ function L(e) {
19
21
  return e == null;
20
22
  }
21
- const a = G().optional(), L = q(), $ = I((e) => e == null ? window.innerWidth : L.parse(e)), U = s({
23
+ const a = S().optional(), M = q(), H = G((e) => e == null ? window.innerWidth : M.parse(e)), U = s({
22
24
  theme_params: s({
23
25
  bg_color: a,
24
26
  text_color: a,
@@ -28,35 +30,35 @@ const a = G().optional(), L = q(), $ = I((e) => e == null ? window.innerWidth :
28
30
  button_text_color: a,
29
31
  secondary_bg_color: a
30
32
  })
31
- }), j = s({
33
+ }), $ = s({
32
34
  height: q(),
33
- width: $(),
35
+ width: H(),
34
36
  is_state_stable: x(),
35
37
  is_expanded: x()
38
+ }), j = s({
39
+ button_id: i({ isEmpty: L }).optional()
36
40
  }), z = s({
37
- button_id: i({ isEmpty: H }).optional()
38
- }), B = s({
39
41
  data: i().optional()
40
- }), F = s({
42
+ }), B = s({
41
43
  slug: i(),
42
44
  status: i()
43
- }), K = s({
45
+ }), F = s({
44
46
  req_id: i(),
45
47
  data: (e) => e === null ? e : i().optional().parse(e)
46
- }), Q = s({ status: i() }), X = s({ status: i() }), Y = s({
48
+ }), K = s({ status: i() }), Q = s({ status: i() }), X = s({
47
49
  req_id: i(),
48
50
  result: (e) => e,
49
51
  error: i().optional()
50
- }), Z = s({
52
+ }), Y = s({
51
53
  eventType: i(),
52
54
  eventData: (e) => e
53
55
  });
54
- function V(e, t) {
56
+ function Z(e, t) {
55
57
  window.dispatchEvent(new MessageEvent("message", {
56
58
  data: JSON.stringify({ eventType: e, eventData: t })
57
59
  }));
58
60
  }
59
- function D() {
61
+ function V() {
60
62
  const e = window;
61
63
  "TelegramGameProxy_receiveEvent" in e || [
62
64
  ["TelegramGameProxy_receiveEvent"],
@@ -69,26 +71,26 @@ function D() {
69
71
  let r = e;
70
72
  t.forEach((n, o, c) => {
71
73
  if (o === c.length - 1) {
72
- r[n] = V;
74
+ r[n] = Z;
73
75
  return;
74
76
  }
75
77
  n in r || (r[n] = {}), r = r[n];
76
78
  });
77
79
  });
78
80
  }
79
- function O(e) {
80
- D(), window.addEventListener("message", (t) => {
81
+ function D(e) {
82
+ V(), window.addEventListener("message", (t) => {
81
83
  try {
82
- const { eventType: r, eventData: n } = Z.parse(t.data);
84
+ const { eventType: r, eventData: n } = Y.parse(t.data);
83
85
  e(r, n);
84
86
  } catch {
85
87
  }
86
88
  });
87
89
  }
88
90
  const b = "__telegram-cached-emitter__";
89
- function ee() {
90
- const e = new S(), t = (r, ...n) => {
91
- g("log", "Emitting processed event:", r, ...n), e.emit(r, ...n);
91
+ function O() {
92
+ const e = new J(), t = (r, ...n) => {
93
+ d.log("Emitting processed event:", r, ...n), e.emit(r, ...n);
92
94
  };
93
95
  return window.addEventListener("resize", () => {
94
96
  t("viewport_changed", {
@@ -97,33 +99,33 @@ function ee() {
97
99
  is_state_stable: !0,
98
100
  is_expanded: !0
99
101
  });
100
- }), O((r, n) => {
101
- g("log", "Received raw event:", r, n);
102
+ }), D((r, n) => {
103
+ d.log("Received raw event:", r, n);
102
104
  try {
103
105
  switch (r) {
104
106
  case "viewport_changed":
105
- return t(r, j.parse(n));
107
+ return t(r, $.parse(n));
106
108
  case "theme_changed":
107
109
  return t(r, U.parse(n));
108
110
  case "popup_closed":
109
111
  return (
110
112
  // Sent on desktop.
111
- n == null ? t(r, {}) : t(r, z.parse(n))
113
+ n == null ? t(r, {}) : t(r, j.parse(n))
112
114
  );
113
115
  case "set_custom_style":
114
116
  return t(r, i().parse(n));
115
117
  case "qr_text_received":
116
- return t(r, B.parse(n));
118
+ return t(r, z.parse(n));
117
119
  case "clipboard_text_received":
118
- return t(r, K.parse(n));
119
- case "invoice_closed":
120
120
  return t(r, F.parse(n));
121
+ case "invoice_closed":
122
+ return t(r, B.parse(n));
121
123
  case "phone_requested":
122
- return t("phone_requested", X.parse(n));
124
+ return t("phone_requested", Q.parse(n));
123
125
  case "custom_method_invoked":
124
- return t("custom_method_invoked", Y.parse(n));
126
+ return t("custom_method_invoked", X.parse(n));
125
127
  case "write_access_requested":
126
- return t("write_access_requested", Q.parse(n));
128
+ return t("write_access_requested", K.parse(n));
127
129
  case "main_button_pressed":
128
130
  case "back_button_pressed":
129
131
  case "settings_button_pressed":
@@ -133,58 +135,58 @@ function ee() {
133
135
  return t(r, n);
134
136
  }
135
137
  } catch (o) {
136
- g("error", "Error processing event:", o);
138
+ d.error("Error processing event:", o);
137
139
  }
138
140
  }), e;
139
141
  }
140
- function d() {
142
+ function p() {
141
143
  const e = window;
142
- return e[b] === void 0 && (e[b] = ee()), e[b];
144
+ return e[b] === void 0 && (e[b] = O()), e[b];
143
145
  }
144
- function k(e, t) {
145
- d().off(e, t);
146
+ function P(e, t) {
147
+ p().off(e, t);
146
148
  }
147
- function te(e, t) {
148
- return d().on(e, t), () => k(e, t);
149
+ function ee(e, t) {
150
+ return p().on(e, t), () => P(e, t);
149
151
  }
150
- function le(e, t) {
151
- return d().once(e, t), () => k(e, t);
152
+ function pe(e, t) {
153
+ return p().once(e, t), () => P(e, t);
152
154
  }
153
- function re(e) {
154
- d().unsubscribe(e);
155
+ function te(e) {
156
+ p().unsubscribe(e);
155
157
  }
156
- function fe(e) {
157
- return d().subscribe(e), () => re(e);
158
+ function le(e) {
159
+ return p().subscribe(e), () => te(e);
158
160
  }
159
- function ne(e) {
160
- return "external" in e && l(e.external) && "notify" in e.external && typeof e.external.notify == "function";
161
+ function re(e) {
162
+ return "external" in e && f(e.external) && "notify" in e.external && typeof e.external.notify == "function";
161
163
  }
162
- function oe(e) {
163
- return "TelegramWebviewProxy" in e && l(e.TelegramWebviewProxy) && "postEvent" in e.TelegramWebviewProxy && typeof e.TelegramWebviewProxy.postEvent == "function";
164
+ function ne(e) {
165
+ return "TelegramWebviewProxy" in e && f(e.TelegramWebviewProxy) && "postEvent" in e.TelegramWebviewProxy && typeof e.TelegramWebviewProxy.postEvent == "function";
164
166
  }
165
- function ie() {
167
+ function oe() {
166
168
  try {
167
169
  return window.self !== window.top;
168
170
  } catch {
169
171
  return !0;
170
172
  }
171
173
  }
172
- function se(e, t, r) {
174
+ function ie(e, t, r) {
173
175
  let n = {}, o;
174
176
  t === void 0 && r === void 0 ? n = {} : t !== void 0 && r !== void 0 ? (n = r, o = t) : t !== void 0 && ("targetOrigin" in t ? n = t : o = t);
175
- const { targetOrigin: c = M() } = n;
176
- if (ie()) {
177
+ const { targetOrigin: c = I() } = n;
178
+ if (oe()) {
177
179
  window.parent.postMessage(JSON.stringify({
178
180
  eventType: e,
179
181
  eventData: o
180
182
  }), c);
181
183
  return;
182
184
  }
183
- if (ne(window)) {
185
+ if (re(window)) {
184
186
  window.external.notify(JSON.stringify({ eventType: e, eventData: o }));
185
187
  return;
186
188
  }
187
- if (oe(window)) {
189
+ if (ne(window)) {
188
190
  window.TelegramWebviewProxy.postEvent(e, JSON.stringify(o));
189
191
  return;
190
192
  }
@@ -192,28 +194,28 @@ function se(e, t, r) {
192
194
  "Unable to determine current environment and possible way to send event."
193
195
  );
194
196
  }
195
- function we(e, t, r, n) {
196
- let o, c, f, w;
197
- typeof t == "string" || Array.isArray(t) ? (f = Array.isArray(t) ? t : [t], o = r) : (c = t, f = Array.isArray(r) ? r : [r], o = n), l(c) && typeof c.req_id == "string" && (w = c.req_id);
198
- const { postEvent: W = se, timeout: h } = o || {}, m = o && "capture" in o ? o.capture : null, y = new Promise((A, R) => {
199
- const C = f.map((u) => te(u, (p) => {
200
- typeof w == "string" && (!l(p) || p.req_id !== w) || typeof m == "function" && !m(p) || (E(), A(p));
201
- })), E = () => C.forEach((u) => u());
197
+ function fe(e, t, r, n) {
198
+ let o, c, w, g;
199
+ typeof t == "string" || Array.isArray(t) ? (w = Array.isArray(t) ? t : [t], o = r) : (c = t, w = Array.isArray(r) ? r : [r], o = n), f(c) && typeof c.req_id == "string" && (g = c.req_id);
200
+ const { postEvent: k = ie, timeout: h } = o || {}, m = o && "capture" in o ? o.capture : null, y = new Promise((W, A) => {
201
+ const R = w.map((u) => ee(u, (l) => {
202
+ typeof g == "string" && (!f(l) || l.req_id !== g) || typeof m == "function" && !m(l) || (E(), W(l));
203
+ })), E = () => R.forEach((u) => u());
202
204
  try {
203
- W(e, c);
205
+ k(e, c);
204
206
  } catch (u) {
205
- E(), R(u);
207
+ E(), A(u);
206
208
  }
207
209
  });
208
- return typeof h == "number" ? N(y, h) : y;
210
+ return typeof h == "number" ? C(y, h) : y;
209
211
  }
210
212
  function _(e, t) {
211
- return T(e, t) <= 0;
213
+ return N(e, t) <= 0;
212
214
  }
213
- function ge(e, t) {
215
+ function we(e, t) {
214
216
  return e === "web_app_open_link" && "try_instant_view" in t ? ["try_instant_view"] : e === "web_app_set_header_color" && "color" in t ? ["color"] : [];
215
217
  }
216
- function be(e, t, r) {
218
+ function ge(e, t, r) {
217
219
  if (typeof r == "string") {
218
220
  if (e === "web_app_open_link" && t === "try_instant_view")
219
221
  return _("6.4", r);
@@ -245,19 +247,19 @@ function be(e, t, r) {
245
247
  }
246
248
  }
247
249
  export {
248
- ge as detectSupportParams,
249
- ne as hasExternalNotify,
250
- oe as hasWebviewProxy,
251
- ie as isIframe,
252
- k as off,
253
- te as on,
254
- le as once,
255
- se as postEvent,
256
- we as request,
257
- de as setDebug,
258
- pe as setTargetOrigin,
259
- fe as subscribe,
260
- be as supports,
261
- re as unsubscribe
250
+ we as detectSupportParams,
251
+ re as hasExternalNotify,
252
+ ne as hasWebviewProxy,
253
+ oe as isIframe,
254
+ P as off,
255
+ ee as on,
256
+ pe as once,
257
+ ie as postEvent,
258
+ fe as request,
259
+ ue as setDebug,
260
+ de as setTargetOrigin,
261
+ le as subscribe,
262
+ ge as supports,
263
+ te as unsubscribe
262
264
  };
263
265
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":["../src/globals.ts","../src/events/parsing.ts","../src/events/onTelegramEvent.ts","../src/events/emitter.ts","../src/events/off.ts","../src/events/on.ts","../src/events/once.ts","../src/events/unsubscribe.ts","../src/events/subscribe.ts","../src/env.ts","../src/methods/postEvent.ts","../src/request.ts","../src/supports.ts"],"sourcesContent":["import { log as utilLog } from '@tma.js/logger';\n\nlet currentDebug = false;\nlet currentTargetOrigin = 'https://web.telegram.org';\n\n/**\n * Sets new debug mode. Enabling debug mode leads to printing\n * additional messages in console, related to the processes\n * inside the package.\n * @param value - should debug mode be enabled.\n */\nexport function setDebug(value: boolean): void {\n currentDebug = value;\n}\n\n/**\n * Sets new global targetOrigin, used by `postEvent` method.\n * Default value is \"https://web.telegram.org\". You don't need to\n * use this method until you know what you are doing.\n *\n * This method could be used for test purposes.\n * @param value - new target origin.\n */\nexport function setTargetOrigin(value: string): void {\n currentTargetOrigin = value;\n}\n\n/**\n * Returns current global target origin.\n */\nexport function targetOrigin(): string {\n return currentTargetOrigin;\n}\n\n/**\n * Logs message in case, debug mode is enabled.\n * @param level - log level\n * @param args - values to print.\n */\nexport const log: typeof utilLog = (level, ...args) => {\n if (currentDebug) {\n utilLog(level, '[Bridge]', ...args);\n }\n};\n","import {\n number,\n string,\n boolean,\n json,\n rgb,\n createValueParserGen,\n} from '@tma.js/parsing';\n\nimport type {\n ClipboardTextReceivedPayload, CustomMethodInvokedPayload,\n InvoiceClosedPayload, PhoneRequestedPayload,\n PopupClosedPayload, QrTextReceivedPayload,\n ThemeChangedPayload,\n ViewportChangedPayload, WriteAccessRequestedPayload,\n} from './payloads.js';\n\nfunction isNullOrUndefined(value: unknown): boolean {\n return value === null || value === undefined;\n}\n\nconst rgbOptional = rgb().optional();\nconst num = number();\n\nconst windowWidthParser = createValueParserGen((value) => (value === null || value === undefined\n ? window.innerWidth\n : num.parse(value)));\n\n/**\n * Parses incoming value as ThemeChangedPayload.\n */\nexport const themeChangedPayload = json<ThemeChangedPayload>({\n theme_params: json({\n bg_color: rgbOptional,\n text_color: rgbOptional,\n hint_color: rgbOptional,\n link_color: rgbOptional,\n button_color: rgbOptional,\n button_text_color: rgbOptional,\n secondary_bg_color: rgbOptional,\n }),\n});\n\n/**\n * Parses incoming value as ViewportChangedPayload.\n * @param value - value to parse.\n */\nexport const viewportChangedPayload = json<ViewportChangedPayload>({\n height: number(),\n width: windowWidthParser(),\n is_state_stable: boolean(),\n is_expanded: boolean(),\n});\n\n/**\n * Parses incoming value as PopupClosedPayload.\n */\nexport const popupClosedPayload = json<PopupClosedPayload>({\n button_id: string({ isEmpty: isNullOrUndefined }).optional(),\n});\n\n/**\n * Parses incoming value as QrTextReceivedPayload.\n */\nexport const qrTextReceivedPayload = json<QrTextReceivedPayload>({\n data: string().optional(),\n});\n\n/**\n * Parses incoming value as InvoiceClosedPayload.\n */\nexport const invoiceClosedPayload = json<InvoiceClosedPayload>({\n slug: string(),\n status: string(),\n});\n\n/**\n * Parses incoming value as clipboard text received payload.\n */\nexport const clipboardTextReceivedPayload = json<ClipboardTextReceivedPayload>({\n req_id: string(),\n data: (value) => (value === null ? value : string().optional().parse(value)),\n});\n\n/**\n * Parses incoming value as WriteAccessRequestedPayload.\n */\nexport const writeAccessRequestedPayload = json<WriteAccessRequestedPayload>({ status: string() });\n\n/**\n * Parses incoming value as PhoneRequestedPayload.\n */\nexport const phoneRequestedPayload = json<PhoneRequestedPayload>({ status: string() });\n\n/**\n * Parses incoming value as CustomMethodInvokedPayload.\n */\nexport const customMethodInvokedPayload = json<CustomMethodInvokedPayload>({\n req_id: string(),\n result: (value) => value,\n error: string().optional(),\n});\n","import { json, string } from '@tma.js/parsing';\n\n/**\n * Extracts event data from native application event.\n */\nconst eventDataJson = json<{ eventType: string; eventData?: unknown }>({\n eventType: string(),\n eventData: (value) => value,\n});\n\n/**\n * Emits event sent from Telegram native application like it was sent in\n * default web environment between 2 iframes. It dispatches new MessageEvent\n * and expects it to be handled via `window.addEventListener('message', ...)`\n * as developer would do it to handle messages sent from parent iframe.\n * @param eventType - event name.\n * @param eventData - event payload.\n */\nfunction emitEvent(eventType: string, eventData: unknown): void {\n window.dispatchEvent(new MessageEvent('message', {\n data: JSON.stringify({ eventType, eventData }),\n }));\n}\n\n/**\n * Defines special handlers by known paths, which are recognized by\n * Telegram as ports to receive events. This function also sets special\n * function in global window object to prevent duplicate declaration.\n */\nfunction defineEventHandlers(): void {\n const wnd: any = window;\n\n // Prevent from duplicate event handlers definition.\n if ('TelegramGameProxy_receiveEvent' in wnd) {\n return;\n }\n\n // Iterate over each path, where \"receiveEvent\" function should be\n // defined. This function is called by external environment in case,\n // it wants to emit some event.\n [\n ['TelegramGameProxy_receiveEvent'], // Windows Phone.\n ['TelegramGameProxy', 'receiveEvent'], // Desktop.\n ['Telegram', 'WebView', 'receiveEvent'], // Android and iOS.\n ].forEach((path) => {\n // Path starts from \"window\" object.\n let pointer = wnd;\n\n path.forEach((item, idx, arr) => {\n // We are on the last iteration, where function property name is passed.\n if (idx === arr.length - 1) {\n pointer[item] = emitEvent;\n return;\n }\n\n if (!(item in pointer)) {\n pointer[item] = {};\n }\n pointer = pointer[item];\n });\n });\n}\n\n/**\n * Adds listener to window \"message\" event assuming, that this event could\n * be sent by Telegram native application. Calls passed callback with event\n * type and data.\n * @param cb - callback to call.\n */\nexport function onTelegramEvent(cb: (eventType: string, eventData: unknown) => void): void {\n // Define event handlers to make sure, message handler will work correctly.\n defineEventHandlers();\n\n // We expect Telegram to send us new event through \"message\" event.\n window.addEventListener('message', (event) => {\n try {\n const { eventType, eventData } = eventDataJson.parse(event.data);\n cb(eventType, eventData);\n } catch {\n // We ignore incorrect messages as they could be generated by any other code.\n }\n });\n}\n","import { EventEmitter as UtilEventEmitter } from '@tma.js/event-emitter';\nimport { string } from '@tma.js/parsing';\n\nimport { log } from '../globals.js';\nimport {\n clipboardTextReceivedPayload,\n customMethodInvokedPayload,\n invoiceClosedPayload,\n phoneRequestedPayload,\n popupClosedPayload,\n qrTextReceivedPayload,\n themeChangedPayload,\n viewportChangedPayload,\n writeAccessRequestedPayload,\n} from './parsing.js';\nimport { onTelegramEvent } from './onTelegramEvent.js';\n\nimport type { EventEmitter, EventName } from './events.js';\n\nconst CACHED_EMITTER = '__telegram-cached-emitter__';\n\n/**\n * Returns event emitter which could be safely used, to process events from\n * Telegram native application.\n */\nexport function createEmitter(): EventEmitter {\n const emitter: EventEmitter = new UtilEventEmitter();\n const emit: EventEmitter['emit'] = (event: any, ...data: any[]) => {\n log('log', 'Emitting processed event:', event, ...data);\n emitter.emit(event, ...data);\n };\n\n // Desktop version of Telegram is sometimes not sending the viewport_changed\n // event. For example, when main button is shown. That's why we should\n // add our own listener to make sure, viewport information is always fresh.\n // Issue: https://github.com/Telegram-Mini-Apps/tma.js/issues/10\n window.addEventListener('resize', () => {\n emit('viewport_changed', {\n width: window.innerWidth,\n height: window.innerHeight,\n is_state_stable: true,\n is_expanded: true,\n });\n });\n\n // In case, any Telegram event was received, we should prepare data before\n // passing it to emitter.\n onTelegramEvent((eventType: EventName | string, eventData): void => {\n log('log', 'Received raw event:', eventType, eventData);\n\n try {\n switch (eventType) {\n case 'viewport_changed':\n return emit(eventType, viewportChangedPayload.parse(eventData));\n\n case 'theme_changed':\n return emit(eventType, themeChangedPayload.parse(eventData));\n\n case 'popup_closed':\n // FIXME: Payloads are different on different platforms.\n // Issue: https://github.com/Telegram-Mini-Apps/tma.js/issues/2\n if (\n // Sent on desktop.\n eventData === undefined\n // Sent on iOS.\n || eventData === null\n ) {\n return emit(eventType, {});\n }\n return emit(eventType, popupClosedPayload.parse(eventData));\n\n case 'set_custom_style':\n return emit(eventType, string().parse(eventData));\n\n case 'qr_text_received':\n return emit(eventType, qrTextReceivedPayload.parse(eventData));\n\n case 'clipboard_text_received':\n return emit(eventType, clipboardTextReceivedPayload.parse(eventData));\n\n case 'invoice_closed':\n return emit(eventType, invoiceClosedPayload.parse(eventData));\n\n case 'phone_requested':\n return emit('phone_requested', phoneRequestedPayload.parse(eventData));\n\n case 'custom_method_invoked':\n return emit('custom_method_invoked', customMethodInvokedPayload.parse(eventData));\n\n case 'write_access_requested':\n return emit('write_access_requested', writeAccessRequestedPayload.parse(eventData));\n\n // Events which have no parameters.\n case 'main_button_pressed':\n case 'back_button_pressed':\n case 'settings_button_pressed':\n case 'scan_qr_popup_closed':\n return emit(eventType);\n\n // All other event listeners will receive unknown type of data.\n default:\n return emit(eventType as any, eventData);\n }\n } catch (cause) {\n log('error', 'Error processing event:', cause);\n }\n });\n\n return emitter;\n}\n\n/**\n * Returns singleton instance of bridge EventEmitter. Also, defines\n * Telegram event handlers.\n */\nexport function singletonEmitter(): EventEmitter {\n const wnd: any = window;\n const cachedEmitter = wnd[CACHED_EMITTER];\n\n if (cachedEmitter === undefined) {\n wnd[CACHED_EMITTER] = createEmitter();\n }\n\n return wnd[CACHED_EMITTER];\n}\n","import { singletonEmitter } from './emitter.js';\n\nimport type { EventName, EventListener } from './events.js';\n\n/**\n * Removes listener from specified event.\n * @param event - event to listen.\n * @param listener - event listener.\n */\nexport function off<E extends EventName>(event: E, listener: EventListener<E>): void {\n singletonEmitter().off(event, listener);\n}\n","import { singletonEmitter } from './emitter.js';\nimport { off } from './off.js';\n\nimport type { EventName, EventListener } from './events.js';\n\ntype StopListening = () => void;\n\n/**\n * Adds new listener to the specified event. Returns handler\n * which allows to stop listening to event.\n * @param event - event name.\n * @param listener - event listener.\n */\nexport function on<E extends EventName>(event: E, listener: EventListener<E>): StopListening {\n singletonEmitter().on(event, listener);\n return () => off(event, listener);\n}\n","import { singletonEmitter } from './emitter.js';\nimport { off } from './off.js';\n\nimport type { EventName, EventListener } from './events.js';\n\ntype StopListening = () => void;\n\n/**\n * Works the same as \"on\" method, but after catching the event, will remove event listener.\n * @param event - event name.\n * @param listener - event listener.\n */\nexport function once<E extends EventName>(event: E, listener: EventListener<E>): StopListening {\n singletonEmitter().once(event, listener);\n return () => off(event, listener);\n}\n","import { singletonEmitter } from './emitter.js';\n\nimport type { GlobalEventListener } from './events.js';\n\n/**\n * Removes global event listener.\n * @param listener - event listener.\n */\nexport function unsubscribe(listener: GlobalEventListener): void {\n singletonEmitter().unsubscribe(listener);\n}\n","import { singletonEmitter } from './emitter.js';\nimport { unsubscribe } from './unsubscribe.js';\n\nimport type { GlobalEventListener } from './events.js';\n\ntype StopListening = () => void;\n\n/**\n * Subscribes to all events sent from the native Telegram application.\n * Returns function used to remove added event listener.\n * @param listener - event listener.\n */\nexport function subscribe(listener: GlobalEventListener): StopListening {\n singletonEmitter().subscribe(listener);\n return () => unsubscribe(listener);\n}\n","import { isRecord } from '@tma.js/utils';\n\ntype AnyFunc = (...args: unknown[]) => unknown;\n\ntype WithExternalNotify<T> = T & {\n external: { notify: AnyFunc }\n};\n\ntype WithWebviewProxy<T> = T & {\n TelegramWebviewProxy: {\n postEvent: AnyFunc;\n }\n};\n\n/**\n * Returns true in case, passed value contains path `external.notify` property and `notify` is a\n * function.\n * @param value - value to check.\n */\nexport function hasExternalNotify<T extends {}>(value: T): value is WithExternalNotify<T> {\n return 'external' in value\n && isRecord(value.external)\n && 'notify' in value.external\n && typeof value.external.notify === 'function';\n}\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 extends {}>(value: T): value is WithWebviewProxy<T> {\n return 'TelegramWebviewProxy' in value\n && isRecord(value.TelegramWebviewProxy)\n && 'postEvent' in value.TelegramWebviewProxy\n && typeof value.TelegramWebviewProxy.postEvent === 'function';\n}\n\n/**\n * Returns true in case, current environment is iframe.\n * @see https://stackoverflow.com/a/326076\n */\nexport function isIframe(): boolean {\n try {\n return window.self !== window.top;\n } catch (e) {\n return true;\n }\n}\n","import {\n isIframe,\n hasExternalNotify,\n hasWebviewProxy,\n} from '../env.js';\nimport { targetOrigin as globalTargetOrigin } from '../globals.js';\n\nimport type {\n EmptyMethodName,\n MethodName,\n MethodParams,\n NonEmptyMethodName,\n} from './params.js';\n\ninterface PostEventOptions {\n /**\n * Origin used while posting message. This option is only used in case,\n * current environment is browser (Web version of Telegram) and could\n * be used for test purposes.\n * @default 'https://web.telegram.org'\n */\n targetOrigin?: string;\n}\n\nexport type PostEvent = typeof postEvent;\n\n/**\n * Sends event to native application which launched Web App. This function\n * accepts only events, which require arguments.\n * @param eventType - event name.\n * @param params - event parameters.\n * @param options - posting options.\n * @throws {Error} Bridge could not determine current\n * environment and possible way to send event.\n */\nexport function postEvent<E extends NonEmptyMethodName>(\n eventType: E,\n params: MethodParams<E>,\n options?: PostEventOptions,\n): void;\n\n/**\n * Sends event to native application which launched Web App. This function\n * accepts only events, which require arguments.\n * @param eventType - event name.\n * @param options - posting options.\n * @throws {Error} Bridge could not determine current\n * environment and possible way to send event.\n */\nexport function postEvent(eventType: EmptyMethodName, options?: PostEventOptions): void;\n\nexport function postEvent(\n eventType: MethodName,\n paramsOrOptions?: MethodParams<MethodName> | PostEventOptions,\n options?: PostEventOptions,\n): void {\n let postOptions: PostEventOptions = {};\n let eventData: any;\n\n if (paramsOrOptions === undefined && options === undefined) {\n // Parameters and options were not passed.\n postOptions = {};\n } else if (paramsOrOptions !== undefined && options !== undefined) {\n // Both parameters and options passed.\n postOptions = options;\n eventData = paramsOrOptions;\n } else if (paramsOrOptions !== undefined) {\n // Only parameters were passed.\n if ('targetOrigin' in paramsOrOptions) {\n postOptions = paramsOrOptions;\n } else {\n eventData = paramsOrOptions;\n }\n }\n const { targetOrigin = globalTargetOrigin() } = postOptions;\n\n // Telegram Web.\n if (isIframe()) {\n window.parent.postMessage(JSON.stringify({\n eventType,\n eventData,\n }), targetOrigin);\n return;\n }\n\n // Telegram for Windows Phone or Android.\n if (hasExternalNotify(window)) {\n window.external.notify(JSON.stringify({ eventType, eventData }));\n return;\n }\n\n // Telegram for iOS and macOS.\n if (hasWebviewProxy(window)) {\n window.TelegramWebviewProxy.postEvent(eventType, JSON.stringify(eventData));\n return;\n }\n\n // Otherwise current environment is unknown, and we are not able to send\n // event.\n throw new Error(\n 'Unable to determine current environment and possible way to send event.',\n );\n}\n","import { withTimeout, isRecord } from '@tma.js/utils';\n\nimport type { And, If, IsNever } from '@tma.js/util-types';\n\nimport { postEvent as defaultPostEvent, type PostEvent } from './methods/postEvent.js';\nimport { on, type EventName, type EventParams, type EventHasParams } from './events/index.js';\n\nimport type {\n EmptyMethodName, MethodHasParams,\n MethodName,\n MethodParams,\n NonEmptyMethodName,\n} from './methods/params.js';\n\n/**\n * Names of methods, which require passing \"req_id\" parameter.\n */\ntype MethodNameWithRequestId = {\n [Method in MethodName]: If<\n And<MethodHasParams<Method>, MethodParams<Method> extends { req_id: string } ? true : false>,\n Method,\n never\n >;\n}[MethodName];\n\n/**\n * Names of events, which contain \"req_id\" parameter.\n */\ntype EventNameWithRequestId = {\n [Event in EventName]: If<\n And<EventHasParams<Event>, EventParams<Event> extends { req_id: string } ? true : false>,\n Event,\n never\n >;\n}[EventName];\n\nexport interface RequestOptions {\n /**\n * Bridge postEvent method.\n * @default Global postEvent method.\n */\n postEvent?: PostEvent;\n\n /**\n * Execution timeout.\n */\n timeout?: number;\n}\n\nexport interface RequestOptionsAdvanced<EventPayload> extends RequestOptions {\n /**\n * Should return true in case, this event should be captured. If not specified,\n * request is not skipping captured events.\n */\n capture?: If<IsNever<EventPayload>, () => boolean, (payload: EventPayload) => boolean>;\n}\n\n/**\n * Calls specified TWA method and captures one of the specified events. Returns promise\n * which will be resolved in case, event with specified in method request identifier\n * was captured.\n * @param method - method to execute.\n * @param params - method parameters.\n * @param event - event or events to listen.\n * @param options - additional execution options.\n */\nexport function request<\n Method extends MethodNameWithRequestId,\n Event extends EventNameWithRequestId,\n>(\n method: Method,\n params: MethodParams<Method>,\n event: Event | Event[],\n options?: RequestOptions,\n): Promise<EventParams<Event>>;\n\n/**\n * Calls specified TWA method and captures one of the specified events. Returns promise\n * which will be resolved in case, specified event was captured.\n * @param method - method to execute.\n * @param event - event or events to listen.\n * @param options - additional execution options.\n */\nexport function request<Method extends EmptyMethodName, Event extends EventName>(\n method: Method,\n event: Event | Event[],\n options?: RequestOptionsAdvanced<EventParams<Event>>,\n): Promise<EventParams<Event>>;\n\n/**\n * Calls specified TWA method and captures one of the specified events. Returns promise\n * which will be resolved in case, specified event was captured.\n * @param method - method to execute\n * @param params - method parameters.\n * @param event - event or events to listen\n * @param options - additional execution options.\n */\nexport function request<Method extends NonEmptyMethodName, Event extends EventName>(\n method: Method,\n params: MethodParams<Method>,\n event: Event | Event[],\n options?: RequestOptionsAdvanced<EventParams<Event>>,\n): Promise<EventParams<Event>>;\n\nexport function request(\n method: MethodName,\n eventOrParams: EventName | EventName[] | EventParams<any>,\n eventOrOptions?: EventName | EventName[] | RequestOptions | RequestOptionsAdvanced<any>,\n options?: RequestOptions | RequestOptionsAdvanced<any>,\n): Promise<any> {\n let executionOptions: RequestOptions | RequestOptionsAdvanced<any> | undefined;\n let methodParams: EventParams<any> | undefined;\n let events: EventName[];\n let requestId: string | undefined;\n\n if (typeof eventOrParams === 'string' || Array.isArray(eventOrParams)) {\n // Override: [method, event, options?]\n events = Array.isArray(eventOrParams) ? eventOrParams : [eventOrParams] as EventName[];\n executionOptions = eventOrOptions as (RequestOptionsAdvanced<any> | undefined);\n } else {\n // Override: [method, params, event, options?]\n methodParams = eventOrParams as EventParams<any>;\n events = Array.isArray(eventOrOptions) ? eventOrOptions : [eventOrOptions] as EventName[];\n executionOptions = options;\n }\n\n // In case, method parameters were passed, and they contained request identifier, we should store\n // it and wait for the event with this identifier to occur.\n if (isRecord(methodParams) && typeof methodParams.req_id === 'string') {\n requestId = methodParams.req_id;\n }\n\n const { postEvent = defaultPostEvent, timeout } = executionOptions || {};\n const capture = executionOptions && 'capture' in executionOptions\n ? executionOptions.capture\n : null;\n\n const promise = new Promise((res, rej) => {\n // Iterate over each event and create event listener.\n const stoppers = events.map((ev) => on(ev, (data?) => {\n // If request identifier was specified, we are waiting for event with the same value\n // to occur.\n if (typeof requestId === 'string' && (!isRecord(data) || data.req_id !== requestId)) {\n return;\n }\n\n if (typeof capture === 'function' && !capture(data)) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n stopListening();\n res(data);\n }));\n\n // Function which removes all event listeners.\n const stopListening = () => stoppers.forEach((stop) => stop());\n\n try {\n // We are wrapping this call in try catch, because it can throw errors in case,\n // compatibility check was enabled. We want an error to be captured by promise, not by\n // another one external try catch.\n postEvent(method as any, methodParams);\n } catch (e) {\n stopListening();\n rej(e);\n }\n });\n\n return typeof timeout === 'number' ? withTimeout(promise, timeout) : promise;\n}\n","import { compareVersions, type Version } from '@tma.js/utils';\n\nimport type {\n HasCheckSupportMethodParam,\n HasCheckSupportMethodName,\n MethodName,\n MethodParams,\n NonEmptyMethodName,\n} from './methods/index.js';\n\nfunction lessOrEqual(a: Version, b: Version): boolean {\n return compareVersions(a, b) <= 0;\n}\n\n/**\n * By specified method and parameters extracts properties which could be used by\n * supports function as TWA method parameter.\n * @param method - TWA method.\n * @param params - method parameters.\n */\nexport function detectSupportParams<M extends NonEmptyMethodName>(\n method: M,\n params: MethodParams<M>,\n): HasCheckSupportMethodParam<HasCheckSupportMethodName>[] {\n if (method === 'web_app_open_link') {\n if ('try_instant_view' in params) {\n return ['try_instant_view'];\n }\n }\n\n if (method === 'web_app_set_header_color') {\n if ('color' in params) {\n return ['color'];\n }\n }\n\n return [];\n}\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 HasCheckSupportMethodName>(\n method: M,\n param: HasCheckSupportMethodParam<M>,\n inVersion: Version,\n): boolean;\n/**\n * Returns true in case, specified method is supported in passed version.\n * @param method - method name.\n * @param inVersion - platform version.\n */\nexport function supports(method: MethodName, inVersion: Version): boolean;\nexport function supports(\n method: MethodName,\n paramOrVersion: Version | string,\n inVersion?: string,\n): boolean {\n // Method name, parameter, target version.\n if (typeof inVersion === 'string') {\n if (method === 'web_app_open_link') {\n if (paramOrVersion === 'try_instant_view') {\n return lessOrEqual('6.4', inVersion);\n }\n }\n\n if (method === 'web_app_set_header_color') {\n if (paramOrVersion === 'color') {\n return lessOrEqual('6.9', inVersion);\n }\n }\n }\n\n // Method name, target version.\n switch (method) {\n case 'web_app_open_tg_link':\n case 'web_app_open_invoice':\n case 'web_app_setup_back_button':\n case 'web_app_set_background_color':\n case 'web_app_set_header_color':\n case 'web_app_trigger_haptic_feedback':\n return lessOrEqual('6.1', paramOrVersion);\n case 'web_app_open_popup':\n return lessOrEqual('6.2', paramOrVersion);\n case 'web_app_close_scan_qr_popup':\n case 'web_app_open_scan_qr_popup':\n case 'web_app_read_text_from_clipboard':\n return lessOrEqual('6.4', paramOrVersion);\n case 'web_app_invoke_custom_method':\n case 'web_app_request_write_access':\n case 'web_app_request_phone':\n return lessOrEqual('6.9', paramOrVersion);\n case 'web_app_setup_settings_button':\n return lessOrEqual('6.10', paramOrVersion);\n default:\n return true;\n }\n}\n"],"names":["currentDebug","currentTargetOrigin","setDebug","value","setTargetOrigin","targetOrigin","log","level","args","utilLog","isNullOrUndefined","rgbOptional","rgb","num","number","windowWidthParser","createValueParserGen","themeChangedPayload","json","viewportChangedPayload","boolean","popupClosedPayload","string","qrTextReceivedPayload","invoiceClosedPayload","clipboardTextReceivedPayload","writeAccessRequestedPayload","phoneRequestedPayload","customMethodInvokedPayload","eventDataJson","emitEvent","eventType","eventData","defineEventHandlers","wnd","path","pointer","item","idx","arr","onTelegramEvent","cb","event","CACHED_EMITTER","createEmitter","emitter","UtilEventEmitter","emit","data","cause","singletonEmitter","off","listener","on","once","unsubscribe","subscribe","hasExternalNotify","isRecord","hasWebviewProxy","isIframe","postEvent","paramsOrOptions","options","postOptions","globalTargetOrigin","request","method","eventOrParams","eventOrOptions","executionOptions","methodParams","events","requestId","defaultPostEvent","timeout","capture","promise","res","rej","stoppers","ev","stopListening","stop","e","withTimeout","lessOrEqual","a","b","compareVersions","detectSupportParams","params","supports","paramOrVersion","inVersion"],"mappings":";;;;AAEA,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AA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACI,aAAAmB,EAAY,OAAOO,CAAc;AAAA,IAC1C,KAAK;AACI,aAAAP,EAAY,OAAOO,CAAc;AAAA,IAC1C,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACI,aAAAP,EAAY,OAAOO,CAAc;AAAA,IAC1C,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACI,aAAAP,EAAY,OAAOO,CAAc;AAAA,IAC1C,KAAK;AACI,aAAAP,EAAY,QAAQO,CAAc;AAAA,IAC3C;AACS,aAAA;AAAA,EACX;AACF;"}
1
+ {"version":3,"file":"index.mjs","sources":["../src/globals.ts","../src/events/parsing.ts","../src/events/onTelegramEvent.ts","../src/events/emitter.ts","../src/events/off.ts","../src/events/on.ts","../src/events/once.ts","../src/events/unsubscribe.ts","../src/events/subscribe.ts","../src/env.ts","../src/methods/postEvent.ts","../src/request.ts","../src/supports.ts"],"sourcesContent":["import { Logger } from '@tma.js/logger';\n\nlet currentTargetOrigin = 'https://web.telegram.org';\n\nexport const logger = new Logger('[Bridge]', false);\n\n/**\n * Sets new debug mode. Enabling debug mode leads to printing\n * additional messages in console, related to the processes\n * inside the package.\n * @param value - should debug mode be enabled.\n */\nexport function setDebug(value: boolean): void {\n if (value) {\n logger.enable();\n return;\n }\n logger.disable();\n}\n\n/**\n * Sets new global targetOrigin, used by `postEvent` method.\n * Default value is \"https://web.telegram.org\". You don't need to\n * use this method until you know what you are doing.\n *\n * This method could be used for test purposes.\n * @param value - new target origin.\n */\nexport function setTargetOrigin(value: string): void {\n currentTargetOrigin = value;\n}\n\n/**\n * Returns current global target origin.\n */\nexport function targetOrigin(): string {\n return currentTargetOrigin;\n}\n","import {\n number,\n string,\n boolean,\n json,\n rgb,\n createValueParserGen,\n} from '@tma.js/parsing';\n\nimport type {\n ClipboardTextReceivedPayload, CustomMethodInvokedPayload,\n InvoiceClosedPayload, PhoneRequestedPayload,\n PopupClosedPayload, QrTextReceivedPayload,\n ThemeChangedPayload,\n ViewportChangedPayload, WriteAccessRequestedPayload,\n} from './payloads.js';\n\nfunction isNullOrUndefined(value: unknown): boolean {\n return value === null || value === undefined;\n}\n\nconst rgbOptional = rgb().optional();\nconst num = number();\n\nconst windowWidthParser = createValueParserGen((value) => (value === null || value === undefined\n ? window.innerWidth\n : num.parse(value)));\n\n/**\n * Parses incoming value as ThemeChangedPayload.\n */\nexport const themeChangedPayload = json<ThemeChangedPayload>({\n theme_params: json({\n bg_color: rgbOptional,\n text_color: rgbOptional,\n hint_color: rgbOptional,\n link_color: rgbOptional,\n button_color: rgbOptional,\n button_text_color: rgbOptional,\n secondary_bg_color: rgbOptional,\n }),\n});\n\n/**\n * Parses incoming value as ViewportChangedPayload.\n * @param value - value to parse.\n */\nexport const viewportChangedPayload = json<ViewportChangedPayload>({\n height: number(),\n width: windowWidthParser(),\n is_state_stable: boolean(),\n is_expanded: boolean(),\n});\n\n/**\n * Parses incoming value as PopupClosedPayload.\n */\nexport const popupClosedPayload = json<PopupClosedPayload>({\n button_id: string({ isEmpty: isNullOrUndefined }).optional(),\n});\n\n/**\n * Parses incoming value as QrTextReceivedPayload.\n */\nexport const qrTextReceivedPayload = json<QrTextReceivedPayload>({\n data: string().optional(),\n});\n\n/**\n * Parses incoming value as InvoiceClosedPayload.\n */\nexport const invoiceClosedPayload = json<InvoiceClosedPayload>({\n slug: string(),\n status: string(),\n});\n\n/**\n * Parses incoming value as clipboard text received payload.\n */\nexport const clipboardTextReceivedPayload = json<ClipboardTextReceivedPayload>({\n req_id: string(),\n data: (value) => (value === null ? value : string().optional().parse(value)),\n});\n\n/**\n * Parses incoming value as WriteAccessRequestedPayload.\n */\nexport const writeAccessRequestedPayload = json<WriteAccessRequestedPayload>({ status: string() });\n\n/**\n * Parses incoming value as PhoneRequestedPayload.\n */\nexport const phoneRequestedPayload = json<PhoneRequestedPayload>({ status: string() });\n\n/**\n * Parses incoming value as CustomMethodInvokedPayload.\n */\nexport const customMethodInvokedPayload = json<CustomMethodInvokedPayload>({\n req_id: string(),\n result: (value) => value,\n error: string().optional(),\n});\n","import { json, string } from '@tma.js/parsing';\n\n/**\n * Extracts event data from native application event.\n */\nconst eventDataJson = json<{ eventType: string; eventData?: unknown }>({\n eventType: string(),\n eventData: (value) => value,\n});\n\n/**\n * Emits event sent from Telegram native application like it was sent in\n * default web environment between 2 iframes. It dispatches new MessageEvent\n * and expects it to be handled via `window.addEventListener('message', ...)`\n * as developer would do it to handle messages sent from parent iframe.\n * @param eventType - event name.\n * @param eventData - event payload.\n */\nfunction emitEvent(eventType: string, eventData: unknown): void {\n window.dispatchEvent(new MessageEvent('message', {\n data: JSON.stringify({ eventType, eventData }),\n }));\n}\n\n/**\n * Defines special handlers by known paths, which are recognized by\n * Telegram as ports to receive events. This function also sets special\n * function in global window object to prevent duplicate declaration.\n */\nfunction defineEventHandlers(): void {\n const wnd: any = window;\n\n // Prevent from duplicate event handlers definition.\n if ('TelegramGameProxy_receiveEvent' in wnd) {\n return;\n }\n\n // Iterate over each path, where \"receiveEvent\" function should be\n // defined. This function is called by external environment in case,\n // it wants to emit some event.\n [\n ['TelegramGameProxy_receiveEvent'], // Windows Phone.\n ['TelegramGameProxy', 'receiveEvent'], // Desktop.\n ['Telegram', 'WebView', 'receiveEvent'], // Android and iOS.\n ].forEach((path) => {\n // Path starts from \"window\" object.\n let pointer = wnd;\n\n path.forEach((item, idx, arr) => {\n // We are on the last iteration, where function property name is passed.\n if (idx === arr.length - 1) {\n pointer[item] = emitEvent;\n return;\n }\n\n if (!(item in pointer)) {\n pointer[item] = {};\n }\n pointer = pointer[item];\n });\n });\n}\n\n/**\n * Adds listener to window \"message\" event assuming, that this event could\n * be sent by Telegram native application. Calls passed callback with event\n * type and data.\n * @param cb - callback to call.\n */\nexport function onTelegramEvent(cb: (eventType: string, eventData: unknown) => void): void {\n // Define event handlers to make sure, message handler will work correctly.\n defineEventHandlers();\n\n // We expect Telegram to send us new event through \"message\" event.\n window.addEventListener('message', (event) => {\n try {\n const { eventType, eventData } = eventDataJson.parse(event.data);\n cb(eventType, eventData);\n } catch {\n // We ignore incorrect messages as they could be generated by any other code.\n }\n });\n}\n","import { EventEmitter as UtilEventEmitter } from '@tma.js/event-emitter';\nimport { string } from '@tma.js/parsing';\n\nimport { logger } from '../globals.js';\nimport {\n clipboardTextReceivedPayload,\n customMethodInvokedPayload,\n invoiceClosedPayload,\n phoneRequestedPayload,\n popupClosedPayload,\n qrTextReceivedPayload,\n themeChangedPayload,\n viewportChangedPayload,\n writeAccessRequestedPayload,\n} from './parsing.js';\nimport { onTelegramEvent } from './onTelegramEvent.js';\n\nimport type { EventEmitter, EventName } from './events.js';\n\nconst CACHED_EMITTER = '__telegram-cached-emitter__';\n\n/**\n * Returns event emitter which could be safely used, to process events from\n * Telegram native application.\n */\nexport function createEmitter(): EventEmitter {\n const emitter: EventEmitter = new UtilEventEmitter();\n const emit: EventEmitter['emit'] = (event: any, ...data: any[]) => {\n logger.log('Emitting processed event:', event, ...data);\n emitter.emit(event, ...data);\n };\n\n // Desktop version of Telegram is sometimes not sending the viewport_changed\n // event. For example, when main button is shown. That's why we should\n // add our own listener to make sure, viewport information is always fresh.\n // Issue: https://github.com/Telegram-Mini-Apps/tma.js/issues/10\n window.addEventListener('resize', () => {\n emit('viewport_changed', {\n width: window.innerWidth,\n height: window.innerHeight,\n is_state_stable: true,\n is_expanded: true,\n });\n });\n\n // In case, any Telegram event was received, we should prepare data before\n // passing it to emitter.\n onTelegramEvent((eventType: EventName | string, eventData): void => {\n logger.log('Received raw event:', eventType, eventData);\n\n try {\n switch (eventType) {\n case 'viewport_changed':\n return emit(eventType, viewportChangedPayload.parse(eventData));\n\n case 'theme_changed':\n return emit(eventType, themeChangedPayload.parse(eventData));\n\n case 'popup_closed':\n // FIXME: Payloads are different on different platforms.\n // Issue: https://github.com/Telegram-Mini-Apps/tma.js/issues/2\n if (\n // Sent on desktop.\n eventData === undefined\n // Sent on iOS.\n || eventData === null\n ) {\n return emit(eventType, {});\n }\n return emit(eventType, popupClosedPayload.parse(eventData));\n\n case 'set_custom_style':\n return emit(eventType, string().parse(eventData));\n\n case 'qr_text_received':\n return emit(eventType, qrTextReceivedPayload.parse(eventData));\n\n case 'clipboard_text_received':\n return emit(eventType, clipboardTextReceivedPayload.parse(eventData));\n\n case 'invoice_closed':\n return emit(eventType, invoiceClosedPayload.parse(eventData));\n\n case 'phone_requested':\n return emit('phone_requested', phoneRequestedPayload.parse(eventData));\n\n case 'custom_method_invoked':\n return emit('custom_method_invoked', customMethodInvokedPayload.parse(eventData));\n\n case 'write_access_requested':\n return emit('write_access_requested', writeAccessRequestedPayload.parse(eventData));\n\n // Events which have no parameters.\n case 'main_button_pressed':\n case 'back_button_pressed':\n case 'settings_button_pressed':\n case 'scan_qr_popup_closed':\n return emit(eventType);\n\n // All other event listeners will receive unknown type of data.\n default:\n return emit(eventType as any, eventData);\n }\n } catch (cause) {\n logger.error('Error processing event:', cause);\n }\n });\n\n return emitter;\n}\n\n/**\n * Returns singleton instance of bridge EventEmitter. Also, defines\n * Telegram event handlers.\n */\nexport function singletonEmitter(): EventEmitter {\n const wnd: any = window;\n const cachedEmitter = wnd[CACHED_EMITTER];\n\n if (cachedEmitter === undefined) {\n wnd[CACHED_EMITTER] = createEmitter();\n }\n\n return wnd[CACHED_EMITTER];\n}\n","import { singletonEmitter } from './emitter.js';\n\nimport type { EventName, EventListener } from './events.js';\n\n/**\n * Removes listener from specified event.\n * @param event - event to listen.\n * @param listener - event listener.\n */\nexport function off<E extends EventName>(event: E, listener: EventListener<E>): void {\n singletonEmitter().off(event, listener);\n}\n","import { singletonEmitter } from './emitter.js';\nimport { off } from './off.js';\n\nimport type { EventName, EventListener } from './events.js';\n\ntype StopListening = () => void;\n\n/**\n * Adds new listener to the specified event. Returns handler\n * which allows to stop listening to event.\n * @param event - event name.\n * @param listener - event listener.\n */\nexport function on<E extends EventName>(event: E, listener: EventListener<E>): StopListening {\n singletonEmitter().on(event, listener);\n return () => off(event, listener);\n}\n","import { singletonEmitter } from './emitter.js';\nimport { off } from './off.js';\n\nimport type { EventName, EventListener } from './events.js';\n\ntype StopListening = () => void;\n\n/**\n * Works the same as \"on\" method, but after catching the event, will remove event listener.\n * @param event - event name.\n * @param listener - event listener.\n */\nexport function once<E extends EventName>(event: E, listener: EventListener<E>): StopListening {\n singletonEmitter().once(event, listener);\n return () => off(event, listener);\n}\n","import { singletonEmitter } from './emitter.js';\n\nimport type { GlobalEventListener } from './events.js';\n\n/**\n * Removes global event listener.\n * @param listener - event listener.\n */\nexport function unsubscribe(listener: GlobalEventListener): void {\n singletonEmitter().unsubscribe(listener);\n}\n","import { singletonEmitter } from './emitter.js';\nimport { unsubscribe } from './unsubscribe.js';\n\nimport type { GlobalEventListener } from './events.js';\n\ntype StopListening = () => void;\n\n/**\n * Subscribes to all events sent from the native Telegram application.\n * Returns function used to remove added event listener.\n * @param listener - event listener.\n */\nexport function subscribe(listener: GlobalEventListener): StopListening {\n singletonEmitter().subscribe(listener);\n return () => unsubscribe(listener);\n}\n","import { isRecord } from '@tma.js/utils';\n\ntype AnyFunc = (...args: unknown[]) => unknown;\n\ntype WithExternalNotify<T> = T & {\n external: { notify: AnyFunc }\n};\n\ntype WithWebviewProxy<T> = T & {\n TelegramWebviewProxy: {\n postEvent: AnyFunc;\n }\n};\n\n/**\n * Returns true in case, passed value contains path `external.notify` property and `notify` is a\n * function.\n * @param value - value to check.\n */\nexport function hasExternalNotify<T extends {}>(value: T): value is WithExternalNotify<T> {\n return 'external' in value\n && isRecord(value.external)\n && 'notify' in value.external\n && typeof value.external.notify === 'function';\n}\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 extends {}>(value: T): value is WithWebviewProxy<T> {\n return 'TelegramWebviewProxy' in value\n && isRecord(value.TelegramWebviewProxy)\n && 'postEvent' in value.TelegramWebviewProxy\n && typeof value.TelegramWebviewProxy.postEvent === 'function';\n}\n\n/**\n * Returns true in case, current environment is iframe.\n * @see https://stackoverflow.com/a/326076\n */\nexport function isIframe(): boolean {\n try {\n return window.self !== window.top;\n } catch (e) {\n return true;\n }\n}\n","import {\n isIframe,\n hasExternalNotify,\n hasWebviewProxy,\n} from '../env.js';\nimport { targetOrigin as globalTargetOrigin } from '../globals.js';\n\nimport type {\n EmptyMethodName,\n MethodName,\n MethodParams,\n NonEmptyMethodName,\n} from './params.js';\n\ninterface PostEventOptions {\n /**\n * Origin used while posting message. This option is only used in case,\n * current environment is browser (Web version of Telegram) and could\n * be used for test purposes.\n * @default 'https://web.telegram.org'\n */\n targetOrigin?: string;\n}\n\nexport type PostEvent = typeof postEvent;\n\n/**\n * Sends event to native application which launched Web App. This function\n * accepts only events, which require arguments.\n * @param eventType - event name.\n * @param params - event parameters.\n * @param options - posting options.\n * @throws {Error} Bridge could not determine current\n * environment and possible way to send event.\n */\nexport function postEvent<E extends NonEmptyMethodName>(\n eventType: E,\n params: MethodParams<E>,\n options?: PostEventOptions,\n): void;\n\n/**\n * Sends event to native application which launched Web App. This function\n * accepts only events, which require arguments.\n * @param eventType - event name.\n * @param options - posting options.\n * @throws {Error} Bridge could not determine current\n * environment and possible way to send event.\n */\nexport function postEvent(eventType: EmptyMethodName, options?: PostEventOptions): void;\n\nexport function postEvent(\n eventType: MethodName,\n paramsOrOptions?: MethodParams<MethodName> | PostEventOptions,\n options?: PostEventOptions,\n): void {\n let postOptions: PostEventOptions = {};\n let eventData: any;\n\n if (paramsOrOptions === undefined && options === undefined) {\n // Parameters and options were not passed.\n postOptions = {};\n } else if (paramsOrOptions !== undefined && options !== undefined) {\n // Both parameters and options passed.\n postOptions = options;\n eventData = paramsOrOptions;\n } else if (paramsOrOptions !== undefined) {\n // Only parameters were passed.\n if ('targetOrigin' in paramsOrOptions) {\n postOptions = paramsOrOptions;\n } else {\n eventData = paramsOrOptions;\n }\n }\n const { targetOrigin = globalTargetOrigin() } = postOptions;\n\n // Telegram Web.\n if (isIframe()) {\n window.parent.postMessage(JSON.stringify({\n eventType,\n eventData,\n }), targetOrigin);\n return;\n }\n\n // Telegram for Windows Phone or Android.\n if (hasExternalNotify(window)) {\n window.external.notify(JSON.stringify({ eventType, eventData }));\n return;\n }\n\n // Telegram for iOS and macOS.\n if (hasWebviewProxy(window)) {\n window.TelegramWebviewProxy.postEvent(eventType, JSON.stringify(eventData));\n return;\n }\n\n // Otherwise current environment is unknown, and we are not able to send\n // event.\n throw new Error(\n 'Unable to determine current environment and possible way to send event.',\n );\n}\n","import { withTimeout, isRecord } from '@tma.js/utils';\n\nimport type { And, If, IsNever } from '@tma.js/util-types';\n\nimport { postEvent as defaultPostEvent, type PostEvent } from './methods/postEvent.js';\nimport { on, type EventName, type EventParams, type EventHasParams } from './events/index.js';\n\nimport type {\n EmptyMethodName, MethodHasParams,\n MethodName,\n MethodParams,\n NonEmptyMethodName,\n} from './methods/params.js';\n\n/**\n * Names of methods, which require passing \"req_id\" parameter.\n */\ntype MethodNameWithRequestId = {\n [Method in MethodName]: If<\n And<MethodHasParams<Method>, MethodParams<Method> extends { req_id: string } ? true : false>,\n Method,\n never\n >;\n}[MethodName];\n\n/**\n * Names of events, which contain \"req_id\" parameter.\n */\ntype EventNameWithRequestId = {\n [Event in EventName]: If<\n And<EventHasParams<Event>, EventParams<Event> extends { req_id: string } ? true : false>,\n Event,\n never\n >;\n}[EventName];\n\nexport interface RequestOptions {\n /**\n * Bridge postEvent method.\n * @default Global postEvent method.\n */\n postEvent?: PostEvent;\n\n /**\n * Execution timeout.\n */\n timeout?: number;\n}\n\nexport interface RequestOptionsAdvanced<EventPayload> extends RequestOptions {\n /**\n * Should return true in case, this event should be captured. If not specified,\n * request is not skipping captured events.\n */\n capture?: If<IsNever<EventPayload>, () => boolean, (payload: EventPayload) => boolean>;\n}\n\n/**\n * Calls specified TWA method and captures one of the specified events. Returns promise\n * which will be resolved in case, event with specified in method request identifier\n * was captured.\n * @param method - method to execute.\n * @param params - method parameters.\n * @param event - event or events to listen.\n * @param options - additional execution options.\n */\nexport function request<\n Method extends MethodNameWithRequestId,\n Event extends EventNameWithRequestId,\n>(\n method: Method,\n params: MethodParams<Method>,\n event: Event | Event[],\n options?: RequestOptions,\n): Promise<EventParams<Event>>;\n\n/**\n * Calls specified TWA method and captures one of the specified events. Returns promise\n * which will be resolved in case, specified event was captured.\n * @param method - method to execute.\n * @param event - event or events to listen.\n * @param options - additional execution options.\n */\nexport function request<Method extends EmptyMethodName, Event extends EventName>(\n method: Method,\n event: Event | Event[],\n options?: RequestOptionsAdvanced<EventParams<Event>>,\n): Promise<EventParams<Event>>;\n\n/**\n * Calls specified TWA method and captures one of the specified events. Returns promise\n * which will be resolved in case, specified event was captured.\n * @param method - method to execute\n * @param params - method parameters.\n * @param event - event or events to listen\n * @param options - additional execution options.\n */\nexport function request<Method extends NonEmptyMethodName, Event extends EventName>(\n method: Method,\n params: MethodParams<Method>,\n event: Event | Event[],\n options?: RequestOptionsAdvanced<EventParams<Event>>,\n): Promise<EventParams<Event>>;\n\nexport function request(\n method: MethodName,\n eventOrParams: EventName | EventName[] | EventParams<any>,\n eventOrOptions?: EventName | EventName[] | RequestOptions | RequestOptionsAdvanced<any>,\n options?: RequestOptions | RequestOptionsAdvanced<any>,\n): Promise<any> {\n let executionOptions: RequestOptions | RequestOptionsAdvanced<any> | undefined;\n let methodParams: EventParams<any> | undefined;\n let events: EventName[];\n let requestId: string | undefined;\n\n if (typeof eventOrParams === 'string' || Array.isArray(eventOrParams)) {\n // Override: [method, event, options?]\n events = Array.isArray(eventOrParams) ? eventOrParams : [eventOrParams] as EventName[];\n executionOptions = eventOrOptions as (RequestOptionsAdvanced<any> | undefined);\n } else {\n // Override: [method, params, event, options?]\n methodParams = eventOrParams as EventParams<any>;\n events = Array.isArray(eventOrOptions) ? eventOrOptions : [eventOrOptions] as EventName[];\n executionOptions = options;\n }\n\n // In case, method parameters were passed, and they contained request identifier, we should store\n // it and wait for the event with this identifier to occur.\n if (isRecord(methodParams) && typeof methodParams.req_id === 'string') {\n requestId = methodParams.req_id;\n }\n\n const { postEvent = defaultPostEvent, timeout } = executionOptions || {};\n const capture = executionOptions && 'capture' in executionOptions\n ? executionOptions.capture\n : null;\n\n const promise = new Promise((res, rej) => {\n // Iterate over each event and create event listener.\n const stoppers = events.map((ev) => on(ev, (data?) => {\n // If request identifier was specified, we are waiting for event with the same value\n // to occur.\n if (typeof requestId === 'string' && (!isRecord(data) || data.req_id !== requestId)) {\n return;\n }\n\n if (typeof capture === 'function' && !capture(data)) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n stopListening();\n res(data);\n }));\n\n // Function which removes all event listeners.\n const stopListening = () => stoppers.forEach((stop) => stop());\n\n try {\n // We are wrapping this call in try catch, because it can throw errors in case,\n // compatibility check was enabled. We want an error to be captured by promise, not by\n // another one external try catch.\n postEvent(method as any, methodParams);\n } catch (e) {\n stopListening();\n rej(e);\n }\n });\n\n return typeof timeout === 'number' ? withTimeout(promise, timeout) : promise;\n}\n","import { compareVersions, type Version } from '@tma.js/utils';\n\nimport type {\n HasCheckSupportMethodParam,\n HasCheckSupportMethodName,\n MethodName,\n MethodParams,\n NonEmptyMethodName,\n} from './methods/index.js';\n\nfunction lessOrEqual(a: Version, b: Version): boolean {\n return compareVersions(a, b) <= 0;\n}\n\n/**\n * By specified method and parameters extracts properties which could be used by\n * supports function as TWA method parameter.\n * @param method - TWA method.\n * @param params - method parameters.\n */\nexport function detectSupportParams<M extends NonEmptyMethodName>(\n method: M,\n params: MethodParams<M>,\n): HasCheckSupportMethodParam<HasCheckSupportMethodName>[] {\n if (method === 'web_app_open_link') {\n if ('try_instant_view' in params) {\n return ['try_instant_view'];\n }\n }\n\n if (method === 'web_app_set_header_color') {\n if ('color' in params) {\n return ['color'];\n }\n }\n\n return [];\n}\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 HasCheckSupportMethodName>(\n method: M,\n param: HasCheckSupportMethodParam<M>,\n inVersion: Version,\n): boolean;\n/**\n * Returns true in case, specified method is supported in passed version.\n * @param method - method name.\n * @param inVersion - platform version.\n */\nexport function supports(method: MethodName, inVersion: Version): boolean;\nexport function supports(\n method: MethodName,\n paramOrVersion: Version | string,\n inVersion?: string,\n): boolean {\n // Method name, parameter, target version.\n if (typeof inVersion === 'string') {\n if (method === 'web_app_open_link') {\n if (paramOrVersion === 'try_instant_view') {\n return lessOrEqual('6.4', inVersion);\n }\n }\n\n if (method === 'web_app_set_header_color') {\n if (paramOrVersion === 'color') {\n return lessOrEqual('6.9', inVersion);\n }\n }\n }\n\n // Method name, target version.\n switch (method) {\n case 'web_app_open_tg_link':\n case 'web_app_open_invoice':\n case 'web_app_setup_back_button':\n case 'web_app_set_background_color':\n case 'web_app_set_header_color':\n case 'web_app_trigger_haptic_feedback':\n return lessOrEqual('6.1', paramOrVersion);\n case 'web_app_open_popup':\n return lessOrEqual('6.2', paramOrVersion);\n case 'web_app_close_scan_qr_popup':\n case 'web_app_open_scan_qr_popup':\n case 'web_app_read_text_from_clipboard':\n return lessOrEqual('6.4', paramOrVersion);\n case 'web_app_invoke_custom_method':\n case 'web_app_request_write_access':\n case 'web_app_request_phone':\n return lessOrEqual('6.9', paramOrVersion);\n case 'web_app_setup_settings_button':\n return lessOrEqual('6.10', paramOrVersion);\n default:\n return true;\n }\n}\n"],"names":["currentTargetOrigin","logger","Logger","setDebug","value","setTargetOrigin","targetOrigin","isNullOrUndefined","rgbOptional","rgb","num","number","windowWidthParser","createValueParserGen","themeChangedPayload","json","viewportChangedPayload","boolean","popupClosedPayload","string","qrTextReceivedPayload","invoiceClosedPayload","clipboardTextReceivedPayload","writeAccessRequestedPayload","phoneRequestedPayload","customMethodInvokedPayload","eventDataJson","emitEvent","eventType","eventData","defineEventHandlers","wnd","path","pointer","item","idx","arr","onTelegramEvent","cb","event","CACHED_EMITTER","createEmitter","emitter","UtilEventEmitter","emit","data","cause","singletonEmitter","off","listener","on","once","unsubscribe","subscribe","hasExternalNotify","isRecord","hasWebviewProxy","isIframe","postEvent","paramsOrOptions","options","postOptions","globalTargetOrigin","request","method","eventOrParams","eventOrOptions","executionOptions","methodParams","events","requestId","defaultPostEvent","timeout","capture","promise","res","rej","stoppers","ev","stopListening","stop","e","withTimeout","lessOrEqual","a","b","compareVersions","detectSupportParams","params","supports","paramOrVersion","inVersion"],"mappings":";;;;AAEA,IAAIA,IAAsB;AAEnB,MAAMC,IAAS,IAAIC,EAAO,YAAY,EAAK;AAQ3C,SAASC,GAASC,GAAsB;AAC7C,MAAIA,GAAO;AACT,IAAAH,EAAO,OAAO;AACd;AAAA,EACF;AACA,EAAAA,EAAO,QAAQ;AACjB;AAUO,SAASI,GAAgBD,GAAqB;AAC7B,EAAAJ,IAAAI;AACxB;AAKO,SAASE,IAAuB;AAC9B,SAAAN;AACT;ACpBA,SAASO,EAAkBH,GAAyB;AAC3C,SAAAA,KAAU;AACnB;AAEA,MAAMI,IAAcC,IAAM,YACpBC,IAAMC,EAAO,GAEbC,IAAoBC,EAAqB,CAACT,MAAWA,KAAU,OACjE,OAAO,aACPM,EAAI,MAAMN,CAAK,CAAE,GAKRU,IAAsBC,EAA0B;AAAA,EAC3D,cAAcA,EAAK;AAAA,IACjB,UAAUP;AAAA,IACV,YAAYA;AAAA,IACZ,YAAYA;AAAA,IACZ,YAAYA;AAAA,IACZ,cAAcA;AAAA,IACd,mBAAmBA;AAAA,IACnB,oBAAoBA;AAAA,EAAA,CACrB;AACH,CAAC,GAMYQ,IAAyBD,EAA6B;AAAA,EACjE,QAAQJ,EAAO;AAAA,EACf,OAAOC,EAAkB;AAAA,EACzB,iBAAiBK,EAAQ;AAAA,EACzB,aAAaA,EAAQ;AACvB,CAAC,GAKYC,IAAqBH,EAAyB;AAAA,EACzD,WAAWI,EAAO,EAAE,SAASZ,EAAmB,CAAA,EAAE,SAAS;AAC7D,CAAC,GAKYa,IAAwBL,E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ACdzB,GACA0B,GACAC,GACS;AAEL,MAAA,OAAOA,KAAc,UAAU;AACjC,QAAI3B,MAAW,uBACT0B,MAAmB;AACd,aAAAP,EAAY,OAAOQ,CAAS;AAIvC,QAAI3B,MAAW,8BACT0B,MAAmB;AACd,aAAAP,EAAY,OAAOQ,CAAS;AAAA,EAGzC;AAGA,UAAQ3B,GAAQ;AAAA,IACd,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACI,aAAAmB,EAAY,OAAOO,CAAc;AAAA,IAC1C,KAAK;AACI,aAAAP,EAAY,OAAOO,CAAc;AAAA,IAC1C,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACI,aAAAP,EAAY,OAAOO,CAAc;AAAA,IAC1C,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACI,aAAAP,EAAY,OAAOO,CAAc;AAAA,IAC1C,KAAK;AACI,aAAAP,EAAY,QAAQO,CAAc;AAAA,IAC3C;AACS,aAAA;AAAA,EACX;AACF;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tma.js/bridge",
3
- "version": "1.3.8",
3
+ "version": "1.3.10",
4
4
  "description": "Communication layer between Telegram and frontend applications.",
5
5
  "author": "Vladislav Kibenko <wolfram.deus@gmail.com>",
6
6
  "homepage": "https://github.com/Telegram-Mini-Apps/tma.js#readme",
@@ -39,8 +39,8 @@
39
39
  },
40
40
  "dependencies": {
41
41
  "@tma.js/colors": "0.0.5",
42
- "@tma.js/event-emitter": "0.0.5",
43
- "@tma.js/logger": "0.0.4",
42
+ "@tma.js/event-emitter": "0.1.0",
43
+ "@tma.js/logger": "0.0.5",
44
44
  "@tma.js/parsing": "0.1.2",
45
45
  "@tma.js/util-types": "0.0.3",
46
46
  "@tma.js/utils": "0.5.5"
@@ -1,7 +1,7 @@
1
1
  import { EventEmitter as UtilEventEmitter } from '@tma.js/event-emitter';
2
2
  import { string } from '@tma.js/parsing';
3
3
 
4
- import { log } from '../globals.js';
4
+ import { logger } from '../globals.js';
5
5
  import {
6
6
  clipboardTextReceivedPayload,
7
7
  customMethodInvokedPayload,
@@ -26,7 +26,7 @@ const CACHED_EMITTER = '__telegram-cached-emitter__';
26
26
  export function createEmitter(): EventEmitter {
27
27
  const emitter: EventEmitter = new UtilEventEmitter();
28
28
  const emit: EventEmitter['emit'] = (event: any, ...data: any[]) => {
29
- log('log', 'Emitting processed event:', event, ...data);
29
+ logger.log('Emitting processed event:', event, ...data);
30
30
  emitter.emit(event, ...data);
31
31
  };
32
32
 
@@ -46,7 +46,7 @@ export function createEmitter(): EventEmitter {
46
46
  // In case, any Telegram event was received, we should prepare data before
47
47
  // passing it to emitter.
48
48
  onTelegramEvent((eventType: EventName | string, eventData): void => {
49
- log('log', 'Received raw event:', eventType, eventData);
49
+ logger.log('Received raw event:', eventType, eventData);
50
50
 
51
51
  try {
52
52
  switch (eventType) {
@@ -102,7 +102,7 @@ export function createEmitter(): EventEmitter {
102
102
  return emit(eventType as any, eventData);
103
103
  }
104
104
  } catch (cause) {
105
- log('error', 'Error processing event:', cause);
105
+ logger.error('Error processing event:', cause);
106
106
  }
107
107
  });
108
108
 
package/src/globals.ts CHANGED
@@ -1,8 +1,9 @@
1
- import { log as utilLog } from '@tma.js/logger';
1
+ import { Logger } from '@tma.js/logger';
2
2
 
3
- let currentDebug = false;
4
3
  let currentTargetOrigin = 'https://web.telegram.org';
5
4
 
5
+ export const logger = new Logger('[Bridge]', false);
6
+
6
7
  /**
7
8
  * Sets new debug mode. Enabling debug mode leads to printing
8
9
  * additional messages in console, related to the processes
@@ -10,7 +11,11 @@ let currentTargetOrigin = 'https://web.telegram.org';
10
11
  * @param value - should debug mode be enabled.
11
12
  */
12
13
  export function setDebug(value: boolean): void {
13
- currentDebug = value;
14
+ if (value) {
15
+ logger.enable();
16
+ return;
17
+ }
18
+ logger.disable();
14
19
  }
15
20
 
16
21
  /**
@@ -31,14 +36,3 @@ export function setTargetOrigin(value: string): void {
31
36
  export function targetOrigin(): string {
32
37
  return currentTargetOrigin;
33
38
  }
34
-
35
- /**
36
- * Logs message in case, debug mode is enabled.
37
- * @param level - log level
38
- * @param args - values to print.
39
- */
40
- export const log: typeof utilLog = (level, ...args) => {
41
- if (currentDebug) {
42
- utilLog(level, '[Bridge]', ...args);
43
- }
44
- };