Metrix.Bar

Documentation / Runtime APIs

Runtime APIs

Networking, sockets, DNS, browser OAuth, local HTTP ingress, SQLite, IndexedDB, caches, local files, WebAssembly, Intl/Temporal, Web Crypto, and background tasks.

Web APIs and network limits

Out of the box (no apis opt-in required), Workers provide fetch, Headers, Request, Response, Blob, File, FormData, ReadableStream, WritableStream, TransformStream, AbortController, AbortSignal (abort, any, timeout, throwIfAborted), TextEncoder/TextDecoder, TextEncoderStream/TextDecoderStream, URL/URLSearchParams, Buffer, and Node-style timers (setTimeout/setInterval returning ref()/unref() handles, plus setImmediate). response.formData() parses application/x-www-form-urlencoded only.

  • Budgets: 8 MiB upload body, 16 MiB decompressed response, 4 concurrent requests per Worker, 60 s per request. Responses hold a slot until consumed or canceled—always read or cancel every body (unread responses older than 1 s may be canceled when requests queue).
  • Identity & permissions: Every outbound request requires a matching <network> permission (or runtime grant) and sends X-Requested-With: bar.metrix and User-Agent: Metrix.Bar/<version>.
  • Redirects (redirect option):
    • "follow" (default): Up to 10 hops; each hop checks permissions, forbids HTTPS→HTTP downgrade even with allow-http="true", and strips Authorization, Cookie, and proxy auth headers across origins (including port/subdomain changes).
    • "manual": Returns the raw 301/302/303/307/308 Response (status, Location, body) without contacting or requiring permission for the target.
    • "error": Rejects on 301/302/303/307/308 (304 is not a redirect).
  • Proxy policy: Follows the app's startup setting (System, Direct, or Manual HTTP/SOCKS5; changes take effect after restart). Proxy failures never fall back to direct connections. macOS evaluates SystemConfiguration static proxies and CFNetwork PAC (10 s limit); Windows evaluates WinHTTP static proxies and PAC/WPAD (10 s limit); Linux reads GNOME/Unity/Cinnamon gsettings or HTTP_PROXY/HTTPS_PROXY/ALL_PROXY/NO_PROXY (unsupported PAC/WPAD blocks outbound access). navigator.onLine reflects the OS connectivity snapshot (does not prove internet reachability).

Realtime WebSocket connections

Declare apis="websocket" (included in all) plus the matching HTTPS origin for wss:// or allowed HTTP origin (allow-http="true" or local/private) for ws://.

  • Standard new WebSocket(url, protocols?) (≤ 32 unique protocols, ≤ 128 bytes each), readyState, send (string or BufferSource), close(code = 1000 | 3000..4999, reason ≤ 123 B), bufferedAmount, and open/message/error/close listeners. Set socket.binaryType = "arraybuffer" for binary ArrayBuffer messages (default is Blob).
  • Redirects, URL credentials, and fragments are rejected. Uses app proxy and standard request headers.
  • Budgets: 4 connections per Worker (including handshakes), 8 MiB max message in either direction, 16 MiB shared outgoing buffer across connections, 256 queued sends per connection, 4 messages / 32 MiB incoming buffer per connection with backpressure, 60 s handshake timeout. Established connections have no cumulative byte cap or 60 s idle timeout. Implement reconnect/backoff in script and call $metrix.invalidate() on async updates. Unavailable in fixtures and Playground.

TCP, TLS & UDP sockets

Declare apis="sockets" (included in all) and exact tcp://host:port, tls://host:port, or udp://host:port permissions (separate from HTTP/HTTPS). Listening servers are unavailable.

TCP & TLS

  • Cloudflare-style: import { connect } from "cloudflare:sockets": connect(address, { secureTransport: "off" | "on" | "starttls", allowHalfOpen? }) returns { readable, writable, opened, closed, close(), startTls(options) }. STARTTLS requires both tcp:// and tls:// grants and upgrades once with no unread buffered plaintext.
  • Node aliases: node:net/net, node:tls/tls, node:events/events, node:stream/stream, node:buffer/buffer, node:stream/web/stream/web (Socket, connect, createConnection, tls.connect with { socket } STARTTLS, EventEmitter, streams, pipeline, finished). rejectUnauthorized: false throws; custom PEM ca, serverName, and alpn are supported.
  • Limits: 4 connections per Worker (shared with UDP), 10 s dial & TLS handshake, 60 s hard idle timer reset on successful I/O, 1 MiB per write, 64 MiB cumulative read and write per connection.

UDP datagrams

Import dgram or node:dgram (createSocket("udp4" | "udp6", listener?)). Call connect(port, hostname?, cb?) once to bind a fixed unicast peer, then send(data, cb?) (wait for callback before sending again—no send queue) and listen for message(Buffer, rinfo) (zero-length packets preserved).

  • Limits: Shares the 4-socket cap; 65,507 B max packet; 65,536 packets / 64 MiB per direction; 10 s dial; 60 s idle timer. Explicit bind, reconnect, broadcast, multicast, and alternate send destinations throw. Uses DIRECT routes only (selecting HTTP/SOCKS rejects with no direct fallback). Probe sockets.udp (false in fixtures/Playground).

DNS queries

Declare apis="dns" (included in all) and exact <dns> grants. $metrix.dns uses Go resolver semantics (local hosts lookup applies; no node:dns aliases or TTL fields):

MethodOptionsResult
$metrix.dns.lookup(name, options?){ family?: 0 | 4 | 6, server? }{ address, family }[]
$metrix.dns.resolve(name, type = "A", options?){ server? }; type is A, AAAA, CNAME, TXT, MX, NS, or SRVStrings (A/AAAA/CNAME/NS/concatenated TXT), { host, preference } (MX), or { target, port, priority, weight } (SRV)
$metrix.dns.reverse(ip, options?){ server? } (permission name is the IP)string[]

Direct queries use UDP with TCP retry for truncated replies; proxy-selected queries use DNS-over-TCP through the app proxy (no direct fallback). Limits: 4 pending queries per Worker, 10 s per query, 1 MiB JSON result. Probe dns / dns.lookup / dns.resolve / dns.reverse (requires at least one valid grant; unavailable in staging/fixtures/Playground).


Browser authorization and secret storage

Declare apis="auth" (included in all; also add crypto for PKCE) plus network permissions for the authorization and token origins (HTTPS, or permitted loopback HTTP).

  • await $metrix.auth.authorize({ url, timeoutMs?, callback? }): Returns Promise<Record<string, string>> (without state; preserves OAuth error params). url (≤ 8192 B before and after expansion) must include {{redirect_uri}} and {{state}}.
    • callback: "loopback" (default) listens once on http://127.0.0.1:<random-port>/callback.
    • callback: "scheme" uses metrixbar://auth/callback (no listener; requires PKCE S256 and a public client—never embed client_secret).
    • Limits: 1 pending auth per Worker; timeoutMs 1..600000 (default 180000, 3 min); callback query ≤ 16 KiB, ≤ 32 unique keys (1..128 B each), values ≤ 8 KiB.
  • await $metrix.setSecret(name, value) / await $metrix.deleteSecret(name): Writes or deletes a declared type="secret" input for this instance (value ≤ 2560 UTF-8 bytes; never touches external credentials).
  • Hook budget rule: Authorization waits do not extend the 15 s hook budget. Return from your event handler immediately and run the OAuth flow in a detached async IIFE that catches errors, saves the token, and calls $metrix.invalidate(). Unavailable in staging, fixtures, and Playground.
js
// Declare apis="auth crypto", <input name="token" type="secret" />, and <network origin="https://gitlab.com" />
const clientID = "REPLACE_WITH_APPLICATION_ID";
let pending = false;
let status = "Sign in";

const b64url = (bytes) =>
  btoa(String.fromCharCode(...bytes))
    .replace(/\+/g, "-")
    .replace(/\//g, "_")
    .replace(/=+$/, "");

function startLogin() {
  if (pending) return;
  pending = true;
  status = "Waiting for sign-in";
  $metrix.invalidate();
  void (async () => {
    try {
      const verifier = b64url(crypto.getRandomValues(new Uint8Array(32)));
      const challenge = b64url(
        new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))),
      );
      const params = await $metrix.auth.authorize({
        callback: "scheme",
        url:
          `https://gitlab.com/oauth/authorize?response_type=code&client_id=${encodeURIComponent(clientID)}` +
          `&scope=read_user&code_challenge_method=S256&code_challenge=${encodeURIComponent(challenge)}` +
          `&redirect_uri={{redirect_uri}}&state={{state}}`,
      });
      if (params.error || !params.code) throw new Error("Authorization failed");
      const res = await fetch("https://gitlab.com/oauth/token", {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: new URLSearchParams({
          grant_type: "authorization_code",
          client_id: clientID,
          redirect_uri: "metrixbar://auth/callback",
          code: params.code,
          code_verifier: verifier,
        }).toString(),
      });
      if (!res.ok) throw new Error("Token exchange failed");
      const { access_token } = await res.json();
      await $metrix.setSecret("token", access_token);
      status = "Signed in";
    } catch {
      status = "Sign-in failed";
    } finally {
      pending = false;
      $metrix.invalidate();
    }
  })();
}

Local HTTP requests

Declare <permissions><http-ingress /></permissions> and export fetch(request, env) on the default object (you can pass requests to a bundled router like Hono or H3 v2).

js
export default {
  render() {
    return null;
  },
  fetch(request, env) {
    if (request.method === "GET" && new URL(request.url).pathname === "/status") {
      return Response.json({ id: env.id, ready: true });
    }
    return new Response("Not found", { status: 404 });
  },
};

Users enable Privacy → Local HTTP requests per instance and click Copy curl command (http://<instance-id>.localhost:6388 with an instance-specific bearer token consumed by the host; disabling invalidates the token; Origin must match the endpoint origin). Requests wake an idle dashboard, buffer up to 1 MiB per request/response, and share a 15 s deadline. Probe http.ingress (false in fixtures/Playground).


Persistent SQLite databases

Declare apis="sqlite" (included in all). Named databases ([A-Za-z0-9_-]{1,64}) are isolated per dashboard instance, persist across reloads and restarts, and are never exported with .bar files (do not store secrets here).

MethodResult
await $metrix.sqlite.open(name)Opens or creates a connection
db.prepare(sql)Synchronously creates a single-statement prepared statement
stmt.bind(...params)Returns a new bound statement (null, boolean as 0/1, finite number, signed 64-bit BigInt, string, or binary buffer/view)
await stmt.all() / await stmt.run(){ success: true, results: rowObject[], meta: { changes, last_row_id, duration } } (supports RETURNING)
await stmt.raw({ columnNames?: boolean })Row arrays, optionally preceded by column names
await stmt.first(column?)First row object or column value (null if empty; throws on missing column)
await db.batch([stmt, ...])Executes atomically; rolls back all writes on failure
await db.close()Idempotent close (keeps database on disk)
js
let db;
async function getDB() {
  if (!db) {
    db = await $metrix.sqlite.open("history");
    await db.prepare("CREATE TABLE IF NOT EXISTS samples (time INTEGER, value REAL)").run();
  }
  return db;
}
  • Limits: 8 database names per dashboard, 8 connections and 4 pending ops per Worker, 10 s per op, 1 MiB SQL+params, 100 statements/batch, 10,000 rows / 8 MiB results, 128 MiB main DB / 32 MiB temp DB, and a 128 MiB process-wide SQLite heap shared with IndexedDB.
  • SQL surface: Tables, indexes, JOINs, and aggregates work; user PRAGMA, ATTACH/DETACH, VACUUM, extensions, virtual tables, and manual BEGIN/COMMIT are unavailable. Prebundled kysely@0.27.6 + kysely-d1@0.4.0 works (kysely@0.28+ fails on missing Symbol.asyncDispose). Unavailable in Playground.

Persistent IndexedDB storage

Declare apis="indexedDB" (included in all). Per-dashboard persistent structured storage separate from SQLite; supports keyPath, autoIncrement, compound/unique/multiEntry indexes, key ranges, cursors, readonly/readwrite/versionchange transactions, and https://esm.sh/idb@8.0.3 (requires <network origin="https://esm.sh" />).

  • Rules: Always wait for transaction complete/abort (or tx.done in idb) and close connections in finally; handle db.onversionchange = () => db.close(). Structured clone supports primitives, BigInt, Date, RegExp, Map, Set, TypedArray, DataView, ArrayBuffer, and circular refs—storing Blob/File throws DataCloneError.
  • Limits: 8 physical DB slots per dashboard, 128 MiB main file, 10 s per op/tx, 100 internal SQL statements & 1 MiB input per tx, 10,000 rows / 8 MiB results, 4 pending ops per Worker, shared 128 MiB SQLite heap. Unavailable in Playground; /v0/check uses disposable databases.

Caches & localStorage

  • apis="caches": caches.default and await caches.open(name) provide match, put, delete for persistent text/JSON/binary Response caching. Limits per dashboard: 64 MiB total (LRU eviction), 64 named caches (names ≤ 128 UTF-8 B), 256 entries/cache, 16 MiB per body, 64 KiB combined metadata, default TTL 1 hour.
  • apis="localStorage": Persistent key-value string storage per dashboard instance across reloads and restarts (never store secrets).

Local files

Directory listing, metadata & byte ranges ($metrix.files)

Available without apis opt-in; reuses <file> declarations, input templates, open-dialog/drop/paste grants, and retained grants via safe directory handles (no symlink escape). Unavailable in staging, fixtures, and Playground.

MethodResult & limits
await $metrix.readFile(path)Full UTF-8 string (≤ 8 MiB, resolves ~).
await $metrix.files.list(path, { cursor?, limit? }?){ entries: [{ name, type }], cursor } (type: file|directory|symlink|other; limit 1..1000, default 100; requires trailing-/ <file> or showOpenDialog({ directory: true }); rescans in ascending UTF-8 byte order).
await $metrix.files.stat(path){ type: "file"|"directory", size, mtime, identity } (mtime Unix ms; identity opaque or null).
await $metrix.files.read(path, { offset?, length? }?)Uint8Array (offset ≥ 0; length 0..1048576, default 1 MiB; short/empty read = EOF).

Budgets: 16 pending list/stat/read calls and 4 MiB reserved read lengths per Worker.

Retained file grants

User grants from file pickers, drops, rich transfers, or explicit pastes normally expire on Worker close. Persist them per instance (probe files.retain; max 256 paths per installation; cleared on uninstall, never copied on duplicate):

  • await $metrix.files.retain(paths) (all paths must have been user-granted in this Worker or the batch rejects)
  • await $metrix.files.release(paths) (stops persisting; current Worker keeps grants until close)
  • await $metrix.files.retained() (returns persisted canonical paths)

Restored grants preserve exact scope (whole-directory picker grants cover children and files.list, whereas opening/revealing/fetching an icon for a folder itself requires an exact folder grant such as a folder drop).

Versioned text and safe saving (apis="dialog")

Declare apis="dialog" for native dialogs and optimistic-conflict file saves (≤ 8 MiB):

  • await $metrix.showOpenDialog(options) → selected paths (added to current Worker's read allowlist; pass { directory: true } for folder listing)
  • await $metrix.showSaveDialog(options) → confirmed destination path (only confirmed save paths are writable; grants no reads)
  • await $metrix.showMessageBox(options) → modal alert dialog
  • await $metrix.readTextFile(path) → { data: string, version: string } (UTF-8 text + SHA-256 hex from the same read)
  • await $metrix.fileInfo(path) → { size, version }
  • await $metrix.writeFile(path, data, { expectedVersion? }?) → { version } (data: string/ArrayBuffer/TypedArray; omit expectedVersion to overwrite, pass null to require absence, or pass a version hash to reject on conflict with "file changed since it was read")

External credentials

Declare <permissions><credential service="Example App" account="{{ user.name }}" /></permissions> and call await $metrix.readCredential("Example App", $metrix.userName) to read an existing third-party entry from the OS credential store (UTF-8 ≤ 1 MiB; bar.metrix* services are reserved; missing/denied items reject without exposing OS error details). Fixtures use user_name and credentials: [{ service, account, value }].


WebAssembly modules

Available by default in native app Workers (no apis opt-in). Import a pinned HTTPS .wasm module statically (import mod from "https://…/x.wasm") or dynamically (await import(url)), or compile local bytes directly (new WebAssembly.Module(bytes) / await WebAssembly.compile(bytes) / WebAssembly.validate(bytes)). Every redirect hop requires HTTPS and <permissions><network>.

bar
<bar protocol-version="0" id="wasm-greet" title="Wasm Greet" refresh="5m">
  <permissions><network origin="https://raw.githubusercontent.com" /></permissions>
  <script><![CDATA[
import module from "https://raw.githubusercontent.com/wg/cf-worker-wasm/d8ac2ddde63ccb6f0bca774051cf1229825725cf/src/wasm/greet_bg.wasm";
import init, { greet } from "https://raw.githubusercontent.com/wg/cf-worker-wasm/d8ac2ddde63ccb6f0bca774051cf1229825725cf/src/wasm/greet.js";

let ready = false, title = "Wasm";
export default {
  async scheduled() {
    if (!ready) { await init(module); ready = true; }
    title = greet("Metrix");
  },
  render() { return { tray: { title } }; },
};
]]></script>
</bar>
  • Supported subset: Core V2 (MultiValue, SignExtension, NonTrappingFloatToIntConversion, ReferenceTypes, BulkMemoryOperations, internal SIMD); WebAssembly.instantiate / new WebAssembly.Instance / Module.imports / Module.exports; synchronous i32/i64 (BigInt)/f32/f64/externref functions; shared Memory (64 KiB pages; .grow() detaches old .buffer), Table (funcref/externref), and numeric Global.
  • Unsupported: compileStreaming/instantiateStreaming, Module.customSections, WASI, threads/shared memory, Memory64, reference-valued Global, and SIMD/funcref params across the JS boundary.
  • Budgets & failures: 128 compilation/validation attempts / 32 MiB cumulative (8 MiB per binary); 8 retained user instances; 128 MiB linear memory (1 GiB with workload="compute"); 4096 elements/table (32768 total); 128 constructor objects; 65536 externref handles; 2 concurrent compile jobs process-wide. Cancellation or timeout after entering Wasm start/exports marks the entire Worker failed.

Intl, Temporal & Web Crypto

  • apis="intl": Intl.getCanonicalLocales, Intl.Locale, Intl.Segmenter, Intl.PluralRules, Intl.NumberFormat, Intl.DateTimeFormat (en/zh locale data, embedded tzdata, host time zone via $metrix.timeZone). Call constructors explicitly (Number/Date prototypes are not patched). RelativeTimeFormat, ListFormat, DisplayNames, and Collator are unavailable.
  • apis="temporal": Enables intl plus Temporal (Instant, ZonedDateTime, PlainDateTime, PlainDate, PlainTime, PlainYearMonth, PlainMonthDay, Duration, Now; iso8601/gregory calendars).
  • apis="crypto": crypto.getRandomValues(intTypedArray) (≤ 65,536 B), crypto.randomUUID(), crypto.subtle.digest (SHA-1/256/384/512), crypto.subtle.importKey ("raw" HMAC SHA-1/256/384/512 only; no exportKey, RSA, ECDSA, or AES), crypto.subtle.sign / verify (HMAC). Limits: 16 MiB per buffer/key, 8 pending ops and 32 MiB input snapshots per Worker.

Background tasks ($metrix.waitUntil)

Declare apis="background" (included in all; probe waitUntil) to call $metrix.waitUntil(promise) from a native Worker callback. Registers 1 pending Promise per Worker and keeps the Worker alive until settled (up to 30 minutes, does not survive Worker restart). Start background file I/O on the next event-loop turn (e.g. setTimeout) so it does not inherit the callback's 15 s deadline.