文档 / 运行时 API
运行时 API
网络与代理、WebSocket、TCP/TLS/UDP、DNS、浏览器 OAuth、本地 HTTP 入口、SQLite、IndexedDB、缓存、本地文件、WebAssembly、Intl/Temporal、Web Crypto 与后台任务。
Web API 与网络限制
默认内置(无需 apis 声明):fetch、Headers、Request、Response、Blob、File、FormData、ReadableStream、WritableStream、TransformStream、AbortController、AbortSignal(abort、any、timeout、throwIfAborted)、TextEncoder/TextDecoder、TextEncoderStream/TextDecoderStream、URL/URLSearchParams、Buffer 以及 Node 风格定时器(setTimeout/setInterval 返回带 ref()/unref() 的句柄,含 setImmediate)。response.formData() 仅解析 application/x-www-form-urlencoded。
- 限额:上传请求体 8 MiB、解压后响应体 16 MiB、单 Worker 并发 4 个请求、单请求超时 60 秒。响应体在读完或取消前持续占用并发槽——务必消费或取消每个响应体(排队时超过 1 秒未读的最早响应可能被取消)。
- 权限与请求头:所有出站请求须匹配
<network>(或运行时授权),并自动附加X-Requested-With: bar.metrix与User-Agent: Metrix.Bar/<version>。 - 重定向(
redirect选项):"follow"(默认):最多 10 跳;每跳校验网络权限,即使声明allow-http="true"也禁止 HTTPS→HTTP 降级;跨源(含端口或子域变化)清除Authorization、Cookie与代理认证头。"manual":直接返回原始 301/302/303/307/308Response(可读status、Location与响应体),不访问也不要求目标源权限。"error":遇 301/302/303/307/308 直接拒绝(304非重定向)。
- 代理策略:遵循 App 启动时的网络策略(系统、直连或手动 HTTP/SOCKS5,修改后重启生效);代理失败绝不回退直连。macOS 支持 SystemConfiguration 静态代理与 CFNetwork PAC(10 秒超时);Windows 支持 WinHTTP 静态代理与 PAC/WPAD(10 秒超时);Linux 读取 GNOME/Unity/Cinnamon gsettings 或
HTTP_PROXY/HTTPS_PROXY/ALL_PROXY/NO_PROXY(未支持的 PAC/WPAD 会阻止出站)。navigator.onLine为操作系统连通性快照(不代表公网可达)。
实时 WebSocket 连接
声明 apis="websocket"(包含在 all 中),并为 wss:// 授予对应 HTTPS 源、为 ws:// 授予允许的 HTTP 源(局域网/回环或 allow-http="true")。
- 标准
new WebSocket(url, protocols?)(最多 32 个不重复子协议、每个 ≤ 128 字节)、readyState、send(字符串或BufferSource)、close(code = 1000 | 3000..4999, reason ≤ 123 B)、bufferedAmount及open/message/error/close监听。接收二进制ArrayBuffer请设socket.binaryType = "arraybuffer"(默认Blob)。 - 拒绝重定向、URL 凭据与 fragment,遵循应用代理与标准请求头。
- 限额:每 Worker 4 条连接(含握手)、单条消息双向均 ≤ 8 MiB、所有连接共享 16 MiB 待发送缓冲、单连接发送队列上限 256 条、单连接接收缓冲 4 条 / 32 MiB(带背压)、握手超时 60 秒。已建立连接无累计 8 MiB 或 60 秒空闲限制。断线重连请在
.bar内实现,异步更新视图后调用$metrix.invalidate()。fixture 与演练场不可用。
TCP、TLS 与 UDP 套接字
声明 apis="sockets"(包含在 all 中)与精确的 tcp://host:port、tls://host:port 或 udp://host:port 权限(独立于 HTTP/HTTPS)。不支持服务端监听。
TCP 与 TLS
- Cloudflare 风格:
import { connect } from "cloudflare:sockets":connect(address, { secureTransport: "off" | "on" | "starttls", allowHalfOpen? })返回{ readable, writable, opened, closed, close(), startTls(options) }。STARTTLS 须同时具备tcp://与tls://授权,且在无未读明文缓冲时升级一次。 - Node 别名:
node:net/net、node:tls/tls、node:events/events、node:stream/stream、node:buffer/buffer、node:stream/web/stream/web(Socket、connect、createConnection、支持{ socket }STARTTLS 的tls.connect、EventEmitter、流、pipeline、finished)。rejectUnauthorized: false会抛错;支持自定义 PEMca、serverName与alpn。 - 限额:每 Worker 4 条连接(与 UDP 共享)、拨号与 TLS 握手各 10 秒、成功 I/O 重置 60 秒硬空闲计时器、单次写入 1 MiB、单连接累计读写各 64 MiB。
UDP 数据报
导入 dgram 或 node:dgram(createSocket("udp4" | "udp6", listener?))。先 connect(port, hostname?, cb?) 绑定单个单播对端,再 send(data, cb?)(须等待回调后再发下一包,不排队)并监听 message(Buffer, rinfo)(保留零长度数据包)。
- 限额:共享 4 连接上限;单包 ≤ 65,507 字节;单方向 65,536 包 / 64 MiB;10 秒拨号;60 秒空闲。不支持显式
bind、重连、广播、组播或替代目标地址。仅支持 DIRECT 路由(命中 HTTP/SOCKS 代理直接拒绝且不回退直连)。探测sockets.udp(fixture/演练场返回false)。
DNS 查询
声明 apis="dns"(包含在 all 中)及精确 <dns> 权限。$metrix.dns 采用 Go 解析器语义(支持本机 hosts;无 node:dns 别名与 TTL):
| 方法 | 选项 | 返回值 |
|---|---|---|
$metrix.dns.lookup(name, options?) | { family?: 0 | 4 | 6, server? } | { address, family }[] |
$metrix.dns.resolve(name, type = "A", options?) | { server? };type 为 A、AAAA、CNAME、TXT、MX、NS 或 SRV | 字符串(A/AAAA/CNAME/NS/拼接后的 TXT)、{ host, preference }(MX)或 { target, port, priority, weight }(SRV) |
$metrix.dns.reverse(ip, options?) | { server? }(权限 name 为该 IP) | string[] |
直连查询使用 UDP 并在截断时重试 TCP;经代理的查询走代理内 DNS-over-TCP(不回退直连或公共 DNS)。限额:每 Worker 4 个并发查询、单查询 10 秒、结果 ≤ 1 MiB JSON。探测 dns / dns.lookup / dns.resolve / dns.reverse(需至少一条有效授权;预检/fixture/演练场不可用)。
浏览器授权与 Secret 存储
声明 apis="auth"(包含在 all 中;PKCE 另需 crypto)及授权页与换取令牌域名的网络权限(HTTPS 或已授权回环 HTTP)。
await $metrix.auth.authorize({ url, timeoutMs?, callback? }):返回Promise<Record<string, string>>(不含state,保留 OAutherror参数)。url(展开前后均 ≤ 8192 B)须包含{{redirect_uri}}与{{state}}。callback: "loopback"(默认)在http://127.0.0.1:<随机端口>/callback单次监听。callback: "scheme"使用metrixbar://auth/callback(无本地监听;须配合 PKCE S256 与公开客户端,切勿内嵌client_secret)。- 限额:每 Worker 同时 1 个待完成授权;
timeoutMs范围1..600000(默认180000,3 分钟);回调查询串 ≤ 16 KiB、最多 32 个唯一键(1..128 B)、值 ≤ 8 KiB。
await $metrix.setSecret(name, value)/await $metrix.deleteSecret(name):写入或删除当前实例已声明的type="secret"输入(值 ≤ 2560 UTF-8 字节;不可读写外部系统凭据)。- 钩子超时规则:授权等待不延长 15 秒钩子预算。事件处理器必须立即返回,在后台异步 IIFE 中完成授权、捕获异常、写入密钥并调用
$metrix.invalidate()。预检、fixture 与演练场不可用。
// 需声明 apis="auth crypto"、<input name="token" type="secret" /> 与 <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();
}
})();
}处理本地 HTTP 请求
声明 <permissions><http-ingress /></permissions> 并在默认导出对象上实现 fetch(request, env)(可将请求直接转给打包好的 Hono 或 H3 v2 路由):
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 });
},
};用户在看板 隐私 → 本地 HTTP 请求 开启并点击 复制 curl 命令(地址为 http://<instance-id>.localhost:6388,附带宿主消费的实例专属 Bearer 令牌;关闭开关即作废令牌;携带 Origin 时须同源)。请求可唤醒闲置看板,请求体与响应体缓冲上限各 1 MiB,共享 15 秒超时。探测 http.ingress(fixture/演练场返回 false)。
SQLite 持久数据库
声明 apis="sqlite"(包含在 all 中)。命名数据库([A-Za-z0-9_-]{1,64})按看板实例隔离,跨重载与重启持久保存,不随 .bar 导出(切勿存放密钥)。
| 方法 | 返回值 |
|---|---|
await $metrix.sqlite.open(name) | 打开或创建数据库连接 |
db.prepare(sql) | 同步创建单条 SQL 预处理语句 |
stmt.bind(...params) | 返回新绑定语句(null、boolean 存为 0/1、有限 number、有符号 64 位 BigInt、string 或二进制视图) |
await stmt.all() / await stmt.run() | { success: true, results: rowObject[], meta: { changes, last_row_id, duration } }(支持 RETURNING) |
await stmt.raw({ columnNames?: boolean }) | 行数组,可选首行带列名 |
await stmt.first(column?) | 首行对象或指定列值(无行返回 null,缺列报错) |
await db.batch([stmt, ...]) | 原子批量执行,任一失败全部回滚 |
await db.close() | 幂等关闭连接(保留磁盘库) |
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;
}- 限额:单看板 8 个库名、每 Worker 8 连接与 4 并发操作、单操作 10 秒、SQL+参数 1 MiB、每批 100 语句、结果 10,000 行 / 8 MiB、主库 128 MiB / 内存临时库 32 MiB,并与 IndexedDB 共享进程级 128 MiB SQLite 堆预算。
- SQL 能力:支持表、索引、
JOIN与聚合;不支持用户PRAGMA、ATTACH/DETACH、VACUUM、扩展加载、虚拟表及手动事务控制。预打包的kysely@0.27.6+kysely-d1@0.4.0可用(kysely@0.28+因缺少Symbol.asyncDispose不可用)。演练场不提供 SQLite。
IndexedDB 持久存储
声明 apis="indexedDB"(包含在 all 中)。按看板隔离的结构化持久存储,与 SQLite 独立;支持 keyPath、autoIncrement、复合/唯一/多值索引、键范围、游标、readonly/readwrite/versionchange 事务及 https://esm.sh/idb@8.0.3(需 <network origin="https://esm.sh" />)。
- 要点:务必等待事务
complete/abort(或idb的tx.done)并在finally中db.close();监听db.onversionchange = () => db.close()。支持基本类型、BigInt、Date、RegExp、Map、Set、TypedArray、DataView、ArrayBuffer与循环引用——存入Blob/File会抛DataCloneError。 - 限额:每看板 8 个物理库槽、主文件 128 MiB、单操作/事务 10 秒、单事务 100 条内部 SQL 与 1 MiB 输入、结果 10,000 行 / 8 MiB、每 Worker 4 并发,共享 128 MiB SQLite 堆预算。演练场不可用;
/v0/check使用临时库。
持久化缓存与 localStorage
apis="caches":caches.default与await caches.open(name)提供match/put/delete持久化缓存(文本/JSON/二进制Response)。单看板上限:64 MiB(LRU 淘汰)、64 个命名缓存(名 ≤ 128 UTF-8 B)、每缓存 256 条、单响应体 16 MiB、元数据合计 64 KiB、默认 TTL 1 小时。apis="localStorage":跨重载与重启的按实例持久键值字符串存储(切勿存放密钥)。
本地文件访问
目录枚举、元数据与分片读取($metrix.files)
无需 apis 声明,复用 <file> 声明、输入模板、打开对话框/拖入/粘贴授权与保留授权,底层使用安全目录句柄(禁止符号链接越界)。预检、fixture 与演练场不可用。
| 方法 | 返回值与限制 |
|---|---|
await $metrix.readFile(path) | 完整 UTF-8 字符串(≤ 8 MiB,支持 ~)。 |
await $metrix.files.list(path, { cursor?, limit? }?) | { entries: [{ name, type }], cursor }(type:file|directory|symlink|other;limit 1..1000,默认 100;须以 / 结尾的 <file> 或 showOpenDialog({ directory: true }) 授权;按 UTF-8 字节升序实时分页)。 |
await $metrix.files.stat(path) | { type: "file"|"directory", size, mtime, identity }(mtime 为 Unix 毫秒;identity 不透明或为 null)。 |
await $metrix.files.read(path, { offset?, length? }?) | Uint8Array(offset ≥ 0;length 0..1048576,默认 1 MiB;短读或空读表示 EOF)。 |
预算:每 Worker 最多 16 个待完成 list/stat/read 操作与 4 MiB 读取长度预约。
跨重启保留文件授权
文件选择器、拖入、富媒体传输与主动粘贴获得的路径授权默认随 Worker 关闭失效;可按实例持久化(探测 files.retain;每实例上限 256 条;卸载时清除,复制实例不继承):
await $metrix.files.retain(paths)(每条路径都须在当前 Worker 内由用户授权,否则整批拒绝)await $metrix.files.release(paths)(停止持久化,当前 Worker 关闭前仍有效)await $metrix.files.retained()(返回已持久化的规范路径数组)
恢复后的授权保持原范围(整目录选择器授权覆盖子项与 files.list,而打开/定位/取图标针对目录本身时需精确目录授权如目录拖入)。
版本化文本与安全保存(apis="dialog")
声明 apis="dialog" 使用原生对话框与带冲突检测的文件读写(上限 8 MiB):
await $metrix.showOpenDialog(options)→ 返回所选路径(加入当前 Worker 读取白名单;传{ directory: true }授权目录枚举)await $metrix.showSaveDialog(options)→ 返回用户确认的保存路径(仅此路径可写,不授予读权)await $metrix.showMessageBox(options)→ 模态消息提示框await $metrix.readTextFile(path)→{ data: string, version: string }(同一次读取的 UTF-8 文本与 SHA-256 摘要)await $metrix.fileInfo(path)→{ size, version }await $metrix.writeFile(path, data, { expectedVersion? }?)→{ version }(data为字符串/ArrayBuffer/TypedArray;省略expectedVersion表示覆盖,传null要求目标不存在,传摘要则在文件变更时拒绝并返回"file changed since it was read")
外部系统凭据
声明 <permissions><credential service="Example App" account="{{ user.name }}" /></permissions> 后调用 await $metrix.readCredential("Example App", $metrix.userName) 读取第三方应用在系统凭据库中的条目(UTF-8 ≤ 1 MiB;bar.metrix* 服务名为保留前缀;缺失或被拒时拒绝且不泄露系统错误细节)。fixture 使用 user_name 与 credentials: [{ service, account, value }]。
WebAssembly 模块
原生 App Worker 默认可用(无需 apis 声明)。支持静态导入(import mod from "https://…/x.wasm")、动态 await import(url) 或直接编译字节(new WebAssembly.Module(bytes) / await WebAssembly.compile(bytes) / WebAssembly.validate(bytes))。远程导入每一跳均须 HTTPS 并声明 <permissions><network>。
<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>- 支持子集:Core V2(
MultiValue、SignExtension、NonTrappingFloatToIntConversion、ReferenceTypes、BulkMemoryOperations、内部 SIMD);WebAssembly.instantiate/new WebAssembly.Instance/Module.imports/Module.exports;同步i32/i64(BigInt)/f32/f64/externref函数;共享Memory(64 KiB/页,.grow()会分离旧.buffer)、Table(funcref/externref)与数值Global。 - 不支持:
compileStreaming/instantiateStreaming、Module.customSections、WASI、线程/共享内存、Memory64、引用类型Global,以及跨越 JS 边界的 SIMD/funcref参数。 - 预算与失败语义:每 Worker 128 次编译/校验 / 累计 32 MiB(单二进制 ≤ 8 MiB);8 个保留实例;128 MiB 线性内存(
workload="compute"提升至 1 GiB);单表 4096 元素(总计 32768);128 个构造对象;65536 个externref句柄;进程级最多 2 个并发编译任务。进入 Wasm start/导出函数后遭遇取消或超预算会将整个 Worker 标记为失败。
Intl、Temporal 与 Web Crypto
apis="intl":Intl.getCanonicalLocales、Intl.Locale、Intl.Segmenter、Intl.PluralRules、Intl.NumberFormat、Intl.DateTimeFormat(含en/zh语言数据、内置 tzdata,默认宿主机时区$metrix.timeZone)。须显式调用构造器(不修改Number/Date原型)。不支持RelativeTimeFormat、ListFormat、DisplayNames与Collator。apis="temporal":同时启用intl与Temporal(Instant、ZonedDateTime、PlainDateTime、PlainDate、PlainTime、PlainYearMonth、PlainMonthDay、Duration、Now;支持iso8601/gregory历法)。apis="crypto":crypto.getRandomValues(整数 TypedArray)(≤ 65,536 B)、crypto.randomUUID()、crypto.subtle.digest(SHA-1/256/384/512)、crypto.subtle.importKey(仅"raw"HMACSHA-1/256/384/512,不支持exportKey/RSA/ECDSA/AES)、crypto.subtle.sign/verify(HMAC)。限额:单缓冲区/密钥 16 MiB,每 Worker 8 个并发操作与 32 MiB 输入快照。
后台任务($metrix.waitUntil)
声明 apis="background"(包含在 all 中;探测 waitUntil)可在原生 Worker 回调中注册 1 个待完成 Promise,保持 Worker 存活直至其完成(最长 30 分钟,不跨 Worker 重启保留)。后台文件 I/O 请在下一个事件循环(如 setTimeout)启动,避免继承回调自身的 15 秒截止时间。