datocms-cma

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

DatoCMS Content Management API Skill

DatoCMS内容管理API(CMA)技能

You are an expert at writing code that interacts with the DatoCMS Content Management API (CMA). Use this workflow as a default. Reorder or skip steps when the task is purely diagnostic, advisory, or the user only needs an explanation.
A short, imperative request in mid-conversation ("publish them", "delete those", "fix the slugs", "check how many drafts I have") that follows earlier DatoCMS context is still a DatoCMS task — do not lose the context just because the latest message is short. Signals that you are on a DatoCMS-connected repo:
@datocms/*
packages in
package.json
,
DATOCMS_*
env vars,
datocms.config.json
,
cma-types.ts
.

您是编写与DatoCMS内容管理API(CMA)交互代码的专家。请将此工作流作为默认流程。当任务仅为诊断、咨询或用户仅需要解释时,可重新排序或跳过步骤。
对话中途的简短命令式请求(如“发布它们”“删除那些内容”“修复slug”“查看我有多少草稿”),如果之前已有DatoCMS相关上下文,仍属于DatoCMS任务——不要因为最新消息简短而丢失上下文。表明当前仓库已关联DatoCMS的信号包括:
package.json
中的
@datocms/*
包、
DATOCMS_*
环境变量、
datocms.config.json
cma-types.ts

Step 1: Detect Context

步骤1:检测上下文

If the project context is already established in this conversation (client package, authentication approach, environment targeting), skip broad detection below. Re-inspect only when a question cannot be answered from prior context.
如果对话中已确立项目上下文(客户端包、认证方式、目标环境),可跳过以下宽泛检测步骤。仅当现有上下文无法回答问题时,才重新检查。

Step 1a — Bootstrap project awareness (CLI +
datocms link
is mandatory)

步骤1a — 初始化项目感知(CLI +
datocms link
是必需步骤)

Any CMA work on a DatoCMS-connected repo requires agent-side visibility into the live project (models, fields, ids, record state).
datocms
installed +
datocms login
+
datocms link
is that bootstrap — treat it like
git init
or
npm install
: missing → fix first, do not route around.
Bootstrap flow (only
datocms login
needs an interactive terminal; the rest the agent drives in non-TTY):
bash
npm install --save-dev datocms        # if missing
npx datocms login                          # user, one-time, interactive
npx datocms projects:list [hint] --json    # agent discovers siteId
npx datocms link --site-id=<ID> [--organization-id=<ID>]   # agent links
Always confirm the target project with the user before running
datocms link
, even when
projects:list
returns a single candidate. Show the candidate(s) (name, id, organization) and wait for an explicit yes. Do not treat "only one result" as consent — the user may have access to a project they did not mean to wire to this repo, and fixing a mis-linked project later is painful.
Detection hints (do not rely on
which datocms
— the CLI runs via
npx
):
  • datocms
    in
    package.json
    devDependencies → CLI available
  • datocms.config.json
    with a
    siteId
    on the active profile → linked
  • npx datocms whoami
    succeeds → OAuth session active
  • none of the above → drive the bootstrap above
Token-in-
.env
is the exception.
An explicit
DATOCMS_API_TOKEN
is only for runtimes that cannot use OAuth: CI, server-side application code, cron, webhooks, shared repo scripts. Even there, the agent still needs CLI + link during development for project visibility.
Learning the project's shape. Once linked, run
npx datocms schema:inspect
(optionally with a model API key, id, or display name) to see the real models, blocks, fields, validators, fieldsets, nested blocks, and relationships — TOON output by default,
--json
for
| jq
. Use this any time the agent or user needs to understand the project structure before writing code, choosing the right field for a mutation, or deciding which model to query. Prefer it to composing
cma:call item_types list
/
fields list
by hand. Reference:
../datocms-cli/references/schema-inspect.md
.
Red flag: if you are about to say "paste a CMA token" or "add
DATOCMS_CMA_TOKEN=...
to
.env
" for a task the user is running interactively, stop. The right answer is the bootstrap above + the actual operation expressed as a
cma:call
/
cma:script
invocation (shapes in Step 4).
任何在已关联DatoCMS的仓库中进行的CMA工作,都需要Agent能够感知项目的实时状态(模型、字段、ID、记录状态)。安装
datocms
+
datocms login
+
datocms link
是初始化流程——将其视为
git init
npm install
:缺失则先修复,不要绕过。
初始化流程(仅
datocms login
需要交互式终端;其余步骤Agent可在非TTY环境下执行):
bash
npm install --save-dev datocms        # 若未安装
npx datocms login                          # 用户需执行一次交互式登录
npx datocms projects:list [hint] --json    # Agent自动发现siteId
npx datocms link --site-id=<ID> [--organization-id=<ID>]   # Agent关联项目
在运行
datocms link
前,务必与用户确认目标项目
,即使
projects:list
仅返回一个候选项目。展示候选项目的名称、ID、所属组织,等待用户明确确认。不要将“仅一个结果”视为同意——用户可能有权访问并非当前仓库目标的项目,后续修复关联错误会非常麻烦。
检测提示(不要依赖
which datocms
——CLI可通过
npx
运行):
  • package.json
    的devDependencies中存在
    datocms
    → CLI可用
  • datocms.config.json
    的活跃配置文件中包含
    siteId
    → 已关联项目
  • npx datocms whoami
    执行成功 → OAuth会话已激活
  • 以上均不满足 → 执行上述初始化流程
.env
中存储令牌是例外情况
。显式设置的
DATOCMS_API_TOKEN
仅适用于无法使用OAuth的运行环境:CI、服务器端应用代码、定时任务、Webhook、共享仓库脚本。即便如此,Agent在开发阶段仍需通过CLI + link来感知项目状态。
了解项目结构。关联项目后,运行
npx datocms schema:inspect
(可选择传入模型API密钥、ID或显示名称)查看真实的模型、区块、字段、验证器、字段集、嵌套区块及关联关系——默认输出TOON格式,添加
--json
参数可配合
| jq
使用。每当Agent或用户需要在编写代码、选择变更字段、确定查询模型前了解项目结构时,都应使用该命令。优先使用此命令,而非手动组合
cma:call item_types list
/
fields list
。参考文档:
../datocms-cli/references/schema-inspect.md
警示:如果您打算让用户“粘贴CMA令牌”或“在
.env
中添加
DATOCMS_CMA_TOKEN=...
”来完成交互式任务,请停止。正确的做法是先执行上述初始化流程,再通过
cma:call
/
cma:script
调用完成实际操作(格式见步骤4)。

Step 1b — Package and project detection

步骤1b — 包与项目检测

Once the auth approach is chosen, examine the project to determine the runtime and which CMA client package is available.
  1. Read
    package.json
    and check for these packages (in priority order):
    • @datocms/cma-client
      — Universal/isomorphic package. Recommended for most cases. Works in any environment with native
      fetch
      . Only provide a
      fetchFn
      if your runtime lacks native Fetch API.
    • @datocms/cma-client-node
      — Node.js-optimized. Adds upload helpers (
      createFromLocalFile
      ,
      createFromUrl
      ). Use when you need file-system upload convenience methods.
    • @datocms/cma-client-browser
      — Browser-optimized. Adds
      createFromFileOrBlob()
      for File/Blob uploads.
  2. If none is installed and the task requires
    buildClient()
    code, recommend the appropriate package:
    • General / universal →
      @datocms/cma-client
    • Node.js project needing upload helpers →
      @datocms/cma-client-node
    • Browser-only project needing File/Blob uploads →
      @datocms/cma-client-browser
    (For pure OAuth-path work via
    cma:call
    /
    cma:script
    , none of these need to be installed — the CLI workspace ships its own client.)
  3. Search for existing
    buildClient()
    calls to understand how the project already configures the client (API token source, environment targeting, etc.).
  4. Only if the deliverable is unattended runtime code (see Step 1a): check for a
    .env
    or
    .env.local
    file and see whether a CMA-enabled
    DATOCMS_API_TOKEN
    (or similar) is already defined. If the only variable present is something read-only (
    DATOCMS_READONLY_API_TOKEN
    ,
    NEXT_PUBLIC_DATOCMS_API_TOKEN
    , a CDA token), flag that a separate CMA-enabled token is needed for that specific runtime — not for the agent's own introspection, which must go through CLI + link regardless.
  5. Check for an existing
    cma-types.ts
    file to determine if CMA type generation is already set up. Do not proactively suggest setting up type generation. For
    cma:docs
    lookups,
    cma:call
    , and
    cma:script
    this skill owns the execution shape directly — see the cheat sheets in Step 4. For schema-change requests, see the decision tree in Step 2.5 — it covers when this skill owns the work directly and when it routes to datocms-cli migrations. Otherwise route to datocms-cli for CLI-workflow topics (
    schema:generate
    , environment operations, imports, plugin management, multi-project sync, CI/CD).
Token scope reminder (only when an unattended runtime genuinely needs one): the token must have
can_access_cma: true
and a role with the permissions the task requires (publishing, editing schema, etc.). It does not need to be "full-access" — it should be scoped to the smallest set of models, actions, and environments that the runtime actually needs.

确定认证方式后,检查项目以确定运行环境及可用的CMA客户端包。
  1. 读取
    package.json
    ,按优先级检查以下包:
    • @datocms/cma-client
      — 通用/同构包。推荐用于大多数场景。适用于任何支持原生
      fetch
      的环境。仅当运行环境缺少原生Fetch API时,才需要提供
      fetchFn
    • @datocms/cma-client-node
      — 针对Node.js优化的包。新增上传辅助方法(
      createFromLocalFile
      createFromUrl
      )。当需要文件系统上传便捷方法时使用。
    • @datocms/cma-client-browser
      — 针对浏览器优化的包。新增
      createFromFileOrBlob()
      方法用于File/Blob上传。
  2. 如果未安装任何上述包且任务需要
    buildClient()
    代码,推荐合适的包:
    • 通用场景 →
      @datocms/cma-client
    • 需要上传辅助方法的Node.js项目 →
      @datocms/cma-client-node
    • 需要File/Blob上传的纯浏览器项目 →
      @datocms/cma-client-browser
    (对于通过
    cma:call
    /
    cma:script
    完成的纯OAuth路径工作,无需安装上述任何包——CLI工作区已自带客户端。)
  3. 搜索现有
    buildClient()
    调用,了解项目当前如何配置客户端(API令牌来源、目标环境等)。
  4. 仅当交付物为无人值守运行时代码时(见步骤1a):检查
    .env
    .env.local
    文件,确认是否已定义支持CMA的
    DATOCMS_API_TOKEN
    (或类似变量)。如果仅存在只读变量(如
    DATOCMS_READONLY_API_TOKEN
    NEXT_PUBLIC_DATOCMS_API_TOKEN
    或CDA令牌),则需标记该运行环境需要单独的支持CMA的令牌——Agent自身的项目感知仍需通过CLI + link完成。
  5. 检查是否存在
    cma-types.ts
    文件,确定是否已设置CMA类型生成。不要主动建议设置类型生成。对于
    cma:docs
    查询、
    cma:call
    cma:script
    ,本技能直接控制执行格式——见步骤4的速查表。对于schema变更请求,见步骤2.5中的决策树——该树明确了本技能直接处理的场景,以及需要路由到datocms-cli迁移的场景。其他CLI工作流相关主题(
    schema:generate
    、环境操作、导入、插件管理、多项目同步、CI/CD)则路由到datocms-cli
令牌范围提醒(仅当无人值守运行环境确实需要时):令牌必须具备
can_access_cma: true
,且角色拥有任务所需权限(发布、编辑schema等)。无需设置为“完全访问”——应将范围限定为运行环境实际需要的最小模型、操作和环境集合。

Step 2: Understand the Task

步骤2:理解任务

Classify the user's task into one or more categories. Ask follow-up questions only when the request is ambiguous or the risk of a wrong assumption is high.
  • Content operations — Create, read, update, delete, publish, or unpublish records
  • Upload operations — Upload files, manage assets, update metadata, bulk tag
  • Schema operations — Create or modify models, fields, fieldsets, block models
  • Filtering & querying — Search records, filter by fields, paginate large collections
  • Localization — Work with localized field values and multi-locale content
  • Blocks & modular content — Modular content fields, single-block fields, nested block payloads
  • Structured text & block tooling — DAST payloads, embedded blocks, block traversal, debugging helpers
  • Environment operations — Fork, promote, rename, delete sandbox environments
  • Webhook & deploy operations — Configure webhooks, build triggers, deploy management
  • Access control — Create roles, manage API tokens, invite users
  • Scheduling — Schedule publish/unpublish, manage workflows
  • Migration & scripting — Bulk data operations, content seeding, field migrations
  • Type generation — Consume generated CMA schema types or wire typed record operations
  • Dashboard & schema menu management — Organize navigation sidebar items, group models in menus
  • Plugin management — Install, configure, or audit plugins programmatically
  • Project settings & usage — Site settings, maintenance mode, subscription limits, usage tracking, white-label
  • Saved filters — Create or manage saved record/upload filter views
  • Audit & debugging — Query audit logs, inspect async job results, CMA-side search
If the user's request is clear and falls into an obvious category, skip the clarifying questions and proceed directly.

将用户任务分类为一个或多个类别。仅当请求模糊或错误假设风险较高时,才提出跟进问题。
  • 内容操作 — 创建、读取、更新、删除、发布或取消发布记录
  • 上传操作 — 上传文件、管理资源、更新元数据、批量打标签
  • Schema操作 — 创建或修改模型、字段、字段集、区块模型
  • 筛选与查询 — 搜索记录、按字段筛选、大型集合分页
  • 本地化 — 处理本地化字段值与多语言内容
  • 区块与模块化内容 — 模块化内容字段、单区块字段、嵌套区块负载
  • 结构化文本与区块工具 — DAST负载、嵌入区块、区块遍历、调试辅助工具
  • 环境操作 — 复制、升级、重命名、删除沙箱环境
  • Webhook与部署操作 — 配置Webhook、构建触发器、部署管理
  • 访问控制 — 创建角色、管理API令牌、邀请用户
  • 定时任务 — 定时发布/取消发布、管理工作流
  • 迁移与脚本 — 批量数据操作、内容填充、字段迁移
  • 类型生成 — 使用生成的CMA schema类型或实现类型化记录操作
  • 仪表盘与schema菜单管理 — 组织导航侧边栏项、在菜单中分组模型
  • 插件管理 — 程序化安装、配置或审计插件
  • 项目设置与使用情况 — 站点设置、维护模式、订阅限制、使用跟踪、白标配置
  • 已保存筛选器 — 创建或管理已保存的记录/上传筛选视图
  • 审计与调试 — 查询审计日志、检查异步任务结果、CMA端搜索
如果用户请求明确且属于明显类别,可跳过澄清问题直接执行。

Step 2.5: Schema changes — decide the approach with the user

步骤2.5:Schema变更——与用户确定处理方式

DatoCMS schema operations fall into four buckets. The choice of approach is not automatic — ask the user when the bucket is not obvious from the request, because reversibility and workflow preference matter more than which tool performs the mutation.
SituationWhat it coversApproach
Destructive schema changeDROP a field, DROP a model,
bulk_destroy
records, lossy
field_type
changes (e.g.
string → json
,
json → string
, anything that discards stored values)
Migration via
datocms-cli
(
migrations:new
), against a forked sandbox first. Never run these against a primary environment without explicit, repeated user confirmation.
Reversible schema changeAdd a field, add a model or block, rename a field, toggle
required
, add or tighten a validation, reorder fieldsets
Ask the user. Both approaches are safe; pick by preference and context. Lean to a migration (
datocms-cli
) when the repo already uses a migrations workflow or the user is on a secondary branch — reviewable, reproducible. Direct mutation (
cma:call
,
cma:script
stdin-mode, or
cma:script
file-mode) is fine for quick iteration on a sandbox. Default to migration only when the user has no preference AND the repo shows migration conventions (
migrations/
directory, prior migration commits).
User-requested one-offPhrases like "quickly, without a migrations workflow", "just patch this", "one-off", "don't scaffold migrations for this"Honor the opt-out. Use direct mutation via
cma:call
(single call with shape from
cma:docs
) or
cma:script
(stdin-mode for loops/multi-step, file-mode when the script is long enough that a heredoc hurts). Do not re-suggest migrations unless the change turns out to be a destructive schema change.
Content operationPublish, unpublish, delete individual records, fix slugs, bulk update a field value, re-tag uploadsNo migration needed. Prefer
cma:call
for a single call;
cma:script
stdin-mode for loops, pagination, or multi-step logic;
cma:script
file-mode only when a heredoc becomes painful. Code that needs to be committed and replayed across environments is a migration (
datocms-cli
), not this skill.
Regardless of which skill is loaded, the question to ask the user is the same for a reversible schema change: "Do you want this as a reviewable migration, or a direct mutation against a sandbox?" The answer determines which skill owns the follow-up — not which skill was loaded first.
Cross-skill routing.
  • User-requested one-offs, content operations, and the direct-mutation branch of a reversible schema change are this skill's core:
    cma:call
    ,
    cma:script
    stdin-mode, and
    cma:script
    file-mode. Stay here and load the references in Step 3.
  • Destructive schema changes, the migration branch of a reversible schema change, and anything that must be committed/versioned/replayed across environments are better covered by datocms-cli (
    migrations:new
    ,
    migrations:run
    ). Switch when the change is destructive, when the repo already uses a migrations workflow, or when the user wants the change as a reviewable migration. The handoff is loading the sibling skill's references — do not bounce the user.
  • Unattended runtime code (CI, app server, webhook, long-lived automation) is a separate scenario — that is where a checked-in
    buildClient()
    script belongs. See Step 4 ("Client Setup").

DatoCMS的Schema操作分为四类。处理方式并非自动确定——当场景无法从请求中明确时,需询问用户,因为可逆性和工作流偏好比工具选择更重要。
场景涵盖内容处理方式
破坏性schema变更删除字段、删除模型、
bulk_destroy
记录、有损
field_type
变更(例如
string → json
json → string
,任何会丢弃存储值的操作)
迁移:通过
datocms-cli
migrations:new
)执行,首先在复制的沙箱环境中操作。未经用户明确、反复确认,绝不能在主环境中执行这些操作。
可逆schema变更添加字段、添加模型或区块、重命名字段、切换
required
属性、添加或收紧验证规则、调整字段集顺序
询问用户。两种方式均安全,根据偏好和上下文选择。当仓库已使用迁移工作流或用户处于次要分支时,优先选择迁移(
datocms-cli
)——可评审、可复现。直接变更(
cma:call
cma:script
标准输入模式或文件模式)适用于沙箱环境中的快速迭代。仅当用户无偏好且仓库存在迁移约定(
migrations/
目录、过往迁移提交)时,默认选择迁移。
用户请求的一次性操作类似“快速完成,无需迁移工作流”“直接修复”“一次性操作”“不要为此生成迁移脚手架”的表述尊重用户选择退出迁移的需求。通过
cma:call
(使用
cma:docs
中的格式进行单次调用)或
cma:script
(循环/多步骤逻辑使用标准输入模式,脚本过长导致 heredoc 不便时使用文件模式)执行直接变更。除非变更被证明是破坏性schema变更,否则不要重新建议迁移。
内容操作发布、取消发布、删除单个记录、修复slug、批量更新字段值、重新标记上传内容无需迁移。单次调用优先使用
cma:call
;循环、分页或多步骤逻辑使用
cma:script
标准输入模式;仅当 heredoc 不便时使用
cma:script
文件模式。需要提交并跨环境重放的代码属于迁移(
datocms-cli
),不属于本技能范畴。
无论加载哪个技能,对于可逆schema变更,向用户提出的问题都是相同的“您希望将此变更作为可评审的迁移,还是直接在沙箱环境中执行变更?” 用户的回答决定后续由哪个技能处理——与初始加载的技能无关。
跨技能路由
  • 用户请求的一次性操作、内容操作,以及可逆schema变更中的直接变更分支,均为本技能的核心场景:
    cma:call
    cma:script
    标准输入模式和文件模式。继续使用本技能并加载步骤3中的参考文档。
  • 破坏性schema变更、可逆schema变更中的迁移分支,以及任何需要提交/版本化/跨环境重放的变更,更适合由datocms-cli
    migrations:new
    migrations:run
    )处理。当变更具有破坏性、仓库已使用迁移工作流,或用户希望将变更作为可评审迁移时,切换到该技能。切换时只需加载关联技能的参考文档——无需让用户跳转。
  • 无人值守运行时代码(CI、应用服务器、Webhook、长期自动化)属于单独场景——此类场景应使用已提交的
    buildClient()
    脚本。见步骤4(“客户端设置”)。

Step 3: Load References

步骤3:加载参考文档

Two documentation sources are available — pick the right one for the question:
  1. npx datocms cma:docs <resource> <action>
    is the live, always-up-to-date source for endpoint shapes, payload attributes, validators, and client TypeScript signatures. Always reflects the installed client version — never stale. Use it as the default for every "what does this endpoint accept / return" question.
  2. The reference files in this directory carry opinionated mental models, decision trees, cross-cutting workflows, and pattern ordering invariants — things
    cma:docs
    doesn't know. Use them for the "how should I approach this" questions.
cma:docs
is a CLI command — its full surface (flags, naming convention, when to pass
--expand-types
) lives in the sibling skill.
Load the datocms-cli skill and read
../datocms-cli/references/direct-cma-calls.md
§ cma:docs the first time this skill needs to consult endpoint documentation. That file is the single source of truth for the command; do not re-derive the flags from this skill.
When writing typed code (
buildBlockRecord<Schema.X>
,
client.items.create<Schema.X>
, …), consider passing
--types-depth 2
(or higher) to surface a deeper "Not expanded" type list, or
--expand-types <SpecificType>
to inline a single declaration. Reach for
--expand-types "*"
only as a last resort — its output is verbose.
Always load:
  • references/client-setup-and-errors.md
    — Package choice, client setup, token/environment config, error handling
Routing per task category — same two-step routine for every row:
  1. Run
    npx datocms cma:docs <resource> <action>
    to fetch the live endpoint shape, payload attributes, and TS signatures.
  2. Then load the reference listed below for the workflow, mental model, ordering invariants, and gotchas
    cma:docs
    doesn't carry.
Each reference opens with a reminder of the specific
cma:docs <resource>
to consult — never re-derive endpoint shapes from prose, always pull them live.
Task categoryReference
Content operations
references/records.md
Upload operations
references/uploads.md
Schema operations
references/schema.md
Filtering & querying
references/filtering-and-pagination.md
Localization
references/localization.md
Blocks & modular content
references/editing-records.md
Structured text & block tooling
references/editing-records.md
Environment operations
references/environments.md
Access control
references/access-control.md
Migration & scripting
references/migration-patterns.md
Type generation
references/type-generation.md
Project settings & usage
references/project-settings-and-usage.md
Webhook & deploy operations
references/resource-gotchas.md
§ Webhooks / Build triggers
Scheduling
references/resource-gotchas.md
§ Scheduling / Workflows
Dashboard & schema menu management
references/resource-gotchas.md
§ Dashboard and schema menus
Plugin management
references/resource-gotchas.md
§ Plugins
Saved filters
references/resource-gotchas.md
§ Saved filters
Audit & debugging
references/resource-gotchas.md
§ Async job results / CMA search results / Audit log events
Load cross-cutting references when needed:
  • If the task involves localized fields in any context → also load
    references/localization.md
  • If the task uses
    raw*()
    methods, generated CMA types, advanced client behavior, or platform limits → also load
    references/client-types-and-behaviors.md
  • If the task involves modular content, single-block fields, DAST structured text, block traversal, or any per-locale backfill → also load
    references/editing-records.md
  • If the task involves listing many records → also load
    references/filtering-and-pagination.md
  • If the task is a migration script → also load
    references/migration-patterns.md
    plus whatever domain refs are needed
  • If the task involves video upload subtitles/tracks or upload tag management → also load
    references/resource-gotchas.md
    § Upload tracks and tags
  • If the task involves maintenance mode before a migration → also load
    references/project-settings-and-usage.md
  • If the task involves checking subscription limits before bulk operations → also load
    references/project-settings-and-usage.md

有两类文档源可供选择——根据问题选择合适的来源:
  1. npx datocms cma:docs <resource> <action>
    是端点格式、负载属性、验证器和客户端TypeScript签名的实时、始终更新的来源。始终反映已安装的客户端版本——不会过时。将其作为所有“此端点接受/返回什么内容”问题的默认来源
  2. 本目录中的参考文件包含经验性思维模型、决策树、跨领域工作流和模式排序规则——这些是
    cma:docs
    未涵盖的内容。将其用于“我应如何处理此问题”类问题
cma:docs
是一个CLI命令——其完整功能(标志、命名约定、何时传递
--expand-types
)由关联技能定义。
首次需要查阅端点文档时,加载datocms-cli技能并阅读
../datocms-cli/references/direct-cma-calls.md
中的
cma:docs
章节。该文件是此命令的唯一权威来源——不要从本技能中推导标志。
编写类型化代码(
buildBlockRecord<Schema.X>
client.items.create<Schema.X>
等)时,可考虑传递
--types-depth 2
(或更高值)以显示更深层次的“未展开”类型列表,或传递
--expand-types <SpecificType>
以内联单个类型声明。仅在万不得已时使用
--expand-types "*"
——其输出过于冗长。
必须加载的文档
  • references/client-setup-and-errors.md
    — 包选择、客户端设置、令牌/环境配置、错误处理
按任务类别路由——每一行均遵循两步流程
  1. 运行
    npx datocms cma:docs <resource> <action>
    获取实时端点格式、负载属性和TS签名。
  2. 然后加载下方列出的参考文档,获取
    cma:docs
    未涵盖的工作流、思维模型、排序规则和注意事项。
每个参考文档开头都会提醒需查阅的特定
cma:docs <resource>
——永远不要从 prose 中推导端点格式,始终实时获取。
任务类别参考文档
内容操作
references/records.md
上传操作
references/uploads.md
Schema操作
references/schema.md
筛选与查询
references/filtering-and-pagination.md
本地化
references/localization.md
区块与模块化内容
references/editing-records.md
结构化文本与区块工具
references/editing-records.md
环境操作
references/environments.md
访问控制
references/access-control.md
迁移与脚本
references/migration-patterns.md
类型生成
references/type-generation.md
项目设置与使用情况
references/project-settings-and-usage.md
Webhook与部署操作
references/resource-gotchas.md
章节:Webhooks / Build triggers
定时任务
references/resource-gotchas.md
章节:Scheduling / Workflows
仪表盘与schema菜单管理
references/resource-gotchas.md
章节:Dashboard and schema menus
插件管理
references/resource-gotchas.md
章节:Plugins
已保存筛选器
references/resource-gotchas.md
章节:Saved filters
审计与调试
references/resource-gotchas.md
章节:Async job results / CMA search results / Audit log events
必要时加载跨领域参考文档
  • 如果任务涉及任何本地化字段 → 同时加载
    references/localization.md
  • 如果任务使用
    raw*()
    方法、生成的CMA类型、高级客户端行为或平台限制 → 同时加载
    references/client-types-and-behaviors.md
  • 如果任务涉及模块化内容、单区块字段、DAST结构化文本、区块遍历或任何按语言环境回填 → 同时加载
    references/editing-records.md
  • 如果任务涉及列出大量记录 → 同时加载
    references/filtering-and-pagination.md
  • 如果任务是迁移脚本 → 同时加载
    references/migration-patterns.md
    及相关领域参考文档
  • 如果任务涉及视频上传字幕/轨道或上传标签管理 → 同时加载
    references/resource-gotchas.md
    章节:Upload tracks and tags
  • 如果任务涉及迁移前的维护模式 → 同时加载
    references/project-settings-and-usage.md
  • 如果任务涉及批量操作前检查订阅限制 → 同时加载
    references/project-settings-and-usage.md

Step 4: Generate the Solution

步骤4:生成解决方案

When the response includes code, follow these default rules:
当响应包含代码时,请遵循以下默认规则:

Authentication (respect the Step 1a bootstrap)

认证(遵循步骤1a的初始化流程)

  • CLI + link is a prerequisite of Step 4, not a choice. If the project is not yet linked, fix that first (propose install + login + link) before writing any solution code.
  • For interactive / one-off work (the majority of CMA tasks), do not write
    buildClient({ apiToken: ... })
    code at all — output a
    cma:call
    invocation (single call with shape from
    cma:docs
    ) or a
    cma:script
    invocation (stdin-mode for loops/multi-step, file-mode when a heredoc becomes painful) using the shapes below. The CLI handles auth silently via the linked project; no cross-skill hop needed.
  • Only when the deliverable is unattended runtime code (CI, server-side app, long-lived automation, repo-committed shared scripts) should the response include
    buildClient()
    + env-var token code.
  • CLI + link是步骤4的先决条件,而非可选步骤。如果项目尚未关联,先修复此问题(建议安装+登录+关联),再编写任何解决方案代码。
  • 对于交互式/一次性工作(大多数CMA任务),完全无需编写
    buildClient({ apiToken: ... })
    代码——输出
    cma:call
    调用(使用
    cma:docs
    中的格式进行单次调用)或
    cma:script
    调用(循环/多步骤逻辑使用标准输入模式,脚本过长导致 heredoc 不便时使用文件模式),格式如下。CLI会通过关联的项目静默处理认证——无需跨技能跳转。
  • 仅当交付物为无人值守运行时代码(CI、服务器端应用、长期自动化、仓库提交的共享脚本)时,响应中才应包含
    buildClient()
    + 环境变量令牌代码。

cma:call
shape — do not invent REST-style flags

cma:call
格式——不要自定义REST风格标志

cma:call
is positional (
<RESOURCE> <METHOD>
+ any URL placeholders as extra positional args), with JSON5 request bodies and query params passed via
--data
/
--params
. It is not a REST wrapper — there is no
--endpoint
,
--method
,
--query-params
, or
--body
flag.
bash
undefined
cma:call
采用位置参数
<RESOURCE> <METHOD>
+ 任何URL占位符作为额外位置参数),JSON5请求体和查询参数通过
--data
/
--params
传递。它不是REST包装器——没有
--endpoint
--method
--query-params
--body
标志。
bash
undefined

List + filter

列表 + 筛选

npx datocms cma:call items list --params='{filter: {type: "article"}}'
npx datocms cma:call items list --params='{filter: {type: "article"}}'

Single resource

单个资源

npx datocms cma:call items find <ITEM_ID>
npx datocms cma:call items find <ITEM_ID>

Mutate (confirm environment first)

变更(先确认环境)

npx datocms cma:call items update <ITEM_ID> --data='{title: "Updated"}' npx datocms cma:call items publish <ITEM_ID>
npx datocms cma:call items update <ITEM_ID> --data='{title: "Updated"}' npx datocms cma:call items publish <ITEM_ID>

Schema (prefer a migration unless the user opted out)

Schema变更(除非用户选择退出,否则优先使用迁移)

npx datocms cma:call fields create <ITEM_TYPE_ID> --data='{label: "Title", api_key: "title", field_type: "string"}'

`--data` / `--params` accept JSON5 (unquoted keys, single-quoted wrapping), which
keeps shell escaping sane. If unsure about the exact resource/method/body shape,
run `npx datocms cma:docs <resource> <action>` — that is the authoritative
source.
npx datocms cma:call fields create <ITEM_TYPE_ID> --data='{label: "Title", api_key: "title", field_type: "string"}'

`--data`/`--params`接受JSON5(无引号键、单引号包裹),可避免shell转义问题。如果不确定确切的资源/方法/体格式,运行`npx datocms cma:docs <resource> <action>`——这是权威来源。

cma:script
shape — typed one-off TypeScript, two modes

cma:script
格式——类型化一次性TypeScript,两种模式

Use
cma:script
when a one-off task needs loops, branching, multiple dependent calls, or typed
Schema.*
record payloads. It has two modes with different ergonomics — pick by how the script is delivered, not by how "complex" it is.
stdin-mode — top-level await, piped or heredoc. Zero setup.
client
(pre-authenticated) and
Schema
(project record types) are ambient globals inside a CLI-bundled workspace;
tsc --noEmit
type-checks before execution;
any
and
unknown
are rejected. Pre-installed packages available without install:
@datocms/cma-client-node
,
datocms-structured-text-*
,
parse5
.
export default
is not supported here — use file-mode if you want a function.
bash
npx datocms cma:script <<'EOF'
const items = await client.items.list({ filter: { type: 'article' } });
console.log(items.length);
EOF
file-mode
export default async function(client: Client)
in a
.ts
file on disk. Runs in the user's own TypeScript context (validation via editor LSP against your
tsconfig.json
, or an explicit
tsc --noEmit
; no CLI-side typecheck). Same throwaway scenario as stdin-mode — this is not "code to commit"; use it when a heredoc becomes painful (long script, fragile quoting with
$
/backticks, local helper imports, or you want to rerun by filename).
ts
// tmp/scripts/publish-drafts.ts
import type { Client } from 'datocms/lib/cma-client-node';
// Optional typed project schema — run once next to the script:
//   npx datocms schema:generate ./datocms-schema.ts
// import * as Schema from './datocms-schema';

export default async function (client: Client): Promise<void> {
  for await (const draft of client.items.listPagedIterator({
    filter: { fields: { _status: { eq: 'draft' } } },
  })) {
    await client.items.publish(draft.id);
  }
}
bash
npx datocms cma:script tmp/scripts/publish-drafts.ts [--environment <env>]
Rules of thumb:
  • Use
    cma:call
    first
    for a single call with a shape you can read from
    cma:docs
    . Reach for
    cma:script
    only when the task needs loops, pagination, branching, dependent calls, or typed
    Schema.*
    payloads.
  • stdin-mode for quick hacks: pipes, heredocs, one-liners. No file on disk, no project prerequisites.
  • file-mode when a heredoc hurts: long script, nested quoting, local helper imports, or you want to rerun the file by name. Requires
    datocms
    reachable in
    node_modules
    from the file's directory; place the file in a gitignored scratch dir (
    tmp/scripts/
    ,
    scratch/
    ,
    ~/scratch/dato/
    ). Prefer a migration for code you want to commit, version, and replay across environments, and do not put file-mode scripts under
    migrations/
    — that directory is owned by
    migrations:run
    .
  • Typed
    Schema.*
    in file-mode is opt-in
    : run
    npx datocms schema:generate ./datocms-schema.ts
    next to the script and
    import * as Schema from './datocms-schema'
    . In stdin-mode
    Schema.*
    is ambient — no generation needed.
  • Import path matters for promotion: file-mode imports
    Client
    from
    datocms/lib/cma-client-node
    — the same import migrations use, so a file-mode script can be promoted into a migration with a plain
    mv
    into
    migrations/
    (signature matches too).
  • Redirect
    2>/dev/null
    when piping stdin-mode stdout into
    jq
    .
  • Pre-installed packages are stdin-only. In file-mode, install what you need into your own
    package.json
    .
  • Reach for a checked-in
    buildClient()
    script
    only when the code must run unattended (CI, app server, webhook, long-lived automation). See "Client Setup" below.
For advanced patterns (workspace flags, stdout shaping, long-running scripts), consult the datocms-cli skill.
当一次性任务需要循环、分支、多个依赖调用或类型化
Schema.*
记录负载时,使用
cma:script
。它有两种模式,各有不同的易用性——根据脚本交付方式选择,而非复杂程度。
标准输入模式——顶级await,通过管道或heredoc传递。零配置。
client
(已预认证)和
Schema
(项目记录类型)是CLI捆绑工作区中的全局变量;执行前会通过
tsc --noEmit
进行类型检查;拒绝
any
unknown
类型。无需安装即可使用预安装包:
@datocms/cma-client-node
datocms-structured-text-*
parse5
。不支持
export default
——如果需要函数,请使用文件模式。
bash
npx datocms cma:script <<'EOF'
const items = await client.items.list({ filter: { type: 'article' } });
console.log(items.length);
EOF
文件模式——在磁盘上的
.ts
文件中编写
export default async function(client: Client)
。在用户自己的TypeScript上下文中运行(通过编辑器LSP根据
tsconfig.json
验证,或显式执行
tsc --noEmit
;无CLI端类型检查)。与标准输入模式一样属于一次性场景——这不是“需要提交的代码”;当heredoc不便时(脚本过长、
$
/反引号导致引用脆弱、本地辅助函数导入,或希望通过文件名重新运行)使用此模式。
ts
// tmp/scripts/publish-drafts.ts
import type { Client } from 'datocms/lib/cma-client-node';
// 可选类型化项目schema——在脚本旁运行一次:
//   npx datocms schema:generate ./datocms-schema.ts
// import * as Schema from './datocms-schema';

export default async function (client: Client): Promise<void> {
  for await (const draft of client.items.listPagedIterator({
    filter: { fields: { _status: { eq: 'draft' } } },
  })) {
    await client.items.publish(draft.id);
  }
}
bash
npx datocms cma:script tmp/scripts/publish-drafts.ts [--environment <env>]
经验法则:
  • **优先使用
    cma:call
    **处理可从
    cma:docs
    获取格式的单次调用。仅当任务需要循环、分页、分支、依赖调用或类型化
    Schema.*
    负载时,才使用
    cma:script
  • 标准输入模式适用于快速临时操作:管道、heredoc、单行脚本。无需磁盘文件,无项目先决条件。
  • 文件模式适用于heredoc不便的场景:长脚本、嵌套引用、本地辅助函数导入,或希望通过文件名重新运行。要求从文件目录可在
    node_modules
    中找到
    datocms
    ;将文件放在git忽略的临时目录(
    tmp/scripts/
    scratch/
    ~/scratch/dato/
    )。对于需要提交、版本化并跨环境重放的代码,优先使用迁移,不要将文件模式脚本放在
    migrations/
    目录下——该目录由
    migrations:run
    管理。
  • 文件模式中的类型化
    Schema.*
    是可选的
    :在脚本旁运行
    npx datocms schema:generate ./datocms-schema.ts
    import * as Schema from './datocms-schema'
    。标准输入模式中
    Schema.*
    是全局变量——无需生成。
  • 导入路径对升级很重要:文件模式从
    datocms/lib/cma-client-node
    导入
    Client
    ——与迁移使用的导入路径相同,因此文件模式脚本可通过简单
    mv
    migrations/
    目录升级为迁移(签名也匹配)。
  • 将标准输入模式的stdout管道到
    jq
    时,重定向
    2>/dev/null
  • 预安装包仅适用于标准输入模式。文件模式下,需将所需包安装到自己的
    package.json
    中。
  • 仅当代码必须无人值守运行时(CI、应用服务器、Webhook、长期自动化),才使用已提交的
    buildClient()
    脚本
    。见下方“客户端设置”。
如需高级模式(工作区标志、stdout格式化、长运行脚本),请查阅datocms-cli技能。

Client Setup (unattended-runtime code only)

客户端设置(仅适用于无人值守运行时代码)

  • Default to
    buildClient()
    from the detected package (Step 1b)
  • Read the API token from an environment variable; never hardcode it and never ask the user to paste it into the chat
  • Set the
    environment
    option when working with sandbox environments
  • 默认使用步骤1b中检测到的包的
    buildClient()
  • 从环境变量读取API令牌;永远不要硬编码令牌,也不要让用户将令牌粘贴到聊天中
  • 处理沙箱环境时,设置
    environment
    选项

API Surface

API接口

  • Default to the simplified API (e.g.,
    client.items.create()
    ) because it handles serialization/deserialization automatically
  • Switch to
    raw*()
    methods only when the task explicitly needs raw JSON:API payloads, relationship metadata, or generated CMA schema types are intentionally part of the solution
  • 默认使用简化API(例如
    client.items.create()
    ),因为它会自动处理序列化/反序列化
  • 仅当任务明确需要原始JSON:API负载、关联元数据,或生成的CMA schema类型是解决方案的有意组成部分时,才切换到
    raw*()
    方法

Pagination

分页

  • Prefer
    *.listPagedIterator()
    (for example
    client.items.listPagedIterator()
    ) when iterating over collections
  • Avoid manual offset/limit pagination loops unless a resource genuinely lacks an iterator
  • Use
    for await...of
    to consume async iterators
  • 遍历集合时,优先使用
    *.listPagedIterator()
    (例如
    client.items.listPagedIterator()
  • 除非资源确实缺少迭代器,否则避免手动offset/limit分页循环
  • 使用
    for await...of
    消费异步迭代器

Blocks

区块

  • Prefer
    buildBlockRecord()
    when creating block records for the simplified API
  • Import it from the same package as
    buildClient
  • 使用简化API创建区块记录时,优先使用
    buildBlockRecord()
  • 从与
    buildClient
    相同的包中导入该方法

Error Handling

错误处理

  • Catch
    ApiError
    for API failures — it provides
    .errors
    getter and
    .findError()
    method
  • Catch
    TimeoutError
    for request timeouts in long-running or request-heavy flows
  • Import both from the same package as
    buildClient
  • 捕获
    ApiError
    处理API失败——它提供
    .errors
    getter和
    .findError()
    方法
  • 在长运行或请求密集型流程中,捕获
    TimeoutError
    处理请求超时
  • 从与
    buildClient
    相同的包中导入这两个错误类型

TypeScript

TypeScript

  • Follow the TypeScript strictness rules: no
    as unknown as
    , no unnecessary
    as
    casts
  • Let TypeScript infer types wherever possible
  • Use
    import type { ... }
    for type-only imports

  • 遵循TypeScript严格规则:不使用
    as unknown as
    ,不使用不必要的
    as
    类型转换
  • 尽可能让TypeScript推断类型
  • 使用
    import type { ... }
    进行仅类型导入

Step 5: Verify

步骤5:验证

Before presenting the final code:
  1. Project-awareness bootstrap — Confirm the repo has the
    datocms
    npm package installed and the project is linked (
    datocms.config.json
    with a
    siteId
    ,
    npx datocms whoami
    succeeds). If not, the final proposal must include the install + login + link sequence before any CMA operation. For interactive / one-off tasks the deliverable should be a
    cma:call
    /
    cma:script
    invocation (shapes in Step 4), not a
    buildClient()
    script that requires a token in
    .env
    . Only when the code will run unattended (CI, server-side app, long-lived automation) should a token-in-env solution be presented — and in that case the token must have CMA access enabled and the role permissions the task needs. Schema changes require a role with
    can_edit_schema: true
    .
  2. Environment targeting — If working with a sandbox, ensure the
    environment
    config option is set
  3. Error handling — Ensure
    ApiError
    is caught at appropriate boundaries
  4. Pagination — If the solution iterates a collection that could exceed a single page, prefer
    listPagedIterator()
  5. Type safety — Ensure no type assertions (
    as
    ) are used to silence errors
  6. Imports — Ensure all imports come from the correct package (the one detected in Step 1)
  7. Generated types — If the solution intentionally uses generated CMA types (
    cma-types.ts
    ), ensure the chosen path is typed end to end: simplified API generics by default, or
    raw*()
    /
    RawApiTypes.Item<>
    only when raw payload access is intentional
If the generated code is a script (migration, seeding, etc.), wrap it in an async function with proper error handling and progress reporting.

展示最终代码前:
  1. 项目感知初始化 — 确认仓库已安装
    datocms
    npm包且项目已关联(
    datocms.config.json
    包含
    siteId
    npx datocms whoami
    执行成功)。如果未满足,最终方案必须包含安装+登录+关联序列,再执行任何CMA操作。对于交互式/一次性任务,交付物应为
    cma:call
    /
    cma:script
    调用(格式见步骤4),而非需要
    .env
    中存储令牌的
    buildClient()
    脚本。仅当代码将无人值守运行时(CI、服务器端应用、长期自动化),才提供令牌存储在环境变量中的解决方案——此时令牌必须启用CMA访问并具备任务所需的角色权限。Schema变更需要角色具备
    can_edit_schema: true
    权限。
  2. 目标环境 — 如果处理沙箱环境,确保已设置
    environment
    配置选项
  3. 错误处理 — 确保在适当的边界捕获
    ApiError
  4. 分页 — 如果解决方案遍历的集合可能超过单页,优先使用
    listPagedIterator()
  5. 类型安全 — 确保未使用类型断言(
    as
    )来掩盖错误
  6. 导入 — 确保所有导入来自步骤1中检测到的正确包
  7. 生成的类型 — 如果解决方案有意使用生成的CMA类型(
    cma-types.ts
    ),确保所选路径全程类型化:默认使用简化API泛型,仅当需要原始负载访问时才使用
    raw*()
    /
    RawApiTypes.Item<>
如果生成的代码是脚本(迁移、填充等),将其包装在带有适当错误处理和进度报告的异步函数中。

Cross-Skill Routing

跨技能路由

This skill covers content management via the REST CMA (mutations, schema, uploads, webhooks, scripts). If the task involves any of the following, activate the companion skill:
ConditionRoute to
CLI-workflow topics: migrations (creating, running, autogenerate),
schema:generate
, environment operations (
fork
/
promote
/
destroy
/
rename
), imports (WordPress, Contentful), CLI plugin management, blueprint/multi-project sync, CI/CD deployment workflows
datocms-cli
Querying content with GraphQL for frontend displaydatocms-cda
Setting up draft mode, Web Previews, Content Link, real-time subscriptions, or framework integrationdatocms-frontend-integrations
Building a DatoCMS plugindatocms-plugin-builder
本技能涵盖通过REST CMA进行内容管理(变更、schema、上传、Webhook、脚本)。如果任务涉及以下任何内容,请激活关联技能:
条件路由到
CLI工作流主题:迁移(创建、运行、自动生成)、
schema:generate
、环境操作(
fork
/
promote
/
destroy
/
rename
)、导入(WordPress、Contentful)、CLI插件管理、蓝图/多项目同步、CI/CD部署工作流
datocms-cli
使用GraphQL查询内容用于前端展示datocms-cda
设置草稿模式、Web预览、内容链接、实时订阅或框架集成datocms-frontend-integrations
构建DatoCMS插件datocms-plugin-builder