# Val Town Utils Documentation

[View val on Val Town](https://www.val.town/x/std/utils)

@std/utils is a collection of utilities for Val Town, including reading files, serving static content, getting Val Town metadata, and more.

## What is the entrypoint?

Many functions below accept an optional `metaImportUrl` parameter that defaults to the entrypoint. The entrypoint is the `import.meta.url` of the file that Val Town executed — the HTTP handler that received a request, the cron job that fired, the email handler that received a message, or the script you clicked "Run" on. Val Town sets this automatically via `Deno.env.get("VALTOWN_ENTRYPOINT")`, so you almost never need to pass it yourself. The main reason to pass `import.meta.url` explicitly is when you're calling these functions from a different val than the one that was triggered.

---

## Table of Contents

### Deploy a static site

- [staticHTTPServer](#statichttpserver)

### File Operations

- [readFile](#readfile)
- [listFiles](#listfiles)
- [listFilesByPath](#listfilesbypath)
- [httpEndpoint](#httpendpoint)
- [emailAddress](#emailaddress)
- [getValId](#getvalid)
- [fetchTranspiledJavaScript](#fetchtranspiledjavascript)

### HTTP Utilities

- [serveFile](#servefile)
- [serveImmutableFile](#serveimmutablefile)
- [immutableFileUrl](#immutablefileurl)
- [getContentType](#getcontenttype)
- [hotReload](#hotreload)

### Val Metadata

- [parseVal](#parseval)
- [isMain](#ismain)

### Testing

- [testServer](#testserver)

---

## staticHTTPServer

[source](https://www.val.town/x/std/utils/code/static.tsx#L78-112)

Creates a simple static HTTP server that serves HTML, CSS, and JS files from your val.

This is the easiest way to deploy a static site or single-page app on Val Town: drop
an `index.html` (plus any CSS/JS/assets) into your val and `export default staticHTTPServer()`.

The server automatically serves `/index.html` for root requests and handles all other file paths.
It also exposes a `/source` route that redirects to the val's source code on Val Town, so visitors
can always click through to view how a page was built.

If you need a little custom routing (an API route, a redirect) but mostly want a static
server, pass a fetch handler as the second argument. It's tried first on every request:
return a `Response` to handle the request yourself, or return `null`/`undefined` to fall
through to the static server (and the `/source` redirect). This is just the fetch standard —
pass a plain function, or any framework's handler (e.g. Hono's `app.fetch`). See the second example.

Asset files are served via `serveImmutableFile`, so they get immutable
version-addressed browser caching automatically (bare paths 302 into
`/__immutable/<version>/`, and publishing the val bumps the version, invalidating
every cached file at once); `/` and `/index.html` always serve fresh.

```ts
function staticHTTPServer(metaImportUrl: string, handler?: FetchHandler): (request: Request): (request: Request) => Response | Promise<Response>
```

### Arguments

- **metaImportUrl** (`string`): the import.meta.url to determine which val to serve files from. Defaults to `Deno.env.get("VALTOWN_ENTRYPOINT")`
- **handler** (`FetchHandler`): A fetch handler `(request: Request) => Response | null | undefined` (or a promise thereof). Tried before static serving: return a `Response` to handle the request, or `null`/`undefined` to defer to the static server and the `/source` redirect. Pass a plain function or any framework's fetch handler (e.g. Hono's `app.fetch`).

### Returns

`(request: Request) => Response | Promise<Response>`: A fetch-compatible handler function `(request: Request) => Response | Promise<Response>` that serves static files with correct Content-Type headers. Returns 404 for missing files.

### Example

```ts
import { staticHTTPServer } from "https://esm.town/v/std/utils/index.ts";

// Most common usage - serves files from current val, plus a /source redirect
export default staticHTTPServer();

// Explicit val specification
export default staticHTTPServer(import.meta.url);

// Mostly static, but with a bit of custom routing.
// Pass a fetch handler: return a Response to handle a request,
// or null/undefined to fall through to static file serving.
import { staticHTTPServer } from "https://esm.town/v/std/utils/index.ts";

export default staticHTTPServer(import.meta.url, (req) => {
  const { pathname } = new URL(req.url);
  if (pathname === "/api/hello") return Response.json({ hello: "world" });
  return null; // defer to the static server (index.html / assets / /source)
});

// Any framework works too, since app.fetch is just a fetch handler.
import { Hono } from "npm:hono@4.11.9";
import { staticHTTPServer } from "https://esm.town/v/std/utils/index.ts";

const app = new Hono();
app.get("/api/hello", (c) => c.json({ hello: "world" }));
// Return 404s as null so unmatched routes fall through to the static server.
app.notFound(() => null as any);

export default staticHTTPServer(import.meta.url, app.fetch);
```

---

## readFile

[source](https://www.val.town/x/std/utils/code/file.ts#L41-56)

Reads the contents of a file.

Use `readFileTranspiled` if you need transpiled JavaScript for execution, like in a browser.

Note: Val Town doesn't provide direct file system access. This function uses the Val Town API to read your val files, allowing Val Town to more efficiently provide a scalable serverless runtime.

```ts
function readFile(path: string, metaImportUrl: string): Promise<string>
```

### Arguments

- **path** (`string`): the file path to read (with or without leading slash)
- **metaImportUrl** (`string`): the import.meta.url to determine which val to read from. Defaults to `Deno.env.get("VALTOWN_ENTRYPOINT")`

### Returns

`Promise<string>`: Promise that resolves to the raw file contents as a string. Throws `File not found: <path>` if the file doesn't exist.

### Example

```ts
import { readFile } from "https://esm.town/v/std/utils/index.ts";

// Most common usage - reads raw TypeScript from current val
const content = await readFile("/utils/helper.ts");
console.log(content); // Contains TypeScript with type annotations

// Explicit val specification
const content2 = await readFile("/README.md", import.meta.url);
console.log(content2);
```

---

## httpEndpoint

[source](https://www.val.town/x/std/utils/code/file.ts#L112-132)

Gets the HTTP endpoint URL for the currently running val or a specific file in the val.

```ts
function httpEndpoint(path: string, metaImportUrl: string): Promise<string>
```

### Arguments

- **path** (`string`): the file path to get the endpoint for. Defaults to the currently running endpoint.
- **metaImportUrl** (`string`): the import.meta.url to determine which val the file belongs to. Defaults to `Deno.env.get("VALTOWN_ENTRYPOINT")`

### Returns

`Promise<string>`: Promise that resolves to the full HTTP URL for the endpoint. Throws `File not found: <path>` if the file doesn't exist, or `No HTTP endpoint available for file: <path>` if it isn't an HTTP file.

### Example

```ts
import { httpEndpoint } from "https://esm.town/v/std/utils/index.ts";

const endpoint = await httpEndpoint();
console.log(endpoint); // Returns the full HTTP URL for the endpoint
```

---

## emailAddress

[source](https://www.val.town/x/std/utils/code/file.ts#L152-170)

Gets the email address for a file with an email trigger in the val.

Note: This function does not work for vanity email addresses. It only works for the UUID version.

```ts
function emailAddress(path: string, metaImportUrl: string): Promise<string>
```

### Arguments

- **path** (`string`): the file path to get the email address for
- **metaImportUrl** (`string`): the import.meta.url to determine which val the file belongs to. Defaults to `Deno.env.get("VALTOWN_ENTRYPOINT")`

### Returns

`Promise<string>`: Promise that resolves to the email address in format: `{username}-{fileIdWithoutDashes}@valtown.email`. Throws `File not found: <path>` if the file doesn't exist, or `File does not have email trigger: <path>` if it isn't an email file.

### Example

```ts
import { emailAddress } from "https://esm.town/v/std/utils/index.ts";

// Get the email address for a file with email trigger
const email = await emailAddress("/handlers/processEmail.ts");
console.log(email); // Returns: username-fileid@valtown.email
```

---

## listFiles

[source](https://www.val.town/x/std/utils/code/file.ts#L193-197)

Lists all files in the current val with their metadata.

Note: Val Town doesn't provide direct file system access. This function uses the Val Town API to list your val files, enabling a more scalable serverless runtime.

```ts
function listFiles(metaImportUrl: string): Promise<{
  name: string;
  id: string;
  path: string;
  version: number;
  updatedAt: string;
  type: "directory" | "file" | "interval" | "http" | "email" | "script";
  links: {
    self: string;
    html: string;
    module: string;
    endpoint?: string;
    email?: string;
  };
}[]>
```

### Arguments

- **metaImportUrl** (`string`): the import.meta.url to determine which val to list files from. Defaults to `Deno.env.get("VALTOWN_ENTRYPOINT")`

### Returns

```ts
Promise<{
  name: string;
  id: string;
  path: string;
  version: number;
  updatedAt: string;
  type: "directory" | "file" | "interval" | "http" | "email" | "script";
  links: {
    self: string;
    html: string;
    module: string;
    endpoint?: string;
    email?: string;
  };
}[]>
```

Promise that resolves to an array of file metadata objects — see the signature above for the full type

### Example

```ts
import { listFiles } from "https://esm.town/v/std/utils/index.ts";

// Most common usage - lists files from current val
const files = await listFiles();
files.forEach((file) => console.log(file.path));

// Explicit val specification
const files2 = await listFiles(import.meta.url);
files2.forEach((file) => console.log(file.path));
```

---

## getValId

[source](https://www.val.town/x/std/utils/code/file.ts#L214-223)

Gets the ID of a val.

```ts
function getValId(metaImportUrl: string): Promise<string>
```

### Arguments

- **metaImportUrl** (`string`): the import.meta.url to determine which val to get the ID for. Defaults to `Deno.env.get("VALTOWN_ENTRYPOINT")`

### Returns

`Promise<string>`: Promise that resolves to the val ID as a string

### Example

```ts
import { getValId } from "https://esm.town/v/std/utils/index.ts";

// Get the val id for the val this code is in
const id = await getValId();
console.log(id); // Returns: "bb8f592e-f528-11ef-b06d-569c3dd06744"
```

---

## listFilesByPath

[source](https://www.val.town/x/std/utils/code/file.ts#L241-276)

Lists files in a specific directory path within the current val.

```ts
function listFilesByPath(path: string, metaImportUrl: string): Promise<{
  name: string;
  id: string;
  path: string;
  version: number;
  updatedAt: string;
  type: "directory" | "file" | "interval" | "http" | "email" | "script";
  links: {
    self: string;
    html: string;
    module: string;
    endpoint?: string;
    email?: string;
  };
}[]>
```

### Arguments

- **path** (`string`): the directory path to list files from (with or without leading slash)
- **metaImportUrl** (`string`): the import.meta.url to determine which val to list files from. Defaults to `Deno.env.get("VALTOWN_ENTRYPOINT")`

### Returns

```ts
Promise<{
  name: string;
  id: string;
  path: string;
  version: number;
  updatedAt: string;
  type: "directory" | "file" | "interval" | "http" | "email" | "script";
  links: {
    self: string;
    html: string;
    module: string;
    endpoint?: string;
    email?: string;
  };
}[]>
```

Promise that resolves to an array of file metadata objects (same shape as `listFiles`). Throws `File not found: <path>` if the val has no such path.

### Example

```ts
import { listFilesByPath } from "https://esm.town/v/std/utils/index.ts";

// List files in a specific directory
const frontendFiles = await listFilesByPath("frontend/");
frontendFiles.forEach((file) => console.log(file.path));
```

---

## fetchTranspiledJavaScript

[source](https://www.val.town/x/std/utils/code/file.ts#L294-296)

Fetches and transpiles TypeScript/JavaScript code from esm.town URLs.

```ts
function fetchTranspiledJavaScript(url: string): Promise<string>
```

### Arguments

- **url** (`string`): the esm.town URL to fetch (e.g., "https://esm.town/v/username/valname@version-branch/file.ts")

### Returns

`Promise<string>`: Promise that resolves to the transpiled JavaScript code as a string

### Example

```ts
import { fetchTranspiledJavaScript } from "https://esm.town/v/std/utils/index.ts";

const code = await fetchTranspiledJavaScript(
  "https://esm.town/v/std/utils@85-main/index.ts"
);
console.log(code);
```

---

## serveFile

[source](https://www.val.town/x/std/utils/code/serve-file.ts#L30-33)

Serves a file from the val as an HTTP Response with the correct Content-Type header.

A file that doesn't exist is logged and answered with a 404 rather than thrown:
a missing asset is ordinary traffic for a static server (favicons, bots, stale
links), not an exception. Every other failure still throws.

```ts
function serveFile(path: string, metaImportUrl?: string): Promise<Response>
```

### Arguments

- **path** (`string`): the file path to serve
- **metaImportUrl** (`string`): the import.meta.url to determine which val to serve from. Defaults to `Deno.env.get("VALTOWN_ENTRYPOINT")`

### Returns

`Promise<Response>`: Promise that resolves to an HTTP Response with the file content and appropriate Content-Type header, or a 404 naming the file if it doesn't exist

### Example

```ts
import { serveFile } from "https://esm.town/v/std/utils/index.ts";

// In a Hono app - most common usage
app.get("/assets/*", async (c) => {
  return await serveFile(c.req.path);
});

// Explicit val specification
app.get("/assets/*", async (c) => {
  return await serveFile(c.req.path, import.meta.url);
});
```

---

## serveFile

[source](https://www.val.town/x/std/utils/code/serve-file.ts#L44-48)

Same as above, but also accepts the incoming `Request` first — the argument
order of Deno's `serveFile`, and a common guess. The request itself is unused.

```ts
function serveFile(request: Request, path: string, metaImportUrl?: string): Promise<Response>
```

### Returns

`Promise<Response>`

### Example

```ts
export default (req: Request) => serveFile(req, "/index.html");
```

---

## getContentType

[source](https://www.val.town/x/std/utils/code/serve-file.ts#L94-100)

Determines the appropriate MIME type for a file based on its extension.

```ts
function getContentType(path: string): string
```

### Arguments

- **path** (`string`): the file path to get the content type for

### Returns

`string`: The MIME type string (e.g., "text/html", "application/json")

### Example

```ts
import { getContentType } from "https://esm.town/v/std/utils/index.ts";

console.log(getContentType("index.html")); // "text/html; charset=utf-8"
console.log(getContentType("script.ts")); // "text/javascript"
console.log(getContentType("data.json")); // "application/json; charset=utf-8"
```

---

## immutableFileUrl

[source](https://www.val.town/x/std/utils/code/serve-immutable-file.ts#L33-39)

Makes your val's frontend faster by letting browsers cache its files immutably —
repeat visits load them straight from the cache instead of re-downloading them.
Works by putting the val's current version in the URL:
`immutableFileUrl("/frontend/index.tsx")` → `"/__immutable/45/frontend/index.tsx"`.
Publishing the val bumps the version, which changes every URL at once — browsers
refetch each file exactly once, and caches never go stale.

Use it in your (never-cached) HTML shell to stamp the client entry script and
favicon, and route `/__immutable/*` to `serveImmutableFile`. The version prefixes
the whole path, so the entry's relative imports stay in versioned space — the
entire client graph ends up immutably cached.

```ts
function immutableFileUrl(path: string, metaImportUrl: string): string
```

### Arguments

- **path** (`string`): the file path to stamp (e.g. "/frontend/index.tsx" or "/logo.png")
- **metaImportUrl** (`string`): the import.meta.url to determine which val's version to stamp. Defaults to `Deno.env.get("VALTOWN_ENTRYPOINT")`

### Returns

`string`: The version-addressed URL (e.g. "/__immutable/45/frontend/index.tsx")

### Example

```ts
// In your (never-cached) HTML shell:
<script type="module" src={immutableFileUrl("/frontend/index.tsx")} />
```

---

## serveImmutableFile

[source](https://www.val.town/x/std/utils/code/serve-immutable-file.ts#L68-94)

Makes your val's frontend faster by letting browsers cache its files immutably —
repeat visits load them straight from the cache instead of re-downloading them.
Serves the version-addressed URLs that `immutableFileUrl` produces; publishing
the val bumps the version, which changes every URL, so caches invalidate
automatically on every publish.

Handles the three cases:
- current version (`/__immutable/45/...`) → serves the file with `Cache-Control: immutable`
- any other version → plain 404: old URLs die when you publish (like Next.js
  build assets — a stale open tab that lazy-loads gets a 404; a reload fixes it)
- no `/__immutable/` prefix → 302 into versioned space — so an existing plain
  asset route can point here too: `<script src="/frontend/index.tsx">` keeps
  working at the cost of one redirect per page view. Note the redirect lands on
  `/__immutable/...`, so that route must exist as well (see the example); stamp
  the URL with `immutableFileUrl` in your HTML shell to skip the redirect entirely

```ts
function serveImmutableFile(path: string, metaImportUrl: string): Promise<Response>
```

### Arguments

- **path** (`string`): the requested path (e.g. `c.req.path`)
- **metaImportUrl** (`string`): the import.meta.url to determine which val (and version) to serve from. Defaults to `Deno.env.get("VALTOWN_ENTRYPOINT")`

### Returns

`Promise<Response>`: Promise resolving to the file Response, a 302 into the current version, or a 404 for non-current versions and missing files (the 404 carries no cache header)

### Example

```ts
// Route the reserved prefix to it in your Hono app:
app.get("/__immutable/*", (c) => serveImmutableFile(c.req.path));
```

---

## parseVal

[source](https://www.val.town/x/std/utils/code/parseImportMeta.ts#L37-78)

Parses Val Town metadata from an import.meta.url.

```ts
function parseVal(metaImportUrl: string): {
  username: string;
  name: string;
  version: string;
  branch: string;
  path: string;
  links: {
    self: {
      latest: string;
      pinned: string;
      val: string;
    };
    module: {
      latest: string;
      pinned: string;
      val: string;
      valPinned: string;
    };
  };
}
```

### Arguments

- **metaImportUrl** (`string`): the import.meta.url to parse. Defaults to `Deno.env.get("VALTOWN_ENTRYPOINT")`

### Returns

```ts
{
  username: string;
  name: string;
  version: string;
  branch: string;
  path: string;
  links: {
    self: {
      latest: string;
      pinned: string;
      val: string;
    };
    module: {
      latest: string;
      pinned: string;
      val: string;
      valPinned: string;
    };
  };
}
```

A `Val` object with `username`, `name`, `version`, `branch`, `path`, and `links` (containing `self` and `module` URL variants)

### Example

```ts
import { parseVal } from "https://esm.town/v/std/utils/index.ts";

const val = parseVal(import.meta.url);
console.log(val);
// Output: { username: "username", name: "valname", version: "1", branch: "main", path: "", links: {...} }
```

---

## isMain

[source](https://www.val.town/x/std/utils/code/is-main.ts#L19-21)

Checks if the current file is the main entry point of the val.

This is a replacement for `import.meta.main` which is not available in Val Town's environment.

```ts
function isMain(metaImportUrl: string): boolean
```

### Arguments

- **metaImportUrl** (`string`): the `import.meta.url` of the current file

### Returns

`boolean`: `true` if the file is the main entry point, `false` otherwise

### Example

```ts
import { isMain } from "https://esm.town/v/std/utils/index.ts";

if (isMain(import.meta.url)) {
  // Code that doesn't run if this file is imported
  // Useful for testing functions near their definitions
}
```

---

## testServer

[source](https://www.val.town/x/std/utils/code/test.tsx#L235-264)

Creates a test runner that displays test results as an HTML page with badges and detailed output.

```ts
function testServer(testGroups: {}): (req: Request): (req: Request) => Promise<Response>
```

### Arguments

- **testGroups** (`{}`): Array of `{ name, tests, before?, after? }` objects. Each test is `{ name, function }` — throw to fail, return to pass.

### Returns

`(req: Request) => Promise<Response>`: A `(req: Request) => Promise<Response>` handler. Returns an HTML results page; an SVG badge at `/badge.svg`; or JSON at `/results.json` — `{ passed, total, duration, groups: [{ name, passed, total, tests: [{ name, pass, duration, message? }] }] }`, with `message` set to the error for failing tests.

### Example

```ts
import { testServer } from "https://esm.town/v/std/utils/index.ts";

const myTests = [{
  name: "Math tests",
  tests: [
    { name: "addition", function: () => { if (1 + 1 !== 2) throw new Error("Math is broken"); } },
    { name: "subtraction", function: () => { if (5 - 3 !== 2) throw new Error("Wrong result"); } }
  ]
}];

export default testServer(myTests);
```

---

## hotReload

[source](https://www.val.town/x/std/utils/code/hot-reload.ts#L34-84)

Wraps an HTTP handler to enable hot reload during development.

When a val is served on a `.val.run` domain, this wrapper:
1. Injects a small script into HTML responses that long-polls for version changes
2. Handles the long-poll endpoint (`/__vt_hot_reload`)
3. Actively checks the Val Town API for new versions of the current branch
4. When a new version is deployed, the client detects the change and reloads the page

On custom domains (non `.val.run`), the handler passes through unmodified.

```ts
function hotReload(handler: (req: Request) => any): (req: Request) => Promise<Response>
```

### Arguments

- **handler** (`(req: Request) => any`): Your HTTP fetch handler

### Returns

`(req: Request) => Promise<Response>`: A wrapped handler with hot reload support

### Example

```ts
import { hotReload } from "https://esm.town/v/std/utils/index.ts";

export default hotReload(async (req: Request) => {
  return new Response("<html><body><h1>Hello!</h1></body></html>", {
    headers: { "Content-Type": "text/html" },
  });
});
```

---
