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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@xats-org/converter-word

v0.5.1

Published

High-fidelity bidirectional conversion between xats and Microsoft Word documents

Readme

@xats-org/converter-word

High-fidelity bidirectional conversion between xats documents and Microsoft Word (.docx) format.

Features

  • Bidirectional Conversion: Convert between xats and Word formats while preserving semantic meaning
  • Educational Content Support: Specialized handling for educational elements like learning objectives, exercises, and assessments
  • Collaboration Features: Preserve and convert track changes, comments, and annotations
  • Style Mapping: Intelligent mapping between Word styles and xats block types
  • Production Ready: Built for publishing workflows with quality assurance and fidelity testing
  • Round-trip Testing: Comprehensive fidelity testing to ensure conversion accuracy

Installation

npm install @xats-org/converter-word

Quick Start

Convert xats to Word

import { WordConverter } from '@xats-org/converter-word';

const converter = new WordConverter();

// Convert xats document to Word
const result = await converter.render(xatsDocument, {
  author: 'Dr. Smith',
  documentTitle: 'Introduction to Biology',
  includeTableOfContents: true,
  theme: 'educational'
});

// Save the Word document
fs.writeFileSync('output.docx', result.content);

Convert Word to xats

// Read Word document
const docxBuffer = fs.readFileSync('input.docx');

// Convert to xats
const result = await converter.parse(docxBuffer, {
  preserveMetadata: true,
  trackChanges: {
    preserve: true,
    convertToAnnotations: true
  },
  comments: {
    preserve: true,
    convertToAnnotations: true
  }
});

const xatsDocument = result.document;

Advanced Usage

Style Mapping

Customize how Word styles map to xats block types:

const converter = new WordConverter({
  defaultStyleMappings: {
    paragraphs: {
      'Learning Goal': 'https://pub.xats.org/vocabularies/blocks/learningObjective',
      'Key Concept': 'https://pub.xats.org/vocabularies/blocks/keyTerm',
      'Case Study': 'https://pub.xats.org/vocabularies/blocks/caseStudy'
    },
    characters: {
      'Important Term': 'keyTerm',
      'Code Snippet': 'code'
    }
  }
});

Track Changes and Comments

Preserve collaborative features when converting:

// Convert Word with track changes to xats
const result = await converter.parse(docxContent, {
  trackChanges: {
    preserve: true,
    convertToAnnotations: true,
    includeRevisionHistory: true,
    authorMappings: {
      'John Smith': 'editor-john',
      'Mary Johnson': 'reviewer-mary'
    }
  },
  comments: {
    preserve: true,
    convertToAnnotations: true,
    includeThreading: true
  }
});

// Access converted annotations
const annotations = result.annotations;
console.log(`Found ${annotations?.length || 0} annotations`);

Round-trip Testing

Test conversion fidelity:

// Test how well content survives round-trip conversion
const fidelityResult = await converter.testRoundTrip(xatsDocument, {
  fidelityThreshold: 0.85,
  semanticComparison: true
});

console.log({
  success: fidelityResult.success,
  overall: fidelityResult.fidelityScore,
  content: fidelityResult.contentFidelity,
  structure: fidelityResult.structureFidelity
});

// Review any issues
fidelityResult.issues.forEach(issue => {
  console.log(`${issue.severity}: ${issue.description}`);
  if (issue.recommendation) {
    console.log(`Recommendation: ${issue.recommendation}`);
  }
});

Educational Content

The converter has specialized support for educational content:

// These Word styles are automatically mapped to educational block types:
const educationalMappings = {
  'Learning Objective': 'learningObjective',
  'Key Term': 'keyTerm', 
  'Definition': 'definition',
  'Example': 'example',
  'Exercise': 'exercise',
  'Case Study': 'caseStudy',
  'Note': 'note',
  'Warning': 'warning',
  'Tip': 'tip',
  'Summary': 'summary'
};

When converting from xats to Word, these block types are rendered with appropriate styling and prefixes.

Production Workflows

Publisher Integration

// Convert manuscript for multi-format publishing
async function processManuscript(docxPath: string) {
  const docxContent = fs.readFileSync(docxPath);
  
  // Convert to xats for processing
  const xatsResult = await converter.parse(docxContent, {
    preserveMetadata: true,
    productionMode: true
  });
  
  // Validate content
  const validation = await validateDocument(xatsResult.document);
  if (!validation.valid) {
    throw new Error('Manuscript validation failed');
  }
  
  // Generate publication formats
  const wordOutput = await converter.render(xatsResult.document, {
    productionMode: true,
    includeTableOfContents: true,
    includeBibliography: true,
    theme: 'professional'
  });
  
  return {
    xatsDocument: xatsResult.document,
    wordDocument: wordOutput.content,
    metadata: wordOutput.metadata
  };
}

Quality Assurance

// Automated quality checks
const result = await converter.render(document, options);

// Check for conversion errors
if (result.errors && result.errors.length > 0) {
  result.errors.forEach(error => {
    if (!error.recoverable) {
      throw new Error(`Fatal conversion error: ${error.message}`);
    }
    console.warn(`Warning: ${error.message}`);
  });
}

// Review style mapping report
if (result.styleReport) {
  console.log('Mapped styles:', result.styleReport.mappedStyles);
  console.log('Unmapped styles:', result.styleReport.unmappedStyles);
  console.log('New styles created:', result.styleReport.newStyles);
}

API Reference

WordConverter

Methods

  • render(document: XatsDocument, options?: WordRenderOptions): Promise<WordRenderResult>
  • parse(content: string | Buffer, options?: WordParseOptions): Promise<WordParseResult>
  • testRoundTrip(document: XatsDocument, options?: RoundTripOptions): Promise<RoundTripResult>
  • validate(content: string | Buffer): Promise<FormatValidationResult>
  • getMetadata(content: string | Buffer): Promise<WordMetadata>

Properties

  • format: 'docx' - The format identifier
  • wcagLevel: 'AA' - WCAG compliance level

Options

WordRenderOptions

interface WordRenderOptions {
  author?: string;
  documentTitle?: string;
  productionMode?: boolean;
  template?: string;
  styleMappings?: WordStyleMappings;
  includeTableOfContents?: boolean;
  includeBibliography?: boolean;
  theme?: 'default' | 'educational' | 'academic' | 'professional';
  accessibilityMode?: boolean;
  trackChanges?: TrackChangesOptions;
  comments?: CommentsOptions;
}

WordParseOptions

interface WordParseOptions {
  preserveMetadata?: boolean;
  productionMode?: boolean;
  styleMappings?: WordStyleMappings;
  trackChanges?: {
    preserve: boolean;
    convertToAnnotations: boolean;
    includeRevisionHistory?: boolean;
    authorMappings?: Record<string, string>;
  };
  comments?: {
    preserve: boolean;
    convertToAnnotations: boolean;
    includeThreading?: boolean;
  };
}

Error Handling

The converter provides detailed error reporting:

try {
  const result = await converter.render(document, options);
  
  // Check for non-fatal errors
  if (result.errors) {
    result.errors.forEach(error => {
      console.warn(`${error.code}: ${error.message}`);
      if (error.suggestion) {
        console.warn(`Suggestion: ${error.suggestion}`);
      }
    });
  }
  
} catch (error) {
  console.error('Conversion failed:', error.message);
}

Best Practices

  1. Validate First: Always validate documents before conversion
  2. Test Fidelity: Use round-trip testing for important content
  3. Map Styles: Define custom style mappings for your content
  4. Handle Errors: Implement proper error handling and recovery
  5. Preserve Metadata: Keep document metadata when possible

Limitations

  • Mathematical content may not convert perfectly (renders as text with notation)
  • Complex graphics and diagrams have limited support
  • Some advanced Word features may not have xats equivalents
  • Track changes conversion is best-effort and may not preserve all details

Contributing

See the main repository's CONTRIBUTING.md for guidelines.

License

MIT - see LICENSE.md for details.