bm-webapp-sdk 0.1.9 → 0.2.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/README.md CHANGED
@@ -69,6 +69,10 @@ param name by setting `botTokenParamName` option. Also, project can have only on
69
69
 
70
70
  __Remember that you have still to include telegram mini app scripts to enable telegram support.__
71
71
 
72
+ ### MAX bot support
73
+
74
+ This library works with [MAX Bridge](https://dev.max.ru/docs/webapps/bridge) also. But you need to specify `botTokenParamName` -- parameter that holds MAX bot token in your project.
75
+
72
76
  ## Request timeout
73
77
 
74
78
  This library automatically handles request timeout which is 20s by default. If scenario is handling request too long,
@@ -1 +1 @@
1
- (()=>{"use strict";var t={d:(e,s)=>{for(var i in s)t.o(s,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:s[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{WebAppHandler:()=>i});const s={retryDelayOnTimeout:2e3,requestTimeout:6e4,apiEndpoint:"https://console.bot-marketing.com/api/public"};class i{constructor(t){this.options={...s,...t}}isActive(){var t;return"active"===(null===(t=this.data)||void 0===t?void 0:t.statusName)}getVariable(t){var e;return((null===(e=this.data)||void 0===e?void 0:e.variables)||{})[t]}async init(){if(this.data)throw new Error("Handler already initialized");if(this.options.sessionHash)return await this.refreshData(),!this.isActive()&&this.isTelegramInitAvailable()?this.initNewSession():this;if(this.isTelegramInitAvailable())return this.initNewSession();throw new Error("Failed to init handler. You must specify `sessionHash`, or `scenarioCode` when working with Telegram")}async refreshData(){var t;const e=(null===(t=this.data)||void 0===t?void 0:t.hash)||this.options.sessionHash;if(!e)throw new Error("Cannot refresh data: session id is missing");try{return this.data=await this.makeRequest("GET",`tunnelSessions/${e}`),this}catch(t){throw new Error(`Failed to get session data: ${t.message}`)}}requestResponse(){return this.options.responseVar?"function"==typeof this.options.responseVar?this.options.responseVar(this):(this.data.variables||{})[this.options.responseVar]:this}async request(t,e,s){if(this.currentRequest)throw new Error("Please wait until pending request is finished");if(this.data||await this.init(),!this.isActive())throw new Error("Cannot make request: session is not active");if(s)return this.makeRequest("POST",`tunnelSessions/${this.data.hash}/request`,{code:t,params:e}),this;try{return this.currentRequest={controller:new AbortController,timeoutId:setTimeout((()=>this.abort()),this.options.requestTimeout)},this.data=await this.makeRequest("POST",`tunnelSessions/${this.data.hash}/request`,{code:t,params:e},this.currentRequest.controller.signal),this.currentRequest=null,this.requestResponse()}catch(t){if("request_timeout"===t.message)return this.waitUntilSessionFinishesTransition();throw this.currentRequest=null,t}}abort(){this.currentRequest&&(this.currentRequest.controller?this.currentRequest.controller.abort("Request timeout"):(clearTimeout(this.currentRequest.retryTimeoutId),this.currentRequest.reject("Request timeout"),this.currentRequest=null))}isTelegramInitAvailable(){return void 0!==window.Telegram&&void 0!==this.options.scenarioCode}async initNewSession(){try{return this.data=await this.makeRequest("POST",`tunnel/${this.options.scenarioCode}/initWebApp`,{initData:Telegram.WebApp.initData,botTokenParamName:this.options.botTokenParamName,variables:this.options.initVariables}),this}catch(t){throw new Error(`Failed to init new session: ${t.message}`)}}async makeRequest(t,e,s,i){const r=await fetch(`${this.options.apiEndpoint}/${e}`,{method:t,signal:i,..."POST"===t?{body:JSON.stringify(s),headers:{"Content-Type":"application/json",Accept:"application/json"}}:{headers:{Accept:"application/json"}}});if(r.status>=400){const t=await r.json();throw new Error(t.message||`Http Error ${r.status}`)}return r.json()}waitUntilSessionFinishesTransition(){return new Promise(((t,e)=>{this.currentRequest.reject=e;const s=()=>{this.currentRequest.retryTimeoutId=setTimeout((async()=>{if(await this.refreshData(),this.data.isTransitioning)s();else try{t(this.requestResponse())}catch(t){e(t)}}),this.options.retryDelayOnTimeout)};s()}))}}window.BotMarketing=e})();
1
+ (()=>{"use strict";var t={d:(e,s)=>{for(var i in s)t.o(s,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:s[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{WebAppHandler:()=>i});const s={retryDelayOnTimeout:2e3,requestTimeout:6e4,apiEndpoint:"https://console.bot-marketing.com/api/public"};class i{constructor(t){this.options={...s,...t}}isActive(){var t;return"active"===(null===(t=this.data)||void 0===t?void 0:t.statusName)}getVariable(t){var e;return((null===(e=this.data)||void 0===e?void 0:e.variables)||{})[t]}async init(){if(this.data)throw new Error("Handler already initialized");if(this.options.sessionHash)return await this.refreshData(),!this.isActive()&&this.isWebAppInitAvailable()?this.initNewSession():this;if(this.isWebAppInitAvailable())return this.initNewSession();throw new Error("Failed to init handler. You must specify `sessionHash`, or `scenarioCode` when working with Telegram")}async refreshData(){var t;const e=(null===(t=this.data)||void 0===t?void 0:t.hash)||this.options.sessionHash;if(!e)throw new Error("Cannot refresh data: session id is missing");try{return this.data=await this.makeRequest("GET",`tunnelSessions/${e}`),this}catch(t){throw new Error(`Failed to get session data: ${t.message}`)}}requestResponse(){return this.options.responseVar?"function"==typeof this.options.responseVar?this.options.responseVar(this):(this.data.variables||{})[this.options.responseVar]:this}async request(t,e,s){if(this.currentRequest)throw new Error("Please wait until pending request is finished");if(this.data||await this.init(),!this.isActive())throw new Error("Cannot make request: session is not active");if(s)return this.makeRequest("POST",`tunnelSessions/${this.data.hash}/request`,{code:t,params:e}),this;try{return this.currentRequest={controller:new AbortController,timeoutId:setTimeout((()=>this.abort()),this.options.requestTimeout)},this.data=await this.makeRequest("POST",`tunnelSessions/${this.data.hash}/request`,{code:t,params:e},this.currentRequest.controller.signal),this.currentRequest=null,this.requestResponse()}catch(t){if("request_timeout"===t.message)return this.waitUntilSessionFinishesTransition();throw this.currentRequest=null,t}}abort(){this.currentRequest&&(this.currentRequest.controller?this.currentRequest.controller.abort("Request timeout"):(clearTimeout(this.currentRequest.retryTimeoutId),this.currentRequest.reject("Request timeout"),this.currentRequest=null))}getWebAppInstance(){return void 0!==window.Telegram?window.Telegram.WebApp:window.WebApp}isWebAppInitAvailable(){return this.getWebAppInstance()&&void 0!==this.options.scenarioCode}async initNewSession(){try{return this.data=await this.makeRequest("POST",`tunnel/${this.options.scenarioCode}/initWebApp`,{initData:this.getWebAppInstance().initData,botTokenParamName:this.options.botTokenParamName,variables:this.options.initVariables}),this}catch(t){throw new Error(`Failed to init new session: ${t.message}`)}}async makeRequest(t,e,s,i){const r=await fetch(`${this.options.apiEndpoint}/${e}`,{method:t,signal:i,..."POST"===t?{body:JSON.stringify(s),headers:{"Content-Type":"application/json",Accept:"application/json"}}:{headers:{Accept:"application/json"}}});if(r.status>=400){const t=await r.json();throw new Error(t.message||`Http Error ${r.status}`)}return r.json()}waitUntilSessionFinishesTransition(){return new Promise(((t,e)=>{this.currentRequest.reject=e;const s=()=>{this.currentRequest.retryTimeoutId=setTimeout((async()=>{if(await this.refreshData(),this.data.isTransitioning)s();else try{t(this.requestResponse())}catch(t){e(t)}}),this.options.retryDelayOnTimeout)};s()}))}}window.BotMarketing=e})();
package/dist/index.d.ts CHANGED
@@ -44,6 +44,9 @@ export interface ICurrentRequest {
44
44
  retryTimeoutId?: number;
45
45
  reject?: (reason?: any) => void;
46
46
  }
47
+ export interface IWebApp {
48
+ initData: string;
49
+ }
47
50
  export default class WebAppHandler {
48
51
  readonly options: HandlerOptions;
49
52
  data?: ScenarioSession;
@@ -56,7 +59,8 @@ export default class WebAppHandler {
56
59
  protected requestResponse(): WebAppHandler | any;
57
60
  request(code: string, params?: TData, async?: boolean): Promise<WebAppHandler | any>;
58
61
  abort(): void;
59
- isTelegramInitAvailable(): boolean;
62
+ getWebAppInstance(): IWebApp | null;
63
+ isWebAppInitAvailable(): boolean;
60
64
  protected initNewSession(): Promise<WebAppHandler>;
61
65
  protected makeRequest(method: string, path: string, json?: TData, signal?: AbortSignal): Promise<any>;
62
66
  private waitUntilSessionFinishesTransition;
@@ -65,7 +69,10 @@ export default class WebAppHandler {
65
69
  export { WebAppHandler };
66
70
  declare global {
67
71
  interface Window {
68
- Telegram: any;
72
+ Telegram: {
73
+ WebApp: IWebApp;
74
+ } | undefined;
75
+ WebApp: IWebApp | undefined;
69
76
  }
70
77
  }
71
78
 
@@ -44,6 +44,9 @@ export interface ICurrentRequest {
44
44
  retryTimeoutId?: number;
45
45
  reject?: (reason?: any) => void;
46
46
  }
47
+ export interface IWebApp {
48
+ initData: string;
49
+ }
47
50
  export default class WebAppHandler {
48
51
  readonly options: HandlerOptions;
49
52
  data?: ScenarioSession;
@@ -56,7 +59,8 @@ export default class WebAppHandler {
56
59
  protected requestResponse(): WebAppHandler | any;
57
60
  request(code: string, params?: TData, async?: boolean): Promise<WebAppHandler | any>;
58
61
  abort(): void;
59
- isTelegramInitAvailable(): boolean;
62
+ getWebAppInstance(): IWebApp | null;
63
+ isWebAppInitAvailable(): boolean;
60
64
  protected initNewSession(): Promise<WebAppHandler>;
61
65
  protected makeRequest(method: string, path: string, json?: TData, signal?: AbortSignal): Promise<any>;
62
66
  private waitUntilSessionFinishesTransition;
@@ -20,11 +20,11 @@ export default class WebAppHandler {
20
20
  throw new Error("Handler already initialized");
21
21
  if (this.options.sessionHash) {
22
22
  await this.refreshData();
23
- if (!this.isActive() && this.isTelegramInitAvailable())
23
+ if (!this.isActive() && this.isWebAppInitAvailable())
24
24
  return this.initNewSession();
25
25
  return this;
26
26
  }
27
- else if (this.isTelegramInitAvailable()) {
27
+ else if (this.isWebAppInitAvailable()) {
28
28
  return this.initNewSession();
29
29
  }
30
30
  else {
@@ -95,13 +95,16 @@ export default class WebAppHandler {
95
95
  this.currentRequest = null;
96
96
  }
97
97
  }
98
- isTelegramInitAvailable() {
99
- return window.Telegram !== undefined && this.options.scenarioCode !== undefined;
98
+ getWebAppInstance() {
99
+ return window.Telegram !== undefined ? window.Telegram.WebApp : window.WebApp;
100
+ }
101
+ isWebAppInitAvailable() {
102
+ return this.getWebAppInstance() && this.options.scenarioCode !== undefined;
100
103
  }
101
104
  async initNewSession() {
102
105
  try {
103
106
  this.data = await this.makeRequest("POST", `tunnel/${this.options.scenarioCode}/initWebApp`, {
104
- initData: Telegram.WebApp.initData,
107
+ initData: this.getWebAppInstance().initData,
105
108
  botTokenParamName: this.options.botTokenParamName,
106
109
  variables: this.options.initVariables,
107
110
  });
@@ -141,6 +144,7 @@ export default class WebAppHandler {
141
144
  resetTimeout();
142
145
  }
143
146
  else {
147
+ this.currentRequest = null;
144
148
  try {
145
149
  resolve(this.requestResponse());
146
150
  }
package/es2019/index.d.ts CHANGED
@@ -1,7 +1,10 @@
1
- import WebAppHandler from './WebAppHandler';
1
+ import WebAppHandler, { IWebApp } from './WebAppHandler';
2
2
  export { WebAppHandler };
3
3
  declare global {
4
4
  interface Window {
5
- Telegram: any;
5
+ Telegram: {
6
+ WebApp: IWebApp;
7
+ } | undefined;
8
+ WebApp: IWebApp | undefined;
6
9
  }
7
10
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bm-webapp-sdk",
3
- "version": "0.1.9",
3
+ "version": "0.2.0",
4
4
  "description": "",
5
5
  "main": "src/index.ts",
6
6
  "types": "dist/index.d.ts",
package/src/index.ts CHANGED
@@ -1,9 +1,13 @@
1
- import WebAppHandler from './WebAppHandler';
1
+ import WebAppHandler, { IWebApp } from './WebAppHandler';
2
2
 
3
3
  export { WebAppHandler };
4
4
 
5
5
  declare global {
6
6
  interface Window {
7
- Telegram: any;
7
+ Telegram: {
8
+ WebApp: IWebApp;
9
+ }|undefined;
10
+
11
+ WebApp: IWebApp|undefined;
8
12
  }
9
13
  }