# @axcode/axcloud-sdk 中文文档

规范地址：https://npmcn.com/package/%40axcode/axcloud-sdk/

版本：1\.0\.0
npm 元数据更新时间：2026-11-02T10:03:27.855Z
中文译文更新时间：2026-11-08T09:31:08.120Z
软件包许可：SEE LICENSE IN LICENSE\.md

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40axcode/axcloud-sdk
原文对照：https://npmcn.com/package/%40axcode/axcloud-sdk/?lang=original
项目主页：https://github.com/axcodeab/axcloud#readme
源码仓库：https://github.com/axcodeab/axcloud

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：935 kB，40 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：2 个
- peer 依赖：react ^18\.0\.0 \|\| ^19\.0\.0，react-dom ^18\.0\.0 \|\| ^19\.0\.0
- 首次发布：2026-02-01T19:01:57.929Z
- 最新版本发布：2026-11-02T10:03:27.623Z
- 近 30 天下载量：1837（2026-10-08 至 2026-11-06，npm 官方下载统计）
- 已发布版本数：49（近 12 个月 49 个）

## 中文简介

SDK 用于使用 AxCloud CMS 和成员管理构建网站

## 安装

```sh
npm install @axcode/axcloud-sdk
```

也可以使用：`pnpm add @axcode/axcloud-sdk`、`yarn add @axcode/axcloud-sdk`、`bun add @axcode/axcloud-sdk`

## README

# @ axcode/ axcloud-sdk (英语)

SDK用于与AxCloud CMS和成员管理建立网站. AxCloud 是个.. 无头:它拥有内容、出版物、访问控制和交付API,同时 消耗性应用程序拥有标记、布局和设计.

## 安装

```bash
npm install @axcode/axcloud-sdk
```

### 版本标记

SDK发布时有两种不同环境的标记:

| 标记 | 目的 | 稳定 | 安装 |
| --- | --- | --- | --- |
| `latest` | 生产 | 稳定、测试 | `npm install @axcode/axcloud-sdk` |
| `next` | 发展/结构 | 预览, 可能有断开的更改 | `npm install @axcode/axcloud-sdk@next` |

**建议的生产设置:**

决定 `latest` 并锁定文件:

```bash
npm install --save-exact @axcode/axcloud-sdk@latest
```

```json
{
  "dependencies": {
    "@axcode/axcloud-sdk": "0.3.1"
  }
}
```

在 CI 或部署时不要安装移动标记 。 测试特定 `next` 在需要时,将版本放在分支中,然后促进和固定稳定释放.

## 快速启动

### 匿名公共网站( 无 Auth0)

没有会员登录的公共产品站点应当导入专用的 供养. 它挂载 SDK 客户端, React 查询缓存和隐私安全分析 不导入或初始化 Auth0 :

```tsx
import { AxCloudPublicProvider } from '@axcode/axcloud-sdk/public';

<AxCloudPublicProvider
  orgId="barnsport"
  apiUrl="https://api.axcloud.app"
  stage="prod"
  apiKey="pk_live_barnsport_read_submit"
>
  <App />
</AxCloudPublicProvider>;
```

公共网站可以通过相同的Auth0免费阅读已公布的 CMS 内容 进入点。 草稿和预览内容仅可通过 已认证主控台 :

```tsx
import { usePageContent } from '@axcode/axcloud-sdk/public';

function HomeHero() {
  const content = usePageContent('home', { lang: 'sv', publicOnly: true });
  return <h1>{content.text('hero.title', 'Fallback title')}</h1>;
}
```

对于非反应适配器和增量迁移,创建相同的范围d 未导入经认证的 SDK 根的 Barnsport 客户端 :

```ts
import { createPublicBarnsportClient } from '@axcode/axcloud-sdk/barnsport';

const barnsport = createPublicBarnsportClient({ apiUrl, apiKey, orgId: 'barnsport' });
const providers = await barnsport.listProviders({ q: 'fotboll', limit: 5 });
```

使用浏览器安全密钥,仅限于网站所需的公共范围. 执行 不使用 `AxCloudPublicProvider` 用于成员或管理员特性。 现有 经认证的应用程序继续使用 `AxCloudProvider` 不变.

### Barnsport 产品客户端和钩子

Barnsport 类型, 核心客户端和 React shocks 可以从一个单独的 其他产品不装入 Barnsport 代码:

```tsx
import {
  useBarnsportProviderSearch,
  useBarnsportProvider,
  useSubmitBarnsportReview,
  useTrackBarnsportEvent,
} from '@axcode/axcloud-sdk/barnsport';

const providers = useBarnsportProviderSearch({ q: searchText, limit: 5 });
const provider = useBarnsportProvider(providerSlug);
```

供应商审查和产品活动仍然是Barnsport域名数据。 SDK这个 通过 AxCloud Barnsport 代理来引导它们; 它不把它们存储在 通用内容服务.

### 1\. 用 AxCloud 程序包装您的应用程序

```tsx
import { AxCloudProvider } from '@axcode/axcloud-sdk';

function App() {
  return (
    <AxCloudProvider
      orgId="org_ba81807b" // Your organization ID
      apiUrl="https://api.axcloud.app"
      apiKey="pk_live_..." // Public API key from Settings → API Keys
      auth0={{
        domain: 'auth.axcloud.app',
        clientId: 'your-client-id',
        redirectUri: window.location.origin,
        organization: 'org_auth0_...', // Optional Auth0 Organization ID for invite-only member sites
      }}
    >
      <Router>
        <Routes />
      </Router>
    </AxCloudProvider>
  );
}
```

`orgId` 是 CMS API 使用的 AxCloud 组织ID,例如 `org_ba81807b`。 。 。 . `auth0.organization` 是登录时使用的 Auth0 组织ID,例如 `org_o960yILn77d4vY6u`。 。 。 . 设定 `auth0.organization` 对只邀请的客户成员网站,因此通用登录范围属于该客户组织.

### 客户自有身份提供者

一个组织可以通过自己的Auth0租户认证AxCloud 继续提供内容、成员和授权API。 配置 完整、经审查的供应商在第一当事方地点静态地翻转:

```tsx
<AxCloudProvider
  orgId="org_customer"
  apiUrl="https://dev-api.axcloud.app"
  stage="dev"
  auth0={{
    identityProviderId: 'idp_customer_dev',
    domain: 'dev-auth.customer.example',
    clientId: 'customer-member-spa-client-id',
    audience: 'https://api.axcloud.app',
    organization: 'org_customer_auth0',
    redirectUri: window.location.origin,
  }}
>
  <App />
</AxCloudProvider>
```

`identityProviderId` 是公开的 AxCloud 标识符,而不是证书。 没错 包含在 SDK 缓存所有者签名中, 因此是提供者切换或旋转 无法重用身份约束的查询数据。 SDK 不发现提供者或 持有 Auth0 管理 API 证书。 保持域名 客户身份 观众, 组织 ID、 AxCloud 阶段和 API URL 一起作为特定环境 配置;从不将客户DEV租户与AxCloud PROD API相混合.

### 2\. 获取内容

```tsx
import { useNews } from '@axcode/axcloud-sdk';

function NewsPage() {
  const { data: news, isLoading, isError } = useNews();

  if (isLoading) return <Spinner />;
  if (isError) return <Error />;

  return (
    <ul>
      {news.map((item) => (
        <li key={item.id}>{item.title}</li>
      ))}
    </ul>
  );
}
```

> **内容交付:** 这些钩子只返回已公布的快照. 当 用户被认证,访问内部、成员和部分内容 来源于已验证的符号。 匿名用户只接收公开内容. 客户提供的状态或区段识别资料绝不允许更广泛的访问.

页面和新闻可保存在 AxCloud 中一次,并附有翻译和每种语言的要求:

```tsx
import { useContentItem, useNews } from '@axcode/axcloud-sdk';

function AboutPage({ locale }: { locale: 'sv' | 'en' }) {
  const { data: page } = useContentItem('pages', 'about-us', {
    lang: locale,
    publicOnly: true,
  });

  return <h1>{page?.title}</h1>;
}

function NewsList({ locale }: { locale: 'sv' | 'en' }) {
  const { data: news } = useNews({ lang: locale });

  return news.map((item) => <article key={item.id}>{item.title}</article>);
}
```

### 3\. 添加认证

```tsx
import { useAuth, LoginButton, LogoutButton, ProtectedRoute } from '@axcode/axcloud-sdk';

function Header() {
  const { isAuthenticated, user } = useAuth();

  return (
    <header>
      {isAuthenticated ? (
        <>
          <span>Welcome, {user.name}</span>
          <LogoutButton />
        </>
      ) : (
        <LoginButton>Sign In</LoginButton>
      )}
    </header>
  );
}

function MemberArea() {
  return (
    <ProtectedRoute>
      <MemberContent />
    </ProtectedRoute>
  );
}
```

SDK在产品场地内不断核查UI. 给自己的品牌 当通知 `needsEmailVerification` 事实 :

```tsx
const { needsEmailVerification, requestEmailVerification, refreshUser } = useAuth();

if (needsEmailVerification) {
  // Render the product's own verification notice.
}

await requestEmailVerification({ returnTo: window.location.href });
await refreshUser();
```

API从认证的代币中解决接受者和组织. 返回URL被限制在组织配置的成员站点.

### 3b. 增加隐私安全分析

分析是可选和提供者独立的。 AxCloud 解决公众 从组织、地点钥匙、部署阶段和 当前主机名 。 SDK消费者从未收到Umami API密钥.

```tsx
import { AxCloudProvider, useAnalytics } from '@axcode/axcloud-sdk';

<AxCloudProvider
  orgId="org_ba81807b"
  apiUrl="https://api.axcloud.app"
  stage="prod"
  analytics={{
    enabled: analyticsConsent === 'accepted',
    siteKey: 'member-site',
    normalizePath: (path) => path.replace(/^\/member\/news\/[^/]+/, '/member/news/:id'),
  }}
  auth0={auth0Config}
>
  <App />
</AxCloudProvider>;
```

SDK 跟踪 SPA 页面在跟踪器准备好后会更改. 查询字符串和 碎片被去除,常见的不透明ID被替换为 `:id`,不跟踪 除非 `trackLocalhost: true` 明确设置.

自定义事件必须允许在 AxCloud 分析站点配置中列出 :

```tsx
function NewsArticle() {
  const analytics = useAnalytics();

  const handleOpen = () => {
    analytics.track('news_opened', { surface: 'member_news' });
  };
}
```

只发粗 en,布林斯和计数. SDK拒绝敏感 属性名称和类似电子邮件的值,但应用程序仍然负责 从不提供姓名、电子邮件地址、用户身份、文档标题、搜索文本, 聊天文本,或其他个人/内容数据. 生产跟踪器只能是 在产品的隐私通知和内容安全政策之后启用 已审查.

### 4\. 使用部分

```tsx
import { useMySection } from '@axcode/axcloud-sdk';

function MySectionPage() {
  const { section, members, isLoading } = useMySection();

  if (isLoading) return <Spinner />;
  if (!section) return <p>You are not assigned to a section</p>;

  return (
    <div>
      <h1>{section.name}</h1>
      <h2>Members ({members.length})</h2>
      <ul>
        {members.map((m) => (
          <li key={m.id}>{m.name}</li>
        ))}
      </ul>
    </div>
  );
}
```

### 4b. 节范围的内容

```tsx
import { useNews, useMySection } from '@axcode/axcloud-sdk';

function SectionNews() {
  const { section } = useMySection();
  // AxCloud derives the allowed sections from the authenticated membership.
  const { data: visibleNews } = useNews();

  return (
    <div>
      <h2>Section News</h2>
      {visibleNews.map((item) => (
        <NewsCard key={item.id} item={item} />
      ))}
      {!section && <p>You are not assigned to a section.</p>}
    </div>
  );
}
```

### 5\. 获取组织品牌和媒体

```tsx
import { useBranding, useLogo, useMedia } from '@axcode/axcloud-sdk';

function Header() {
  const { logoUrl, branding, organizationName } = useBranding();

  return (
    <header style={{ backgroundColor: branding?.primaryColor }}>
      {logoUrl && <img src={logoUrl} alt={organizationName} />}
      <h1>{organizationName}</h1>
    </header>
  );
}

// Or just the logo
function Logo() {
  const { logoUrl, isLoading } = useLogo();

  if (isLoading) return <Skeleton />;
  return logoUrl ? <img src={logoUrl} alt="Logo" /> : <DefaultLogo />;
}

// Fetch specific media file
function HeroImage() {
  const { mediaUrl } = useMedia('hero-banner.jpg');
  return mediaUrl ? <img src={mediaUrl} alt="Hero" /> : null;
}
```

> **说明:** 媒体URL由1小时后到期的S3 URL签名. SDK在到期前会自动刷新它们(时间:30分).

### 6\. 获取公共文件

```tsx
import { useDocuments, useDocumentDownload } from '@axcode/axcloud-sdk';

function PublicDocuments() {
  const { documents, isLoading } = useDocuments({ tags: ['handbook'], limit: 20 });

  if (isLoading) return <Skeleton />;
  return (
    <ul>
      {documents.map((doc) => (
        <li key={doc.document_id}>
          <DocumentLink documentId={doc.document_id} title={doc.title} />
        </li>
      ))}
    </ul>
  );
}

function DocumentLink({ documentId, title }: { documentId: string; title: string }) {
  const { documentUrl } = useDocumentDownload(documentId);
  return documentUrl ? <a href={documentUrl}>{title}</a> : <span>{title}</span>;
}
```

只有文档 `status: "published"` 财务报告和审定财务报表 `audience: "public"` 通过SDK文档钩被曝光.

### 7\. 按单元划分的大门特征

```tsx
import { ModuleGate, useOrg } from '@axcode/axcloud-sdk';

function Dashboard() {
  const { hasModule } = useOrg();

  return (
    <div>
      <NewsSection />

      <ModuleGate module="training" fallback={<UpgradePrompt />}>
        <TrainingSection />
      </ModuleGate>

      {hasModule('ai') && <AIChatWidget />}
    </div>
  );
}
```

### 8\. 有章节选择的成员申请

```tsx
import { createFormHelper } from '@axcode/axcloud-sdk';

const forms = createFormHelper({
  apiUrl: 'https://api.axcloud.app/forms',
  apiKey: import.meta.env.VITE_AXCLOUD_FORMS_API_KEY, // forms:submit only
  site: 'example.org',
});

// Sections the organization ticked as selectable, e.g. [{ id: 'section_x', name: 'SAS' }]
const sections = await forms.getMembershipSections();

// Either the chosen section…
await forms.submitMembership(email, { firstName, lastName, sectionId: sections[0].id });
// …or a company without a section of its own.
await forms.submitMembership(email, { firstName, lastName, company: 'Example Air' });
```

API拒绝 `sectionId` 这不在名单上。 控制台的审批邀请 申请人进入选定的部分. `getMembershipSections` 当 API 拒绝时抛出 (例如,当会员表未启用时),所以一个网站可以倒回自由文本 公司领域。 使用表单键检查通话, 如提交文件, 但不计数到 键的速率限制,浏览器可能会将答案保存5分钟.

## API 参考

### 提供者

| 构成部分 | 说明 |
| --- | --- |
| `AxCloudProvider` | 结合 Auth0 、 React 查询和 SDK 上下文的主要提供者 |

### 钩子

| 钩子 | 说明 |
| --- | --- |
| `useAuth()` | 登录/ 登录、 电子邮件核查状态、 重新发送和配置更新 |
| `useUser()` | 获取已规范的用户和经核实的组织成员 |
| `useUpdateMyProfile()` | 更新登录用户的姓名、电话和地址 |
| `useOrg()` | 获取组织信息和检查模块 |
| `useNews(options?)` | 获取当前访问者可见的已发布新闻集 |
| `useContent(type, options?)` | 获取已发布 `news`, (中文(简体) ), `pages`,或 `events` 收藏 |
| `useContentItem(type, id, opts?)` | 通过 ID 或 swit 直接获取一个已公布的项目 |
| `usePageContent(slug, options?)` | 获取页面并读取结构化模板槽 |
| `useMySection()` | 用成员获取当前用户区域 |
| `useSections()` | 获取所有组织区域 |
| `useBranding()` | 获取组织品牌(标志、颜色) |
| `useLogo()` | 获取组织标志 URL |
| `useMedia(mediaId)` | 获取特定媒体文件 URL |
| `useAvatar(userId)` | 获取用户外观 URL |
| `useMediaList(type)` | 列出媒体文件 |
| `useDocuments(options?)` | 列出已公布的公开文件 |
| `useDocumentDownload(documentId)` | 获取已签名的文档下载 URL |

配置自助服务被故意限制在个人接触领域. 组织名称, 电子邮件、角色、地位、组织和科级任务仍由管理员管理.

`useUser()` 规范对骆驼Case的API响应. 组织特有的价值观总是会出现 从会员中选出提供者 `orgId`数字 :

```tsx
const {
  user,
  roleInOrg,
  title,
  section, // { id, name, role } | null
  sections, // all verified section memberships
  sectionId,
  sectionIds,
  memberSince, // normalized from joined_at
} = useUser();

return (
  <p>
    {section?.name ?? 'No section'} · member since {memberSince}
  </p>
);
```

```tsx
import { useUpdateMyProfile } from '@axcode/axcloud-sdk';

function ProfileForm() {
  const updateProfile = useUpdateMyProfile();

  const save = () =>
    updateProfile.mutateAsync({
      firstName: 'Anna',
      lastName: 'Pilot',
      phone: '+46701234567',
      address: 'Flyggatan 1',
    });

  return (
    <button onClick={save} disabled={updateProfile.isPending}>
      Save profile
    </button>
  );
}
```

### 内容查询选项

```typescript
interface ContentQueryOptions {
  page?: number; // Page number (default: 1)
  pageSize?: number; // Items per page (default: 20)
  search?: string; // Search in title/content
  sortBy?: 'publishedAt' | 'createdAt' | 'updatedAt' | 'title';
  sortOrder?: 'asc' | 'desc';
  tags?: string[];
  lang?: string; // Return translated title/slug/blocks when available
  publicOnly?: boolean; // Force public endpoint even when authenticated
}
```

收藏钩返回 `data`, (中文(简体) ), `count`, (中文(简体) ), `total`, (中文(简体) ), `page`, (中文(简体) ), `pageSize`, (中文(简体) ), `hasMore`, (中文(简体) ), `nextCursor`, (中文(简体) ), `isLoading`, (中文(简体) ), `isFetching`, (中文(简体) ), `isError`, (中文(简体) ), `error` 财务报告和审定财务报表 `refetch`。在 Auth0 的初始会话检查中, 成员能力钩等待 而不是简单地要求公开内容。 成员缓存被隔离 Auth0 科目,并在登录或账户更改时删除. 所有其他身份标记的 AxCloud 查询数据在同一边界被删除.

结构化槽是CMS的不可信输入. 偏爱 `text()`, (中文(简体) ), `list()` 财务报告和审定财务报表 `image()`。 。 。 . `unsafeHtml()` (和被堕落者) `html()` (别名)必须进行消毒 使用前为 `dangerouslySetInnerHTML`。 。 。 .

### 构成部分

| 构成部分 | 说明 |
| --- | --- |
| `<LoginButton>` | 触发 Auth0 登录 |
| `<LogoutButton>` | 触发登录 |
| `<ProtectedRoute>` | 需要认证查看内容 |
| `<ModuleGate>` | 基于启用模块的有条件渲染 |

## 高级使用

### 自定义 API 呼叫

```tsx
import { useAuth } from '@axcode/axcloud-sdk';

function MyComponent() {
  const { getAccessToken } = useAuth();

  const fetchCustomData = async () => {
    const token = await getAccessToken();
    const response = await fetch('/api/custom', {
      headers: { Authorization: `Bearer ${token}` },
    });
    return response.json();
  };
}
```

### 访问基本的 Auth0 客户端

```tsx
const { getAuth0Client } = useAuth();
const auth0 = getAuth0Client();

// Full Auth0 API available
await auth0.getAccessTokenSilently();
await auth0.getIdTokenClaims();
```

## 担保模式

### API 密钥对认证托肯

SDK使用两种类型的证书:

1.  **API 密钥** (单位:千美元)`apiKey` 道具: A _公共标识符_ 为您的组织服务
    
    -   安全包含在客户端代码中
    -   用于公共内容终点
    -   基于 API 密钥的后端验证和费率限制
    -   没有有效的 API 密钥, 请求返回 401
2.  **认证托肯** (通过Auth0): A _隐藏_ JWT 标志
    
    -   由 SDK 自动管理
    -   仅供成员使用的内容和用户数据
    -   从未在客户端代码中曝光

### API 密钥保护什么

| 没有 API 密钥 | 带有 API 密钥 | 用 Auth Token 键 |
| --- | --- | --- |
| 没什么 | 公共新闻/内容 | 成员内容 |
|  | 组织品牌 | 用户配置 |
|  | 公共媒体 | 链接账户 |
|  |  | 管理职能 |

### 端点安全

| 终点类型 | 认证 | 示例 |
| --- | --- | --- |
| 公开内容 | API 密钥 (x- api- key 头) | `/content/public/{orgId}/news` |
| 成员内容 | 日本 借记符 | `/content/members/{orgId}/news` |
| 用户数据 | 日本 借记符 | `/api/users/me` |
| 管理员 | 日本 持牌人 + 角色 | `/forms/admin/submissions` |

## 处理错误

```tsx
import { useNews, isAxCloudError } from '@axcode/axcloud-sdk';

function NewsPage() {
  const { data, error, isError } = useNews();

  if (isError) {
    if (isAxCloudError(error)) {
      switch (error.code) {
        case 'UNAUTHORIZED':
          return <LoginPrompt />;
        case 'NOT_FOUND':
          return <NotFound />;
        default:
          return <Error message={error.message} />;
      }
    }
    return <Error message="Something went wrong" />;
  }

  return <NewsList items={data} />;
}
```

## 许可证

内部使用。 联系 Axcode AB 访问 .

## 常见问题

### @axcode/axcloud-sdk 是什么？

SDK 用于使用 AxCloud CMS 和成员管理构建网站

### 如何安装 @axcode/axcloud-sdk？

在项目目录运行 npm install @axcode/axcloud-sdk，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：react（^18\.0\.0 \|\| ^19\.0\.0）、react-dom（^18\.0\.0 \|\| ^19\.0\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @axcode/axcloud-sdk 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @axcode/axcloud-sdk 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @axcode/axcloud-sdk 可以商用吗？

@axcode/axcloud-sdk 使用 SEE LICENSE IN LICENSE\.md 许可。许可条款写在包内的独立文件中，请阅读该文件确认可否商用。以上为概括，不构成法律意见，请以许可原文为准。

### @axcode/axcloud-sdk 的下载量有多少？

根据 npm 官方下载统计，@axcode/axcloud-sdk 在 2026/10/08 – 2026/11/06 这 30 天内被下载 1,837 次，日均约 61 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @axcode/axcloud-sdk 还在维护吗？

最新版本 1\.0\.0 发布于 2026/11/02（6 天前）；至今共发布 49 个版本，其中过去 12 个月发布了 49 个；首次发布于 2026/02/02。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

