@tma.js/bridge 1.3.12 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/dts/errors/MethodUnsupportedError.d.ts +8 -0
- package/dist/dts/errors/ParameterUnsupportedError.d.ts +8 -0
- package/dist/dts/errors/index.d.ts +2 -0
- package/dist/dts/events/events.d.ts +7 -2
- package/dist/dts/events/payloads.d.ts +2 -7
- package/dist/dts/index.d.ts +1 -0
- package/dist/dts/methods/createPostEvent.d.ts +10 -0
- package/dist/dts/methods/index.d.ts +5 -4
- package/dist/dts/methods/{params.d.ts → methods.d.ts} +30 -18
- package/dist/dts/methods/postEvent.d.ts +1 -1
- package/dist/dts/request.d.ts +10 -10
- package/dist/dts/supports.d.ts +2 -9
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.iife.js +1 -1
- package/dist/index.iife.js.map +1 -1
- package/dist/index.mjs +174 -146
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/errors/MethodUnsupportedError.ts +13 -0
- package/src/errors/ParameterUnsupportedError.ts +13 -0
- package/src/errors/index.ts +2 -0
- package/src/events/emitter.ts +1 -0
- package/src/events/events.ts +10 -5
- package/src/events/parsing.ts +9 -3
- package/src/events/payloads.ts +16 -7
- package/src/index.ts +1 -0
- package/src/methods/createPostEvent.ts +39 -0
- package/src/methods/index.ts +5 -4
- package/src/methods/{params.ts → methods.ts} +33 -18
- package/src/methods/postEvent.ts +1 -1
- package/src/request.ts +27 -30
- package/src/supports.ts +19 -40
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Version } from '@tma.js/utils';
|
|
2
|
+
import type { MethodName } from '../methods/index.js';
|
|
3
|
+
/**
|
|
4
|
+
* Error thrown in case, unsupported method was called.
|
|
5
|
+
*/
|
|
6
|
+
export declare class MethodUnsupportedError extends Error {
|
|
7
|
+
constructor(method: MethodName, version: Version);
|
|
8
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Version } from '@tma.js/utils';
|
|
2
|
+
import type { MethodName } from '../methods/index.js';
|
|
3
|
+
/**
|
|
4
|
+
* Error thrown in case, unsupported parameter was used.
|
|
5
|
+
*/
|
|
6
|
+
export declare class ParameterUnsupportedError extends Error {
|
|
7
|
+
constructor(method: MethodName, param: string, version: Version);
|
|
8
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { EventEmitter as UtilEventEmitter,
|
|
1
|
+
import type { EventEmitter as UtilEventEmitter, EventListener as UtilEventListener, EventParams as UtilEventParams, AnySubscribeListener } from '@tma.js/event-emitter';
|
|
2
2
|
import type { IsNever, Not } from '@tma.js/util-types';
|
|
3
3
|
import type { ClipboardTextReceivedPayload, CustomMethodInvokedPayload, InvoiceClosedPayload, PhoneRequestedPayload, PopupClosedPayload, QrTextReceivedPayload, ThemeChangedPayload, ViewportChangedPayload, WriteAccessRequestedPayload } from './payloads.js';
|
|
4
4
|
/**
|
|
@@ -50,6 +50,11 @@ export interface Events {
|
|
|
50
50
|
* @see https://docs.telegram-mini-apps.com/apps-communication/events#popup-closed
|
|
51
51
|
*/
|
|
52
52
|
popup_closed: (payload: PopupClosedPayload) => void;
|
|
53
|
+
/**
|
|
54
|
+
* Parent iframe requested current iframe reload.
|
|
55
|
+
* @see https://docs.telegram-mini-apps.com/apps-communication/events#reload-iframe
|
|
56
|
+
*/
|
|
57
|
+
reload_iframe: () => void;
|
|
53
58
|
/**
|
|
54
59
|
* The QR scanner scanned some QR and extracted its content.
|
|
55
60
|
* @param payload - event payload.
|
|
@@ -102,7 +107,7 @@ export interface Events {
|
|
|
102
107
|
/**
|
|
103
108
|
* Any known event name.
|
|
104
109
|
*/
|
|
105
|
-
export type EventName =
|
|
110
|
+
export type EventName = keyof Events;
|
|
106
111
|
/**
|
|
107
112
|
* Parameters of specified event.
|
|
108
113
|
*/
|
|
@@ -42,19 +42,14 @@ export interface QrTextReceivedPayload {
|
|
|
42
42
|
*/
|
|
43
43
|
data?: string;
|
|
44
44
|
}
|
|
45
|
+
export type ThemeParamsKey = 'accent_text_color' | 'bg_color' | 'button_color' | 'button_text_color' | 'destructive_text_color' | 'header_bg_color' | 'hint_color' | 'link_color' | 'secondary_bg_color' | 'section_header_text_color' | 'section_bg_color' | 'subtitle_text_color' | 'text_color';
|
|
45
46
|
export interface ThemeChangedPayload {
|
|
46
47
|
/**
|
|
47
48
|
* Map where the key is a theme stylesheet key and value is the corresponding color in
|
|
48
49
|
* `#RRGGBB` format.
|
|
49
50
|
*/
|
|
50
51
|
theme_params: {
|
|
51
|
-
|
|
52
|
-
text_color?: RGB;
|
|
53
|
-
hint_color?: RGB;
|
|
54
|
-
link_color?: RGB;
|
|
55
|
-
button_color?: RGB;
|
|
56
|
-
button_text_color?: RGB;
|
|
57
|
-
secondary_bg_color?: RGB;
|
|
52
|
+
[Key in ThemeParamsKey]?: RGB;
|
|
58
53
|
};
|
|
59
54
|
}
|
|
60
55
|
export interface ViewportChangedPayload {
|
package/dist/dts/index.d.ts
CHANGED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type Version } from '@tma.js/utils';
|
|
2
|
+
import { type PostEvent } from './index.js';
|
|
3
|
+
/**
|
|
4
|
+
* Creates function which checks if specified method and parameters are supported. In case,
|
|
5
|
+
* method or parameters are unsupported, an error will be thrown.
|
|
6
|
+
* @param version - Telegram Mini Apps version.
|
|
7
|
+
* @throws {MethodUnsupportedError} Method is unsupported.
|
|
8
|
+
* @throws {ParameterUnsupportedError} Method parameter is unsupported.
|
|
9
|
+
*/
|
|
10
|
+
export declare function createPostEvent(version: Version): PostEvent;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
export
|
|
2
|
-
export
|
|
3
|
-
export
|
|
4
|
-
export
|
|
1
|
+
export * from './createPostEvent.js';
|
|
2
|
+
export * from './haptic.js';
|
|
3
|
+
export * from './invoke-custom-method.js';
|
|
4
|
+
export * from './methods.js';
|
|
5
|
+
export * from './popup.js';
|
|
5
6
|
export * from './postEvent.js';
|
|
@@ -12,21 +12,31 @@ export type HeaderColorKey = 'bg_color' | 'secondary_bg_color';
|
|
|
12
12
|
* Chat type which could be used when calling `web_app_switch_inline_query` method.
|
|
13
13
|
*/
|
|
14
14
|
export type SwitchInlineQueryChatType = 'users' | 'bots' | 'groups' | 'channels';
|
|
15
|
-
|
|
16
|
-
params:
|
|
17
|
-
|
|
18
|
-
}
|
|
15
|
+
interface CreateParams<Params = undefined, VersionedParam extends UnionKeys<Params> = never> {
|
|
16
|
+
params: Params;
|
|
17
|
+
versionedParams: VersionedParam;
|
|
18
|
+
}
|
|
19
19
|
/**
|
|
20
20
|
* Describes list of events and their parameters that could be posted by Bridge.
|
|
21
21
|
* @see https://docs.telegram-mini-apps.com/apps-communication/methods
|
|
22
22
|
*/
|
|
23
|
-
export interface
|
|
23
|
+
export interface Methods {
|
|
24
24
|
/**
|
|
25
25
|
* Notifies parent iframe about the current frame is ready. This method is only used in the Web
|
|
26
26
|
* version of Telegram. As a result, Mini App will receive `set_custom_style` event.
|
|
27
27
|
* @see https://docs.telegram-mini-apps.com/apps-communication/methods#iframe-ready
|
|
28
28
|
*/
|
|
29
|
-
iframe_ready: CreateParams
|
|
29
|
+
iframe_ready: CreateParams<{
|
|
30
|
+
/**
|
|
31
|
+
* True, if current Mini App supports native reloading.
|
|
32
|
+
*/
|
|
33
|
+
reload_supported?: boolean;
|
|
34
|
+
} | undefined>;
|
|
35
|
+
/**
|
|
36
|
+
* Notifies parent iframe about the current iframe is going to reload.
|
|
37
|
+
* @see https://docs.telegram-mini-apps.com/apps-communication/methods#iframe-will-reload
|
|
38
|
+
*/
|
|
39
|
+
iframe_will_reload: CreateParams;
|
|
30
40
|
/**
|
|
31
41
|
* Closes Mini App.
|
|
32
42
|
* @see https://docs.telegram-mini-apps.com/apps-communication/methods#web-app-close
|
|
@@ -284,35 +294,37 @@ export interface MethodsParams {
|
|
|
284
294
|
web_app_trigger_haptic_feedback: CreateParams<AnyHapticFeedbackParams>;
|
|
285
295
|
}
|
|
286
296
|
/**
|
|
287
|
-
* Any
|
|
297
|
+
* Any Telegram Mini Apps known method name.
|
|
288
298
|
*/
|
|
289
|
-
export type MethodName = keyof
|
|
299
|
+
export type MethodName = keyof Methods;
|
|
290
300
|
/**
|
|
291
301
|
* Returns parameters for specified post-available event.
|
|
292
302
|
*/
|
|
293
|
-
export type MethodParams<
|
|
303
|
+
export type MethodParams<M extends MethodName> = Methods[M]['params'];
|
|
294
304
|
/**
|
|
295
|
-
*
|
|
305
|
+
* True if specified method accepts parameters.
|
|
296
306
|
*/
|
|
297
|
-
export type
|
|
307
|
+
export type MethodAcceptParams<M extends MethodName> = Not<IsNever<Exclude<MethodParams<M>, undefined>>>;
|
|
298
308
|
/**
|
|
299
309
|
* Any post-available event name which does not require arguments.
|
|
300
310
|
*/
|
|
301
311
|
export type EmptyMethodName = {
|
|
302
|
-
[
|
|
312
|
+
[M in MethodName]: undefined extends MethodParams<M> ? M : never;
|
|
303
313
|
}[MethodName];
|
|
304
314
|
/**
|
|
305
315
|
* Any post-available event name which require arguments.
|
|
306
316
|
*/
|
|
307
|
-
export type NonEmptyMethodName =
|
|
317
|
+
export type NonEmptyMethodName = {
|
|
318
|
+
[M in MethodName]: MethodAcceptParams<M> extends true ? M : never;
|
|
319
|
+
}[MethodName];
|
|
308
320
|
/**
|
|
309
|
-
* Method names which
|
|
321
|
+
* Method names which have versioned params.
|
|
310
322
|
*/
|
|
311
|
-
export type
|
|
312
|
-
[
|
|
323
|
+
export type MethodWithVersionedParams = {
|
|
324
|
+
[M in MethodName]: IsNever<Methods[M]['versionedParams']> extends true ? never : M;
|
|
313
325
|
}[MethodName];
|
|
314
326
|
/**
|
|
315
|
-
* Method
|
|
327
|
+
* Method parameters which appear only in the specific Telegram Mini Apps version.
|
|
316
328
|
*/
|
|
317
|
-
export type
|
|
329
|
+
export type MethodVersionedParams<M extends MethodWithVersionedParams> = Methods[M]['versionedParams'];
|
|
318
330
|
export {};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { EmptyMethodName, MethodParams, NonEmptyMethodName } from './
|
|
1
|
+
import type { EmptyMethodName, MethodParams, NonEmptyMethodName } from './methods.js';
|
|
2
2
|
interface PostEventOptions {
|
|
3
3
|
/**
|
|
4
4
|
* Origin used while posting message. This option is only used in case,
|
package/dist/dts/request.d.ts
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
1
|
import type { And, If, IsNever } from '@tma.js/util-types';
|
|
2
2
|
import { type PostEvent } from './methods/postEvent.js';
|
|
3
3
|
import { type EventName, type EventParams, type EventHasParams } from './events/index.js';
|
|
4
|
-
import type { EmptyMethodName,
|
|
4
|
+
import type { EmptyMethodName, MethodAcceptParams, MethodName, MethodParams, NonEmptyMethodName } from './methods/methods.js';
|
|
5
5
|
/**
|
|
6
6
|
* Names of methods, which require passing "req_id" parameter.
|
|
7
7
|
*/
|
|
8
|
-
type
|
|
9
|
-
[
|
|
8
|
+
type MethodWithRequestId = {
|
|
9
|
+
[M in MethodName]: If<And<MethodAcceptParams<M>, MethodParams<M> extends {
|
|
10
10
|
req_id: string;
|
|
11
|
-
} ? true : false>,
|
|
11
|
+
} ? true : false>, M, never>;
|
|
12
12
|
}[MethodName];
|
|
13
13
|
/**
|
|
14
14
|
* Names of events, which contain "req_id" parameter.
|
|
15
15
|
*/
|
|
16
|
-
type
|
|
17
|
-
[
|
|
16
|
+
type EventWithRequestId = {
|
|
17
|
+
[E in EventName]: If<And<EventHasParams<E>, EventParams<E> extends {
|
|
18
18
|
req_id: string;
|
|
19
|
-
} ? true : false>,
|
|
19
|
+
} ? true : false>, E, never>;
|
|
20
20
|
}[EventName];
|
|
21
21
|
export interface RequestOptions {
|
|
22
22
|
/**
|
|
@@ -45,7 +45,7 @@ export interface RequestOptionsAdvanced<EventPayload> extends RequestOptions {
|
|
|
45
45
|
* @param event - event or events to listen.
|
|
46
46
|
* @param options - additional execution options.
|
|
47
47
|
*/
|
|
48
|
-
export declare function request<
|
|
48
|
+
export declare function request<M extends MethodWithRequestId, E extends EventWithRequestId>(method: M, params: MethodParams<M>, event: E | E[], options?: RequestOptions): Promise<EventParams<E>>;
|
|
49
49
|
/**
|
|
50
50
|
* Calls specified TWA method and captures one of the specified events. Returns promise
|
|
51
51
|
* which will be resolved in case, specified event was captured.
|
|
@@ -53,7 +53,7 @@ export declare function request<Method extends MethodNameWithRequestId, Event ex
|
|
|
53
53
|
* @param event - event or events to listen.
|
|
54
54
|
* @param options - additional execution options.
|
|
55
55
|
*/
|
|
56
|
-
export declare function request<
|
|
56
|
+
export declare function request<M extends EmptyMethodName, E extends EventName>(method: M, event: E | E[], options?: RequestOptionsAdvanced<EventParams<E>>): Promise<EventParams<E>>;
|
|
57
57
|
/**
|
|
58
58
|
* Calls specified TWA method and captures one of the specified events. Returns promise
|
|
59
59
|
* which will be resolved in case, specified event was captured.
|
|
@@ -62,5 +62,5 @@ export declare function request<Method extends EmptyMethodName, Event extends Ev
|
|
|
62
62
|
* @param event - event or events to listen
|
|
63
63
|
* @param options - additional execution options.
|
|
64
64
|
*/
|
|
65
|
-
export declare function request<
|
|
65
|
+
export declare function request<M extends NonEmptyMethodName, E extends EventName>(method: M, params: MethodParams<M>, event: E | E[], options?: RequestOptionsAdvanced<EventParams<E>>): Promise<EventParams<E>>;
|
|
66
66
|
export {};
|
package/dist/dts/supports.d.ts
CHANGED
|
@@ -1,19 +1,12 @@
|
|
|
1
1
|
import { type Version } from '@tma.js/utils';
|
|
2
|
-
import type {
|
|
3
|
-
/**
|
|
4
|
-
* By specified method and parameters extracts properties which could be used by
|
|
5
|
-
* supports function as TWA method parameter.
|
|
6
|
-
* @param method - TWA method.
|
|
7
|
-
* @param params - method parameters.
|
|
8
|
-
*/
|
|
9
|
-
export declare function detectSupportParams<M extends NonEmptyMethodName>(method: M, params: MethodParams<M>): HasCheckSupportMethodParam<HasCheckSupportMethodName>[];
|
|
2
|
+
import type { MethodVersionedParams, MethodWithVersionedParams, MethodName } from './methods/index.js';
|
|
10
3
|
/**
|
|
11
4
|
* Returns true in case, passed parameter in specified method is supported.
|
|
12
5
|
* @param method - method name
|
|
13
6
|
* @param param - method parameter
|
|
14
7
|
* @param inVersion - platform version.
|
|
15
8
|
*/
|
|
16
|
-
export declare function supports<M extends
|
|
9
|
+
export declare function supports<M extends MethodWithVersionedParams>(method: M, param: MethodVersionedParams<M>, inVersion: Version): boolean;
|
|
17
10
|
/**
|
|
18
11
|
* Returns true in case, specified method is supported in passed version.
|
|
19
12
|
* @param method - method name.
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("@tma.js/utils"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("@tma.js/utils"),S=require("@tma.js/logger"),I=require("@tma.js/event-emitter"),o=require("@tma.js/parsing");class g extends Error{constructor(t,r){super(`Method "${t}" is unsupported in the Mini Apps version ${r}.`),Object.setPrototypeOf(this,g.prototype)}}class f extends Error{constructor(t,r,n){super(`Parameter "${r}" in method "${t}" is unsupported in the Mini Apps version ${n}.`),Object.setPrototypeOf(this,f.prototype)}}let j="https://web.telegram.org";const _=new S.Logger("[Bridge]",!1);function J(e){if(e){_.enable();return}_.disable()}function L(e){j=e}function G(){return j}function U(e){return e==null}const s=o.rgb().optional(),H=o.number(),z=o.createValueParserGenerator(e=>e==null?window.innerWidth:H.parse(e)),B=o.json({theme_params:o.json({accent_text_color:s,bg_color:s,button_color:s,button_text_color:s,destructive_text_color:s,header_bg_color:s,hint_color:s,link_color:s,secondary_bg_color:s,section_bg_color:s,section_header_text_color:s,subtitle_text_color:s,text_color:s})}),F=o.json({height:o.number(),width:z(),is_state_stable:o.boolean(),is_expanded:o.boolean()}),K=o.json({button_id:o.string({isEmpty:U}).optional()}),Q=o.json({data:o.string().optional()}),X=o.json({slug:o.string(),status:o.string()}),Y=o.json({req_id:o.string(),data:e=>e===null?e:o.string().optional().parse(e)}),Z=o.json({status:o.string()}),D=o.json({status:o.string()}),V=o.json({req_id:o.string(),result:e=>e,error:o.string().optional()}),O=o.json({eventType:o.string(),eventData:e=>e});function ee(e,t){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:e,eventData:t})}))}function te(){const e=window;"TelegramGameProxy_receiveEvent"in e||[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(t=>{let r=e;t.forEach((n,i,c)=>{if(i===c.length-1){r[n]=ee;return}n in r||(r[n]={}),r=r[n]})})}function re(e){te(),window.addEventListener("message",t=>{try{const{eventType:r,eventData:n}=O.parse(t.data);e(r,n)}catch{}})}const h="__telegram-cached-emitter__";function ne(){const e=new I.EventEmitter,t=(r,...n)=>{_.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})}),re((r,n)=>{_.log("Received raw event:",r,n);try{switch(r){case"viewport_changed":return t(r,F.parse(n));case"theme_changed":return t(r,B.parse(n));case"popup_closed":return n==null?t(r,{}):t(r,K.parse(n));case"set_custom_style":return t(r,o.string().parse(n));case"qr_text_received":return t(r,Q.parse(n));case"clipboard_text_received":return t(r,Y.parse(n));case"invoice_closed":return t(r,X.parse(n));case"phone_requested":return t("phone_requested",D.parse(n));case"custom_method_invoked":return t("custom_method_invoked",V.parse(n));case"write_access_requested":return t("write_access_requested",Z.parse(n));case"main_button_pressed":case"back_button_pressed":case"settings_button_pressed":case"scan_qr_popup_closed":case"reload_iframe":return t(r);default:return t(r,n)}}catch(i){_.error("Error processing event:",i)}}),e}function p(){const e=window;return e[h]===void 0&&(e[h]=ne()),e[h]}function E(e,t){p().off(e,t)}function k(e,t){return p().on(e,t),()=>E(e,t)}function oe(e,t){return p().once(e,t),()=>E(e,t)}function R(e){p().unsubscribe(e)}function ie(e){return p().subscribe(e),()=>R(e)}function a(e,t){return u.compareVersions(e,t)<=0}function y(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_switch_inline_query":return a("6.7",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}}function se(e){return(t,r)=>{if(!y(t,e))throw new g(t,e);if(u.isRecord(r)){let n;if(t==="web_app_open_link"&&"try_instant_view"in r?n="try_instant_view":t==="web_app_set_header_color"&&"color"in r&&(n="color"),n&&!y(t,n,e))throw new f(t,n,e)}return m(t,r)}}function W(e){return"external"in e&&u.isRecord(e.external)&&"notify"in e.external&&typeof e.external.notify=="function"}function A(e){return"TelegramWebviewProxy"in e&&u.isRecord(e.TelegramWebviewProxy)&&"postEvent"in e.TelegramWebviewProxy&&typeof e.TelegramWebviewProxy.postEvent=="function"}function M(){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:c=G()}=n;if(_.log(`Calling method "${e}"`,i),M()){window.parent.postMessage(JSON.stringify({eventType:e,eventData:i}),c);return}if(W(window)){window.external.notify(JSON.stringify({eventType:e,eventData:i}));return}if(A(window)){window.TelegramWebviewProxy.postEvent(e,JSON.stringify(i));return}throw new Error("Unable to determine current environment and possible way to send event.")}function ce(e,t,r,n){let i,c,w,b;typeof t=="string"||Array.isArray(t)?(w=Array.isArray(t)?t:[t],i=r):(c=t,w=Array.isArray(r)?r:[r],i=n),u.isRecord(c)&&typeof c.req_id=="string"&&(b=c.req_id);const{postEvent:$=m,timeout:x}=i||{},q=i&&"capture"in i?i.capture:null,v=new Promise((C,N)=>{const T=w.map(d=>k(d,l=>{typeof b=="string"&&(!u.isRecord(l)||l.req_id!==b)||typeof q=="function"&&!q(l)||(P(),C(l))})),P=()=>T.forEach(d=>d());try{$(e,c)}catch(d){P(),N(d)}});return typeof x=="number"?u.withTimeout(v,x):v}exports.MethodUnsupportedError=g;exports.ParameterUnsupportedError=f;exports.createPostEvent=se;exports.hasExternalNotify=W;exports.hasWebviewProxy=A;exports.isIframe=M;exports.off=E;exports.on=k;exports.once=oe;exports.postEvent=m;exports.request=ce;exports.setDebug=J;exports.setTargetOrigin=L;exports.subscribe=ie;exports.supports=y;exports.unsubscribe=R;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -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 { 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 createValueParserGenerator,\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 = createValueParserGenerator(\n (value) => (value === null || value === undefined\n ? window.innerWidth\n : num.parse(value)),\n);\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 { logger, targetOrigin as globalTargetOrigin } from '../globals.js';\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 Mini 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 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 Mini 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 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 logger.log(`Calling method \"${eventType}\"`, eventData);\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 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_switch_inline_query':\n return lessOrEqual('6.7', 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","createValueParserGenerator","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,2BACvBT,GAAWA,GAAU,KAClB,OAAO,WACPM,EAAI,MAAMN,CAAK,CACrB,EAKaU,EAAsBC,EAAAA,KAA0B,CAC3D,aAAcA,EAAAA,KAAK,CACjB,SAAUP,EACV,WAAYA,EACZ,WAAYA,EACZ,WAAYA,EACZ,aAAcA,EACd,kBAAmBA,EACnB,mBAAoBA,CAAA,CACrB,CACH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I3B,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,8BACI,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/errors/MethodUnsupportedError.ts","../src/errors/ParameterUnsupportedError.ts","../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/supports.ts","../src/methods/createPostEvent.ts","../src/env.ts","../src/methods/postEvent.ts","../src/request.ts"],"sourcesContent":["import type { Version } from '@tma.js/utils';\n\nimport type { MethodName } from '../methods/index.js';\n\n/**\n * Error thrown in case, unsupported method was called.\n */\nexport class MethodUnsupportedError extends Error {\n constructor(method: MethodName, version: Version) {\n super(`Method \"${method}\" is unsupported in the Mini Apps version ${version}.`);\n Object.setPrototypeOf(this, MethodUnsupportedError.prototype);\n }\n}\n","import type { Version } from '@tma.js/utils';\n\nimport type { MethodName } from '../methods/index.js';\n\n/**\n * Error thrown in case, unsupported parameter was used.\n */\nexport class ParameterUnsupportedError extends Error {\n constructor(method: MethodName, param: string, version: Version) {\n super(`Parameter \"${param}\" in method \"${method}\" is unsupported in the Mini Apps version ${version}.`);\n Object.setPrototypeOf(this, ParameterUnsupportedError.prototype);\n }\n}\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 createValueParserGenerator,\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 = createValueParserGenerator(\n (value) => (value === null || value === undefined\n ? window.innerWidth\n : num.parse(value)),\n);\n\n/**\n * Parses incoming value as ThemeChangedPayload.\n */\nexport const themeChangedPayload = json<ThemeChangedPayload>({\n theme_params: json({\n accent_text_color: rgbOptional,\n bg_color: rgbOptional,\n button_color: rgbOptional,\n button_text_color: rgbOptional,\n destructive_text_color: rgbOptional,\n header_bg_color: rgbOptional,\n hint_color: rgbOptional,\n link_color: rgbOptional,\n secondary_bg_color: rgbOptional,\n section_bg_color: rgbOptional,\n section_header_text_color: rgbOptional,\n subtitle_text_color: rgbOptional,\n text_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 case 'reload_iframe':\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 { compareVersions, type Version } from '@tma.js/utils';\n\nimport type {\n MethodVersionedParams,\n MethodWithVersionedParams,\n MethodName,\n} from './methods/index.js';\n\n/**\n * Returns true if \"a\" version is less than or equal to \"b\" version.\n * @param a\n * @param b\n */\nfunction versionLessOrEqual(a: Version, b: Version): boolean {\n return compareVersions(a, b) <= 0;\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 MethodWithVersionedParams>(\n method: M,\n param: MethodVersionedParams<M>,\n inVersion: Version,\n): boolean;\n\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;\n\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 versionLessOrEqual('6.4', inVersion);\n }\n }\n\n if (method === 'web_app_set_header_color') {\n if (paramOrVersion === 'color') {\n return versionLessOrEqual('6.9', inVersion);\n }\n }\n }\n\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 versionLessOrEqual('6.1', paramOrVersion);\n case 'web_app_open_popup':\n return versionLessOrEqual('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 versionLessOrEqual('6.4', paramOrVersion);\n case 'web_app_switch_inline_query':\n return versionLessOrEqual('6.7', paramOrVersion);\n case 'web_app_invoke_custom_method':\n case 'web_app_request_write_access':\n case 'web_app_request_phone':\n return versionLessOrEqual('6.9', paramOrVersion);\n case 'web_app_setup_settings_button':\n return versionLessOrEqual('6.10', paramOrVersion);\n default:\n return true;\n }\n}\n","import { isRecord, type Version } from '@tma.js/utils';\n\nimport { supports } from '../supports.js';\nimport { MethodUnsupportedError, ParameterUnsupportedError } from '../errors/index.js';\nimport { postEvent, type PostEvent } from './index.js';\n\n/**\n * Creates function which checks if specified method and parameters are supported. In case,\n * method or parameters are unsupported, an error will be thrown.\n * @param version - Telegram Mini Apps version.\n * @throws {MethodUnsupportedError} Method is unsupported.\n * @throws {ParameterUnsupportedError} Method parameter is unsupported.\n */\nexport function createPostEvent(version: Version): PostEvent {\n return (method: any, params: any) => {\n // Firstly, check if method itself is supported.\n if (!supports(method, version)) {\n throw new MethodUnsupportedError(method, version);\n }\n\n // Method could use parameters, which are supported only in specific versions of Telegram\n // Mini Apps.\n if (isRecord(params)) {\n let validateParam: string | undefined;\n\n if (method === 'web_app_open_link' && 'try_instant_view' in params) {\n validateParam = 'try_instant_view';\n } else if (method === 'web_app_set_header_color' && 'color' in params) {\n validateParam = 'color';\n }\n\n if (validateParam && !supports(method, validateParam, version)) {\n throw new ParameterUnsupportedError(method, validateParam, version);\n }\n }\n\n return postEvent(method, params);\n };\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 { logger, targetOrigin as globalTargetOrigin } from '../globals.js';\nimport type {\n EmptyMethodName,\n MethodName,\n MethodParams,\n NonEmptyMethodName,\n} from './methods.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 Mini 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 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 Mini 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 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 logger.log(`Calling method \"${eventType}\"`, eventData);\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 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';\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,\n MethodAcceptParams,\n MethodName,\n MethodParams,\n NonEmptyMethodName,\n} from './methods/methods.js';\n\n/**\n * Names of methods, which require passing \"req_id\" parameter.\n */\ntype MethodWithRequestId = {\n [M in MethodName]: If<\n And<MethodAcceptParams<M>, MethodParams<M> extends { req_id: string } ? true : false>,\n M,\n never\n >;\n}[MethodName];\n\n/**\n * Names of events, which contain \"req_id\" parameter.\n */\ntype EventWithRequestId = {\n [E in EventName]: If<\n And<EventHasParams<E>, EventParams<E> extends { req_id: string } ? true : false>,\n E,\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<M extends MethodWithRequestId, E extends EventWithRequestId>(\n method: M,\n params: MethodParams<M>,\n event: E | E[],\n options?: RequestOptions,\n): Promise<EventParams<E>>;\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<M extends EmptyMethodName, E extends EventName>(\n method: M,\n event: E | E[],\n options?: RequestOptionsAdvanced<EventParams<E>>,\n): Promise<EventParams<E>>;\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<M extends NonEmptyMethodName, E extends EventName>(\n method: M,\n params: MethodParams<M>,\n event: E | E[],\n options?: RequestOptionsAdvanced<EventParams<E>>,\n): Promise<EventParams<E>>;\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"],"names":["MethodUnsupportedError","method","version","ParameterUnsupportedError","param","currentTargetOrigin","logger","Logger","setDebug","value","setTargetOrigin","targetOrigin","isNullOrUndefined","rgbOptional","rgb","num","number","windowWidthParser","createValueParserGenerator","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","versionLessOrEqual","a","b","compareVersions","supports","paramOrVersion","inVersion","createPostEvent","params","isRecord","validateParam","postEvent","hasExternalNotify","hasWebviewProxy","isIframe","paramsOrOptions","options","postOptions","globalTargetOrigin","request","eventOrParams","eventOrOptions","executionOptions","methodParams","events","requestId","defaultPostEvent","timeout","capture","promise","res","rej","stoppers","ev","stopListening","stop","e","withTimeout"],"mappings":"6MAOO,MAAMA,UAA+B,KAAM,CAChD,YAAYC,EAAoBC,EAAkB,CAChD,MAAM,WAAWD,CAAM,6CAA6CC,CAAO,GAAG,EACvE,OAAA,eAAe,KAAMF,EAAuB,SAAS,CAC9D,CACF,CCLO,MAAMG,UAAkC,KAAM,CACnD,YAAYF,EAAoBG,EAAeF,EAAkB,CAC/D,MAAM,cAAcE,CAAK,gBAAgBH,CAAM,6CAA6CC,CAAO,GAAG,EAC/F,OAAA,eAAe,KAAMC,EAA0B,SAAS,CACjE,CACF,CCVA,IAAIE,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,2BACvBT,GAAWA,GAAU,KAClB,OAAO,WACPM,EAAI,MAAMN,CAAK,CACrB,EAKaU,EAAsBC,EAAAA,KAA0B,CAC3D,aAAcA,EAAAA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ty,F=(t,e,r)=>e in t?z(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,S=(t,e,r)=>(F(t,typeof e!="symbol"?e+"":e,r),r);let Z=class{constructor(){S(this,"listeners",new Map),S(this,"subscribeListeners",[])}addListener(e,r,n){let i=this.listeners.get(e);return i||(i=[],this.listeners.set(e,i)),i.push([r,n]),()=>this.off(e,r)}emit(e,...r){this.subscribeListeners.forEach(i=>i(e,...r));const n=this.listeners.get(e);n&&n.forEach(([i,s],c)=>{i(...r),s&&n.splice(c,1)})}on(e,r){return this.addListener(e,r,!1)}once(e,r){return this.addListener(e,r,!0)}off(e,r){const n=this.listeners.get(e);if(n){for(let i=0;i<n.length;i+=1)if(r===n[i][0]){n.splice(i,1);return}}}subscribe(e){return this.subscribeListeners.push(e),()=>this.unsubscribe(e)}unsubscribe(e){for(let r=0;r<this.subscribeListeners.length;r+=1)if(this.subscribeListeners[r]===e){this.subscribeListeners.splice(r,1);return}}};function K(t){return/^#[\da-f]{3}$/i.test(t)}function Q(t){return/^#[\da-f]{6}$/i.test(t)}function X(t){const e=t.replace(/\s/g,"").toLowerCase();if(Q(e))return e;if(K(e)){let n="#";for(let i=0;i<3;i+=1)n+=e[1+i].repeat(2);return n}const r=e.match(/^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/)||e.match(/^rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),\d{1,3}\)$/);if(r===null)throw new Error(`Value "${t}" does not satisfy any of known RGB formats.`);return r.slice(1).reduce((n,i)=>{const s=parseInt(i,10).toString(16);return n+(s.length===1?"0":"")+s},"#")}var Y=Object.defineProperty,O=(t,e,r)=>e in t?Y(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,D=(t,e,r)=>(O(t,typeof e!="symbol"?e+"":e,r),r);let k=class H extends Error{constructor(e,{cause:r,type:n}={}){super(`Unable to parse value${n?` as ${n}`:""}`,{cause:r}),D(this,"type"),this.value=e,Object.setPrototypeOf(this,H.prototype),this.type=n}},A=class{constructor(e,r,n,i){this.parser=e,this.isOptional=r,this.isEmpty=n,this.type=i}parse(e){if(!(this.isOptional&&this.isEmpty(e)))try{return this.parser(e)}catch(r){throw new k(e,{type:this.type,cause:r})}}optional(){return this.isOptional=!0,this}};function y(){return new TypeError("Value has unexpected type")}function L(t){return t===void 0}function b(t,{type:e,isEmpty:r=L}={}){return({isEmpty:n=r}={})=>new A(t,!1,n,e)}const N=b(t=>{if(typeof t=="boolean")return t;const e=String(t);if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw y()},{type:"boolean"}),v=b(t=>{if(typeof t=="number")return t;if(typeof t=="string"){const e=Number(t);if(!Number.isNaN(e))return e}throw y()},{type:"number"});v();class g extends Error{constructor(e,{cause:r,type:n}={}){super(`Unable to parse field "${e}"${n?` as ${n}`:""}`,{cause:r}),Object.setPrototypeOf(this,g.prototype)}}function V(t,e){const r={};for(const n in t){const i=t[n];if(!i)continue;let s,c;if(typeof i=="function"||"parse"in i)s=n,c=typeof i=="function"?i:i.parse.bind(i);else{const{type:u}=i;s=i.from||n,c=typeof u=="function"?u:u.parse.bind(u)}let p;const x=e(s);try{p=c(x)}catch(u){throw u instanceof k?new g(s,{type:u.type,cause:u}):new g(s,{cause:u})}p!==void 0&&(r[n]=p)}return r}function l(t,e={}){const{type:r,isEmpty:n=L}=e;return new A(i=>{let s=i;if(typeof s=="string"&&(s=JSON.parse(s)),typeof s!="object"||s===null||Array.isArray(s))throw y();return V(t,c=>s[c])},!1,n,r)}const a=b(t=>{if(typeof t=="string"||typeof t=="number")return t.toString();throw y()},{type:"string"}),ee=a(),te=b(t=>X(ee.parse(t)),{type:"rgb"});class re{constructor(e,r){this.prefix=e,this.enabled=r}print(e,...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[e](`[${i}]`,this.prefix,...r)}disable(){this.enabled=!1}error(...e){this.print("error",...e)}enable(){this.enabled=!0}log(...e){this.print("log",...e)}warn(...e){this.print("warn",...e)}}let j="https://web.telegram.org";const _=new re("[Bridge]",!1);function ne(t){if(t){_.enable();return}_.disable()}function ie(t){j=t}function se(){return j}function oe(t){return t==null}const d=te().optional(),ce=v(),ae=b(t=>t==null?window.innerWidth:ce.parse(t)),ue=l({theme_params:l({bg_color:d,text_color:d,hint_color:d,link_color:d,button_color:d,button_text_color:d,secondary_bg_color:d})}),le=l({height:v(),width:ae(),is_state_stable:N(),is_expanded:N()}),pe=l({button_id:a({isEmpty:oe}).optional()}),fe=l({data:a().optional()}),de=l({slug:a(),status:a()}),_e=l({req_id:a(),data:t=>t===null?t:a().optional().parse(t)}),be=l({status:a()}),he=l({status:a()}),we=l({req_id:a(),result:t=>t,error:a().optional()}),ye=l({eventType:a(),eventData:t=>t});function ge(t,e){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:t,eventData:e})}))}function me(){const t=window;"TelegramGameProxy_receiveEvent"in t||[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(e=>{let r=t;e.forEach((n,i,s)=>{if(i===s.length-1){r[n]=ge;return}n in r||(r[n]={}),r=r[n]})})}function Ee(t){me(),window.addEventListener("message",e=>{try{const{eventType:r,eventData:n}=ye.parse(e.data);t(r,n)}catch{}})}const P="__telegram-cached-emitter__";function ve(){const t=new Z,e=(r,...n)=>{_.log("Emitting processed event:",r,...n),t.emit(r,...n)};return window.addEventListener("resize",()=>{e("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),Ee((r,n)=>{_.log("Received raw event:",r,n);try{switch(r){case"viewport_changed":return e(r,le.parse(n));case"theme_changed":return e(r,ue.parse(n));case"popup_closed":return n==null?e(r,{}):e(r,pe.parse(n));case"set_custom_style":return e(r,a().parse(n));case"qr_text_received":return e(r,fe.parse(n));case"clipboard_text_received":return e(r,_e.parse(n));case"invoice_closed":return e(r,de.parse(n));case"phone_requested":return e("phone_requested",he.parse(n));case"custom_method_invoked":return e("custom_method_invoked",we.parse(n));case"write_access_requested":return e("write_access_requested",be.parse(n));case"main_button_pressed":case"back_button_pressed":case"settings_button_pressed":case"scan_qr_popup_closed":return e(r);default:return e(r,n)}}catch(i){_.error("Error processing event:",i)}}),t}function h(){const t=window;return t[P]===void 0&&(t[P]=ve()),t[P]}function $(t,e){h().off(t,e)}function T(t,e){return h().on(t,e),()=>$(t,e)}function Pe(t,e){return h().once(t,e),()=>$(t,e)}function W(t){h().unsubscribe(t)}function $e(t){return h().subscribe(t),()=>W(t)}function m(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function qe(t,e){const r=t.split("."),n=e.split("."),i=Math.max(r.length,n.length);for(let s=0;s<i;s+=1){const c=parseInt(r[s]||"0",10),p=parseInt(n[s]||"0",10);if(c!==p)return c>p?1:-1}return 0}class q extends Error{constructor(e){super(`Async call timeout exceeded. Timeout: ${e}`),Object.setPrototypeOf(this,q.prototype)}}function C(t){return new Promise((e,r)=>{setTimeout(r,t,new q(t))})}function xe(t,e){return typeof t=="function"?(...r)=>Promise.race([t(...r),C(e)]):Promise.race([t,C(e)])}function I(t){return"external"in t&&m(t.external)&&"notify"in t.external&&typeof t.external.notify=="function"}function R(t){return"TelegramWebviewProxy"in t&&m(t.TelegramWebviewProxy)&&"postEvent"in t.TelegramWebviewProxy&&typeof t.TelegramWebviewProxy.postEvent=="function"}function M(){try{return window.self!==window.top}catch{return!0}}function J(t,e,r){let n={},i;e===void 0&&r===void 0?n={}:e!==void 0&&r!==void 0?(n=r,i=e):e!==void 0&&("targetOrigin"in e?n=e:i=e);const{targetOrigin:s=se()}=n;if(_.log(`Calling method "${t}"`,i),M()){window.parent.postMessage(JSON.stringify({eventType:t,eventData:i}),s);return}if(I(window)){window.external.notify(JSON.stringify({eventType:t,eventData:i}));return}if(R(window)){window.TelegramWebviewProxy.postEvent(t,JSON.stringify(i));return}throw new Error("Unable to determine current environment and possible way to send event.")}function Se(t,e,r,n){let i,s,c,p;typeof e=="string"||Array.isArray(e)?(c=Array.isArray(e)?e:[e],i=r):(s=e,c=Array.isArray(r)?r:[r],i=n),m(s)&&typeof s.req_id=="string"&&(p=s.req_id);const{postEvent:x=J,timeout:u}=i||{},G=i&&"capture"in i?i.capture:null,U=new Promise((Le,Ne)=>{const je=c.map(w=>T(w,E=>{typeof p=="string"&&(!m(E)||E.req_id!==p)||typeof G=="function"&&!G(E)||(B(),Le(E))})),B=()=>je.forEach(w=>w());try{x(t,s)}catch(w){B(),Ne(w)}});return typeof u=="number"?xe(U,u):U}function f(t,e){return qe(t,e)<=0}function ke(t,e){return t==="web_app_open_link"&&"try_instant_view"in e?["try_instant_view"]:t==="web_app_set_header_color"&&"color"in e?["color"]:[]}function Ae(t,e,r){if(typeof r=="string"){if(t==="web_app_open_link"&&e==="try_instant_view")return f("6.4",r);if(t==="web_app_set_header_color"&&e==="color")return f("6.9",r)}switch(t){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 f("6.1",e);case"web_app_open_popup":return f("6.2",e);case"web_app_close_scan_qr_popup":case"web_app_open_scan_qr_popup":case"web_app_read_text_from_clipboard":return f("6.4",e);case"web_app_switch_inline_query":return f("6.7",e);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return f("6.9",e);case"web_app_setup_settings_button":return f("6.10",e);default:return!0}}return o.detectSupportParams=ke,o.hasExternalNotify=I,o.hasWebviewProxy=R,o.isIframe=M,o.off=$,o.on=T,o.once=Pe,o.postEvent=J,o.request=Se,o.setDebug=ne,o.setTargetOrigin=ie,o.subscribe=$e,o.supports=Ae,o.unsubscribe=W,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"}),o}({});
|
|
1
|
+
this.tmajs=this.tmajs||{};this.tmajs.bridge=function(o){"use strict";class g extends Error{constructor(e,r){super(`Method "${e}" is unsupported in the Mini Apps version ${r}.`),Object.setPrototypeOf(this,g.prototype)}}class m extends Error{constructor(e,r,n){super(`Parameter "${r}" in method "${e}" is unsupported in the Mini Apps version ${n}.`),Object.setPrototypeOf(this,m.prototype)}}var Z=Object.defineProperty,K=(t,e,r)=>e in t?Z(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,N=(t,e,r)=>(K(t,typeof e!="symbol"?e+"":e,r),r);let Q=class{constructor(){N(this,"listeners",new Map),N(this,"subscribeListeners",[])}addListener(e,r,n){let i=this.listeners.get(e);return i||(i=[],this.listeners.set(e,i)),i.push([r,n]),()=>this.off(e,r)}emit(e,...r){this.subscribeListeners.forEach(i=>i(e,...r));const n=this.listeners.get(e);n&&n.forEach(([i,s],c)=>{i(...r),s&&n.splice(c,1)})}on(e,r){return this.addListener(e,r,!1)}once(e,r){return this.addListener(e,r,!0)}off(e,r){const n=this.listeners.get(e);if(n){for(let i=0;i<n.length;i+=1)if(r===n[i][0]){n.splice(i,1);return}}}subscribe(e){return this.subscribeListeners.push(e),()=>this.unsubscribe(e)}unsubscribe(e){for(let r=0;r<this.subscribeListeners.length;r+=1)if(this.subscribeListeners[r]===e){this.subscribeListeners.splice(r,1);return}}};function X(t){return/^#[\da-f]{3}$/i.test(t)}function Y(t){return/^#[\da-f]{6}$/i.test(t)}function D(t){const e=t.replace(/\s/g,"").toLowerCase();if(Y(e))return e;if(X(e)){let n="#";for(let i=0;i<3;i+=1)n+=e[1+i].repeat(2);return n}const r=e.match(/^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/)||e.match(/^rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),\d{1,3}\)$/);if(r===null)throw new Error(`Value "${t}" does not satisfy any of known RGB formats.`);return r.slice(1).reduce((n,i)=>{const s=parseInt(i,10).toString(16);return n+(s.length===1?"0":"")+s},"#")}var V=Object.defineProperty,ee=(t,e,r)=>e in t?V(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,te=(t,e,r)=>(ee(t,typeof e!="symbol"?e+"":e,r),r);let S=class F extends Error{constructor(e,{cause:r,type:n}={}){super(`Unable to parse value${n?` as ${n}`:""}`,{cause:r}),te(this,"type"),this.value=e,Object.setPrototypeOf(this,F.prototype),this.type=n}},M=class{constructor(e,r,n,i){this.parser=e,this.isOptional=r,this.isEmpty=n,this.type=i}parse(e){if(!(this.isOptional&&this.isEmpty(e)))try{return this.parser(e)}catch(r){throw new S(e,{type:this.type,cause:r})}}optional(){return this.isOptional=!0,this}};function E(){return new TypeError("Value has unexpected type")}function T(t){return t===void 0}function b(t,{type:e,isEmpty:r=T}={}){return({isEmpty:n=r}={})=>new M(t,!1,n,e)}const W=b(t=>{if(typeof t=="boolean")return t;const e=String(t);if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw E()},{type:"boolean"}),$=b(t=>{if(typeof t=="number")return t;if(typeof t=="string"){const e=Number(t);if(!Number.isNaN(e))return e}throw E()},{type:"number"});$();class v extends Error{constructor(e,{cause:r,type:n}={}){super(`Unable to parse field "${e}"${n?` as ${n}`:""}`,{cause:r}),Object.setPrototypeOf(this,v.prototype)}}function re(t,e){const r={};for(const n in t){const i=t[n];if(!i)continue;let s,c;if(typeof i=="function"||"parse"in i)s=n,c=typeof i=="function"?i:i.parse.bind(i);else{const{type:l}=i;s=i.from||n,c=typeof l=="function"?l:l.parse.bind(l)}let f;const k=e(s);try{f=c(k)}catch(l){throw l instanceof S?new v(s,{type:l.type,cause:l}):new v(s,{cause:l})}f!==void 0&&(r[n]=f)}return r}function p(t,e={}){const{type:r,isEmpty:n=T}=e;return new M(i=>{let s=i;if(typeof s=="string"&&(s=JSON.parse(s)),typeof s!="object"||s===null||Array.isArray(s))throw E();return re(t,c=>s[c])},!1,n,r)}const a=b(t=>{if(typeof t=="string"||typeof t=="number")return t.toString();throw E()},{type:"string"}),ne=a(),ie=b(t=>D(ne.parse(t)),{type:"rgb"});class se{constructor(e,r){this.prefix=e,this.enabled=r}print(e,...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[e](`[${i}]`,this.prefix,...r)}disable(){this.enabled=!1}error(...e){this.print("error",...e)}enable(){this.enabled=!0}log(...e){this.print("log",...e)}warn(...e){this.print("warn",...e)}}let C="https://web.telegram.org";const _=new se("[Bridge]",!1);function oe(t){if(t){_.enable();return}_.disable()}function ce(t){C=t}function ae(){return C}function ue(t){return t==null}const u=ie().optional(),le=$(),pe=b(t=>t==null?window.innerWidth:le.parse(t)),fe=p({theme_params:p({accent_text_color:u,bg_color:u,button_color:u,button_text_color:u,destructive_text_color:u,header_bg_color:u,hint_color:u,link_color:u,secondary_bg_color:u,section_bg_color:u,section_header_text_color:u,subtitle_text_color:u,text_color:u})}),de=p({height:$(),width:pe(),is_state_stable:W(),is_expanded:W()}),_e=p({button_id:a({isEmpty:ue}).optional()}),be=p({data:a().optional()}),he=p({slug:a(),status:a()}),we=p({req_id:a(),data:t=>t===null?t:a().optional().parse(t)}),ye=p({status:a()}),ge=p({status:a()}),me=p({req_id:a(),result:t=>t,error:a().optional()}),Ee=p({eventType:a(),eventData:t=>t});function ve(t,e){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:t,eventData:e})}))}function Pe(){const t=window;"TelegramGameProxy_receiveEvent"in t||[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(e=>{let r=t;e.forEach((n,i,s)=>{if(i===s.length-1){r[n]=ve;return}n in r||(r[n]={}),r=r[n]})})}function $e(t){Pe(),window.addEventListener("message",e=>{try{const{eventType:r,eventData:n}=Ee.parse(e.data);t(r,n)}catch{}})}const x="__telegram-cached-emitter__";function xe(){const t=new Q,e=(r,...n)=>{_.log("Emitting processed event:",r,...n),t.emit(r,...n)};return window.addEventListener("resize",()=>{e("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),$e((r,n)=>{_.log("Received raw event:",r,n);try{switch(r){case"viewport_changed":return e(r,de.parse(n));case"theme_changed":return e(r,fe.parse(n));case"popup_closed":return n==null?e(r,{}):e(r,_e.parse(n));case"set_custom_style":return e(r,a().parse(n));case"qr_text_received":return e(r,be.parse(n));case"clipboard_text_received":return e(r,we.parse(n));case"invoice_closed":return e(r,he.parse(n));case"phone_requested":return e("phone_requested",ge.parse(n));case"custom_method_invoked":return e("custom_method_invoked",me.parse(n));case"write_access_requested":return e("write_access_requested",ye.parse(n));case"main_button_pressed":case"back_button_pressed":case"settings_button_pressed":case"scan_qr_popup_closed":case"reload_iframe":return e(r);default:return e(r,n)}}catch(i){_.error("Error processing event:",i)}}),t}function h(){const t=window;return t[x]===void 0&&(t[x]=xe()),t[x]}function q(t,e){h().off(t,e)}function I(t,e){return h().on(t,e),()=>q(t,e)}function qe(t,e){return h().once(t,e),()=>q(t,e)}function R(t){h().unsubscribe(t)}function Ae(t){return h().subscribe(t),()=>R(t)}function w(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Le(t,e){const r=t.split("."),n=e.split("."),i=Math.max(r.length,n.length);for(let s=0;s<i;s+=1){const c=parseInt(r[s]||"0",10),f=parseInt(n[s]||"0",10);if(c!==f)return c>f?1:-1}return 0}class A extends Error{constructor(e){super(`Async call timeout exceeded. Timeout: ${e}`),Object.setPrototypeOf(this,A.prototype)}}function U(t){return new Promise((e,r)=>{setTimeout(r,t,new A(t))})}function je(t,e){return typeof t=="function"?(...r)=>Promise.race([t(...r),U(e)]):Promise.race([t,U(e)])}function d(t,e){return Le(t,e)<=0}function L(t,e,r){if(typeof r=="string"){if(t==="web_app_open_link"&&e==="try_instant_view")return d("6.4",r);if(t==="web_app_set_header_color"&&e==="color")return d("6.9",r)}switch(t){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 d("6.1",e);case"web_app_open_popup":return d("6.2",e);case"web_app_close_scan_qr_popup":case"web_app_open_scan_qr_popup":case"web_app_read_text_from_clipboard":return d("6.4",e);case"web_app_switch_inline_query":return d("6.7",e);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return d("6.9",e);case"web_app_setup_settings_button":return d("6.10",e);default:return!0}}function ke(t){return(e,r)=>{if(!L(e,t))throw new g(e,t);if(w(r)){let n;if(e==="web_app_open_link"&&"try_instant_view"in r?n="try_instant_view":e==="web_app_set_header_color"&&"color"in r&&(n="color"),n&&!L(e,n,t))throw new m(e,n,t)}return j(e,r)}}function J(t){return"external"in t&&w(t.external)&&"notify"in t.external&&typeof t.external.notify=="function"}function G(t){return"TelegramWebviewProxy"in t&&w(t.TelegramWebviewProxy)&&"postEvent"in t.TelegramWebviewProxy&&typeof t.TelegramWebviewProxy.postEvent=="function"}function B(){try{return window.self!==window.top}catch{return!0}}function j(t,e,r){let n={},i;e===void 0&&r===void 0?n={}:e!==void 0&&r!==void 0?(n=r,i=e):e!==void 0&&("targetOrigin"in e?n=e:i=e);const{targetOrigin:s=ae()}=n;if(_.log(`Calling method "${t}"`,i),B()){window.parent.postMessage(JSON.stringify({eventType:t,eventData:i}),s);return}if(J(window)){window.external.notify(JSON.stringify({eventType:t,eventData:i}));return}if(G(window)){window.TelegramWebviewProxy.postEvent(t,JSON.stringify(i));return}throw new Error("Unable to determine current environment and possible way to send event.")}function Ne(t,e,r,n){let i,s,c,f;typeof e=="string"||Array.isArray(e)?(c=Array.isArray(e)?e:[e],i=r):(s=e,c=Array.isArray(r)?r:[r],i=n),w(s)&&typeof s.req_id=="string"&&(f=s.req_id);const{postEvent:k=j,timeout:l}=i||{},H=i&&"capture"in i?i.capture:null,O=new Promise((Se,Me)=>{const Te=c.map(y=>I(y,P=>{typeof f=="string"&&(!w(P)||P.req_id!==f)||typeof H=="function"&&!H(P)||(z(),Se(P))})),z=()=>Te.forEach(y=>y());try{k(t,s)}catch(y){z(),Me(y)}});return typeof l=="number"?je(O,l):O}return o.MethodUnsupportedError=g,o.ParameterUnsupportedError=m,o.createPostEvent=ke,o.hasExternalNotify=J,o.hasWebviewProxy=G,o.isIframe=B,o.off=q,o.on=I,o.once=qe,o.postEvent=j,o.request=Ne,o.setDebug=oe,o.setTargetOrigin=ce,o.subscribe=Ae,o.supports=L,o.unsubscribe=R,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"}),o}({});
|
|
2
2
|
//# sourceMappingURL=index.iife.js.map
|