> ## Documentation Index
> Fetch the complete documentation index at: https://docs.squarecloud.app/llms.txt
> Use this file to discover all available pages before exploring further.

# 网络与边缘

> 为网站应用管理自定义域名、DNS、边缘分析、错误跟踪、请求日志、延迟百分位数以及缓存失效。

`network` 模块仅在**网站应用**上可用。请先用 `app.isWebsite()` 收窄类型：

```typescript theme={null}
const app = await api.applications.fetch("abc123def456abc123def456");

if (!app.isWebsite()) {
    throw new Error("This application is not a website");
}

app.network; // NetworkModule
```

## 自定义域名

`app.network.setCustomDomain(domain)` 设置或移除绑定到网站的自定义域名。

```typescript theme={null}
await app.network.setCustomDomain("yoursite.com");

// Pass "@" to remove the configured custom domain
await app.network.setCustomDomain("@");
```

<Note>
  自定义域名需要 [Senior 套餐](https://squarecloud.app/plans)或更高级别。
</Note>

## DNS 记录

绑定自定义域名后，你需要在域名注册商处配置 DNS。`app.network.dns()` 返回所有权记录和 SSL 状态。

```typescript theme={null}
const dns = await app.network.dns();

console.log(`${dns.ownership.type} ${dns.ownership.name} → ${dns.ownership.value}`);
console.log(`SSL: ${dns.ssl.status}`); // "pending" | "pending_validation" | "active"
```

<Warning>
  结构在 v4 中发生了变化。`app.network.dns()` 以前返回一个记录数组，现在返回单个对象：`{ ownership, ssl }`。
</Warning>

## 分析

`app.network.analytics({ start, end })` 返回聚合的边缘分析数据。`start` 和 `end` 接受 ISO 8601 字符串或 `Date` 对象。最大保留窗口为 **7 天**。

```typescript theme={null}
const since = new Date(Date.now() - 24 * 60 * 60 * 1000);

const analytics = await app.network.analytics({
    start: since,
    end: new Date(),
});

if ("visits" in analytics) {
    console.log(analytics.visits.length, "time buckets");
    console.log("Top countries:", analytics.countries.slice(0, 5));
    console.log("Top paths:",     analytics.paths.slice(0, 5));
}
```

<Warning>
  对于空窗口（例如应用创建之前），API 会返回 `{}`。读取前请用 `"visits" in analytics` 进行保护。
</Warning>

<Warning>
  v3 调用此 endpoint 时不带参数。**v4 要求传入 `{ start, end }`。**
</Warning>

## 错误跟踪

`app.network.errors({ start, end, include4xx? })` 返回边缘错误明细。默认仅包含 5xx 错误。

```typescript theme={null}
const errors = await app.network.errors({
    start: since,
    end: new Date(),
    include4xx: true, // include 4xx alongside 5xx
});

if ("summary" in errors) {
    console.log(`Total: ${errors.summary.total}`);
    console.log("By class:",          errors.summary.by_class);
    console.log("Top failing paths:", errors.top_paths.slice(0, 3));
}
```

## 单请求日志

`app.network.logs({ start, end })` 返回逐请求的边缘日志。

```typescript theme={null}
const logs = await app.network.logs({ start: since, end: new Date() });

for (const log of logs.slice(0, 5)) {
    console.log(
        log.timestamp,
        log.request.method, log.request.path,
        "→",
        log.response.status,
        `(${log.client.country ?? "??"})`,
    );
}
```

<Note>
  单请求日志需要 [Pro 套餐](https://squarecloud.app/plans)或更高级别。
</Note>

## 延迟百分位数

`app.network.performance({ start, end })` 返回边缘层和源站层的 p50 / p95 / p99 延迟。

```typescript theme={null}
const perf = await app.network.performance({ start: since, end: new Date() });

if ("summary" in perf) {
    const { p50, p95, p99 } = perf.summary.edge;
    console.log(`Edge p50/p95/p99: ${p50}/${p95}/${p99}ms`);
    console.log("Slowest paths:", perf.slowest_paths.slice(0, 3));
}
```

<Note>
  性能指标需要 [Pro 套餐](https://squarecloud.app/plans)或更高级别。
</Note>

## 清除边缘缓存

`app.network.purgeCache()` 会使应用各域名的整个边缘缓存失效。

```typescript theme={null}
await app.network.purgeCache();
```

<Warning>
  在 v3（以及短暂存在的 v4.0.0）中，`purgeCache(paths?)` 接受一个路径列表以选择性清除。**从 v4.0.1 起该参数已被移除**，调用 `purgeCache()` 始终会清除整个缓存。
</Warning>
