CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-gts

Google TypeScript Style guide, formatter, linter, and code fixer with zero configuration required

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

utilities.mddocs/

Utility Functions

Helper functions for configuration management, package detection, and file operations in gts.

Capabilities

TypeScript Configuration Management

Read and parse TypeScript configuration files with support for extends inheritance.

/**
 * Find, read, and parse tsconfig.json with extends support
 * @param rootDir - Directory where tsconfig.json should be found
 * @param customReadFilep - Optional custom file reading function for testing
 * @returns Promise resolving to parsed and merged configuration
 * @throws Error on circular references or parsing errors
 */
function getTSConfig(
  rootDir: string,
  customReadFilep?: ReadFileP
): Promise<ConfigFile>;

interface ConfigFile {
  files?: string[];
  compilerOptions?: {};
  include?: string[];
  exclude?: string[];
  extends?: string[];
}

interface ReadFileP {
  (path: string, encoding: string): Promise<string>;
}

Usage Example:

import { getTSConfig } from "gts/build/src/util";

// Read tsconfig.json from current directory
const config = await getTSConfig(process.cwd());

console.log("Compiler options:", config.compilerOptions);
console.log("Include patterns:", config.include);

Features:

  • Supports TypeScript's extends configuration inheritance
  • Handles relative path resolution for extended configurations
  • Detects and prevents circular references
  • Uses JSON5 parser for flexible JSON syntax
  • Merges configurations correctly (child overrides parent)

Package Manager Detection

Automatically detect whether to use npm or yarn based on lock files.

/**
 * Determine if yarn should be used based on lock file presence
 * @param existsSync - Optional file existence check function for testing
 * @returns true if yarn should be used, false for npm
 */
function isYarnUsed(existsSync?: Function): boolean;

Detection Logic:

  • If package-lock.json exists: use npm
  • If only yarn.lock exists: use yarn
  • If both exist: use npm (npm takes precedence)
  • If neither exists: use npm (default)

Usage Example:

import { isYarnUsed } from "gts/build/src/util";

const useYarn = isYarnUsed();
console.log(`Using ${useYarn ? 'yarn' : 'npm'}`);

Package Manager Command Generation

Get the appropriate package manager command for the current platform.

/**
 * Get package manager command with platform-specific extension
 * @param isYarnUsed - Whether to use yarn (true) or npm (false)
 * @returns Package manager command ('npm', 'yarn', 'npm.cmd', or 'yarn.cmd')
 */
function getPkgManagerCommand(isYarnUsed?: boolean): string;

Platform Handling:

  • Windows: Appends .cmd extension
  • Unix/Linux/macOS: Uses bare command name

Usage Example:

import { getPkgManagerCommand, isYarnUsed } from "gts/build/src/util";

const useYarn = isYarnUsed();
const command = getPkgManagerCommand(useYarn);

// Use in child process spawning
import { spawn } from "child_process";
spawn(command, ['install'], { stdio: 'inherit' });

File Operations

Promisified versions of common file system operations.

/**
 * Promisified fs.readFile for async/await usage
 */
const readFilep: (path: string, options?: any) => Promise<string | Buffer>;

/**
 * Promisified rimraf for recursive directory removal
 */
const rimrafp: (path: string) => Promise<void>;

/**
 * Promisified ncp.ncp for recursive file copying
 */
const ncpp: (source: string, dest: string, options?: any) => Promise<void>;

Usage Examples:

import { readFilep, rimrafp, ncpp } from "gts/build/src/util";

// Read file content
const content = await readFilep("package.json", "utf8");

// Remove directory recursively
await rimrafp("build/");

// Copy directory recursively
await ncpp("template/", "src/");

JSON Parsing

Read and parse JSON5 files with better error messages.

/**
 * Read and parse JSON5 files
 * @param jsonPath - Path to JSON/JSON5 file
 * @returns Promise resolving to parsed object
 * @throws Error with enhanced error messages for parsing failures
 */
function readJsonp(jsonPath: string): Promise<any>;

Features:

  • Supports JSON5 syntax (comments, trailing commas, etc.)
  • Enhanced error messages with file path context
  • UTF-8 encoding by default

Usage Example:

import { readJsonp } from "gts/build/src/util";

try {
  const packageJson = await readJsonp("./package.json");
  console.log("Package name:", packageJson.name);
} catch (error) {
  console.error("Failed to parse JSON:", error.message);
}

Utility Types and Interfaces

Type definitions for common data structures.

/**
 * Generic object with string keys
 */
interface Bag<T> {
  [script: string]: T;
}

/**
 * Default package dependencies for gts initialization
 */
interface DefaultPackage extends Bag<string> {
  gts: string;
  typescript: string;
  '@types/node': string;
}

No-Operation Function

Utility function for testing and optional callbacks.

/**
 * No-operation function for testing and optional callbacks
 */
function nop(): void;

Usage Example:

import { nop } from "gts/build/src/util";

// Use as logger in tests
const testOptions = {
  logger: { log: nop, error: nop, dir: nop }
};

Configuration File Processing

Internal functions for handling TypeScript configuration inheritance.

The getTSConfig function implements TypeScript's configuration resolution algorithm:

  1. Base Resolution: Recursively resolves extends configurations
  2. Path Resolution: Handles relative paths from configuration file directories
  3. Circular Detection: Prevents infinite loops from circular references
  4. Configuration Merging: Properly merges parent and child configurations
  5. Error Enhancement: Provides detailed error messages with file context

Example with complex inheritance:

// Base config: node_modules/gts/tsconfig-google.json
{
  "compilerOptions": {
    "strict": true,
    "target": "es2018"
  }
}

// Project tsconfig.json
{
  "extends": "./node_modules/gts/tsconfig-google.json",
  "compilerOptions": {
    "outDir": "build",
    "rootDir": "."
  },
  "include": ["src/**/*.ts"]
}

// Resolved configuration
const config = await getTSConfig(".");
// Results in merged configuration with all options

Error Handling Patterns

All utility functions follow consistent error handling patterns:

  • File Not Found: Specific error messages for missing files
  • Parse Errors: Enhanced JSON parsing errors with file context
  • Path Resolution: Clear errors for invalid path references
  • System Errors: Preserved system error details with additional context

Example error handling:

import { getTSConfig, readJsonp } from "gts/build/src/util";

try {
  const config = await getTSConfig("./invalid-dir");
} catch (error) {
  if (error.message.includes("ENOENT")) {
    console.error("tsconfig.json not found");
  } else {
    console.error("Configuration error:", error.message);
  }
}

docs

build-management.md

cli-commands.md

index.md

initialization.md

utilities.md

tile.json