@omnizapi/connect
Version:
Omnizapi SDK for browser applications
2 lines (1 loc) • 21.7 kB
JavaScript
;(()=>{var r=class extends Error{constructor(e,t){super(t);this.code=e;this.name="OmnizapiError"}};var fe={PRODUCTION:{api:"https://api.omni.z-api.io",front:"https://app.omni.z-api.io"},STAGING:{api:"https://api.staging.omni.z-api.io",front:"https://app.staging.omni.z-api.io"},SANDBOX:{api:"",front:""}},pe=({environment:o="PRODUCTION",apiUrl:n,frontUrl:e}={})=>{if(!Object.prototype.hasOwnProperty.call(fe,o))throw new r("INVALID_CONFIGURATION","Unknown environment.");let t=fe[o],i={api:n!=null?n:t.api,front:e!=null?e:t.front};for(let a of["api","front"]){let l;try{l=new URL(i[a])}catch(c){throw new r("INVALID_CONFIGURATION",`A valid ${a}Url is required for this environment.`)}if(!["http:","https:"].includes(l.protocol)||l.username||l.password||l.href.includes("?")||l.href.includes("#"))throw new r("INVALID_CONFIGURATION",`${a}Url must be an HTTP(S) base URL without credentials, query or fragment.`);i[a]=l.href.replace(/\/+$/,"")}return i};var he="omnizapi-wildcard-label";function Ce(o){let n=o.trim();if(!n)return null;let e=n.indexOf("://"),t=e<0?"https":n.slice(0,e).toLowerCase();if(t!=="https"&&t!=="http")return null;let i=e<0?n:n.slice(e+3),a=i.startsWith("*."),l=a?i.slice(2):i,c=l.split(/[/\\?#]/,1)[0];if(c.includes("*")||c.includes("@"))return null;let d;try{d=new URL(`${t}://${a?`${he}.`:""}${l}`)}catch(A){return null}if(d.username||d.password)return null;let s=d.hostname;if(a){let A=`${he}.`;if(!s.startsWith(A)||(s=s.slice(A.length),s.split(".").filter(Boolean).length<2))return null}return{protocol:d.protocol,hostname:s,port:d.port,wildcard:a}}function De(o,n){return n.protocol!==o.protocol||n.port!==o.port?!1:o.wildcard?n.hostname.endsWith(`.${o.hostname}`):n.hostname===o.hostname}function me(o,n){let e;try{e=new URL(o)}catch(t){return!1}return e.origin==="null"?!1:n.some(t=>{let i=Ce(t);return i!==null&&De(i,e)})}var be=Symbol.for("omnizapi.connect.runtime.v1");function $(o){var t,i,a;let n=o,e=n[be];return e||(e={nativeLoginPending:!1,failedFacebookScripts:new WeakSet,erroredFacebookScripts:new WeakSet,facebookAppIds:new WeakMap,facebookInitObservers:new WeakMap},Object.defineProperty(n,be,{configurable:!0,value:e})),(t=e.facebookAppIds)!=null||(e.facebookAppIds=new WeakMap),(i=e.facebookInitObservers)!=null||(e.facebookInitObservers=new WeakMap),(a=e.erroredFacebookScripts)!=null||(e.erroredFacebookScripts=new WeakSet),e}function Ie(o){return!!o&&!("__buffer"in o)&&typeof o.init=="function"&&typeof o.login=="function"}function we(o,n){var e;try{let t=Object.getOwnPropertyDescriptor(n,"init"),i=o.facebookInitObservers.get(n);if(i){if((t==null?void 0:t.value)!==i.init)throw new Error("FB.init was replaced.");return i}if(!t||typeof t.value!="function"||!t.writable&&!t.configurable)throw new Error("FB.init cannot be observed.");let a=t.value,l={calls:0,init:function(...c){return l.calls++,o.facebookAppIds.delete(n),Reflect.apply(a,this,c)}};if(Object.defineProperty(n,"init",{...t,value:l.init}),((e=Object.getOwnPropertyDescriptor(n,"init"))==null?void 0:e.value)!==l.init)throw new Error("FB.init was not replaced.");return o.facebookInitObservers.set(n,l),l}catch(t){throw o.facebookAppIds.delete(n),new r("INVALID_CONFIGURATION","The Meta SDK initialization cannot be observed safely. Use the popup flow or reload a fresh page.")}}function ge(o,n,e){var c;if(o.FB!==n||!n||"__buffer"in n||typeof n.login!="function")throw new r("INVALID_CONFIGURATION","The Meta SDK is not ready or was replaced before initialization.");if(typeof e!="string"||!/^[0-9]+$/.test(e))throw new r("INVALID_CONFIGURATION","A numeric Meta appId is required for native login.");let t=$(o);t.facebookAppIds.get(n)===null&&(t.facebookLoadUncertain||t.facebookLoading||typeof o.fbAsyncInit=="function")&&t.facebookAppIds.delete(n);let i=t.facebookAppIds.get(n);if(i===void 0||i!==null&&!t.facebookInitObservers.has(n))throw t.facebookAppIds.delete(n),new r("INVALID_CONFIGURATION","The host Meta SDK configuration is unknown. Use the popup flow or a fresh page without a host-initialized SDK for native login.");let a=we(t,n);if(i!==null){if(i!==e)throw new r("INVALID_CONFIGURATION","The Meta SDK is already initialized for another app. Use the popup flow or reload a fresh page before changing apps.");return}let l=a.calls;t.facebookAppIds.delete(n);try{n.init({appId:e,version:"v25.0",autoLogAppEvents:!0,xfbml:!0})}catch(d){throw new r("PROVIDER_ERROR","The Meta SDK could not be initialized.")}if(a.calls!==l+1||o.FB!==n||((c=Object.getOwnPropertyDescriptor(n,"init"))==null?void 0:c.value)!==a.init)throw new r("INVALID_CONFIGURATION","The Meta SDK changed during initialization. Use the popup flow or reload a fresh page.");t.facebookAppIds.set(n,e)}function Ae(o,n){if(n.aborted)return Promise.reject(new r("SDK_LOAD_FAILED","The Meta SDK load was cancelled."));let e=$(o),t=e.facebookLoadObserver;if(!t&&Ie(o.FB)&&(t={promise:Promise.resolve(o.FB),consumers:0}),!t){let a={consumers:0,promise:Promise.resolve().then(()=>new Promise((l,c)=>{var f;let d=!1,s,A=!1,R=!1,w,v,z,G=(m,u,_=!1)=>{if(!d){d=!0,clearTimeout(U),s==null||s.removeEventListener("load",L),s==null||s.removeEventListener("error",V);try{o.fbAsyncInit===K&&(v?Object.defineProperty(o,"fbAsyncInit",v):Reflect.deleteProperty(o,"fbAsyncInit"))}catch(N){}if(u&&s&&(e.failedFacebookScripts.add(s),_?e.erroredFacebookScripts.add(s):A||(e.facebookLoadUncertain=!0),A))try{s.remove()}catch(N){}e.facebookLoadObserver===a&&delete e.facebookLoadObserver,m?l(m):c(u)}},L=()=>{var _;if(d)return;let m=o.FB;if(!m)return;"__buffer"in m&&(w=m),(((_=w==null?void 0:w.__buffer)==null?void 0:_.opts)!=null||o.fbAsyncInit!==K||s!=null&&s.onload||e.facebookLoading||e.facebookLoadUncertain)&&(R=!1,e.facebookAppIds.get(m)===null&&e.facebookAppIds.delete(m),w&&e.facebookAppIds.get(w)===null&&e.facebookAppIds.delete(w));let u=Ie(m);if(R&&e.facebookAppIds.get(m)==null){if(!u)e.facebookAppIds.set(m,null);else if(!e.facebookInitObservers.has(m))try{we(e,m),e.facebookAppIds.set(m,null)}catch(N){}}u&&G(m)},V=()=>G(void 0,new r("SDK_LOAD_FAILED","The Meta SDK could not be loaded."),!0),K=()=>{if(!d){try{z==null||z.call(o)}catch(m){}L()}},U=setTimeout(()=>G(void 0,new r("SDK_LOAD_FAILED","The Meta SDK load timed out.")),30*1e3);a.cancelIfUnused=()=>{A&&a.consumers===0&&G(void 0,new r("SDK_LOAD_FAILED","The Meta SDK load was cancelled."))};try{v=Object.getOwnPropertyDescriptor(o,"fbAsyncInit"),z=typeof o.fbAsyncInit=="function"?o.fbAsyncInit:void 0;let m=o.document,u=m.getElementById("facebook-jssdk");if(s=Array.from(m.scripts).find(_=>{try{let N=new URL(_.src);return N.origin!=="https://connect.facebook.net"||!/^\/[^/]+\/sdk\.js$/.test(N.pathname)?!1:e.failedFacebookScripts.has(_)?(e.erroredFacebookScripts.has(_)||(e.facebookLoadUncertain=!0),!1):!0}catch(N){return!1}}),!s){s=m.createElement("script"),A=!0;let _=o.FB;_&&"__buffer"in _&&(w=_),R=!e.facebookLoadUncertain&&!e.facebookLoading&&!z&&(!_||!!w&&e.facebookAppIds.get(_)===null&&((f=w.__buffer)==null?void 0:f.opts)==null),u||(s.id="facebook-jssdk"),s.src="https://connect.facebook.net/en_US/sdk.js",s.crossOrigin="anonymous",s.async=!0,s.defer=!0}if(a.cancelIfUnused(),d)return;Object.defineProperty(o,"fbAsyncInit",v&&!v.configurable?{value:K}:{configurable:!0,enumerable:!0,writable:!0,value:K}),s.addEventListener("load",L),s.addEventListener("error",V),L(),!d&&A&&m.head.appendChild(s)}catch(m){G(void 0,new r("SDK_LOAD_FAILED","The Meta SDK could not be loaded."))}}))};e.facebookLoadObserver=t=a}let i=t;return new Promise((a,l)=>{let c=!1;i.consumers++;let d=(A,R)=>{var w;c||(c=!0,n.removeEventListener("abort",s),i.consumers--,A?a(A):l(R),(w=i.cancelIfUnused)==null||w.call(i))},s=()=>d(void 0,new r("SDK_LOAD_FAILED","The Meta SDK load was cancelled."));i.promise.then(A=>n.aborted?s():d(A),A=>d(void 0,new r("SDK_LOAD_FAILED",A.message))),n.addEventListener("abort",s,{once:!0}),n.aborted&&s()})}var Oe=(o,n,e=600,t=700)=>{let i=window,a=i.document,l=i.screenLeft!==void 0?i.screenLeft:i.screenX,c=i.screenTop!==void 0?i.screenTop:i.screenY,d=i.innerWidth?i.innerWidth:a.documentElement.clientWidth?a.documentElement.clientWidth:i.screen.width,s=i.innerHeight?i.innerHeight:a.documentElement.clientHeight?a.documentElement.clientHeight:i.screen.height,A=d/2-e/2+l,R=s/2-t/2+c;return i.open(o,n,`scrollbars=yes, width=${e}, height=${t}, top=${R}, left=${A}`)};var Fe=600*1e3,Ue=30*1e3;function E(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function O(o){return typeof o=="string"&&o.trim()?o:null}function ye(o){if(o==="."||o==="..")throw new r("INVALID_OPTIONS","The channelId cannot be a URL path navigation segment.");try{return encodeURIComponent(o)}catch(n){throw new r("INVALID_OPTIONS","The channelId cannot be encoded as a URL path.")}}function Me(o){let n;try{n=new URL(o)}catch(e){return!1}return n.protocol==="https:"&&(n.hostname==="facebook.com"||n.hostname.endsWith(".facebook.com"))}function We(o){return["META_MESSENGER","META_INSTAGRAM","META_WHATSAPP","BOT_TELEGRAM","Z_API_WHATSAPP"].includes(o)}function Re(o){return typeof o=="string"&&["cancelled","popup_closed","not_completed","invalid_channel","origin_not_allowed","unsupported_channel"].includes(o)}var ze=64;function Ge(o){return!E(o)||o.value!=null&&typeof o.value!="string"||o.connected!==void 0&&typeof o.connected!="boolean"?{error:{status:null,message:null}}:{connected:o.connected===!0,value:typeof o.value=="string"?o.value:null}}var Ve=300;function Ke(o){let n=E(o)?o:{},e=E(n.response)?n.response:void 0,t=e&&E(e.data)?e.data:{},i=[n.status,e==null?void 0:e.status].find(c=>typeof c=="number"&&Number.isInteger(c)&&c>=100&&c<=599),l=(e?[t.message,t.error,t.detail]:[n.message]).find(c=>typeof c=="string"&&c.trim()!=="");return{status:i!=null?i:null,message:l?l.trim().slice(0,Ve):null}}function te(o,n,e){return{success:!1,reason:e,channelId:o,type:n,code:null,wabaId:null,phoneId:null}}function _e(o,n,e){return typeof fetch!="function"||typeof AbortController!="function"?Promise.reject(new r("INVALID_CONFIGURATION","Fetch and AbortController are required.")):new Promise((t,i)=>{let a=new AbortController,l=!1,c=(R,w)=>{l||(l=!0,clearTimeout(s),e==null||e.removeEventListener("abort",d),a.abort(),w?i(w):t(R))},d=()=>c(void 0,new r("ABORTED","The API request was aborted.")),s=setTimeout(()=>c(void 0,new r("TIMEOUT","The API request timed out.")),Ue);if(e==null||e.addEventListener("abort",d,{once:!0}),e!=null&&e.aborted){d();return}(async()=>{let R;try{R=await fetch(o.href,{...n,signal:a.signal})}catch(w){c(void 0,new r("NETWORK_ERROR","The API request failed."));return}if(!l){if(!R||typeof R.ok!="boolean"){c(void 0,new r("INVALID_RESPONSE","The API response is invalid."));return}if(!R.ok){c(void 0,new r("HTTP_ERROR","The API returned an unsuccessful status."));return}try{let w=await R.json();l||c(w)}catch(w){c(void 0,new r("INVALID_RESPONSE","The API did not return valid JSON."))}}})().catch(()=>c(void 0,new r("NETWORK_ERROR","The API request failed.")))})}var oe=class{constructor(n){if(!E(n)||!O(n.publicKey)||Array.from(n.publicKey).some(e=>{let t=e.charCodeAt(0);return t<32||t===127})||n.logo!==void 0&&typeof n.logo!="string"||n.apiUrl!==void 0&&!O(n.apiUrl)||n.frontUrl!==void 0&&!O(n.frontUrl))throw new r("INVALID_CONFIGURATION","Valid client properties and a publicKey are required.");this.publicKey=n.publicKey,this.logo=n.logo,this.constants=pe({environment:n.environment,apiUrl:n.apiUrl,frontUrl:n.frontUrl})}async getListMessengerPages(n,e,t){if(!O(n)||!O(e))throw new r("INVALID_OPTIONS","A channelId and authorization code are required.");if(t!==void 0&&(!E(t)||typeof t.aborted!="boolean"||typeof t.addEventListener!="function"||typeof t.removeEventListener!="function"))throw new r("INVALID_OPTIONS","The abort signal is invalid.");if(t!=null&&t.aborted)throw new r("ABORTED","The API request was aborted.");return _e(new URL(`${this.constants.api}/v1/channels/${ye(n)}/list-messenger-pages`),{method:"POST",body:JSON.stringify({redirectUri:new URL(`${this.constants.front}/oauth/proxy-messenger`).href,code:e}),headers:{"Content-Type":"application/json",Authorization:this.publicKey}},t)}async connect(n){var e;try{if(typeof window=="undefined"||!window.document||!window.location)throw new r("BROWSER_REQUIRED","Connecting requires a browser window.");let t=window,i=$(t);if(i.activeConnection)throw new r("CONNECTION_IN_PROGRESS","A connection is already in progress in this window.");if(!E(n))throw new r("INVALID_OPTIONS","Connection options are required.");let{channelId:a,direct:l,getQRCode:c,timeoutMs:d=Fe,signal:s}=n;if(typeof a!="string"||l!==void 0&&typeof l!="boolean"||c!==void 0&&typeof c!="function"||typeof d!="number"||!Number.isFinite(d)||d<=0||d>2147483647||s!==void 0&&(!E(s)||typeof s.aborted!="boolean"||typeof s.addEventListener!="function"||typeof s.removeEventListener!="function"))throw new r("INVALID_OPTIONS","Invalid channelId, direct, getQRCode, timeoutMs or signal option.");if(s!=null&&s.aborted)throw new r("ABORTED","The connection was aborted.");if(!a.trim())return te(a,null,"invalid_channel");let A=ye(a);if(typeof t.open!="function"||typeof t.addEventListener!="function"||typeof t.removeEventListener!="function"||typeof t.location.origin!="string"||typeof t.location.href!="string"||typeof((e=t.crypto)==null?void 0:e.getRandomValues)!="function"||typeof AbortController!="function"||typeof fetch!="function")throw new r("INVALID_CONFIGURATION","Required browser APIs are unavailable.");let R=t.location.origin;if(R==="null")return te(a,null,"origin_not_allowed");let w=t.location.href,v=new URL(this.constants.front).origin;return await new Promise((z,G)=>{let L=Symbol("omnizapi-connection"),V=new AbortController,K=Date.now()+d,U=!1,f=null,m=null,u=null,_,N,H,x,J=!1,X=!1,B=null,Y=()=>{i.nativeLoginOwner===L&&(i.nativeLoginPending=!1,delete i.nativeLoginOwner)},ie=[],P=p=>{if(U)return;U=!0,clearTimeout(N),clearInterval(H);try{s==null||s.removeEventListener("abort",ee)}catch(M){}if(x)try{t.removeEventListener("message",x)}catch(M){}try{V.abort()}catch(M){}let D=u;u=null;try{D==null||D.close()}catch(M){}for(let{name:M,previous:g,value:F}of ie)try{let S=Object.getOwnPropertyDescriptor(t,M);if(!S||!("value"in S)||S.value!==F)continue;g?Object.defineProperty(t,M,g):Reflect.deleteProperty(t,M)}catch(S){}i.activeConnection===L&&delete i.activeConnection,J&&(X||!(p instanceof r)&&p.success)&&Y(),p instanceof r?G(p):z(p)},ee=()=>P(new r("ABORTED","The connection was aborted.")),T=()=>(!U&&(s!=null&&s.aborted)&&ee(),!U&&Date.now()>=K&&P(new r("TIMEOUT","The connection timed out.")),!U),C=p=>P(te(a,f,p)),se=()=>{try{let p=Oe("about:blank","_blank",600,740);if(!p||p===t)throw new Error("Popup unavailable");if(!T()){p.close();return}u=p}catch(p){throw new r("POPUP_BLOCKED","The connection popup could not be opened.")}},ke=()=>{H||(H=setInterval(()=>{if(T())try{u!=null&&u.closed&&C("popup_closed")}catch(p){P(new r("PROVIDER_ERROR","The connection popup could not be monitored."))}},500))},Se=()=>{clearInterval(H),H=void 0},ae=p=>{!T()||!f||P({success:!0,channelId:a,type:f,code:O(p.code),wabaId:O(p.wabaId),phoneId:O(p.phoneId),coexistence:p.coexistence===!0,redirectUri:m,botToken:O(p.botToken),pageId:O(p.pageId),accessToken:O(p.accessToken)})};try{if(i.activeConnection=L,s==null||s.addEventListener("abort",ee,{once:!0}),!T())return;let p=t.crypto.getRandomValues(new Uint8Array(16)),D=Array.from(p,g=>g.toString(16).padStart(2,"0")).join("");for(let[g,F]of[["__omnizapiPublicKey",this.publicKey],["__omnizapiCurrentChannel",a],["__omnizapiGetQrCode",c]]){let S=Object.getOwnPropertyDescriptor(t,g);Object.defineProperty(t,g,S&&!S.configurable?{value:F}:{configurable:!0,enumerable:!0,writable:!0,value:F}),ie.push({name:g,previous:S,value:F})}if(N=setTimeout(()=>P(new r("TIMEOUT","The connection timed out.")),d),!l)try{se()}catch(g){_=g instanceof r?g:new r("POPUP_BLOCKED","The connection popup could not be opened.")}if(!T())return;(async()=>{var le,de,ue;let g=await _e(new URL(`${this.constants.api}/instances/${A}/sdk-info`),{headers:{Authorization:this.publicKey,"Content-Type":"application/json"}},V.signal);if(!T())return;if(!E(g)||!O(g.middleware))throw new r("INVALID_RESPONSE","The channel configuration is invalid.");let F=(le=g.allowOrigins)!=null?le:[];if(!Array.isArray(F)||!F.every(b=>typeof b=="string"))throw new r("INVALID_RESPONSE","The channel origins are invalid.");let S=g.middleware;if(f=We(S)?S:null,R!==v&&!me(R,F)){C("origin_not_allowed");return}if(!f){C("unsupported_channel");return}if(f==="Z_API_WHATSAPP"&&!c)throw new r("INVALID_OPTIONS","getQRCode is required to connect a Z_API_WHATSAPP channel.");let j=(de=O(f==="META_INSTAGRAM"?g.appInstagramId:g.appId))!=null?de:"",ne=(ue=O(g.appConfig))!=null?ue:"";if(f.startsWith("META_")&&!j||f==="META_WHATSAPP"&&!ne)throw new r("INVALID_RESPONSE","The channel provider configuration is invalid.");let Pe=f==="META_WHATSAPP"&&l===!0,ce=!1,Q;if(Pe){if(Se(),i.nativeLoginPending)throw new r("CONNECTION_IN_PROGRESS","A previous Meta login is incomplete. Reload this window before retrying a native login.");if(Q=await Ae(t,V.signal),!T())return;try{ge(t,Q,j),ce=!0}catch(b){if(!(b instanceof r&&b.code==="INVALID_CONFIGURATION"))throw b}if(!T())return}if(ce&&Q){u==null||u.close(),u=null;let b=null,h=null,W=null,Z=!1,q=()=>{!T()||!b||!h||ae({code:b,wabaId:h,phoneId:W,coexistence:Z})};x=k=>{if(!T()||!Me(k.origin))return;let I=k.data;if(typeof I=="string")try{I=JSON.parse(I)}catch(Le){return}if(!(!E(I)||I.type!=="WA_EMBEDDED_SIGNUP")){if(I.event==="CANCEL")C("cancelled");else if(I.event==="ERROR")P(new r("PROVIDER_ERROR","Meta could not complete the connection."));else if(I.event==="FINISH"||I.event==="FINISH_ONLY_WABA"||I.event==="FINISH_WHATSAPP_BUSINESS_APP_ONBOARDING"){if(!E(I.data)||!O(I.data.waba_id)||I.data.phone_number_id!=null&&typeof I.data.phone_number_id!="string")return;h=O(I.data.waba_id),W=O(I.data.phone_number_id),Z=I.event==="FINISH_WHATSAPP_BUSINESS_APP_ONBOARDING",q()}}},t.addEventListener("message",x),i.nativeLoginPending=!0,i.nativeLoginOwner=L,J=!0;try{Q.login(k=>{if(!X){if(X=!0,U){Y();return}if(T()){if(!E(k)||k.error){P(new r("PROVIDER_ERROR","Meta returned an invalid login response."));return}if(k.authResponse==null){C("not_completed");return}if(!E(k.authResponse)||!O(k.authResponse.code)){C("not_completed");return}b=O(k.authResponse.code),q()}}},{config_id:ne,response_type:"code",override_default_response_type:!0,extras:{setup:{},featureType:"whatsapp_business_app_onboarding",sessionInfoVersion:"3"}})}catch(k){throw Y(),J=!1,new r("PROVIDER_ERROR","The Meta login could not be started.")}return}let y;if(f==="META_MESSENGER"||f==="META_INSTAGRAM"){let b=f==="META_MESSENGER";m=new URL(`${this.constants.front}/oauth/proxy-${b?"messenger":"instagram"}`).href,y=new URL(b?"https://www.facebook.com/dialog/oauth":"https://www.instagram.com/oauth/authorize"),y.searchParams.set("client_id",j),b&&y.searchParams.set("display","popup"),y.searchParams.set("redirect_uri",m),y.searchParams.set("response_type","code"),y.searchParams.set("scope",b?"public_profile,business_management,pages_messaging,pages_show_list,pages_manage_metadata,pages_read_engagement":"instagram_business_basic,instagram_business_manage_messages"),y.searchParams.set("state",JSON.stringify({currentUrl:w,attemptId:D,channelId:a,pk:this.publicKey}))}else f==="META_WHATSAPP"?(y=new URL(`${this.constants.front}/oauth/proxy-cloud-api`),y.searchParams.set("configId",ne),y.searchParams.set("appId",j),y.searchParams.set("channelId",a),y.searchParams.set("channelType",f),y.searchParams.set("logo",this.logo||new URL(`${this.constants.front}/logos/SVG/Ativo%2016.svg`).href),y.searchParams.set("pk",this.publicKey)):(y=new URL(`${this.constants.front}/connect/${f==="BOT_TELEGRAM"?"telegram":"whatsapp-web"}`),y.searchParams.set("channelId",a),y.searchParams.set("pk",this.publicKey),f==="Z_API_WHATSAPP"&&y.searchParams.set("qr","message"));f!=="META_MESSENGER"&&f!=="META_INSTAGRAM"&&y.searchParams.set("attemptId",D);let ve=(b,h)=>{let W=c;if(f!=="Z_API_WHATSAPP"||!W||b.attemptId!==D||b.channelId!==a||typeof b.requestId!="string"||!b.requestId||b.requestId.length>ze)return;let Z=b.requestId,q=I=>{if(!(!T()||u!==h))try{h.postMessage({type:"qr-code-response",attemptId:D,channelId:a,requestId:Z,...I},v)}catch(Le){}},k=B!=null?B:B=Promise.resolve().then(()=>W());k.then(I=>q(Ge(I)),I=>q({error:Ke(I)})).finally(()=>{B===k&&(B=null)})};if(x=b=>{if(!T()||!u||b.origin!==v||b.source!==u)return;let h=b.data;if(E(h)&&h.type==="qr-code-request"){ve(h,u);return}!E(h)||h.type!=="after-connect"||h.attemptId!==D||h.channelId!==a||typeof h.success!="boolean"||h.reason!==void 0&&!Re(h.reason)||h.coexistence!==void 0&&typeof h.coexistence!="boolean"||["code","wabaId","phoneId","botToken","pageId","accessToken","redirectUri"].some(W=>h[W]!=null&&typeof h[W]!="string")||(h.success?f!=null&&f.startsWith("META_")&&!O(h.code)||f==="BOT_TELEGRAM"&&!O(h.botToken)?C("not_completed"):ae(h):C(Re(h.reason)?h.reason:"not_completed"))},t.addEventListener("message",x),!!T()){if(_)throw _;if(u||se(),u!=null&&u.closed){C("popup_closed");return}ke();try{u==null||u.location.replace(y.href)}catch(b){throw new r("PROVIDER_ERROR","The connection popup could not be navigated.")}}})().catch(g=>{T()&&P(g instanceof r?g:new r("PROVIDER_ERROR","The connection could not be completed."))})}catch(p){P(p instanceof r?p:new r("INVALID_CONFIGURATION","The connection could not be initialized."))}})}catch(t){throw t instanceof r?t:new r("INVALID_OPTIONS","The connection could not be started with these options.")}}},Te=oe;var re=class{static newClient(n){return new Te(n)}};var Ee=re;Object.assign(window,{Omnizapi:Ee});})();