diff --git a/src/mock/generator.ts b/src/mock/generator.ts index b3766a8..8b1c2c0 100644 --- a/src/mock/generator.ts +++ b/src/mock/generator.ts @@ -1,3 +1,4 @@ +import { getOperationAST, Kind, parse } from 'graphql'; import { unwrapType } from '../operations/variables.js'; import { GraphQLExecutor } from '../mcp/executor.js'; import type { ParsedSchema, SchemaField, TypeReference } from '../types/index.js'; @@ -11,6 +12,18 @@ export interface MockConfig { const DEFAULT_ARRAY_LENGTH = 3; const DEFAULT_MAX_DEPTH = 3; +const validateConfig = (config?: MockConfig): void => { + const limits = [ + config?.arrayLength ?? DEFAULT_ARRAY_LENGTH, + config?.maxDepth ?? DEFAULT_MAX_DEPTH, + ]; + for (const value of limits) { + if (!Number.isSafeInteger(value) || value < 0) { + throw new RangeError('Mock arrayLength and maxDepth must be non-negative safe integers'); + } + } +}; + /** * Simple deterministic hash from a string. * Returns a positive integer. @@ -223,6 +236,7 @@ export const generateMockData = ( typeName: string, config?: MockConfig, ): Record => { + validateConfig(config); const seed = config?.seed ?? 0; const arrayLength = config?.arrayLength ?? DEFAULT_ARRAY_LENGTH; const maxDepth = config?.maxDepth ?? DEFAULT_MAX_DEPTH; @@ -244,11 +258,14 @@ export const generateMockData = ( /** * Extract the root field name from a GraphQL operation string. */ -const extractRootFieldName = (operation: string): string | null => { - // Match the first field after the opening brace of the operation - // e.g., "query UserQuery($id: ID!) {\n user(id: $id) {\n..." - const match = operation.match(/\{\s*(?\w+)/u); - return match?.groups?.fieldName ?? null; +const extractRootFieldName = (operation: string): { name: string; responseName: string } | null => { + const definition = getOperationAST(parse(operation)); + const field = definition?.selectionSet.selections.find( + (selection) => selection.kind === Kind.FIELD, + ); + return field + ? { name: field.name.value, responseName: field.alias?.value ?? field.name.value } + : null; }; /** @@ -320,6 +337,7 @@ const isListField = (schema: ParsedSchema, fieldName: string): boolean => { * Implements the same interface as GraphQLExecutor. */ export const createMockExecutor = (schema: ParsedSchema, config?: MockConfig): GraphQLExecutor => { + validateConfig(config); const mockExecutor = Object.create(GraphQLExecutor.prototype) as GraphQLExecutor; // Override the execute method @@ -327,15 +345,17 @@ export const createMockExecutor = (schema: ParsedSchema, config?: MockConfig): G operation: string, ): Promise => { // Parse the operation to find the root field name and its return type - const rootFieldName = extractRootFieldName(operation); - if (!rootFieldName) { + const rootField = extractRootFieldName(operation); + if (!rootField) { return JSON.stringify({ data: null }); } + const { name: rootFieldName, responseName } = rootField; + // Find the return type from the schema const returnTypeName = findReturnTypeName(schema, rootFieldName); if (!returnTypeName) { - return JSON.stringify({ data: { [rootFieldName]: null } }); + return JSON.stringify({ data: { [responseName]: null } }); } // Check if it's a scalar return type @@ -345,7 +365,7 @@ export const createMockExecutor = (schema: ParsedSchema, config?: MockConfig): G index: 0, seed: config?.seed ?? 0, }); - return JSON.stringify({ data: { [rootFieldName]: scalarValue } }, null, 2); + return JSON.stringify({ data: { [responseName]: scalarValue } }, null, 2); } // Check if the field returns a list @@ -361,11 +381,11 @@ export const createMockExecutor = (schema: ParsedSchema, config?: MockConfig): G }), ); } - return JSON.stringify({ data: { [rootFieldName]: items } }, null, 2); + return JSON.stringify({ data: { [responseName]: items } }, null, 2); } const mockData = generateMockData(schema, returnTypeName, config); - return JSON.stringify({ data: { [rootFieldName]: mockData } }, null, 2); + return JSON.stringify({ data: { [responseName]: mockData } }, null, 2); }; return mockExecutor; diff --git a/src/pagination/handler.ts b/src/pagination/handler.ts index d5cd4e1..609b707 100644 --- a/src/pagination/handler.ts +++ b/src/pagination/handler.ts @@ -176,12 +176,15 @@ const executeRelayPaginated = async ({ variables, }: PaginationExecutionContext): Promise => { const allItems: unknown[] = []; - let cursor: string | null = null; + let cursor: string | null = typeof variables.after === 'string' ? variables.after : null; + const requestedCursors = new Set(); + let canFetchMore = true; let startCursor: string | null = null; let hasMore = true; let pageCount = 0; - while (hasMore && (pageCount === 0 || Boolean(cursor)) && pageCount < maxPages) { + while (hasMore && canFetchMore && pageCount < maxPages) { + requestedCursors.add(cursor); const pageVariables: Record = { ...variables, first: pageSize, @@ -219,8 +222,9 @@ const executeRelayPaginated = async ({ } hasMore = hasNextPage; + canFetchMore = Boolean(endCursor) && !requestedCursors.has(endCursor); // The cursor is loop-carried state and is also returned to the caller. - // eslint-disable-next-line sonarjs/no-redundant-assignments + cursor = endCursor; pageCount += 1; } @@ -249,12 +253,12 @@ const executeOffsetPaginated = async ({ variables, }: PaginationExecutionContext): Promise => { const allItems: unknown[] = []; - let currentOffset = 0; let hasMore = true; let pageCount = 0; // Detect whether to use limit/offset or skip/take const useSkipTake = operation.includes('$skip') && operation.includes('$take'); + let currentOffset = Number((useSkipTake ? variables.skip : variables.offset) ?? 0); while (hasMore && pageCount < maxPages) { const pageVariables: Record = { ...variables }; @@ -304,6 +308,16 @@ export const executePaginated = async ( const style = config?.style ?? 'auto'; const pageSize = config?.pageSize ?? DEFAULT_PAGE_SIZE; const maxPages = config?.maxPages ?? DEFAULT_MAX_PAGES; + if ( + !Number.isSafeInteger(pageSize) || + pageSize <= 0 || + !Number.isSafeInteger(maxPages) || + maxPages < 0 + ) { + throw new RangeError( + 'pageSize must be a positive safe integer and maxPages a non-negative safe integer', + ); + } if (style === 'relay' || (style === 'auto' && isRelayOperation(operation))) { return executeRelayPaginated({ executor, maxPages, operation, pageSize, variables }); diff --git a/src/summarizer/summarizer.ts b/src/summarizer/summarizer.ts index bd7283a..74904e5 100644 --- a/src/summarizer/summarizer.ts +++ b/src/summarizer/summarizer.ts @@ -94,7 +94,12 @@ export const summarizeResponse = ( const result: Record = {}; for (const [key, currentValue] of Object.entries(value as Record)) { - result[key] = summarize(currentValue, depth + 1); + Object.defineProperty(result, key, { + configurable: true, + enumerable: true, + value: summarize(currentValue, depth + 1), + writable: true, + }); } return result; } diff --git a/tests/maintenance-regression.test.ts b/tests/maintenance-regression.test.ts new file mode 100644 index 0000000..f6ea842 --- /dev/null +++ b/tests/maintenance-regression.test.ts @@ -0,0 +1,73 @@ +import { expect, it, vi } from 'vitest'; +import { buildSchema, introspectionFromSchema } from 'graphql'; +import { parseSchema } from '../src/introspection/parser.js'; +import { executePaginated } from '../src/pagination/handler.js'; +import { createMockExecutor, generateMockData } from '../src/mock/generator.js'; +import { summarizeResponse } from '../src/summarizer/summarizer.js'; +import type { GraphQLExecutor } from '../src/mcp/executor.js'; + +const schema = parseSchema( + introspectionFromSchema( + buildSchema('type Query { users: [User] user: User } type User { name: String }'), + ), +); + +it.each(['offset', 'skip'])('starts pagination at the supplied %s', async (key) => { + const execute = vi.fn().mockResolvedValue('{"users":[]}'); + const operation = + key === 'skip' ? 'query($skip:Int,$take:Int){users}' : 'query($offset:Int,$limit:Int){users}'; + await executePaginated( + { execute } as unknown as GraphQLExecutor, + operation, + { [key]: 40 }, + { pageSize: 20, style: 'offset' }, + ); + expect(execute.mock.calls[0][1][key]).toBe(40); +}); + +it('rejects invalid pagination bounds before making a request', async () => { + const execute = vi.fn().mockResolvedValue('{"users":[]}'); + const executor = { execute } as unknown as GraphQLExecutor; + await expect( + executePaginated(executor, '{users}', {}, { pageSize: 0, style: 'offset' }), + ).rejects.toThrow(RangeError); + await expect( + executePaginated(executor, '{users}', {}, { maxPages: NaN, pageSize: 20, style: 'offset' }), + ).rejects.toThrow(RangeError); + expect(execute).not.toHaveBeenCalled(); +}); + +it('stops when a Relay server repeats a cursor', async () => { + const execute = vi + .fn() + .mockResolvedValue( + '{"users":{"edges":[{"node":{"name":"A"}}],"pageInfo":{"hasNextPage":true,"endCursor":"same"}}}', + ); + const result = await executePaginated( + { execute } as unknown as GraphQLExecutor, + '{users}', + {}, + { maxPages: 5, pageSize: 1, style: 'relay' }, + ); + expect(execute).toHaveBeenCalledTimes(2); + expect(result.hasMore).toBe(true); +}); + +it('uses the actual root field and the response alias in mock operations', async () => { + const executor = createMockExecutor(schema); + const result = JSON.parse(await executor.execute('{ alias: user { name } }')); + expect(result.data.alias).toEqual({ name: 'mock_name' }); +}); + +it('rejects mock sizes that can overrun or skip generation', () => { + expect(() => generateMockData(schema, 'User', { arrayLength: 1.5 })).toThrow(RangeError); + expect(() => createMockExecutor(schema, { arrayLength: -1 })).toThrow(RangeError); +}); + +it('preserves own prototype-named JSON fields when summarizing', () => { + const data = JSON.parse('{"__proto__":{"name":"kept"},"name":"other"}'); + const { summary } = summarizeResponse(data); + expect(Object.getPrototypeOf(summary)).toBe(Object.prototype); + expect(Object.hasOwn(summary as object, '__proto__')).toBe(true); + expect(JSON.stringify(summary)).toBe(JSON.stringify(data)); +}); diff --git a/tests/pagination/handler.test.ts b/tests/pagination/handler.test.ts index 0199805..ac5e3e5 100644 --- a/tests/pagination/handler.test.ts +++ b/tests/pagination/handler.test.ts @@ -242,7 +242,11 @@ describe('executePaginated - Relay', () => { }); const mockExecutor = { - execute: vi.fn().mockResolvedValue(pageResponse), + execute: vi + .fn() + .mockResolvedValueOnce(pageResponse.replace('cursorN', 'cursor1')) + .mockResolvedValueOnce(pageResponse.replace('cursorN', 'cursor2')) + .mockResolvedValueOnce(pageResponse.replace('cursorN', 'cursor3')), } as unknown as GraphQLExecutor; const operation = `query Users($first: Int, $after: String) {