CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-graphql-tools--code-file-loader

GraphQL code file loader that extracts documents and schemas from various code files using graphql-tag-pluck

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

GraphQL Tools Code File Loader

GraphQL Tools Code File Loader is a specialized loader that extracts GraphQL documents and schema definitions from various code files. It supports extraction through two primary methods: plucking GraphQL strings from template literals and comments using graphql-tag-pluck, and loading GraphQL schemas or documents from module exports.

Package Information

  • Package Name: @graphql-tools/code-file-loader
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @graphql-tools/code-file-loader

Core Imports

import { CodeFileLoader } from "@graphql-tools/code-file-loader";
import { DocumentNode, GraphQLSchema } from "graphql";

For CommonJS:

const { CodeFileLoader } = require("@graphql-tools/code-file-loader");
const { DocumentNode, GraphQLSchema } = require("graphql");

Basic Usage

import { CodeFileLoader } from "@graphql-tools/code-file-loader";

// Create a loader instance
const loader = new CodeFileLoader();

// Load GraphQL documents from code files
const sources = await loader.load("./src/**/*.{ts,js}", {
  cwd: process.cwd(),
  noSilentErrors: true
});

// Each source contains the loaded GraphQL content
sources.forEach(source => {
  console.log(source.location); // File path
  console.log(source.document); // Parsed GraphQL document
  console.log(source.rawSDL); // Raw SDL string (if available)
});

Architecture

The CodeFileLoader operates through several key mechanisms:

  • File Pattern Matching: Uses globby for flexible file pattern matching across supported extensions
  • Dual Extraction Methods: Combines graphql-tag-pluck for extracting template literals and module loading for exported schemas
  • Synchronous/Asynchronous Operations: Provides both sync and async variants of all methods
  • Error Handling: Configurable error handling with silent mode or strict validation
  • Module Export Resolution: Automatically resolves common export patterns (default, schema, typeDefs, data)

Capabilities

CodeFileLoader Class

Main loader class implementing the GraphQL Tools Loader interface.

/**
 * GraphQL code file loader that extracts documents and schemas from code files
 * using graphql-tag-pluck and module loading.
 */
class CodeFileLoader {
  /**
   * Creates a new CodeFileLoader instance
   * @param config - Optional configuration for the loader behavior
   */
  constructor(config?: CodeFileLoaderConfig);
  
  /**
   * Check if the loader can handle the given file path
   * @param pointer - File path or glob pattern to check
   * @param options - Loader options including cwd and configuration
   * @returns Promise resolving to true if the file can be loaded
   */
  canLoad(pointer: string, options: CodeFileLoaderOptions): Promise<boolean>;
  
  /**
   * Synchronous version of canLoad
   * @param pointer - File path or glob pattern to check
   * @param options - Loader options including cwd and configuration
   * @returns True if the file can be loaded
   */
  canLoadSync(pointer: string, options: CodeFileLoaderOptions): boolean;
  
  /**
   * Resolve glob patterns to actual file paths
   * @param glob - Glob pattern to resolve
   * @param options - Options including cwd and ignore patterns
   * @returns Promise resolving to array of file paths
   */
  resolveGlobs(glob: string, options: CodeFileLoaderOptions): Promise<string[]>;
  
  /**
   * Synchronous version of resolveGlobs
   * @param glob - Glob pattern to resolve
   * @param options - Options including cwd and ignore patterns
   * @returns Array of file paths
   */
  resolveGlobsSync(glob: string, options: CodeFileLoaderOptions): string[];
  
  /**
   * Load GraphQL documents/schemas from files matching the pointer pattern
   * @param pointer - File path or glob pattern to load from
   * @param options - Loader options and configuration
   * @returns Promise resolving to array of Source objects
   * @throws AggregateError when multiple files fail to load with noSilentErrors: true
   */
  load(pointer: string, options: CodeFileLoaderOptions): Promise<Source[]>;
  
  /**
   * Synchronous version of load
   * @param pointer - File path or glob pattern to load from
   * @param options - Loader options and configuration
   * @returns Array of Source objects or null if no files found
   * @throws AggregateError when multiple files fail to load with noSilentErrors: true
   */
  loadSync(pointer: string, options: CodeFileLoaderOptions): Source[] | null;
  
  /**
   * Handle loading from a single file path
   * @param location - Absolute file path to load from
   * @param options - Loader options and configuration
   * @returns Promise resolving to array of Source objects
   */
  handleSinglePath(location: string, options: CodeFileLoaderOptions): Promise<Source[]>;
  
  /**
   * Synchronous version of handleSinglePath
   * @param location - Absolute file path to load from
   * @param options - Loader options and configuration
   * @returns Array of Source objects or null if file cannot be loaded
   */
  handleSinglePathSync(location: string, options: CodeFileLoaderOptions): Source[] | null;
}

Configuration Options

CodeFileLoaderConfig

Configuration options for the loader behavior.

interface CodeFileLoaderConfig {
  /** Configuration for graphql-tag-pluck extraction */
  pluckConfig?: GraphQLTagPluckOptions;
  
  /** Disable GraphQL string plucking from code */
  noPluck?: boolean;
  
  /** Disable module requiring/importing */
  noRequire?: boolean;
  
  /** Set to true to raise errors if any matched files are not valid GraphQL */
  noSilentErrors?: boolean;
}

CodeFileLoaderOptions

Extended options for loader operations.

interface CodeFileLoaderOptions extends CodeFileLoaderConfig, BaseLoaderOptions {
  /** Modules to require before loading */
  require?: string | string[];
}

Supported File Extensions

The loader supports extraction from multiple file types:

const FILE_EXTENSIONS: string[] = [
  '.ts',    // TypeScript files
  '.mts',   // TypeScript ES modules
  '.cts',   // TypeScript CommonJS modules
  '.tsx',   // TypeScript React files
  '.js',    // JavaScript files
  '.mjs',   // JavaScript ES modules
  '.cjs',   // JavaScript CommonJS modules
  '.jsx',   // JavaScript React files
  '.vue',   // Vue.js single file components
  '.svelte', // Svelte components
  '.astro', // Astro components
  '.gts',   // Glimmer TypeScript templates
  '.gjs'    // Glimmer JavaScript templates
];

Usage Examples

Basic File Loading

import { CodeFileLoader } from "@graphql-tools/code-file-loader";

const loader = new CodeFileLoader();

// Load from specific files
const sources = await loader.load("./schema.ts", {
  cwd: __dirname
});

Glob Pattern Matching

// Load from multiple files using glob patterns
const sources = await loader.load("./src/**/*.{ts,js}", {
  cwd: process.cwd(),
  ignore: ["**/*.test.*"]
});

Configuration Options

// Configure the loader behavior
const loader = new CodeFileLoader({
  noPluck: false,        // Enable GraphQL string plucking
  noRequire: false,      // Enable module loading
  noSilentErrors: true,  // Throw errors for invalid files
  pluckConfig: {
    modules: [
      { name: 'graphql-tag', identifier: 'gql' },
      { name: '@apollo/client', identifier: 'gql' }
    ]
  }
});

// Load with additional options
const sources = await loader.load("./queries/*.ts", {
  cwd: process.cwd(),
  require: ["ts-node/register"], // Require TypeScript support
  noSilentErrors: true
});

Handling Different Export Patterns

The loader automatically handles various export patterns:

// Default export
export default gql`query { users { id name } }`;

// Named schema export
export const schema = buildSchema(`type Query { hello: String }`);

// Module exports (CommonJS)
module.exports = {
  typeDefs: gql`type User { id: ID! name: String! }`
};

// Data export (introspection)
export const data = { __schema: { ... } };

Error Handling

try {
  const sources = await loader.load("./invalid-files/*.js", {
    noSilentErrors: true // Enable strict error reporting
  });
} catch (error) {
  if (error instanceof AggregateError) {
    // Handle multiple file errors
    error.errors.forEach(err => console.error(err.message));
  } else {
    // Handle single error
    console.error(error.message);
  }
}

Synchronous Operations

// All methods have synchronous equivalents
const loader = new CodeFileLoader();

// Check if file can be loaded
const canLoad = loader.canLoadSync("./schema.js", { cwd: __dirname });

if (canLoad) {
  // Load synchronously
  const sources = loader.loadSync("./schema.js", { 
    cwd: __dirname,
    noRequire: true // Only use plucking, no module loading
  });
}

Types

Source

Result object containing loaded GraphQL content.

interface Source {
  /** File path where the GraphQL content was found */
  location?: string;
  
  /** Parsed GraphQL document (if SDL was found) */
  document?: DocumentNode;
  
  /** Raw SDL string content */
  rawSDL?: string;
  
  /** GraphQL schema object (if schema was exported) */
  schema?: GraphQLSchema;
}

BaseLoaderOptions

Common options inherited by CodeFileLoaderOptions.

type BaseLoaderOptions = GraphQLParseOptions & BuildSchemaOptions & {
  /** Working directory for relative paths */
  cwd?: string;
  
  /** Patterns to ignore during file resolution */
  ignore?: string | string[];
  
  /** Include source locations in parsed documents */
  includeSources?: boolean;
};

GraphQLParseOptions

Options for parsing GraphQL documents.

interface GraphQLParseOptions {
  /** Disable location information in parsed documents */
  noLocation?: boolean;
  
  /** Allow legacy SDL syntax for empty fields */
  allowLegacySDLEmptyFields?: boolean;
  
  /** Allow legacy SDL syntax for implements interfaces */
  allowLegacySDLImplementsInterfaces?: boolean;
  
  /** Enable experimental fragment variables support */
  experimentalFragmentVariables?: boolean;
  
  /** Convert GraphQL comments (# sign) to descriptions (\"\"\"}) */
  commentDescriptions?: boolean;
}

BuildSchemaOptions

Options from GraphQL.js for building schemas.

interface BuildSchemaOptions {
  /** Assume the SDL is valid and skip validation */
  assumeValid?: boolean;
  
  /** Assume the SDL is valid during execution */
  assumeValidSDL?: boolean;
  
  /** Include source information in schema AST nodes */
  noLocation?: boolean;
  
  /** Allow legacy SDL syntax */
  allowLegacySDLEmptyFields?: boolean;
  allowLegacySDLImplementsInterfaces?: boolean;
  
  /** Enable experimental features */
  experimentalFragmentVariables?: boolean;
}

GraphQLTagPluckOptions

Options for configuring the graphql-tag-pluck extraction behavior.

interface GraphQLTagPluckOptions {
  /** Configured modules to extract GraphQL from */
  modules?: Array<{
    name: string;
    identifier?: string;
  }>;
  
  /** Global identifiers to look for */
  globalGqlIdentifierName?: string | string[];
  
  /** Whether to skip indent normalization */
  skipIndent?: boolean;
  
  /** Custom tag extraction patterns */
  customTags?: string[];
}

GraphQL Core Types

Core types from the GraphQL.js library used throughout the API.

/**
 * Parsed representation of a GraphQL document (query, mutation, subscription, or schema)
 */
interface DocumentNode {
  readonly kind: 'Document';
  readonly definitions: ReadonlyArray<DefinitionNode>;
  readonly loc?: Location;
}

/**
 * Runtime representation of a GraphQL schema
 */
class GraphQLSchema {
  constructor(config: GraphQLSchemaConfig);
  
  /** Get the query type */
  getQueryType(): GraphQLObjectType | null;
  
  /** Get the mutation type */
  getMutationType(): GraphQLObjectType | null;
  
  /** Get the subscription type */
  getSubscriptionType(): GraphQLObjectType | null;
  
  /** Get all types in the schema */
  getTypeMap(): TypeMap;
}
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@graphql-tools/code-file-loader@8.1.x
Publish Source
CLI
Badge
tessl/npm-graphql-tools--code-file-loader badge