or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

code-completion.mdevent-streaming.mdfile-system.mdhttp-client.mdindex.mdnetwork-utilities.mdpackage-management.mdsvelte-integration.mdworker-management.md
tile.json

http-client.mddocs/

HTTP Client

ASGI-compliant HTTP request handling through the WebAssembly worker. Enables web applications to make HTTP requests processed by Python code running in the worker environment.

Capabilities

HTTP Request Processing

Process HTTP requests through the WebAssembly worker using ASGI-compliant interfaces.

/**
 * Make an HTTP request through the worker
 * @param request - HTTP request object with method, path, headers, and body
 * @returns Promise that resolves with the HTTP response
 */
httpRequest(request: HttpRequest): Promise<HttpResponse>;

/**
 * Initialize an ASGI connection for HTTP request handling
 * @param scope - ASGI scope object containing request metadata
 * @returns MessagePort for bidirectional communication
 */
requestAsgi(scope: Record<string, unknown>): MessagePort;

HTTP Request Interface

Structure for HTTP requests sent to the worker.

/**
 * HTTP request structure for worker processing
 */
interface HttpRequest {
  /** HTTP method for the request */
  method: "GET" | "POST" | "PUT" | "DELETE";
  /** Request path without query parameters */
  path: string;
  /** Query string without leading ? character */
  query_string: string;
  /** Request headers as key-value pairs */
  headers: Record<string, string>;
  /** Optional request body as binary data or stream */
  body?: Uint8Array | ReadableStream<Uint8Array> | null;
}

HTTP Response Interface

Structure for HTTP responses returned from the worker.

/**
 * HTTP response structure from worker processing
 */
interface HttpResponse {
  /** HTTP status code */
  status: number;
  /** Response headers as key-value pairs */
  headers: Record<string, string>;
  /** Response body as binary data */
  body: Uint8Array;
}

Usage Examples:

import { WorkerProxy } from "@gradio/wasm";

const worker = new WorkerProxy(options);

// Wait for worker initialization
worker.addEventListener("initialization-completed", async () => {
  // Simple GET request
  const getResponse = await worker.httpRequest({
    method: "GET",
    path: "/api/info",
    query_string: "format=json",
    headers: {
      "Accept": "application/json"
    }
  });

  console.log("GET Response:", {
    status: getResponse.status,
    headers: getResponse.headers,
    body: new TextDecoder().decode(getResponse.body)
  });

  // POST request with JSON body
  const postData = JSON.stringify({
    inputs: ["Hello", "World"],
    parameters: { temperature: 0.7 }
  });

  const postResponse = await worker.httpRequest({
    method: "POST",
    path: "/api/predict",
    query_string: "",
    headers: {
      "Content-Type": "application/json",
      "Accept": "application/json"
    },
    body: new TextEncoder().encode(postData)
  });

  console.log("POST Response:", {
    status: postResponse.status,
    body: new TextDecoder().decode(postResponse.body)
  });

  // File upload request
  const fileData = new TextEncoder().encode("file content");
  const uploadResponse = await worker.httpRequest({
    method: "POST",
    path: "/api/upload",
    query_string: "filename=test.txt",
    headers: {
      "Content-Type": "text/plain",
      "Content-Length": fileData.length.toString()
    },
    body: fileData
  });

  console.log("Upload status:", uploadResponse.status);
});

HTTP Utility Functions

Utility functions for HTTP header and data processing.

/**
 * Convert HTTP headers to ASGI format
 * @param headers - HTTP headers as key-value record
 * @returns Array of header tuples in ASGI format
 */
function headersToASGI(headers: HttpRequest["headers"]): [string, string][];

/**
 * Convert ASGI headers to record format
 * @param headers - ASGI headers as array of tuples
 * @returns Headers as key-value record
 */
function asgiHeadersToRecord(headers: any): Record<string, string>;

/**
 * Get header value with case-insensitive lookup
 * @param headers - HTTP headers as key-value record
 * @param key - Header name to look up (case-insensitive)
 * @returns Header value or undefined if not found
 */
function getHeaderValue(headers: HttpRequest["headers"], key: string): string | undefined;

/**
 * Log HTTP request and response for debugging
 * @param request - HTTP request object
 * @param response - HTTP response object
 */
function logHttpReqRes(request: HttpRequest, response: HttpResponse): void;

/**
 * Convert Uint8Array to string representation
 * @param buf - Binary data to convert
 * @returns String representation of the binary data
 */
function uint8ArrayToString(buf: Uint8Array): string;

Utility Usage Examples:

import { headersToASGI, getHeaderValue } from "@gradio/wasm";

const headers = {
  "Content-Type": "application/json",
  "Authorization": "Bearer token123",
  "Accept": "application/json"
};

// Convert to ASGI format
const asgiHeaders = headersToASGI(headers);
console.log(asgiHeaders);
// Output: [["content-type", "application/json"], ["authorization", "Bearer token123"], ["accept", "application/json"]]

// Case-insensitive header lookup
const contentType = getHeaderValue(headers, "content-type"); // Works with lowercase
const auth = getHeaderValue(headers, "AUTHORIZATION"); // Works with uppercase
console.log(contentType); // "application/json"
console.log(auth); // "Bearer token123"

ASGI Integration

ASGI (Asynchronous Server Gateway Interface) types and utilities for web application integration.

/**
 * ASGI scope type for request metadata
 */
type ASGIScope = Record<string, unknown>;

/**
 * ASGI application function signature
 */
type ASGIApplication = (scope: ASGIScope, receive: () => Promise<ReceiveEvent>, send: (event: SendEvent) => Promise<void>) => Promise<void>;

/**
 * ASGI receive event types
 */
type ReceiveEvent = RequestReceiveEvent | DisconnectReceiveEvent;

/**
 * ASGI send event types
 */
type SendEvent = ResponseStartSendEvent | ResponseBodySendEvent;

/**
 * HTTP request receive event
 */
interface RequestReceiveEvent {
  type: "http.request";
  body?: Uint8Array;
  more_body?: boolean;
}

/**
 * HTTP disconnect receive event
 */
interface DisconnectReceiveEvent {
  type: "http.disconnect";
}

/**
 * HTTP response start send event
 */
interface ResponseStartSendEvent {
  type: "http.response.start";
  status: number;
  headers?: [string, string][];
}

/**
 * HTTP response body send event
 */
interface ResponseBodySendEvent {
  type: "http.response.body";
  body?: Uint8Array;
  more_body?: boolean;
}

Error Handling

HTTP requests through the worker can encounter various error conditions:

  • Network Errors: When the worker cannot process the request
  • Python Errors: When Python code in the worker raises exceptions
  • ASGI Errors: When ASGI application encounters errors
  • Timeout Errors: When requests take too long to process
// Example error handling
try {
  const response = await worker.httpRequest(request);
  
  if (response.status >= 400) {
    const errorBody = new TextDecoder().decode(response.body);
    console.error(`HTTP ${response.status}:`, errorBody);
  }
} catch (error) {
  console.error("Request failed:", error);
}

// Listen for Python errors during HTTP processing
worker.addEventListener("python-error", (event) => {
  console.error("Python error during HTTP request:", event.error);
});