Troubleshooting Guide

Common issues and solutions when using the Asterisms JS SDK Backend.

Installation Issues

Package Installation Fails

Problem: npm install @asterisms/sdk-backend fails

Possible Causes:

  • Network connectivity issues
  • Registry configuration problems
  • Node.js version compatibility

Solutions:

  1. Check Node.js version:

    node --version
    # Requires Node.js 16+
  2. Clear npm cache:

    npm cache clean --force
  3. Try different registry:

    npm install @asterisms/sdk-backend --registry https://registry.npmjs.org/
  4. Check network connectivity:

    npm config get registry
    ping registry.npmjs.org

TypeScript Compilation Errors

Problem: TypeScript errors after installation

Error Messages:

Cannot find module '@asterisms/sdk-backend' Module has no exported member 'AsterismsBackendSDK'

Solutions:

  1. Install type dependencies:

    npm install @types/node
  2. Check tsconfig.json:

    {
      "compilerOptions": {
        "moduleResolution": "node",
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true
      }
    }
  3. Restart TypeScript server:

    • In VS Code: Ctrl+Shift+P → "TypeScript: Restart TS Server"

SDK Initialization Issues

SDK Boot Fails

Problem: sdk.boot() throws errors

Common Error Messages:

  • "Failed to initialize SDK"
  • "Invalid configuration"
  • "Connection timeout"

Solutions:

  1. Check environment variables:

    echo $ASTERISMS_DOMAIN
    echo $ASTERISMS_BUNDLE_ID
    echo $ASTERISMS_SUBDOMAIN
  2. Verify configuration:

    const sdk = getAsterismsBackendSDK({
      bundleId: 'com.example.app', // Must be unique
      domain: 'asterisms.example.com', // Must be valid domain
      subdomain: 'app', // Must match your app
      httpServiceAdapterFactory: createFetchAdapter(fetch),
      registrationData: {
        // Must be complete
        bundleId: 'com.example.app',
        capabilities: ['FRONTEND_WEBSITE'],
        description: 'My App',
        name: 'My App',
        subdomain: 'app',
        title: 'My App'
      }
    });
  3. Check network connectivity:

    ping asterisms.example.com
    curl -I https://asterisms.example.com
  4. Add debug logging:

    try {
      console.log('Starting SDK boot...');
      await sdk.boot();
      console.log('SDK boot successful');
    } catch (error) {
      console.error('SDK boot failed:', error);
      console.error('Error details:', error.stack);
    }

"SDK Not Available" Errors

Problem: locals.sdk is undefined in SvelteKit

Solutions:

  1. Check hooks.server.ts:

    import { useAsterismsBackendSDK } from '$lib/sdkInstance';
    
    export const handle: Handle = async ({ event, resolve }) => {
      const provider = useAsterismsBackendSDK();
    
      if (provider) {
        await provider.bootSDK();
        event.locals.sdk = provider.sdk;
      }
    
      return resolve(event);
    };
  2. Verify SDK instance creation:

    // In sdkInstance.ts
    export function useAsterismsBackendSDK() {
      if (building) return undefined; // Important!
    
      if (!provider) {
        provider = createSvelteKitBackendSDK(props);
      }
    
      return provider;
    }
  3. Check app.d.ts:

    declare global {
      namespace App {
        interface Locals {
          sdk?: AsterismsBackendSDK;
        }
      }
    }

Authentication Issues

"User not authenticated" Errors

Problem: Authentication service returns null user

Solutions:

  1. Check product authorization key:

    ASTERISMS_PRODUCT_AUTHORIZATION_KEY=your-valid-key
  2. Verify bundle ID registration:

    const registration = sdk.registration();
    const appInfo = await registration.getAppInfo();
    console.log('App registration:', appInfo);
  3. Check authorization service:

    try {
      const auth = sdk.authorization();
      const user = await auth.getCurrentUser();
      console.log('Current user:', user);
    } catch (error) {
      console.error('Auth error:', error);
    }

Permission Denied Errors

Problem: hasPermission() returns false

Solutions:

  1. Check user permissions:

    const auth = sdk.authorization();
    const user = await auth.getCurrentUser();
    console.log('User permissions:', user.permissions);
  2. Verify permission names:

    // Use exact permission names
    const canRead = await auth.hasPermission('resource.read');
    const canWrite = await auth.hasPermission('resource.write');
  3. Check role assignments:

    const user = await auth.getCurrentUser();
    console.log('User roles:', user.roles);

Storage Issues

Storage Operations Fail

Problem: storage.get() or storage.set() throw errors

Solutions:

  1. Check storage service availability:

    try {
      const storage = sdk.storage();
      console.log('Storage service available');
    } catch (error) {
      console.error('Storage service unavailable:', error);
    }
  2. Verify data format:

    // Store serializable data only
    await storage.set('key', { data: 'value' }); // Good
    await storage.set('key', new Date()); // May fail
  3. Handle storage errors:

    try {
      await storage.set('key', data);
    } catch (error) {
      if (error.code === 'STORAGE_QUOTA_EXCEEDED') {
        // Handle quota exceeded
      } else {
        console.error('Storage error:', error);
      }
    }

Data Not Found

Problem: storage.get() returns null unexpectedly

Solutions:

  1. Check key format:

    // Keys are case-sensitive
    await storage.set('userPrefs', data);
    const data = await storage.get('userPrefs'); // Same case
  2. Verify data was stored:

    await storage.set('key', data);
    const stored = await storage.get('key');
    console.log('Stored data:', stored);
  3. Check user context:

    // Storage is user-scoped
    const auth = sdk.authorization();
    const user = await auth.getCurrentUser();
    console.log('Storage user:', user.id);

Notification Issues

Notifications Not Sending

Problem: notifications.sendToUser() fails

Solutions:

  1. Check notification service:

    try {
      const notifications = sdk.notifications();
      console.log('Notification service available');
    } catch (error) {
      console.error('Notification service unavailable:', error);
    }
  2. Verify user ID:

    const auth = sdk.authorization();
    const user = await auth.getCurrentUser();
    
    await notifications.sendToUser(user.id, {
      title: 'Test',
      message: 'Test message'
    });
  3. Check notification format:

    // Required fields
    await notifications.sendToUser(userId, {
      title: 'Required title',
      message: 'Required message'
    });

Notification Delivery Issues

Problem: Notifications sent but not received

Solutions:

  1. Check user notification preferences:

    const user = await auth.getCurrentUser();
    console.log('User notification settings:', user.notificationSettings);
  2. Verify workspace notifications:

    // For workspace notifications
    const workspaceId = 'workspace-123';
    await notifications.sendToWorkspace(workspaceId, {
      title: 'Workspace Update',
      message: 'Important update'
    });
  3. Check notification history:

    // Check if notifications are being logged
    const logger = sdk.logging();
    logger.info('Notification sent', { userId, title });

SvelteKit Specific Issues

Build Errors

Problem: Build fails with SDK-related errors

Solutions:

  1. Check building flag:

    import { building } from '$app/environment';
    
    export function useAsterismsBackendSDK() {
      if (building) return undefined; // Critical!
      // ... rest of code
    }
  2. Verify vite.config.js:

    import { sveltekit } from '@sveltejs/kit/vite';
    
    export default {
      plugins: [sveltekit()],
      define: {
        global: 'globalThis'
      }
    };
  3. Check server-side imports:

    // Only import SDK in server-side code
    import { useAsterismsBackendSDK } from '$lib/sdkInstance';
    
    export const load: PageServerLoad = async ({ locals }) => {
      const sdk = locals.sdk; // Use from locals
      // ... rest of code
    };

API Route Errors

Problem: API routes return 500 errors

Solutions:

  1. Check error handling:

    export const GET: RequestHandler = async ({ locals }) => {
      try {
        const sdk = locals.sdk;
        if (!sdk) {
          return json({ error: 'SDK not available' }, { status: 503 });
        }
    
        // ... rest of code
      } catch (error) {
        console.error('API error:', error);
        return json({ error: 'Internal error' }, { status: 500 });
      }
    };
  2. Verify hooks execution:

    // In hooks.server.ts
    export const handle: Handle = async ({ event, resolve }) => {
      console.log('Processing request:', event.url.pathname);
    
      const provider = useAsterismsBackendSDK();
      if (provider) {
        await provider.bootSDK();
        event.locals.sdk = provider.sdk;
      }
    
      return resolve(event);
    };

Performance Issues

Slow SDK Boot

Problem: SDK takes too long to boot

Solutions:

  1. Cache SDK instance:

    let sdkInstance: AsterismsBackendSDK | null = null;
    
    export function getSDKInstance() {
      if (!sdkInstance) {
        sdkInstance = getAsterismsBackendSDK(props);
      }
      return sdkInstance;
    }
  2. Use background boot:

    // Boot in background
    const provider = createSvelteKitBackendSDK(props);
    provider.bootSDK(); // Don't await
    
    // Check if booted later
    if (provider.sdk.isBooted()) {
      // Use SDK
    }
  3. Optimize configuration:

    const sdk = getAsterismsBackendSDK({
      // ... required props
      secure: true, // Use HTTPS
      proxyTerminatedSSL: true // If behind proxy
    });

Memory Leaks

Problem: Memory usage increases over time

Solutions:

  1. Reuse service instances:

    class MyService {
      private auth = this.sdk.authorization();
      private storage = this.sdk.storage();
    
      constructor(private sdk: AsterismsBackendSDK) {}
    }
  2. Clean up resources:

    // In cleanup code
    if (sdk.isBooted()) {
      // Clean up any pending operations
    }

Development Tools

Debug Logging

Enable debug logging to troubleshoot issues:

// Set environment variable
process.env.DEBUG = 'asterisms:*';

// Or use SDK logging
const logger = sdk.logging();
logger.setLevel('debug');

Network Debugging

Check network requests:

# Monitor network traffic
curl -v https://asterisms.example.com/api/status

# Check DNS resolution
nslookup asterisms.example.com

Health Checks

Implement health checks:

app.get('/health', async (req, res) => {
  const health = {
    sdk: sdk.isBooted(),
    timestamp: new Date().toISOString(),
    version: process.env.npm_package_version
  };

  res.json(health);
});

Getting Additional Help

If these solutions don't resolve your issue:

  1. Check the API Reference: API Reference
  2. Review Examples: Examples
  3. Check Core Concepts: Core Concepts
  4. Submit an Issue: Include error messages and steps to reproduce

Common Error Messages

"Cannot find module"

  • Check package installation
  • Verify import paths
  • Restart TypeScript server

"SDK not initialized"

  • Call sdk.boot() before using services
  • Check SDK configuration
  • Verify environment variables

"Invalid bundle ID"

  • Use reverse domain notation
  • Ensure bundle ID is unique
  • Check registration data

"Connection timeout"

  • Check network connectivity
  • Verify domain configuration
  • Check firewall settings

"Permission denied"

  • Check user authentication
  • Verify user roles
  • Check permission names

Prevention Tips

  1. Always handle errors:

    try {
      await sdk.boot();
    } catch (error) {
      console.error('SDK boot failed:', error);
    }
  2. Use TypeScript:

    const sdk: AsterismsBackendSDK = getAsterismsBackendSDK(props);
  3. Validate configuration:

    if (!process.env.ASTERISMS_DOMAIN) {
      throw new Error('ASTERISMS_DOMAIN is required');
    }
  4. Monitor your application:

    const logger = sdk.logging();
    logger.info('Operation completed', { operation: 'user-login' });
  5. Test thoroughly:

    // Write tests for SDK integration
    describe('SDK Integration', () => {
      it('should boot successfully', async () => {
        await expect(sdk.boot()).resolves.not.toThrow();
      });
    });