Skip to content

Commit

Permalink
Backport GraphQL-Tag fix
Browse files Browse the repository at this point in the history
  • Loading branch information
JoviDeCroock committed Oct 31, 2024
1 parent 0e92930 commit 5a44f58
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/tiny-gifts-exercise.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@0no-co/graphql.web': patch
---

Add `loc` getter to parsed `DocumentNode` fragment outputs to ensure that using fragments created by `gql.tada`'s `graphql()` function with `graphql-tag` doesn't crash. `graphql-tag` does not treat the `DocumentNode.loc` property as optional on interpolations, which leads to intercompatibility issues.
2 changes: 1 addition & 1 deletion src/__tests__/parser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { Kind } from '../kind';

describe('parse', () => {
it('parses the kitchen sink document like graphql.js does', () => {
const doc = parse(kitchenSinkDocument);
const doc = parse(kitchenSinkDocument, { noLocation: true });
expect(doc).toMatchSnapshot();
});

Expand Down
37 changes: 33 additions & 4 deletions src/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/
import type { Kind, OperationTypeNode } from './kind';
import { GraphQLError } from './error';
import type { Source } from './types';
import type { Location, Source } from './types';
import type * as ast from './ast';

let input: string;
Expand Down Expand Up @@ -483,7 +483,7 @@ function operationDefinition(
}
}

function document(): ast.DocumentNode {
function document(input: string, noLoc: boolean): ast.DocumentNode {
let match: string | undefined;
let definition: ast.OperationDefinitionNode | undefined;
ignored();
Expand All @@ -498,6 +498,35 @@ function document(): ast.DocumentNode {
throw error('Document');
}
} while (idx < input.length);

if (!noLoc) {
let loc: Location | undefined;
return {
kind: 'Document' as Kind.DOCUMENT,
definitions,
set loc(_loc: Location) {
loc = _loc;
},
// @ts-ignore
get loc() {
if (!loc) {
loc = {
start: 0,
end: input.length,
startToken: undefined,
endToken: undefined,
source: {
body: input,
name: 'graphql.web',
locationOffset: { line: 1, column: 1 },
},
};
}
return loc;
},
};
}

return {
kind: 'Document' as Kind.DOCUMENT,
definitions,
Expand All @@ -510,11 +539,11 @@ type ParseOptions = {

export function parse(
string: string | Source,
_options?: ParseOptions | undefined
options?: ParseOptions | undefined
): ast.DocumentNode {
input = typeof string.body === 'string' ? string.body : string;
idx = 0;
return document();
return document(input, options && options.noLocation);
}

export function parseValue(
Expand Down

0 comments on commit 5a44f58

Please sign in to comment.