Skip to content

Troubleshooting

This guide helps you diagnose and resolve common issues when working with ziegel packages.

Common Issues

Installation Problems

Package Not Found

Error: npm ERR! 404 Not Found - GET https://registry.npmjs.org/@breadstone/ziegel-core

Solution: ziegel packages are published to a private Azure DevOps registry. Configure your npm to use the correct registry:

bash
# Configure npm to use the Azure DevOps registry
npm config set registry https://breadstone.pkgs.visualstudio.com/ziegel/_packaging/breadstone-ziegel-public/npm/registry/

# Or use .npmrc file
echo "registry=https://breadstone.pkgs.visualstudio.com/ziegel/_packaging/breadstone-ziegel-public/npm/registry/" > .npmrc

Authentication Issues

Error: npm ERR! 401 Unauthorized

Solution: You need proper authentication credentials for the private registry. Contact your administrator for access.

TypeScript Compilation Issues

Type Definition Errors

Error: Cannot find module '@breadstone/ziegel-core' or its corresponding type declarations

Solution:

  1. Ensure the package is properly installed:

    bash
    npm install @breadstone/ziegel-core
  2. Check your tsconfig.json includes the correct module resolution:

    json
    {
      "compilerOptions": {
        "moduleResolution": "node",
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true
      }
    }
  3. Clear TypeScript cache:

    bash
    rm -rf node_modules/.cache/typescript
    npx tsc --build --clean

Generic Type Issues

Error: Type 'unknown' is not assignable to type 'T'

Solution: Ensure proper type annotations when using generic methods:

typescript
// ❌ Incorrect
const config = ServiceLocator.get('config');

// ✅ Correct
const config = ServiceLocator.get<ConfigurationManager>('config');

Runtime Issues

Service Not Registered

Error: Service not found: userService

Solution: Ensure services are registered before they're accessed:

typescript
// Register services at application startup
ServiceLocator.register('userService', () => new UserService());

// Then use the service
const userService = ServiceLocator.get<UserService>('userService');

Circular Dependencies

Error: RangeError: Maximum call stack size exceeded

Solution: Restructure your dependencies to avoid circular references:

typescript
// ❌ Circular dependency
class UserService {
    constructor(private orderService: OrderService) {}
}

class OrderService {
    constructor(private userService: UserService) {} // Circular!
}

// ✅ Use events or interfaces to break the cycle
class UserService {
    constructor(private eventAggregator: EventAggregator) {}

    createUser(userData: any) {
        const user = this.createUserRecord(userData);
        this.eventAggregator.publish('user:created', user);
        return user;
    }
}

class OrderService {
    constructor(private eventAggregator: EventAggregator) {
        this.eventAggregator.subscribe('user:created', this.onUserCreated.bind(this));
    }

    onUserCreated(user: User) {
        // Handle user creation
    }
}

HTTP Client Issues

CORS Errors

Error: Access to fetch at 'https://api.example.com' from origin 'http://localhost:3000' has been blocked by CORS policy

Solution: This is a server-side configuration issue. Contact your API administrator to configure CORS headers, or use a proxy during development:

typescript
// Development proxy configuration
const httpClient = new HttpClient('/api', {
    // Your local proxy will forward to the actual API
});

Request Timeout

Error: Request timeout of 5000ms exceeded

Solution: Increase timeout or implement retry logic:

typescript
const httpClient = new HttpClient('https://api.example.com', {
    timeout: 30000, // 30 seconds
    retryAttempts: 3,
    retryDelay: 1000
});

Authentication Failures

Error: 401 Unauthorized

Solution: Ensure your authentication interceptor is properly configured:

typescript
class AuthInterceptor implements HttpInterceptor {
    async intercept(request: Request): Promise<Request> {
        const token = await this.getValidToken(); // Ensure token is valid
        if (token) {
            request.headers.set('Authorization', `Bearer ${token}`);
        }
        return request;
    }

    private async getValidToken(): Promise<string | null> {
        let token = localStorage.getItem('authToken');

        // Check if token needs refresh
        if (this.isTokenExpired(token)) {
            token = await this.refreshToken();
        }

        return token;
    }
}

Configuration Issues

Configuration Not Loading

Error: Configuration value not found: database:connectionString

Solution:

  1. Verify configuration files exist and are properly formatted:

    json
    // appsettings.json
    {
      "database": {
        "connectionString": "your-connection-string"
      }
    }
  2. Ensure configuration is loaded before accessing values:

    typescript
    const config = new ConfigurationManager();
    await config.addJsonFile('appsettings.json'); // Make sure this completes
    
    const connectionString = config.getValue<string>('database:connectionString');
  3. Check file paths are correct relative to your application root.

Environment Variables Not Working

Error: Environment variables are not being loaded

Solution: Ensure environment variables are properly configured:

typescript
// Load environment variables
const config = new ConfigurationManager();
config.addEnvironmentVariables('MYAPP_'); // Prefix optional

// Access with proper naming
const dbUrl = config.getValue<string>('database:url');
// Looks for MYAPP_DATABASE__URL (double underscore for hierarchy)

Localization Issues

Missing Translations

Error: Translation keys return [key] instead of translated text

Solution:

  1. Verify translation files are loaded:

    typescript
    const translations = new Map([
        ['en-US', new Map([
            ['welcome', 'Welcome!']
        ])]
    ]);
    
    const provider = new MapLocalizationProvider(translations);
  2. Check culture is set correctly:

    typescript
    await localizationManager.setCulture('en-US');
  3. Implement proper fallback handling:

    typescript
    const localizationManager = new LocalizationManager(
        provider,
        cultureProvider,
        (key, culture) => {
            console.warn(`Missing translation: ${key} for ${culture}`);
            return key; // Return key as fallback
        }
    );

Culture Changes Not Reflected

Error: UI doesn't update when culture changes

Solution: Subscribe to culture change events:

typescript
const cultureProvider = new CultureProvider();
cultureProvider.cultureChanged.add((newCulture) => {
    // Reload UI components
    this.updateUserInterface();

    // Reload localized content
    this.reloadLocalizedContent();
});

Performance Issues

Slow Application Startup

Symptoms: Long delays during application initialization

Solution:

  1. Use lazy loading for expensive services:

    typescript
    ServiceLocator.register('expensiveService', () => {
        // Only create when first accessed
        return new ExpensiveService();
    });
  2. Parallelize independent initialization tasks:

    typescript
    async initialize() {
        await Promise.all([
            this.initializeConfiguration(),
            this.initializeLogging(),
            this.initializeLocalization()
        ]);
    }

Large Bundle Size

Symptoms: Application bundle is larger than expected

Solution:

  1. Use tree-shaking friendly imports:

    typescript
    // ✅ Good - tree-shakeable
    import { StringExtensions } from '@breadstone/ziegel-core';
    
    // ❌ Bad - imports entire package
    import * as ZiegelCore from '@breadstone/ziegel-core';
  2. Analyze your bundle to identify large dependencies:

    bash
    npm install --save-dev webpack-bundle-analyzer
    # Analyze your build
  3. Use dynamic imports for optional features:

    typescript
    async loadOptionalFeature() {
        if (featureEnabled) {
            const { OptionalService } = await import('./OptionalService');
            return new OptionalService();
        }
    }

Memory Leaks

Symptoms: Memory usage grows over time

Solution:

  1. Properly dispose of event subscriptions:

    typescript
    class UserService {
        private subscriptions: Array<() => void> = [];
    
        constructor(eventAggregator: EventAggregator) {
            const unsubscribe = eventAggregator.subscribe('event', this.handler);
            this.subscriptions.push(unsubscribe);
        }
    
        dispose() {
            this.subscriptions.forEach(unsub => unsub());
            this.subscriptions = [];
        }
    }
  2. Clear caches when appropriate:

    typescript
    class CacheManager {
        private cache = new Map();
    
        clear() {
            this.cache.clear();
        }
    
        // Clear cache periodically
        startCleanup() {
            setInterval(() => this.clear(), 60000); // Every minute
        }
    }

Debugging Tips

Enable Debug Logging

typescript
// Enable debug logging in development
if (process.env.NODE_ENV === 'development') {
    LoggerManager.configure({
        level: LogLevel.Debug,
        providers: [new ConsoleLogProvider()]
    });
}

Use Browser DevTools

  1. Network Tab: Monitor HTTP requests and responses
  2. Console: Check for JavaScript errors and log messages
  3. Application Tab: Inspect localStorage, sessionStorage, and cookies
  4. Performance Tab: Profile application performance

TypeScript Debugging

typescript
// Add type assertions for debugging
function debugUser(user: unknown) {
    console.log('User type check:', TypeGuard.isObject(user));
    console.log('Has name property:', TypeGuard.hasProperty(user, 'name'));

    if (TypeGuard.isObject(user) && TypeGuard.hasProperty(user, 'name')) {
        console.log('User name:', user.name);
    }
}

Getting Help

Before Seeking Help

  1. Check this troubleshooting guide
  2. Review the relevant package documentation
  3. Check existing issues on Azure DevOps
  4. Ensure you're using the latest version

Creating Bug Reports

When reporting issues, include:

  1. Environment information:

    • Node.js version
    • TypeScript version
    • Package versions
    • Operating system
  2. Steps to reproduce:

    1. Install packages
    2. Create service with configuration X
    3. Call method Y
    4. Observe error Z
  3. Expected vs actual behavior

  4. Minimal reproduction case

  5. Error messages and stack traces

Support Channels

Quick Reference

Common Commands

bash
# Clear npm cache
npm cache clean --force

# Reinstall dependencies
rm -rf node_modules package-lock.json
npm install

# Clear TypeScript cache
rm -rf node_modules/.cache/typescript

# Check package versions
npm list @breadstone/ziegel-core

# Build with verbose output
npm run build -- --verbose

Environment Variables

bash
# Common ziegel environment variables
NODE_ENV=development
ZIEGEL_LOG_LEVEL=debug
ZIEGEL_CONFIG_PATH=/path/to/config

Configuration Examples

json
// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "CommonJS",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "skipLibCheck": true
  }
}
json
// package.json
{
  "dependencies": {
    "@breadstone/ziegel-core": "^0.0.1",
    "@breadstone/ziegel-platform": "^0.0.1"
  }
}