UNPKG

11.3 kBSource Map (JSON)View Raw
1{"version":3,"file":"231258ed.mjs","sources":["../src/utils/stringifyVariables.ts","../src/internal/fetchSource.ts","../src/utils/request.ts","../src/utils/result.ts","../src/internal/fetchOptions.ts","../src/utils/error.ts","../src/utils/hash.ts"],"sourcesContent":["const seen = new Set();\nconst cache = new WeakMap();\n\nconst stringify = (x: any): string => {\n if (x === null || seen.has(x)) {\n return 'null';\n } else if (typeof x !== 'object') {\n return JSON.stringify(x) || '';\n } else if (x.toJSON) {\n return stringify(x.toJSON());\n } else if (Array.isArray(x)) {\n let out = '[';\n for (let i = 0, l = x.length; i < l; i++) {\n if (i > 0) out += ',';\n const value = stringify(x[i]);\n out += value.length > 0 ? value : 'null';\n }\n\n out += ']';\n return out;\n }\n\n const keys = Object.keys(x).sort();\n if (!keys.length && x.constructor && x.constructor !== Object) {\n const key = cache.get(x) || Math.random().toString(36).slice(2);\n cache.set(x, key);\n return `{\"__key\":\"${key}\"}`;\n }\n\n seen.add(x);\n let out = '{';\n for (let i = 0, l = keys.length; i < l; i++) {\n const key = keys[i];\n const value = stringify(x[key]);\n if (value) {\n if (out.length > 1) out += ',';\n out += stringify(key) + ':' + value;\n }\n }\n\n seen.delete(x);\n out += '}';\n return out;\n};\n\nexport const stringifyVariables = (x: any): string => {\n seen.clear();\n return stringify(x);\n};\n","import { Operation, OperationResult } from '../types';\nimport { makeResult, makeErrorResult } from '../utils';\nimport { make } from 'wonka';\n\nconst executeFetch = (\n operation: Operation,\n url: string,\n fetchOptions: RequestInit\n): Promise<OperationResult> => {\n const fetcher = operation.context.fetch;\n\n let statusNotOk = false;\n let response: Response;\n\n return (fetcher || fetch)(url, fetchOptions)\n .then((res: Response) => {\n response = res;\n statusNotOk =\n res.status < 200 ||\n res.status >= (fetchOptions.redirect === 'manual' ? 400 : 300);\n return res.json();\n })\n .then((result: any) => {\n if (!('data' in result) && !('errors' in result)) {\n throw new Error('No Content');\n }\n\n return makeResult(operation, result, response);\n })\n .catch((error: Error) => {\n if (error.name !== 'AbortError') {\n return makeErrorResult(\n operation,\n statusNotOk ? new Error(response.statusText) : error,\n response\n );\n }\n }) as Promise<OperationResult>;\n};\n\nexport const makeFetchSource = (\n operation: Operation,\n url: string,\n fetchOptions: RequestInit\n) => {\n return make<OperationResult>(({ next, complete }) => {\n const abortController =\n typeof AbortController !== 'undefined' ? new AbortController() : null;\n\n let ended = false;\n\n Promise.resolve()\n .then(() => {\n if (ended) {\n return;\n } else if (abortController) {\n fetchOptions.signal = abortController.signal;\n }\n\n return executeFetch(operation, url, fetchOptions);\n })\n .then((result: OperationResult | undefined) => {\n if (!ended) {\n ended = true;\n if (result) next(result);\n complete();\n }\n });\n\n return () => {\n ended = true;\n if (abortController) {\n abortController.abort();\n }\n };\n });\n};\n","import { TypedDocumentNode } from '@graphql-typed-document-node/core';\nimport { DocumentNode, Kind, parse, print } from 'graphql';\nimport { hash, phash } from './hash';\nimport { stringifyVariables } from './stringifyVariables';\nimport { GraphQLRequest } from '../types';\n\ninterface Documents {\n [key: number]: DocumentNode;\n}\n\nconst hashQuery = (q: string): number =>\n hash(q.replace(/([\\s,]|#[^\\n\\r]+)+/g, ' ').trim());\n\nconst docs: Documents = Object.create(null);\n\nexport const createRequest = <Data = any, Variables = object>(\n q: string | DocumentNode | TypedDocumentNode<Data, Variables>,\n vars?: Variables\n): GraphQLRequest<Data, Variables> => {\n let key: number;\n let query: DocumentNode;\n if (typeof q === 'string') {\n key = hashQuery(q);\n query =\n docs[key] !== undefined ? docs[key] : parse(q, { noLocation: true });\n } else if ((q as any).__key !== undefined) {\n key = (q as any).__key;\n query = q;\n } else {\n key = hashQuery(print(q));\n query = docs[key] !== undefined ? docs[key] : q;\n }\n\n docs[key] = query;\n (query as any).__key = key;\n\n return {\n key: vars ? phash(key, stringifyVariables(vars)) >>> 0 : key,\n query,\n variables: vars || ({} as Variables),\n };\n};\n\n/**\n * Finds the Name value from the OperationDefinition of a Document\n */\nexport const getOperationName = (query: DocumentNode): string | undefined => {\n for (let i = 0, l = query.definitions.length; i < l; i++) {\n const node = query.definitions[i];\n if (node.kind === Kind.OPERATION_DEFINITION && node.name) {\n return node.name.value;\n }\n }\n};\n","import { Operation, OperationResult } from '../types';\nimport { CombinedError } from './error';\n\nexport const makeResult = (\n operation: Operation,\n result: any,\n response?: any\n): OperationResult => ({\n operation,\n data: result.data,\n error: Array.isArray(result.errors)\n ? new CombinedError({\n graphQLErrors: result.errors,\n response,\n })\n : undefined,\n extensions:\n (typeof result.extensions === 'object' && result.extensions) || undefined,\n});\n\nexport const makeErrorResult = (\n operation: Operation,\n error: Error,\n response?: any\n): OperationResult => ({\n operation,\n data: undefined,\n error: new CombinedError({\n networkError: error,\n response,\n }),\n extensions: undefined,\n});\n","import { DocumentNode, print } from 'graphql';\n\nimport { getOperationName, stringifyVariables } from '../utils';\nimport { Operation } from '../types';\n\nexport interface FetchBody {\n query?: string;\n operationName: string | undefined;\n variables: undefined | Record<string, any>;\n extensions: undefined | Record<string, any>;\n}\n\nconst shouldUseGet = (operation: Operation): boolean => {\n return operation.kind === 'query' && !!operation.context.preferGetMethod;\n};\n\nexport const makeFetchBody = (request: {\n query: DocumentNode;\n variables?: object;\n}): FetchBody => ({\n query: print(request.query),\n operationName: getOperationName(request.query),\n variables: request.variables || undefined,\n extensions: undefined,\n});\n\nexport const makeFetchURL = (\n operation: Operation,\n body?: FetchBody\n): string => {\n const useGETMethod = shouldUseGet(operation);\n const url = operation.context.url;\n if (!useGETMethod || !body) return url;\n\n const search: string[] = [];\n if (body.operationName) {\n search.push('operationName=' + encodeURIComponent(body.operationName));\n }\n\n if (body.query) {\n search.push(\n 'query=' +\n encodeURIComponent(\n body.query.replace(/([\\s,]|#[^\\n\\r]+)+/g, ' ').trim()\n )\n );\n }\n\n if (body.variables) {\n search.push(\n 'variables=' + encodeURIComponent(stringifyVariables(body.variables))\n );\n }\n\n if (body.extensions) {\n search.push(\n 'extensions=' + encodeURIComponent(stringifyVariables(body.extensions))\n );\n }\n\n return `${url}?${search.join('&')}`;\n};\n\nexport const makeFetchOptions = (\n operation: Operation,\n body?: FetchBody\n): RequestInit => {\n const useGETMethod = shouldUseGet(operation);\n\n const extraOptions =\n typeof operation.context.fetchOptions === 'function'\n ? operation.context.fetchOptions()\n : operation.context.fetchOptions || {};\n\n return {\n ...extraOptions,\n body: !useGETMethod && body ? JSON.stringify(body) : undefined,\n method: useGETMethod ? 'GET' : 'POST',\n headers: useGETMethod\n ? extraOptions.headers\n : { 'content-type': 'application/json', ...extraOptions.headers },\n };\n};\n","import { GraphQLError } from 'graphql';\n\nconst generateErrorMessage = (\n networkErr?: Error,\n graphQlErrs?: GraphQLError[]\n) => {\n let error = '';\n if (networkErr !== undefined) {\n return (error = `[Network] ${networkErr.message}`);\n }\n\n if (graphQlErrs !== undefined) {\n graphQlErrs.forEach(err => {\n error += `[GraphQL] ${err.message}\\n`;\n });\n }\n\n return error.trim();\n};\n\nconst rehydrateGraphQlError = (error: any): GraphQLError => {\n if (typeof error === 'string') {\n return new GraphQLError(error);\n } else if (typeof error === 'object' && error.message) {\n return new GraphQLError(\n error.message,\n error.nodes,\n error.source,\n error.positions,\n error.path,\n error,\n error.extensions || {}\n );\n } else {\n return error as any;\n }\n};\n\n/** An error which can consist of GraphQL errors and Network errors. */\nexport class CombinedError extends Error {\n public name: string;\n public message: string;\n public graphQLErrors: GraphQLError[];\n public networkError?: Error;\n public response?: any;\n\n constructor({\n networkError,\n graphQLErrors,\n response,\n }: {\n networkError?: Error;\n graphQLErrors?: Array<string | Partial<GraphQLError> | Error>;\n response?: any;\n }) {\n const normalizedGraphQLErrors = (graphQLErrors || []).map(\n rehydrateGraphQlError\n );\n const message = generateErrorMessage(networkError, normalizedGraphQLErrors);\n\n super(message);\n\n this.name = 'CombinedError';\n this.message = message;\n this.graphQLErrors = normalizedGraphQLErrors;\n this.networkError = networkError;\n this.response = response;\n }\n\n toString() {\n return this.message;\n }\n}\n","// When we have separate strings it's useful to run a progressive\n// version of djb2 where we pretend that we're still looping over\n// the same string\nexport const phash = (h: number, x: string): number => {\n h = h | 0;\n for (let i = 0, l = x.length | 0; i < l; i++) {\n h = (h << 5) + h + x.charCodeAt(i);\n }\n\n return h;\n};\n\n// This is a djb2 hashing function\nexport const hash = (x: string): number => phash(5381 | 0, x) >>> 0;\n"],"names":["out","c","value","i","f","x","Object","result","statusNotOk","response","res","a","makeErrorResult","print","node","operation","graphQLErrors","body","url","useGETMethod","networkError","query","key","phash","ended","docs","Error","h","generateErrorMessage","error","b","seen","WeakMap","toString"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;OAeMA,IAAsBC,IAAfC,qBAAPF;;;;;;AAgBKG;EAAAA,gBCDcC;;;;;;;;WDiBNC;;;;qBElCKC;oBCRtBC;;;;YFMIC,uBAKAC;WACAD,IACEE,YACAA;;QAIEC;;;;WAQKC,EADUR;;;;;;AGVhBS;;;;;WF6BDC;;;;;SE9BU;;;WAYJC;MAlBcC;;;;;;;AAyCtBC;SAMMC;;;iBAOJC;MAGsCC;gBAIrCnB;;;;;;AFxCNoB,SAAAA;EAAAA,oBAGCC,QAAYC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;sDDgBJC;;;;;;oBAiBE;;;;;;gBChDVF;8BAEEG,MAA+BH,EAA/BG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EGe6BC;IAAAA,aCpCFrB,cAC/BsB;;;;;;iBDsDkBC,KAAAA,oBAtCWC;aACR;;;MCfTC,UADH3B,yBAAyBA;;SAI3BwB;;INTHI,qBACYC;;oBAGED;;;;cAIXE;;;;iBAqBE5B;;;;"}
\No newline at end of file