UNPKG

@nhost/graphql-js

Version:

Nhost GraphQL client

3 lines (2 loc) 5.35 kB
(function(u,l){typeof exports=="object"&&typeof module!="undefined"?l(exports,require("graphql")):typeof define=="function"&&define.amd?define(["exports","graphql"],l):(u=typeof globalThis!="undefined"?globalThis:u||self,l(u["@nhost/graphql-js"]={},u.graphql))})(this,function(u,l){"use strict";function w(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function T(t){if(t.__esModule)return t;var e=t.default;if(typeof e=="function"){var s=function n(){return this instanceof n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};s.prototype=e.prototype}else s={};return Object.defineProperty(s,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(s,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}),s}function b(t,e){return e=e||{},new Promise(function(s,n){var r=new XMLHttpRequest,i=[],h=[],c={},p=function(){return{ok:(r.status/100|0)==2,statusText:r.statusText,status:r.status,url:r.responseURL,text:function(){return Promise.resolve(r.responseText)},json:function(){return Promise.resolve(r.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([r.response]))},clone:p,headers:{keys:function(){return i},entries:function(){return h},get:function(a){return c[a.toLowerCase()]},has:function(a){return a.toLowerCase()in c}}}};for(var g in r.open(e.method||"get",t,!0),r.onload=function(){r.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(a,o,d){i.push(o=o.toLowerCase()),h.push([o,d]),c[o]=c[o]?c[o]+","+d:d}),s(p())},r.onerror=n,r.withCredentials=e.credentials=="include",e.headers)r.setRequestHeader(g,e.headers[g]);r.send(e.body||null)})}const m=T(Object.freeze(Object.defineProperty({__proto__:null,default:b},Symbol.toStringTag,{value:"Module"})));var k=self.fetch||(self.fetch=m.default||m);const v=w(k);function O(t,e,s){return t.document?t:{document:t,variables:e,config:s}}function y(t){var n;let e;const s=t.definitions.filter(r=>r.kind==="OperationDefinition");return s.length===1&&(e=(n=s[0].name)==null?void 0:n.value),e}function _(t){if(typeof t=="string"){let s;try{const n=l.parse(t);s=y(n)}catch{}return{query:t,operationName:s}}const e=y(t);return{query:l.print(t),operationName:e}}class f extends Error{}f.prototype.name="InvalidTokenError";function N(t){return decodeURIComponent(atob(t).replace(/(.)/g,(e,s)=>{let n=s.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n}))}function j(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return N(e)}catch{return atob(e)}}function A(t,e){if(typeof t!="string")throw new f("Invalid token specified: must be a string");e||(e={});const s=e.header===!0?0:1,n=t.split(".")[s];if(typeof n!="string")throw new f(`Invalid token specified: missing part #${s+1}`);let r;try{r=j(n)}catch(i){throw new f(`Invalid token specified: invalid base64 for part #${s+1} (${i.message})`)}try{return JSON.parse(r)}catch(i){throw new f(`Invalid token specified: invalid json for part #${s+1} (${i.message})`)}}class q{constructor(e){this.headers={},this.isAccessTokenValidOrNull=()=>{if(!this.accessToken)return!0;try{const r=A(this.accessToken);return r.exp!=null&&r.exp*1e3>Date.now()}catch(r){return console.error("Error decoding token:",r),!1}},this.awaitForValidAccessTokenOrNull=async()=>{if(this.isAccessTokenValidOrNull())return!0;const r=()=>this.isAccessTokenValidOrNull()?Promise.resolve(!0):new Promise(i=>{setTimeout(()=>r().then(i),100)});return r()};const{url:s,adminSecret:n}=e;this._url=s,this.accessToken=null,this.adminSecret=n}async request(e,...s){const[n,r]=s,i=O(e,n,r),{headers:h,...c}=r||{},{query:p,operationName:g}=_(i.document);typeof process!="undefined"&&!process.env.TEST_MODE&&await this.awaitForValidAccessTokenOrNull();try{const a=await v(this.httpUrl,{method:"POST",body:JSON.stringify({operationName:g,query:p,variables:n}),headers:{"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...this.headers,...h},...c});if(!a.ok)return{data:null,error:{error:a.statusText,message:a.statusText,status:a.status}};const{data:o,errors:d}=await a.json();return d?{data:null,error:d}:typeof o!="object"||Array.isArray(o)||o===null?{data:null,error:{error:"invalid-response",message:"incorrect response data from GraphQL server",status:0}}:{data:o,error:null}}catch(a){const o=a;return{data:null,error:{message:o.message,status:o.name==="AbortError"?0:500,error:o.name==="AbortError"?"abort-error":"unknown"}}}}get httpUrl(){return this._url}get wsUrl(){return this._url.replace(/^(http)(s?):\/\//,"ws$2://")}get url(){return this._url}getUrl(){return this._url}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}getHeaders(){return this.headers}setHeaders(e){e&&(this.headers={...this.headers,...e})}unsetHeaders(){const e=this.headers["x-hasura-role"];this.headers=e?{"x-hasura-role":e}:{}}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}u.NhostGraphqlClient=q,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"})}); //# sourceMappingURL=graphql-js.umd.js.map