npm package: @schemashift/core
Description: Core schema analysis, transformation engine, ecosystem detection, governance, and migration utilities for SchemaShift
Author: Joseph May
Latest version: 0.14.0

# @schemashift/core

Core functionality for SchemaShift schema migrations. Provides schema analysis, detection, transformation engine, ecosystem analysis, governance, and migration utilities.

[![npm version](https://img.shields.io/npm/v/@schemashift/core.svg)](https://www.npmjs.com/package/@schemashift/core)
[![npm downloads](https://img.shields.io/npm/dm/@schemashift/core.svg)](https://www.npmjs.com/package/@schemashift/core)
[![CI](https://github.com/jdmay2/schemashift/actions/workflows/ci.yml/badge.svg)](https://github.com/jdmay2/schemashift/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)

## Installation

```bash
npm install @schemashift/core
```

## API

### SchemaAnalyzer

Analyzes TypeScript/JavaScript files to detect schema definitions.

```typescript
import { SchemaAnalyzer } from '@schemashift/core';

const analyzer = new SchemaAnalyzer('./tsconfig.json');
analyzer.addSourceFiles(['src/**/*.ts']);

const result = analyzer.analyze();
console.log(`Found ${result.schemas.length} schemas in ${result.filesWithSchemas} files`);
```

#### Methods

- `addSourceFiles(patterns: string[])` — Add files to analyze by glob patterns
- `analyze(): AnalysisResult` — Run analysis and return results
- `getProject(): Project` — Get the underlying ts-morph Project

### TransformEngine

Manages transformation handlers and executes migrations.

```typescript
import { TransformEngine } from '@schemashift/core';
import { createYupToZodHandler } from '@schemashift/yup-zod';

const engine = new TransformEngine();
engine.registerHandler('yup', 'zod', createYupToZodHandler());

const sourceFile = project.getSourceFileOrThrow('schema.ts');
const result = engine.transform(sourceFile, 'yup', 'zod');

if (result.success) {
  console.log(result.transformedCode);
}
```

#### Methods

- `registerHandler(from, to, handler)` — Register a transformation handler
- `getHandler(from, to)` — Get a registered handler
- `transform(sourceFile, from, to)` — Transform a source file

### DetailedAnalyzer

Provides complexity scoring, migration readiness analysis, and library version detection.

```typescript
import { DetailedAnalyzer, SchemaAnalyzer } from '@schemashift/core';

const analyzer = new SchemaAnalyzer();
analyzer.addSourceFiles(['src/**/*.ts']);

const detailed = new DetailedAnalyzer();

// Complexity scoring per-schema
const complexities = detailed.analyzeComplexity(analyzer);
for (const c of complexities) {
  console.log(`${c.schemaName}: score=${c.score}, level=${c.level}`);
}

// Migration readiness
const readiness = detailed.analyzeReadiness(schemas, 'yup', 'zod', supportedMethods);
console.log(`${readiness.readinessPercent}% ready, risk: ${readiness.riskLevel}`);

// Library versions from package.json
const versions = detailed.detectLibraryVersions('./project');
// [{ library: 'zod', version: '^3.22.0' }, ...]

// Full detailed result
const result = detailed.generateDetailedResult(complexities, './project');
console.log(`Average complexity: ${result.averageComplexity}`);
```

### EcosystemAnalyzer

Detects ecosystem packages affected by a migration. Checks for compatibility issues with tRPC, drizzle-zod, zod-validation-error, @hookform/resolvers, Formik, Mantine, OpenAPI generators, and more.

```typescript
import { EcosystemAnalyzer } from '@schemashift/core';

const ecosystem = new EcosystemAnalyzer();
const report = ecosystem.analyze('./project', 'zod-v3', 'v4');

// Blockers — packages that will break
for (const blocker of report.blockers) {
  console.error(blocker);
}

// Warnings — packages that may need updating
for (const warning of report.warnings) {
  console.warn(warning);
}

// Full issue details
for (const dep of report.dependencies) {
  console.log(`${dep.package}@${dep.installedVersion}: ${dep.issue}`);
  console.log(`  Suggestion: ${dep.suggestion}`);
  console.log(`  Severity: ${dep.severity}, Category: ${dep.category}`);
}
```

#### Detected Packages

| Package | Migration | Category |
|---------|-----------|----------|
| `drizzle-zod` | zod-v3→v4 | ORM |
| `zod-prisma` / `zod-prisma-types` | zod-v3→v4 | ORM |
| `@trpc/server` | zod-v3→v4 | API |
| `trpc-ui` | zod-v3→v4 | UI |
| `zod-validation-error` | zod-v3→v4 | Validation |
| `@hookform/resolvers` | all→zod, zod-v3→v4 | Form |
| `formik` | yup→zod, joi→zod | Form |
| `@mantine/form` | yup→zod, joi→zod | Form |
| `zod-openapi` / `@asteasolutions/zod-to-openapi` | zod-v3→v4 | OpenAPI |

### PackageUpdater

Plans and applies dependency changes to `package.json` after migration.

```typescript
import { PackageUpdater } from '@schemashift/core';

const updater = new PackageUpdater();

// Plan changes (doesn't modify files)
const plan = updater.plan('./project', 'yup', 'zod');
console.log('Add:', plan.add);       // { zod: '^3.24.0' }
console.log('Remove:', plan.remove); // ['yup'] (suggested, not auto-removed)
console.log('Warnings:', plan.warnings);

// Apply the additions to package.json
updater.apply('./project', plan);
```

### IncrementalTracker

Tracks progress for file-by-file incremental migrations. State is persisted in `.schemashift/incremental.json`.

```typescript
import { IncrementalTracker } from '@schemashift/core';

const tracker = new IncrementalTracker('./project');

// Start a new incremental migration
const state = tracker.start(['a.ts', 'b.ts', 'c.ts'], 'yup', 'zod');

// Process files in batches
const batch = tracker.getNextBatch(2); // ['a.ts', 'b.ts']

// Mark files as complete or failed
tracker.markComplete('a.ts');
tracker.markFailed('b.ts');

// Check progress
const progress = tracker.getProgress();
// { completed: 1, remaining: 1, failed: 1, total: 3, percent: 33 }

// Resume a previous migration
const resumed = tracker.resume();

// Clear state when done
tracker.clear();
```

### GovernanceEngine

Enforces schema quality rules across a codebase.

```typescript
import { GovernanceEngine } from '@schemashift/core';
import { Project } from 'ts-morph';

const engine = new GovernanceEngine();
engine.configure({
  'naming-convention': { pattern: '.*Schema$' },
  'max-complexity': { threshold: 80 },
  'no-any': {},
  'required-validations': {},
});

const project = new Project();
project.addSourceFilesAtPaths(['src/**/*.ts']);

const result = engine.analyze(project);
console.log(`Passed: ${result.passed}`);
console.log(`Files scanned: ${result.filesScanned}`);
console.log(`Schemas checked: ${result.schemasChecked}`);

for (const v of result.violations) {
  console.log(`[${v.severity}] ${v.rule}: ${v.message} (${v.filePath}:${v.lineNumber})`);
}
```

#### Built-in Rules

| Rule | Description | Severity |
|------|-------------|----------|
| `naming-convention` | Schemas must match a regex pattern | warning |
| `max-complexity` | Reject schemas exceeding a complexity score | warning |
| `no-any` | Disallow `.any()` usage | error |
| `required-validations` | String schemas must include `.max()` | warning |

### CompatibilityAnalyzer

Checks schema library version compatibility before migration.

```typescript
import { CompatibilityAnalyzer } from '@schemashift/core';

const compat = new CompatibilityAnalyzer();
const result = compat.checkCompatibility('./project', 'zod-v3', 'v4');
```

### MigrationChain

Executes multi-step migrations (e.g., `yup→zod→valibot`).

```typescript
import { MigrationChain } from '@schemashift/core';

const chain = new MigrationChain(engine);
const result = chain.execute(sourceFile, [
  { from: 'yup', to: 'zod' },
  { from: 'zod', to: 'valibot' },
]);
```

### SchemaDependencyResolver

Resolves cross-file schema imports for dependency-ordered transformations.

```typescript
import { SchemaDependencyResolver } from '@schemashift/core';

const resolver = new SchemaDependencyResolver();
const graph = resolver.resolve(project, files);
// graph.order: files sorted by dependency (leaves first)
```

### PluginLoader

Loads custom transform plugins from file paths or npm packages.

```typescript
import { PluginLoader } from '@schemashift/core';

const loader = new PluginLoader();
const result = loader.load('./my-plugin.js');
if (result.success) {
  engine.registerHandler(result.plugin.from, result.plugin.to, result.plugin.handler);
}
```

### detectStandardSchema

Detects Standard Schema-compatible libraries in a project.

```typescript
import { detectStandardSchema } from '@schemashift/core';

const info = detectStandardSchema('./project');
if (info.detected) {
  console.log('Compatible libraries:', info.compatibleLibraries);
  console.log(info.recommendation);
}
```

Supports: Zod 3.23+, Valibot 1.0+, ArkType 2.0+, @effect/schema, TypeBox 0.34+.

### BehavioralWarningAnalyzer

Detects behavioral differences between schema libraries during migration.

```typescript
import { BehavioralWarningAnalyzer } from '@schemashift/core';

const analyzer = new BehavioralWarningAnalyzer();
const result = analyzer.analyze(sourceFiles, 'yup', 'zod');
// result.warnings: grouped by category (coercion, validation-order, error-format)
for (const w of result.warnings) {
  console.log(`[${w.category}] ${w.message}`);
}
```

**Tier:** FREE (all tiers)

### BundleEstimator

Estimates bundle size impact of switching schema libraries.

```typescript
import { BundleEstimator } from '@schemashift/core';

const estimator = new BundleEstimator();
const estimate = estimator.estimate(sourceFiles, 'zod', 'valibot');
console.log(`From: ${estimate.from.minifiedGzipKB}kB → To: ${estimate.to.minifiedGzipKB}kB`);
console.log(`Delta: ${estimate.estimatedDelta.toFixed(1)}kB (${estimate.deltaPercent.toFixed(0)}%)`);
```

**Tier:** INDIVIDUAL+

### PerformanceAnalyzer

Identifies potential performance impacts of migration.

```typescript
import { PerformanceAnalyzer } from '@schemashift/core';

const analyzer = new PerformanceAnalyzer();
const result = analyzer.analyze(sourceFiles, 'zod-v3', 'v4');
for (const w of result.warnings) {
  console.log(`[${w.severity}] ${w.message}: ${w.detail}`);
}
```

**Tier:** INDIVIDUAL+

### TypeDedupDetector

Finds structurally similar schema definitions across files.

```typescript
import { TypeDedupDetector } from '@schemashift/core';

const detector = new TypeDedupDetector();
const result = detector.detect(sourceFiles);
for (const candidate of result.candidates) {
  console.log(`Duplicate: ${candidate.schemas.map(s => s.name).join(', ')} (${candidate.confidence}% confidence)`);
}
```

**Tier:** INDIVIDUAL+

### TestScaffolder

Generates validation test stubs for migrated schemas.

```typescript
import { TestScaffolder } from '@schemashift/core';

const scaffolder = new TestScaffolder();
const result = scaffolder.scaffold(sourceFiles, 'yup', 'zod');
console.log(`Generated ${result.tests.length} test files for ${result.totalSchemas} schemas`);
for (const test of result.tests) {
  console.log(`  ${test.filePath} (${test.schemaCount} schemas)`);
}
```

**Tier:** PRO+

### MigrationAuditLog

Records detailed migration history for compliance and auditing.

```typescript
import { MigrationAuditLog } from '@schemashift/core';

const auditLog = new MigrationAuditLog('./project');
const entry = auditLog.createEntry({
  file: 'src/schema.ts',
  from: 'yup',
  to: 'zod',
  success: true,
  warningsCount: 2,
});
auditLog.append(entry);
// Writes to .schemashift/audit-log.json
```

**Tier:** TEAM

### detectSchemaLibrary

Detects which schema library a module import refers to.

```typescript
import { detectSchemaLibrary } from '@schemashift/core';

detectSchemaLibrary('zod');      // 'zod'
detectSchemaLibrary('yup');      // 'yup'
detectSchemaLibrary('joi');      // 'joi'
detectSchemaLibrary('io-ts');    // 'io-ts'
detectSchemaLibrary('valibot');  // 'valibot'
detectSchemaLibrary('lodash');   // 'unknown'
```

### detectFormLibraries

Detects form libraries (React Hook Form, Formik, Mantine) in use.

```typescript
import { detectFormLibraries } from '@schemashift/core';

const forms = detectFormLibraries(project);
// [{ library: 'react-hook-form', resolverUsed: 'yupResolver' }]
```

### AST Utilities

Low-level helpers for working with schema ASTs:

```typescript
import {
  parseCallChain,
  buildCallChain,
  isInsideStringLiteral,
  isInsideComment,
  startsWithBase,
  transformMethodChain,
} from '@schemashift/core';

// Parse z.string().email().min(5) into structured chain info
const chain = parseCallChain(callExpression);
// { base: 'z', factoryMethod: 'string', factoryArgs: [], methods: [...] }
```

## Types

```typescript
type SchemaLibrary = 'zod' | 'zod-v3' | 'yup' | 'joi' | 'io-ts' | 'valibot' | 'v4' | 'unknown';

interface SchemaInfo {
  name: string;
  filePath: string;
  library: SchemaLibrary;
  lineNumber: number;
  code: string;
}

interface TransformResult {
  success: boolean;
  filePath: string;
  originalCode: string;
  transformedCode?: string;
  errors: TransformError[];
  warnings: string[];
}

interface TransformError {
  message: string;
  lineNumber?: number;
  code?: string;
}

interface EcosystemReport {
  dependencies: EcosystemIssue[];
  warnings: string[];
  blockers: string[];
}

interface EcosystemIssue {
  package: string;
  installedVersion: string;
  migration: string;
  issue: string;
  suggestion: string;
  severity: 'info' | 'warning' | 'error';
  category: 'orm' | 'form' | 'api' | 'validation-util' | 'openapi' | 'ui';
}

interface PackageUpdatePlan {
  add: Record<string, string>;
  remove: string[];
  warnings: string[];
}

interface IncrementalState {
  migrationId: string;
  from: SchemaLibrary;
  to: SchemaLibrary;
  startedAt: string;
  completedFiles: string[];
  remainingFiles: string[];
  failedFiles: string[];
}

interface StandardSchemaInfo {
  detected: boolean;
  compatibleLibraries: Array<{ name: string; version: string }>;
  recommendation: string;
}

interface SchemaComplexity {
  schemaName: string;
  filePath: string;
  library: SchemaLibrary;
  lineNumber: number;
  chainLength: number;
  nestedDepth: number;
  validationCount: number;
  score: number;
  level: 'low' | 'medium' | 'high' | 'critical';
}

interface GovernanceResult {
  violations: GovernanceViolation[];
  filesScanned: number;
  schemasChecked: number;
  passed: boolean;
}
```

## Related Packages

- [schemashift-cli](https://www.npmjs.com/package/schemashift-cli) — CLI tool (most users should install this)
- [@schemashift/yup-zod](https://www.npmjs.com/package/@schemashift/yup-zod) — Yup ↔ Zod transformer
- [@schemashift/joi-zod](https://www.npmjs.com/package/@schemashift/joi-zod) — Joi → Zod transformer
- [@schemashift/zod-v3-v4](https://www.npmjs.com/package/@schemashift/zod-v3-v4) — Zod v3 → v4 upgrade
- [@schemashift/io-ts-zod](https://www.npmjs.com/package/@schemashift/io-ts-zod) — io-ts → Zod transformer
- [@schemashift/zod-valibot](https://www.npmjs.com/package/@schemashift/zod-valibot) — Zod ↔ Valibot transformer
- [@schemashift/zod-arktype](https://www.npmjs.com/package/@schemashift/zod-arktype) — Zod ↔ ArkType transformer
- [@schemashift/zod-superstruct](https://www.npmjs.com/package/@schemashift/zod-superstruct) — Zod ↔ Superstruct transformer
- [@schemashift/io-ts-effect](https://www.npmjs.com/package/@schemashift/io-ts-effect) — io-ts → Effect Schema transformer

## License

MIT