@svelkit/graphql
Version:
> A lightweight [GraphQL] client for [svelte]
7 lines (6 loc) • 7.66 kB
JavaScript
;Object.defineProperty(exports,"__esModule",{value:!0});const store=require("svelte/store"),svelte=require("svelte"),stableStringify=require("fast-json-stable-stringify"),plainTag=require("plain-tag");function _interopDefault(e){return e&&e.__esModule?e:{default:e}}const stableStringify__default=_interopDefault(stableStringify),plainTag__default=_interopDefault(plainTag),getOperation=e=>{const t=/(?:^|})\s*(?:(query|mutation|subscription)\s*(\w+)?\s*[({]|{)/m.exec(e)||[];return{type:t[1]||"query",name:t[2]}},hl=Array.from({length:256},(e,t)=>(t>>4&15).toString(16)+(t&15).toString(16)),toHex=e=>hl[e>>8]+hl[e&255],M=65535,R=315,fnv1a128=e=>{let t=e.length,s=0,r=0,n=0,c=0,a=0,i=0,o=0,u=0,l=5247,h=20042,d=11120,p=30865,f=36015,g=4122,m=52073,y=53800;for(;t--;)l^=e.charCodeAt(t),s=l*R,r=h*R,n=d*R,c=p*R,a=f*R,i=g*R,o=m*R,u=y*R,i+=l<<8,o+=h<<8,u+=d<<8,r+=s>>>16,l=s&M,n+=r>>>16,h=r&M,c+=n>>>16,d=n&M,a+=c>>>16,p=c&M,i+=a>>>16,f=a&M,o+=i>>>16,g=i&M,y=u+(o>>>16)&M,m=o&M;return toHex(y)+toHex(m)+toHex(g)+toHex(f)+toHex(p)+toHex(d)+toHex(h)+toHex(l)},defaultHash=e=>({version:-1,fnv1a128Hash:fnv1a128(e)}),automaticPersistedQueriesExchange=({generateHash:e=defaultHash,preferGETForHashedQueries:t=!0,notFoundError:s="PersistedQueryNotFound",notSupportedError:r="PersistedQueryNotSupported"}={})=>{const n=new Map,c=i=>{let o=n.get(i);return o||n.set(i,o=e(i)),o};let a=!0;return async({query:i,extensions:o,options:u,...l},h)=>{if(!a||!i||o.persistedQuery||l.operation.type!=="query")return h();const d=c(i),p=await h({...l,query:"",extensions:{...o,persistedQuery:d},options:{...u,preferGetForQueries:t||u.preferGetForQueries}}).catch(f=>{if(f.message===s||f.message===r)return{errors:[f]};throw f});return p.errors&&(a=p.errors.every(f=>f.message!==r),!a||p.errors.some(f=>f.message===s))?h({...l,query:i,extensions:o,options:u}):p}},isString=e=>typeof e=="string";class GraphQLFetchError extends Error{constructor(e,t){super((isString(t)?t:(s=(t.errors||[])[0])==null?void 0:s.message)||`[${e.status}] ${e.statusText}`);var s;this.name="GraphQLFetchError",this.status=e.status,this.body=t,this.headers=e.headers}}const emptyToUndefined=e=>e&&Object.keys(e).length>0?e:void 0,MAX_URL_LENGTH=2e3,isJsonResponse=e=>{var t;return(t=e.headers.get("Content-Type"))==null?void 0:t.startsWith("application/json")},fetchExchange=(e={})=>async({operation:t,query:s,variables:r,extensions:n,options:c},a)=>{if(t.type==="query"||t.type==="mutation"){const{fetch:i=globalThis.fetch,uri:o="/graphql",preferGetForQueries:u,...l}={referrerPolicy:"strict-origin-when-cross-origin",...e,...c,headers:{Accept:"application/json",...e.headers,...c.headers}};let h;const d={operationName:t.name,query:s||void 0,variables:emptyToUndefined(r),extensions:emptyToUndefined(n)};if(u&&t.type==="query"){const p=new URL(o,document.baseURI);for(const[f,g]of Object.entries(d))g&&p.searchParams.set(f,isString(g)?g:stableStringify__default.default(g));p.href.length<MAX_URL_LENGTH&&(h=await i(p.href,{...l,method:"GET"}))}if(h||(h=await i(new URL(o,document.baseURI).href,{...l,method:"POST",headers:{...l.headers,"Content-Type":"application/json"},body:JSON.stringify(d)})),h.ok&&isJsonResponse(h))return h.json();throw new GraphQLFetchError(h,await(isJsonResponse(h)?h.json():h.text()))}return a()};let position=0,char,string;const isWhitespace=e=>`
\r,`.includes(e),isPunctuator=e=>"!|$&():=@[]{}.".includes(e),isCommentStart=e=>e==="#",isQuatationMark=e=>e==='"',isEscapedQuotation=e=>e==="\\"&&isQuatationMark(string[position]),isLineEnding=e=>e===`
`||e==="\r"&&string[position]===`
`&&(position+=1),isBlockString=()=>isQuatationMark(string[position])&&isQuatationMark(string[position+1])&&(position+=2),skipComment=()=>{for(;position<string.length&&!isLineEnding(string[position++]););},collapseWhitespace=e=>{for(;position<string.length&&isWhitespace(string[position]);)position++;return isPunctuator(string[position])?string[position++]+collapseWhitespace(""):isCommentStart(string[position])?(skipComment(),collapseWhitespace(e)):isQuatationMark(string[position])?"":e},extractBlockString=()=>{var r;let e="";for(;position<string.length;)if(char=string[position++],isQuatationMark(char)){if(isBlockString())break;e+="\\"+char}else e+=char,isEscapedQuotation(char)&&(e+=string[position++]);const t=e.replace(/^(?:\s*\r?\n)*|(?:\r?\n\s*)*$/g,"").split(/\r?\n/),s=t.reduce((n,c)=>{if(!c)return n;let a=0;for(;isWhitespace(c[a])&&n[a]===c[a];)a+=1;return n.slice(0,a)},((r=/^(\s*)/.exec(t[0]))==null?void 0:r[1])||"").length;return t.map(n=>n.slice(s)).join(`
`)},extractString=()=>{let e="";for(;position<string.length&&!(char=string[position++],isQuatationMark(char));)e+=char,isEscapedQuotation(char)&&(e+=string[position++]);return e},minimize=e=>{position=0,string=e;let t="";for(;position<string.length;)char=string[position++],isWhitespace(char)?t+=collapseWhitespace(" "):isCommentStart(char)?skipComment():(t+=char,isPunctuator(char)?t+=collapseWhitespace(""):isQuatationMark(char)&&(t+=(isBlockString()?extractBlockString():extractString())+char));return t.trim()},minimizeExchange=()=>{const e=new Map,t=s=>{let r=e.get(s);return r||e.set(s,r=minimize(s)),r};return(s,r)=>r({...s,query:t(s.query)})},defaultExchanges=[minimizeExchange()];class ClientError extends Error{constructor(e,t){super(((s=e==null?void 0:e[0])==null?void 0:s.message)||"GraphQL Error");var s;this.name="GraphQLClientError",this.errors=e,this.extensions=t}}const fromServerResult=({fetching:e,error:t,data:s,errors:r,extensions:n})=>({fetching:Boolean(e),data:s,error:t||r&&new ClientError(r,n),extensions:n});class Client{constructor({exchanges:e=defaultExchanges,...t}){this.lastId=0,this.exchanges=e.filter(Boolean),this.exchanges.push(fetchExchange()),this.options=t}setHeader(e,t){const s={...this.options.headers,[e]:t||""};return t||delete s[e],this.options={...this.options,headers:s},s[e]}request(e,t,s={}){const r=store.writable({},n=>{const c=new AbortController;n({fetching:!0});const a=(i,o)=>{const u=this.exchanges[o];if(u)return u(i,(l=i)=>a(l,o+1),r.update);throw new Error(`No exchange has handled operations of type "${i.operation.type}". Check whether you've added an exchange responsible for these operations.`)};return a({query:e,variables:t||{},operation:{...getOperation(e),id:++this.lastId},extensions:{},options:{...this.options,...s,headers:{...this.options.headers,...s.headers},signal:c.signal}},0).catch(i=>({error:i})).then(i=>r.set({...i,fetching:!1})),()=>c.abort()});return store.derived(r,fromServerResult)}}const CLIENT_CONTEXT_KEY=Symbol.for("@svelkit/graphql/client"),initGraphQLClient=e=>{const t=new Client(e);return svelte.setContext(CLIENT_CONTEXT_KEY,t),t},useGraphQLClient=()=>svelte.getContext(CLIENT_CONTEXT_KEY),toPromise=e=>new Promise((t,s)=>{const r=e.subscribe(n=>{n.data?(r(),t(n)):n.error&&(r(),s(n.error))})}),useRequest=(e,t={},s={})=>{const r=useGraphQLClient(),n=(a,i)=>{const o=r.request(e,{...t,...a},{...s,...i});return o.then=then,o.fetch=(u,l)=>n({...a,...u},{...i,...l}),o},c=n();return Object.assign(c.fetch,c)};function then(e,t){return toPromise(this).then(e,t)}Object.defineProperty(exports,"gql",{enumerable:!0,get:function(){return plainTag__default.default}}),exports.GraphQLFetchError=GraphQLFetchError,exports.automaticPersistedQueries=automaticPersistedQueriesExchange,exports.defaultExchanges=defaultExchanges,exports.fetch=fetchExchange,exports.fnv1a128=fnv1a128,exports.initGraphQLClient=initGraphQLClient,exports.minimize=minimizeExchange,exports.useGraphQLClient=useGraphQLClient,exports.useMutation=useRequest,exports.useQuery=useRequest,exports.useRequest=useRequest;
//# sourceMappingURL=graphql.js.map