UNPKG

graphql

Version:

A Query Language and Runtime which can target any service.

1 lines 2.13 kB
{"version":3,"file":"location.js","sourceRoot":"","sources":["../../src/language/location.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,SAAS,EAAE,iCAAgC;AAIpD,MAAM,UAAU,GAAG,cAAc,CAAC;AA0BlC,MAAM,UAAU,WAAW,CAAC,MAAc,EAAE,QAAgB;IAC1D,IAAI,aAAa,GAAG,CAAC,CAAC;IACtB,IAAI,IAAI,GAAG,CAAC,CAAC;IAEb,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE,CAAC;cAC3C,OAAO,KAAK,CAAC,KAAK,KAAK,QAAQ;YAAzC,SAAS;QACT,IAAI,KAAK,CAAC,KAAK,IAAI,QAAQ,EAAE,CAAC;YAC5B,MAAM;QACR,CAAC;QACD,aAAa,GAAG,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;QAC9C,IAAI,IAAI,CAAC,CAAC;IACZ,CAAC;IAED,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,GAAG,CAAC,GAAG,aAAa,EAAE,CAAC;AACxD,CAAC","sourcesContent":["/** @category Source */\n\nimport { invariant } from '../jsutils/invariant.ts';\n\nimport type { Source } from './source.ts';\n\nconst LineRegExp = /\\r\\n|[\\n\\r]/g;\n\n/** Represents a location in a Source. */\nexport interface SourceLocation {\n /** One-indexed line number in the source document. */\n readonly line: number;\n /** One-indexed column number in the source document. */\n readonly column: number;\n}\n\n/**\n * Takes a Source and a UTF-8 character offset, and returns the corresponding\n * line and column as a SourceLocation.\n * @param source - The source document that contains the position.\n * @param position - The UTF-8 character offset in the source body.\n * @returns The 1-indexed line and column for the given source position.\n * @example\n * ```ts\n * import { Source, getLocation } from 'graphql/language';\n *\n * const source = new Source('type Query { hello: String }');\n * const location = getLocation(source, 13);\n *\n * location; // => { line: 1, column: 14 }\n * ```\n */\nexport function getLocation(source: Source, position: number): SourceLocation {\n let lastLineStart = 0;\n let line = 1;\n\n for (const match of source.body.matchAll(LineRegExp)) {\n invariant(typeof match.index === 'number');\n if (match.index >= position) {\n break;\n }\n lastLineStart = match.index + match[0].length;\n line += 1;\n }\n\n return { line, column: position + 1 - lastLineStart };\n}\n"]}