CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-stream-http

Streaming HTTP implementation for browsers with Node.js API compatibility

Pending
Overview
Eval results
Files

browser-features.mddocs/

Browser Features

Enhanced browser functionality beyond the standard Node.js HTTP module, including CORS credentials, request modes, timeout handling, and automatic capability detection.

Capabilities

CORS and Credentials

Browser-specific options for handling Cross-Origin Resource Sharing (CORS) and authentication.

interface CORSOptions {
  /**
   * Send cookies and authentication information with CORS requests
   * @default false
   */
  withCredentials?: boolean;
}

Usage Examples:

const http = require('stream-http');

// Request with credentials (cookies, auth headers)
http.request({
  hostname: 'api.example.com',
  path: '/protected',
  withCredentials: true
}, function(res) {
  // This request will include cookies and auth headers
  console.log('Authenticated request status:', res.statusCode);
});

// Without credentials (default)
http.get('https://public-api.example.com/data', function(res) {
  // This request won't include cookies
});

Request Modes

Fine-grained control over streaming behavior and data handling to balance performance with correctness.

interface ModeOptions {
  /**
   * Request mode affecting streaming behavior and data correctness
   * @default 'default'
   */
  mode?: 'default' | 'allow-wrong-content-type' | 'prefer-streaming' | 'disable-fetch' | 'prefer-fast';
}

Mode Descriptions:

  • 'default': Balanced performance and correctness for most use cases
  • 'allow-wrong-content-type': More streaming opportunities but may report incorrect content-type header
  • 'prefer-streaming': Maximum streaming performance, may corrupt binary data (text only)
  • 'disable-fetch': Force XHR usage, preserves binary data and content-type correctness
  • 'prefer-fast': Deprecated, now equivalent to 'default'

Usage Examples:

// Maximum streaming for text data
http.get({
  hostname: 'api.example.com',
  path: '/text-stream',
  mode: 'prefer-streaming'
}, function(res) {
  // Optimized for streaming text data
});

// Force XHR for binary data
http.get({
  hostname: 'cdn.example.com',
  path: '/image.jpg',
  mode: 'disable-fetch'
}, function(res) {
  // Ensures binary data integrity
});

// Balanced approach (default)
http.get({
  hostname: 'api.example.com',
  path: '/mixed-content'
  // mode: 'default' is implicit
}, function(res) {
  // Good balance of streaming and correctness
});

Timeout Options

Multiple timeout mechanisms for different aspects of the HTTP request lifecycle.

interface TimeoutOptions {
  /**
   * Request timeout in milliseconds (entire request lifecycle)
   * Browser-specific feature for XHR and Fetch
   */
  requestTimeout?: number;
  
  /**
   * Socket timeout in milliseconds (Node.js compatibility)
   * Applies to pauses in data transfer
   */
  timeout?: number;
}

Usage Examples:

// Request timeout (entire request must complete within time)
http.request({
  hostname: 'slow-api.example.com',
  path: '/heavy-computation',
  requestTimeout: 10000 // 10 seconds total
}, function(res) {
  // Request will timeout if not completed in 10 seconds
});

// Socket timeout (pauses in data transfer)
const req = http.request('https://api.example.com/streaming-data');
req.setTimeout(5000, function() {
  console.log('Socket timeout - no data received for 5 seconds');
  req.abort();
});

// Combined timeouts
http.request({
  hostname: 'api.example.com',
  path: '/data',
  requestTimeout: 30000, // Total request timeout
  timeout: 5000 // Socket inactivity timeout
}, function(res) {
  // Will timeout if total request > 30s OR if no data for 5s
});

URL Final Resolution

Access to final URLs after browser-handled redirects (when supported).

interface ResponseURL {
  /** Final URL after all redirects (browser-dependent) */
  url?: string;
}

Usage Examples:

http.get('https://short.ly/redirect-url', function(res) {
  if (res.url) {
    console.log('Original URL: https://short.ly/redirect-url');
    console.log('Final URL:', res.url);
  } else {
    console.log('URL tracking not supported in this browser');
  }
});

Capability Detection

Stream-http automatically detects browser capabilities to choose the optimal implementation strategy.

Browser Capabilities

interface BrowserCapabilities {
  /** Fetch API and ReadableStream support */
  fetch: boolean;
  
  /** WritableStream support for backpressure */
  writableStream: boolean;
  
  /** AbortController support for request cancellation */
  abortController: boolean;
  
  /** ArrayBuffer responseType support */
  arraybuffer: boolean;
  
  /** IE-specific MSStream support */
  msstream: boolean;
  
  /** Firefox-specific chunked arraybuffer support */
  mozchunkedarraybuffer: boolean;
  
  /** XHR overrideMimeType support */
  overrideMimeType: boolean;
}

Automatic Strategy Selection

Stream-http automatically selects the best implementation:

  1. Fetch API (preferred when available)

    • Modern browsers with full streaming support
    • Backpressure support in Chrome 58+
    • AbortController support for cancellation
  2. XHR with Progressive Response

    • Firefox: moz-chunked-arraybuffer for true streaming
    • IE: ms-stream for streaming support
    • Other browsers: arraybuffer or text modes
  3. Standard XHR (universal fallback)

    • Pseudo-streaming where data is available before completion
    • Full browser compatibility

Implementation Details

The library chooses implementation based on:

  • Available browser APIs (fetch, XHR response types)
  • Request options (mode, timeout requirements)
  • Data type requirements (binary vs text)
  • Performance characteristics needed
// The library handles this automatically:
// if (capability.fetch && useFetch) {
//   return 'fetch'
// } else if (capability.mozchunkedarraybuffer) {
//   return 'moz-chunked-arraybuffer'
// } else if (capability.msstream) {
//   return 'ms-stream'
// } else if (capability.arraybuffer && preferBinary) {
//   return 'arraybuffer'
// } else {
//   return 'text'
// }

Browser Compatibility Matrix

Comprehensive Browser Support

BrowserVersionFetch APITrue StreamingBackpressureAbortControllerresponse.url
Chrome43+42+✓ (43+)✓ (58+)✓ (66+)✓ (37+)
Firefox9+39+✓ (moz-chunked)✓ (57+)✓ (32+)
Safari6+10.1+✓ (10.1+)✓ (11.1+)✓ (9+)
Edge12+14+✓ (14+)✓ (16+)✓ (14+)
IE11✗ (pseudo)

Feature Detection Results

Stream-http automatically detects these capabilities:

// Detected automatically by the library
const capabilities = {
  fetch: typeof fetch === 'function' && typeof ReadableStream === 'function',
  writableStream: typeof WritableStream === 'function',
  abortController: typeof AbortController === 'function',
  arraybuffer: true, // or detected via XHR responseType support
  msstream: false, // IE-specific, detected via XHR responseType
  mozchunkedarraybuffer: false, // Firefox-specific streaming
  overrideMimeType: true // or detected via XHR.overrideMimeType
};

Internet Explorer Compatibility

  • IE11: Supported with pseudo-streaming using standard XHR
  • IE10 and below: Not supported (as of stream-http v3.0.0)
  • Limitations: No true streaming, no fetch API, no AbortController

Implementation Selection Priority

  1. Fetch API (preferred): Chrome 43+, Firefox 39+, Safari 10.1+, Edge 14+
  2. moz-chunked-arraybuffer: Firefox 9+ for true streaming via XHR
  3. ms-stream: IE11 for pseudo-streaming via XHR
  4. arraybuffer: Fallback for binary data preservation
  5. text: Universal fallback with pseudo-streaming

Error Handling

Browser-Specific Errors

// Request timeout (requestTimeout option)
req.on('requestTimeout', function() {
  console.log('Request exceeded requestTimeout limit');
});

// Socket timeout (setTimeout method)
req.on('timeout', function() {
  console.log('Socket was inactive for too long');
});

// Network/CORS errors
req.on('error', function(err) {
  console.log('Request failed:', err.message);
});

Common Error Scenarios

  • CORS failures: Cross-origin requests blocked by browser policy
  • Network errors: Connection failures, DNS resolution issues
  • Timeout errors: Request or socket timeouts exceeded
  • Abort errors: Request cancelled via abort() method
// Comprehensive error handling
const req = http.request({
  hostname: 'api.example.com',
  path: '/data',
  requestTimeout: 10000
});

req.on('error', function(err) {
  console.error('Request error:', err);
});

req.on('requestTimeout', function() {
  console.error('Request timed out');
});

req.setTimeout(5000, function() {
  console.error('Socket timeout');
  req.abort();
});

req.end();

Install with Tessl CLI

npx tessl i tessl/npm-stream-http

docs

browser-features.md

http-requests.md

index.md

streaming.md

tile.json