> ## 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.

# 管理应用

> 通过 Application 类查看、控制和操作应用 —— 状态、日志、指标、生命周期（启动、停止、重启）以及删除。

本页的每个操作都从获取一个 `Application` 实例开始：

```typescript theme={null}
import { SquareCloudAPI } from "@squarecloud/api";

const api = new SquareCloudAPI(process.env.SQUARE_API_KEY!);
const app = await api.applications.fetch("abc123def456abc123def456");
```

`api.applications.fetch(id)` 返回一个 `Application`。当应用绑定了网站域名时，它会作为 `WebsiteApplication` 返回 —— 在使用 `.network` 之前，先在运行时用 `app.isWebsite()` 细化类型（参见 [Network](/zh/sdks/js/network)）。

## 应用属性

| 属性            | 类型               | 描述                                                                                                                |
| ------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------- |
| `id`          | `string`         | 应用 ID（24 位十六进制字符）                                                                                                 |
| `name`        | `string`         | 显示名称                                                                                                              |
| `description` | `string?`        | 来自 `squarecloud.app` 的描述                                                                                          |
| `url`         | `string`         | Web 仪表盘 URL                                                                                                       |
| `ram`         | `number`         | 分配的 RAM（以 MB 为单位）                                                                                                 |
| `cluster`     | `string`         | 应用运行所在的集群                                                                                                         |
| `language`    | `string`         | `javascript` \| `typescript` \| `python` \| `java` \| `elixir` \| `rust` \| `go` \| `php` \| `dotnet` \| `static` |
| `domain`      | `string \| null` | 默认的 `<subdomain>.squareweb.app` 主机（非 web 应用为 `null`）                                                              |
| `custom`      | `string \| null` | 绑定到应用的自定义域名（如已配置）                                                                                                 |
| `createdAt`   | `Date`           | 创建日期                                                                                                              |

<Note>
  在 v4 中，当未设置自定义域名时，`app.custom` 为 `null`（在 v3 中为 `undefined`）。
</Note>

## 获取应用状态

`app.getStatus()` 返回一个 `ApplicationStatus` 实例，包含实时的运行时状态。

```typescript theme={null}
const status = await app.getStatus();

console.log(status.status);          // "running" | "starting" | "restarting" | "exited" | "created" | "deleting"
console.log(status.running);         // boolean
console.log(status.usage.cpu);       // "0.22%"
console.log(status.usage.ram);       // "70MB"
console.log(status.usage.network);   // { total: "0 KB ↑ 0 KB ↓", now: "0 KB ↑ 0 KB ↓" }
console.log(status.usage.storage);   // "0B"
console.log(status.uptime);          // Date | undefined
console.log(status.uptimeTimestamp); // number | undefined
```

### 所有应用的状态摘要

为避免每个应用一次请求，调用 `api.applications.statusAll()`：

```typescript theme={null}
const list = await api.applications.statusAll();

for (const summary of list) {
    console.log(`${summary.applicationId} → running=${summary.running}`);
    if (summary.running) {
        console.log(`  cpu=${summary.usage.cpu}, ram=${summary.usage.ram}`);
    }

    // Promote a summary to the full status with .fetch()
    const full = await summary.fetch();
    console.log(full.uptime);
}
```

## 获取日志

`app.getLogs()` 以 `string` 形式返回最近的日志输出。

```typescript theme={null}
const logs = await app.getLogs();
console.log(logs);
```

## 获取指标

`app.getMetrics()` 返回过去 24 小时的 CPU、RAM 和网络采样（最多 **288 个数据点**，每 5 分钟一个）。

```typescript theme={null}
const metrics = await app.getMetrics();

console.log(metrics.length, "data points");
console.log(metrics[0]);
// { timestamp: 1717084800000, cpu: 12.3, ram: 187, network: { ... } }
```

<Warning>
  `getMetrics()` 要求应用至少分配了 **512MB 的 RAM**。
</Warning>

## 实时事件流

`app.realtime()` 打开一个 [Server-Sent Events](https://developer.mozilla.org/docs/Web/API/Server-sent_events) 流。完整示例参见专门的 [Realtime](/zh/sdks/js/realtime) 页面。

## 生命周期

所有生命周期方法都解析为 `boolean`（成功时为 `true`）。

```typescript theme={null}
await app.start();
await app.restart();
await app.stop();
```

## 删除应用

<Warning>
  `app.delete()` 会永久移除应用。除非你有 [snapshot](/zh/sdks/js/snapshots)，否则数据**无法恢复**。
</Warning>

```typescript theme={null}
const deleted = await app.delete();
console.log(deleted); // true | false
```

## 刷新应用数据

`app.fetch()` 从 API 重新获取应用，并返回一个全新的 `Application` 实例。当你怀疑缓存数据已过时时使用它。

```typescript theme={null}
const fresh = await app.fetch();
```
