npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@graphjson/core

v0.0.1

Published

> Transform JSON queries into GraphQL documents with variables and plugins

Readme

@graphjson/core

Transform JSON queries into GraphQL documents with variables and plugins

npm version License: MIT TypeScript

GraphJSON Core is the heart of the GraphJSON ecosystem, providing tools to convert JSON-based query definitions into executable GraphQL documents with full variable support and extensibility through plugins.

Why Use This?

  • 📝 Write GraphQL queries in JSON format - More structured and easier to manipulate
  • 🔄 Automatic variable extraction - Variables are managed for you
  • 🎨 Extensible plugin system - Transform queries with custom logic
  • 🎯 Full TypeScript support - Complete type safety
  • 🚀 Zero runtime dependencies - Lightweight and fast

Installation

npm install @graphjson/core @graphjson/json-dsl

Quick Start

import { generateDocument } from '@graphjson/core';
import { print } from 'graphql';

const { ast, variables } = generateDocument({
  query: {
    users: {
      args: {
        limit: { $var: 'limit', type: 'Int!', default: 10 }
      },
      select: {
        id: true,
        name: true,
        email: true
      }
    }
  }
});

// Print the generated GraphQL query
console.log(print(ast));
// Output:
// query($limit: Int!) {
//   users(limit: $limit) {
//     id
//     name
//     email
//   }
// }

console.log(variables);
// Output: { limit: 10 }

Features

1. Document Generation

Convert JSON to GraphQL DocumentNode:

const { ast, variables } = generateDocument({
  query: { /* ... */ },
  mutation: { /* ... */ },
  subscription: { /* ... */ }
});

Supports:

  • Query, Mutation, and Subscription operations
  • Nested field selections
  • Arguments and variables
  • Multiple root fields

2. Variable Management

Variables are automatically extracted and managed:

const result = generateDocument({
  query: {
    user: {
      args: {
        id: { $var: 'userId', type: 'ID!', default: '123' }
      },
      select: {
        id: true,
        name: true
      }
    }
  }
});

// Variables extracted automatically
console.log(result.variables); // { userId: '123' }

Variable Features:

  • Automatic extraction from $var syntax
  • Type definitions (ID!, String, Int, Boolean, etc.)
  • Default values
  • Proper GraphQL variable declarations

3. Plugin System

Transform documents with reusable plugins:

import { applyPlugins } from '@graphjson/core';
import { relayPagination } from '@graphjson/presets';

const transformed = applyPlugins(document, [
  relayPagination(),
  customPlugin()
]);

Plugin Capabilities:

  • Transform entire document
  • Modify individual fields
  • Add pagination structures
  • Inject directives
  • Custom query transformations

API Reference

generateDocument(json: JsonDocument): GenerateResult

Generates a GraphQL document from JSON definition.

Parameters:

| Parameter | Type | Description | |-----------|------|-------------| | json | JsonDocument | JSON query definition with query/mutation/subscription |

Returns: GenerateResult object containing:

| Property | Type | Description | |----------|------|-------------| | ast | DocumentNode | GraphQL AST (use with GraphQL clients) | | variables | Record<string, any> | Extracted variable values |

Example:

const { ast, variables } = generateDocument({
  query: {
    posts: {
      args: { first: 10 },
      select: {
        id: true,
        title: true
      }
    }
  }
});

applyPlugins(document: DocumentNode, plugins: GraphJsonPlugin[]): DocumentNode

Applies transformation plugins to a GraphQL document.

Parameters:

| Parameter | Type | Description | |-----------|------|-------------| | document | DocumentNode | GraphQL AST to transform | | plugins | GraphJsonPlugin[] | Array of plugins to apply |

Returns: DocumentNode - Transformed GraphQL AST

Example:

import { applyPlugins } from '@graphjson/core';
import { relayPagination } from '@graphjson/presets';

const transformed = applyPlugins(document, [
  relayPagination()
]);

Usage Examples

Basic Query

import { generateDocument } from '@graphjson/core';

const { ast, variables } = generateDocument({
  query: {
    users: {
      select: {
        id: true,
        name: true
      }
    }
  }
});

With Variables

const { ast, variables } = generateDocument({
  query: {
    user: {
      args: {
        id: { $var: 'userId', type: 'ID!' }
      },
      select: {
        id: true,
        email: true
      }
    }
  }
});

// Use with GraphQL client
const result = await client.request(ast, {
  ...variables,
  userId: 'user-123'  // Override variable
});

Nested Queries

const { ast, variables } = generateDocument({
  query: {
    companies: {
      args: { first: 5 },
      select: {
        id: true,
        name: true,
        departments: {
          args: { first: 3 },
          select: {
            id: true,
            name: true,
            employees: {
              args: { first: 10 },
              select: {
                id: true,
                firstName: true,
                lastName: true
              }
            }
          }
        }
      }
    }
  }
});

Multiple Operations

const { ast, variables } = generateDocument({
  query: {
    users: {
      select: { id: true, name: true }
    }
  },
  mutation: {
    createUser: {
      args: {
        input: { $var: 'userInput', type: 'UserInput!' }
      },
      select: {
        id: true,
        name: true
      }
    }
  }
});

With Plugins

import { generateDocument, applyPlugins } from '@graphjson/core';
import { relayPagination } from '@graphjson/presets';

// Generate base document
const { ast } = generateDocument({
  query: {
    posts: {
      args: { first: 20 },
      select: {
        id: true,
        title: true
      }
    }
  }
});

// Apply Relay pagination transformation
const relayQuery = applyPlugins(ast, [relayPagination()]);

// Result automatically includes edges/pageInfo structure

TypeScript Support

Full TypeScript definitions included for type-safe development.

Import Types

import type {
  JsonDocument,
  JsonField,
  JsonVariable,
  GenerateResult
} from '@graphjson/core';

Type Definitions

interface JsonDocument {
  query?: Record<string, JsonField>;
  mutation?: Record<string, JsonField>;
  subscription?: Record<string, JsonField>;
}

interface JsonField {
  args?: Record<string, JsonValue | JsonVariable>;
  select?: Record<string, boolean | JsonField>;
}

interface JsonVariable {
  $var: string;
  type: string;
  default?: any;
}

interface GenerateResult {
  ast: DocumentNode;
  variables: Record<string, any>;
}

Usage with Types

import type { JsonDocument } from '@graphjson/core';
import { generateDocument } from '@graphjson/core';

const query: JsonDocument = {
  query: {
    users: {
      args: {
        limit: { $var: 'limit', type: 'Int!', default: 10 }
      },
      select: {
        id: true,
        name: true
      }
    }
  }
};

const result = generateDocument(query);

Integration with GraphQL Clients

Apollo Client

import { ApolloClient, InMemoryCache } from '@apollo/client';
import { generateDocument } from '@graphjson/core';

const client = new ApolloClient({
  uri: 'https://api.example.com/graphql',
  cache: new InMemoryCache()
});

const { ast, variables } = generateDocument(myQuery);

const result = await client.query({
  query: ast,
  variables
});

urql

import { createClient } from 'urql';
import { generateDocument } from '@graphjson/core';

const client = createClient({
  url: 'https://api.example.com/graphql'
});

const { ast, variables } = generateDocument(myQuery);

const result = await client.query(ast, variables).toPromise();

graphql-request

import { GraphQLClient } from 'graphql-request';
import { generateDocument } from '@graphjson/core';

const client = new GraphQLClient('https://api.example.com/graphql');

const { ast, variables } = generateDocument(myQuery);

const result = await client.request(ast, variables);

Examples

Basic Example

const { ast } = generateDocument({
  query: {
    users: {
      select: {
        id: true,
        name: true
      }
    }
  }
});

Generates:

query {
  users {
    id
    name
  }
}

With Arguments

const { ast } = generateDocument({
  query: {
    user: {
      args: { id: "123" },
      select: {
        id: true,
        name: true
      }
    }
  }
});

Generates:

query {
  user(id: "123") {
    id
    name
  }
}

With Variables

const { ast, variables } = generateDocument({
  query: {
    users: {
      args: {
        limit: { $var: 'pageSize', type: 'Int!', default: 20 },
        offset: { $var: 'offset', type: 'Int', default: 0 }
      },
      select: {
        id: true,
        name: true
      }
    }
  }
});

Generates:

query($pageSize: Int!, $offset: Int) {
  users(limit: $pageSize, offset: $offset) {
    id
    name
  }
}

With variables:

{
  "pageSize": 20,
  "offset": 0
}

GraphJSON Ecosystem

This package is part of the GraphJSON ecosystem:

| Package | Description | NPM | |---------|-------------|-----| | @graphjson/json-dsl | JSON DSL type definitions | npm | | @graphjson/ast | AST building utilities | npm | | @graphjson/printer | Query string printer | npm | | @graphjson/plugins | Plugin system types | npm | | @graphjson/presets | Common presets (Relay, etc.) | npm | | @graphjson/sdk | High-level type-safe SDK | npm | | @graphjson/schema | Schema validation | npm |

Examples

Check out the examples directory for complete working examples:

Contributing

Contributions are welcome! Please see CONTRIBUTING.md for guidelines.

License

MIT © NexaLeaf

Support