@colophon-cms/sdk is a small client for both of Colophon’s HTTP APIs. A website uses it to read published
content from the delivery API; a build step, import script or tool uses it to write drafts
and publish through the management API. It sends exactly the requests you would send with
curl, keeps the API’s field names as they are (next_cursor, not nextCursor), and turns every refusal
into one error type.
Its types are generated from the OpenAPI document the server serves, so a field the API answers is a field the SDK knows. It is ESM only, has no runtime dependencies, and runs on Node.js 22.17 or newer and in browsers.
Install it from a clone
Section titled “Install it from a clone”-
Build the package.
@colophon-cms/sdkisn’t on npm yet, so build its package from a clone of the repository:Terminal window git clone https://github.com/akira-shirase-oss/colophon-cms.gitcd colophon-cmsnpm ci --workspace @colophon-cms/sdk --include-workspace-root=false --no-audit --no-fund >/dev/nullnpm pack --workspace @colophon-cms/sdk --silentcolophon-cms-sdk-0.1.0-alpha.1.tgz -
Build the rich-text renderer too, if you show rich text.
@colophon-cms/rich-textturns a rich-text field into HTML. It isn’t on npm either; pack it the same way:Terminal window npm ci --workspace @colophon-cms/rich-text --include-workspace-root=false --no-audit --no-fund >/dev/nullnpm pack --workspace @colophon-cms/rich-text --silentcolophon-cms-rich-text-0.1.0-alpha.1.tgz -
Install the tarballs into your own project, beside the clone:
Terminal window mkdir ../recipe-script && cd ../recipe-scriptnpm init -y >/dev/nullnpm install --no-audit --no-fund \../colophon-cms/colophon-cms-sdk-0.1.0-alpha.1.tgz \../colophon-cms/colophon-cms-rich-text-0.1.0-alpha.1.tgz
The examples below continue from the quick start: the project “Field notes” with its recipes,
and PROJECT and COLOPHON_TOKEN in your environment. They call https://cms.example.com: put your
Colophon’s address there (the quick start on this machine is http://localhost:8080), or enter it once in
Your Colophon URL above.
Make a client
Section titled “Make a client”import { Client } from '@colophon-cms/sdk';
const client = new Client({ baseUrl: 'https://cms.example.com', token: process.env.COLOPHON_TOKEN });
const site = client.delivery(process.env.PROJECT); // published content: /content/v1/…const cms = client.environment(process.env.PROJECT); // drafts and writes: /api/v1/projects/…/environments/…Both take the project id, the one in Settings → General → Technical details, and an
environment name, production when you leave it out: client.environment(id, 'staging'). The delivery API
doesn’t know a project by its URL name: delivery('field-notes') is answered 404 not_found.
new Client() takes these options:
| Option | Default | What it does |
|---|---|---|
baseUrl |
(required) | Colophon’s origin, such as https://cms.example.com. Must be http: or https: |
token |
none | A bearer credential: a project API token (colophon_api_…) or a personal access token from colophon login. Sent as Authorization: Bearer |
session |
none | A Studio session instead of a token: { csrf, cookie? }. csrf is the colophon_csrf cookie’s value, sent as X-CSRF-Token on writes; cookie is the colophon_session value, outside a browser only. Pass token or session, not both |
timeoutMs |
15000 |
How long one request may take. A per-call signal joins it |
maxBodyBytes |
16 MiB | The largest answer it will read, declared or measured. Past it the call fails with response_too_large |
compat |
'warn' |
The server-version check: 'warn', 'throw' or 'off'. See Is this SDK right for the server? |
headers |
none | Extra headers on every request, such as an Origin the server trusts for session writes outside a browser. The credential’s own headers win over them |
fetch |
the runtime’s | The fetch to use |
The client attaches the credential you give it and nothing more. It never signs in, refreshes or stores a credential: make a token in the Studio (Authentication & API tokens) or sign in with the CLI.
The client itself also has a few calls that aren’t about one environment: livez(), readyz() and
version() (no credential needed); me(), listProjects() and getProject(id), which are for people (an
API token is refused); validateRichText(doc), which checks a rich-text document without storing it; and
compatibility().
Read published content
Section titled “Read published content”Save this as read.mjs:
import { Client, ApiError, mediaFor } from '@colophon-cms/sdk';import { renderToHtml } from '@colophon-cms/rich-text';
const baseUrl = 'https://cms.example.com';const project = process.env.PROJECT; // the project id, not its URL name
const client = new Client({ baseUrl });const site = client.delivery(project); // the production environment
// A page of published entries, and the release it came from.const page = await site.list('recipes', { limit: 10 });console.log('published:', page.data.map((entry) => entry.title), 'etag:', page.response.etag);
// One entry, its rich text rendered to HTML.const { data: tart } = await site.get('recipes', page.data[0].id);const html = renderToHtml(tart.content.method, { assetUrl: (id) => `${baseUrl}/media/v1/${project}/production/${id}`, media: mediaFor(tart),});console.log(html);
// Every read through `pinned` names release 1.const pinned = site.atGeneration(1);const quick = await pinned.query('recipes', { filters: [{ field: 'minutes', op: 'lte', value: 60 }], fields: ['dish', 'minutes'],});console.log('release 1, under an hour:', quick.data.map((entry) => entry.content));
// A refusal is an ApiError.try { await site.query('recipes', { filters: [{ field: 'dish', op: 'eq', value: 'Lemon tart' }] });} catch (error) { if (!(error instanceof ApiError)) throw error; console.log(error.status, error.code, error.reason, error.pointer, error.retryable); console.log(error.message, error.requestId);}node read.mjspublished: [ 'Lemon tart' ] etag: "5a53d3b764fde469e9d76ec852d5faaf"<p>Blind-bake the pastry, then fill it with lemon curd and bake until just set.</p>release 1, under an hour: [ { dish: 'Lemon tart', minutes: 45 } ]422 validation_failed field_not_indexed /filters/0/field false`dish` isn't declared `index`ed 01a1ee85-704f-760e-bb09-3e888dc81dc9The query filters on minutes, so it works once that field is filterable, as
Filter and sort sets up; dish isn’t, and the refusal says so at the
filter’s pointer.
client.delivery(project, environment?) has three reads, each the route of the same name on the
delivery API:
| Method | Route | Options |
|---|---|---|
list(collection, opts?) |
GET /content/v1/{project}/{environment}/{collection} |
limit, cursor, generation |
get(collection, entry, opts?) |
GET …/{collection}/{entry} |
generation |
query(collection, document, opts?) |
POST …/{collection}/query |
cursor, generation |
A list answers data and next_cursor; pass next_cursor back as cursor for the next page, until it is
null.
Pin a release
Section titled “Pin a release”site.atGeneration(g) returns the same three reads, each pinned to release g. A page built from several
reads through one pinned scope can never mix two releases, even if someone publishes in the middle. Asking a
pinned scope for a different generation throws a TypeError instead of quietly mixing them.
Render rich text and images
Section titled “Render rich text and images”A rich-text field arrives as JSON (colophon/rich-text, version 1), never as HTML. renderToHtml(value, options) from @colophon-cms/rich-text turns it into HTML the same way the Studio’s preview does: escaped
text, links limited to https:, http:, mailto:, site paths and fragments, and no inline styles or
scripts. It takes:
assetUrl(id): the address of a media-library image, used whenmediadoesn’t know it;media(id): optional, an image’s source, size and responsive candidates.
mediaFor(row) builds media from the media record a delivery row carries for the images its release
published. For each image it answers src, the exact version that release published, with its width and
height (so the page doesn’t shift as images load), and, when smaller wN renditions exist, a srcset and
a sizes that defaults to the full width up to 1280 px. An image the record doesn’t hold answers
undefined, and the renderer falls back to assetUrl. mediaFor(row, { current: true }) follows replaced images
instead, and { sizes: '50vw' } changes the slot. For an image field, call it with the asset id:
mediaFor(row)(row.content.photo).
In TypeScript, content is typed as a plain record, so cast a rich-text field:
row.content?.['method'] as RichTextValue, with type RichTextValue imported from
@colophon-cms/rich-text. A document the renderer doesn’t understand throws UnrenderableContent; content
reaches the delivery API only after the server validated it, so that means a bug, not content to guess at.
Write drafts with a token
Section titled “Write drafts with a token”client.environment(project, environment?) is the management API for one environment. The example below
runs with the quick start’s token. Give a script of your own a Custom token with only what it does
(See, Create and Edit to write drafts and open publish requests; Publish only if it
publishes), the shortest lifetime that fits, and revoke it when the script is retired. Without Approve,
the example’s approve step is refused with missing_permission before the agent_self_review rule is
reached. See Authentication & API tokens.
Every answer is the API’s body with one more field, response:
response. |
What it is |
|---|---|
status |
The HTTP status of the success, such as 200 or 201 |
etag |
The ETag header: the revision or hash the next guarded write sends back as ifMatch. null when the route sends none |
replayed |
true when the server answered from an earlier request with the same idempotency key (Idempotent-Replayed: true) |
requestId |
The x-request-id to quote when you report a problem |
Writes name their guards as options, and the SDK makes them required where the route requires them:
idempotencyKeyon every write that creates something.newIdempotencyKey()makes one (a random UUID). Use one key per logical write and keep it: if the answer is lost and you send the same write again with the same key, Colophon answers with the first result instead of writing twice. See Idempotency-Key.ifMatchon every write that changes something that exists: theresponse.etagof the read or write you based it on. If someone saved in between, the write is refused with409and nothing is lost. See If-Match.
Save this as write.mjs:
import { Client, ApiError, newIdempotencyKey } from '@colophon-cms/sdk';
const baseUrl = 'https://cms.example.com';const project = process.env.PROJECT;
const client = new Client({ baseUrl, token: process.env.COLOPHON_TOKEN, compat: 'throw' });const cms = client.environment(project); // production
const mine = await cms.ownPermissions();console.log('kind:', mine.data.kind, 'actions:', mine.data.permissions.length);
// Create a draft. Keep the key: a retry with the same key is answered from the first result.const key = newIdempotencyKey();const created = await cms.createEntry('recipes', { dish: 'Bakewell tart', minutes: 50 }, { idempotencyKey: key });const again = await cms.createEntry('recipes', { dish: 'Bakewell tart', minutes: 50 }, { idempotencyKey: key });console.log('created:', created.data.id, created.response.status, created.response.replayed);console.log('retried:', again.data.id, again.response.status, again.response.replayed);
// Save on top of the revision just read: ifMatch is the ETag that answer carried.const id = created.data.id;const saved = await cms.saveEntry('recipes', id, { ...created.data.content, minutes: 55 }, { ifMatch: created.response.etag, idempotencyKey: newIdempotencyKey(),});console.log('saved:', saved.data.content, saved.response.etag);
// The same save on top of the old ETag is a conflict, and the error carries the current one.try { await cms.saveEntry('recipes', id, { ...created.data.content, minutes: 40 }, { ifMatch: created.response.etag, idempotencyKey: newIdempotencyKey(), });} catch (error) { if (!(error instanceof ApiError)) throw error; console.log('conflict:', error.status, error.code, error.reason, error.etag);}
// Open a publish request and send it for review.const request = await cms.createChangeset( { title: 'Add the Bakewell tart', entries: [id] }, { idempotencyKey: newIdempotencyKey() },);const hash = request.response.etag;const submitted = await cms.submitChangeset(request.data.id, { ifMatch: hash });console.log('request:', submitted.data.status.state, hash);
// A token can't approve what a token sent: a person approves it.try { await cms.reviewChangeset(request.data.id, { decision: 'approve' }, { ifMatch: hash });} catch (error) { if (!(error instanceof ApiError)) throw error; console.log('approve:', error.status, error.code, error.reason); console.log(error.message);}node write.mjskind: token actions: 8created: 01a1ee85-afa4-779f-895f-42780642e364 201 falseretried: 01a1ee85-afa4-779f-895f-42780642e364 201 truesaved: { dish: 'Bakewell tart', minutes: 55 } "01a1ee85-afb2-7023-be82-d666cd76c119"conflict: 409 conflict stale_revision "01a1ee85-afb2-7023-be82-d666cd76c119"request: awaiting_review "sha256:acc0efd34baa0deacc66de7757b02a85c6d3ee28264809999a671300375f98e9"approve: 403 forbidden agent_self_reviewan API token can't approve a changeset an API token submitted; it needs a person's approvalWhat happened:
- The second
createEntrywith the same key made nothing new: same id,replayed: true. - The save sent the create’s
ETagasIf-Matchand made a new revision, whoseETagcame back. - The second save was based on a revision that is no longer current, so it was refused with
409andstale_revision;error.etagis the current revision, theifMatcha retry would send after looking at what changed. - The publish request pins the entry’s current revision; its
ETagis the request’s hash, which every later step sends asifMatch. - A token may send a request for review but not approve one a token sent: that needs a person.
Publish through the API
Section titled “Publish through the API”Once a person has approved the request (in the Studio, Publish requests → the request → Approve this
version), the token may publish it. base_generation is the newest release you have seen, 0 before the
first:
const { response: current } = await cms.getChangeset(request.data.id);const releases = await cms.listReleases();const release = await cms.publishChangeset( request.data.id, { base_generation: releases.data[0]?.generation ?? 0 }, { ifMatch: current.etag, idempotencyKey: newIdempotencyKey() },);const receipt = await cms.getReceipt(release.data.generation);console.log(receipt.data.label, receipt.data.deliveries);The answers are those in Publish through the API. If another
release went out after the one you named, publishChangeset is refused with 409 generation_moved: read the
releases again, check what changed, and publish on top of the new one.
Every method
Section titled “Every method”Every method takes an optional signal (an AbortSignal) with its other options. { idempotencyKey },
{ ifMatch } and { ifMatch, idempotencyKey } are required where shown. Routes are under
/api/v1/projects/{project}/environments/{environment}.
Entries
| Method | Route |
|---|---|
listEntries(collection, { limit, cursor, q, created_by, locale }) |
GET collections/{collection}/entries |
getEntry(collection, entry) |
GET …/entries/{entry}; its ETag is the next save’s ifMatch |
createEntry(collection, document, { idempotencyKey, locale }) |
POST …/entries |
saveEntry(collection, entry, document, { ifMatch, idempotencyKey, locale }) |
PUT …/entries/{entry} |
deleteEntry(collection, entry, { ifMatch, idempotencyKey }) |
DELETE …/entries/{entry}; refused with 409 still_referenced while anything still refers to it |
entryHistory(collection, entry) |
GET …/entries/{entry}/revisions |
getRevision(collection, entry, revision) |
GET …/revisions/{revision} |
queryEntries(collection, document, { cursor }) |
POST …/entries/query: the query document, over drafts |
Content types
| Method | Route |
|---|---|
listContentTypes() |
GET content-types |
getContentType(slug) |
GET content-types/{slug} |
createContentType(body, { idempotencyKey }) |
POST content-types |
updateContentType(slug, definition, { ifMatch, idempotencyKey }) |
PUT content-types/{slug} |
deleteContentType(slug, { ifMatch, idempotencyKey }) |
DELETE content-types/{slug}; only an empty one |
Publish requests and releases
| Method | Route |
|---|---|
listChangesets() |
GET changesets |
getChangeset(changeset) |
GET changesets/{changeset}; its ETag is the hash later steps send |
createChangeset({ title, entries, unpublish }, { idempotencyKey }) |
POST changesets |
submitChangeset(changeset, { ifMatch }) |
POST …/submit |
reviewChangeset(changeset, { decision, comment, stage }, { ifMatch }) |
POST …/reviews; decision is approve or request_changes |
publishChangeset(changeset, { base_generation }, { ifMatch, idempotencyKey }) |
POST …/publish |
listReleases() |
GET releases, newest first (the first page) |
getReceipt(generation) |
GET releases/{generation}: the receipt |
Comments and tasks
| Method | Route |
|---|---|
listComments(collection, entry, { limit, cursor, revision, state }) |
GET …/entries/{entry}/comments |
getComment(collection, entry, comment) |
GET …/comments/{comment} |
createComment(collection, entry, { revision, body, field }, { idempotencyKey }) |
POST …/comments |
resolveComment(collection, entry, comment, { ifMatch, idempotencyKey }) |
POST …/comments/{comment}/resolve |
reopenComment(collection, entry, comment, { ifMatch, idempotencyKey }) |
POST …/comments/{comment}/reopen |
listTasks({ status, collection, entry, assignee, limit, cursor }) |
GET tasks |
getTask(task) |
GET tasks/{task} |
createTask({ entry, title, revision, changeset, assignee }, { idempotencyKey }) |
POST tasks |
updateTask(task, { title, assignee, status }, { ifMatch, idempotencyKey }) |
PATCH tasks/{task}; status is open, done or cancelled |
Schema migrations, media and permissions
| Method | Route |
|---|---|
listMigrations({ collection, state }) |
GET migrations |
getMigration(migration) |
GET migrations/{migration} |
listMigrationItems(migration, { outcome, after, limit }) |
GET migrations/{migration}/items |
listAssets() |
GET assets (the first page) |
getAsset(asset) |
GET assets/{asset}, with its renditions |
ownPermissions() |
GET permissions: what this credential may do here |
Migrations are read-only here: planning, approving and applying one is a person’s job, with
colophon migration. Image bytes come from /media/v1, not through the SDK.
For anything else (members, tokens, website connections, schedules, imports and exports, bulk jobs), the
generated types are exported as paths, operations and components, and the common schemas by name
(EntryDocument, ChangesetView, ReceiptView and others), so a call of your own is still typed. Every
route is in the API reference.
Errors
Section titled “Errors”Every failure is an ApiError, never a bare network error:
| Field | What it holds |
|---|---|
status |
The HTTP status, or 0 when no answer arrived |
code |
The error envelope’s code, or one the SDK raised itself (below) |
message |
Words safe to show a person. Don’t branch on them |
requestId |
The request id, from the envelope or the x-request-id header |
details |
The envelope’s details: reason, pointer, and whatever the refusal lists (the missing permission, the entries in the way) |
reason, pointer |
Shortcuts for details.reason and details.pointer |
etag |
The ETag the failed answer carried: on a 409, the current one |
retryAfterMs |
Retry-After in milliseconds on a 429, capped at a minute |
retryable |
true when sending the same request again may succeed: no answer (status 0), 429, a 5xx, deadline_exceeded, rate_limited or unavailable. A write may still have happened when no answer came, so retry a write only with the same idempotency key. Never true for incompatible_server |
Branch on code and reason. The codes the SDK raises itself:
code |
status |
When |
|---|---|---|
no_answer |
0 |
No answer: refused connection, DNS, or timeoutMs or your signal ran out |
invalid_response |
the status | The answer wasn’t the JSON the API promises, such as a proxy’s error page |
response_too_large |
the status | The answer ran past maxBodyBytes |
incompatible_server |
0 |
compat: 'throw' and the server doesn’t fit; nothing was sent |
The client never retries by itself. When you retry a write, send the same idempotency key, so a write whose answer was lost isn’t made twice:
import { ApiError, Client, newIdempotencyKey } from '@colophon-cms/sdk';
// One key for the logical write, reused by every attempt.async function createWithRetry(cms, collection, document, attempts = 3) { const idempotencyKey = newIdempotencyKey(); for (let attempt = 1; ; attempt++) { try { return await cms.createEntry(collection, document, { idempotencyKey }); } catch (error) { if (!(error instanceof ApiError) || !error.retryable || attempt === attempts) throw error; console.log(`attempt ${attempt}: ${error.code}, trying again with the same key`); await new Promise((resolve) => setTimeout(resolve, error.retryAfterMs ?? 500 * attempt)); } }}
// Against a server that isn't there:const cms = new Client({ baseUrl: 'http://127.0.0.1:9', token: 'not-a-real-token', compat: 'off' }).environment('field-notes');try { await createWithRetry(cms, 'recipes', { dish: 'Parkin', minutes: 90 });} catch (error) { console.log('gave up:', error.code, error.retryable);}node retry.mjsattempt 1: no_answer, trying again with the same keyattempt 2: no_answer, trying again with the same keygave up: no_answer trueThe third failure is thrown. A 409, 403 or 422 answers the same every time, so retryable is
false for them.
If you call the API with your own fetch, errorOf(body) reads a parsed body as the error envelope’s error
object (code, message, details, request_id), or null when it isn’t one.
Is this SDK right for the server?
Section titled “Is this SDK right for the server?”Before 1.0, each minor release may change the API, so the SDK and the server must be on the same minor
version (any 0.1.x with any 0.1.x), the server must serve API v1, and it must be at least the oldest
server this SDK supports (OLDEST_SERVER, 0.1.0-alpha.1). The colophon CLI uses the same rule.
client.compatibility() reads the server’s /version and says whether it fits:
import { Client } from '@colophon-cms/sdk';
const fit = await new Client({ baseUrl: 'https://cms.example.com' }).compatibility();console.log(fit);node fit.mjs{ compatible: true, sdk: '0.1.0-alpha.1', server: '0.1.0-alpha.1', api: [ 'v1' ]}When it doesn’t fit, misfit is a stable code (api_dropped, api_not_yet, later_line, earlier_line,
before_oldest, no_version_report) and reason says which side to upgrade. Against a server on 0.2.0:
@colophon-cms/sdk 0.1.0-alpha.1 is too old for the server at https://cms.example.com, which runs 0.2.0: before 1.0 each minor release may change the API, so the SDK and the server must share a minor version, and the server is on a later one (0.1 here, 0.2 there). Install @colophon-cms/[email protected] to match it.The client also checks once by itself, before its first API call, as the compat option says:
'warn'(the default): printsreasonwithconsole.warnif the server doesn’t fit, and never delays or fails a call;'throw': waits for the check, then fails every call withincompatible_serverwhile the server doesn’t fit, sending nothing;'off': never asks.
A check that gets no answer decides nothing and is tried again on the next call. livez(), readyz() and
version() never wait for it.
Draft preview on your own site
Section titled “Draft preview on your own site”When an editor presses Preview in the Studio, your site receives a one-time code and trades it for a
short-lived preview token. The SDK has the pieces, built on the standard Request and Response, so they
work in any framework:
createPreviewHandler({ baseUrl, project, isAllowedPath }): your site’s preview route. It exchanges the code, keeps the token in anHttpOnlycookie and redirects to the page, never to another site;previewTokenFromRequest(request): the token from that cookie, ornull;previewClient({ baseUrl, project }).reader(token):list,getandquerythat see the draft;previewHeaders({ studioOrigin }): headers for a preview page, so no cache keeps it, no search engine indexes it, and only the Studio may frame it.
exitPreviewHandler() clears the cookie, and listenForDraftUpdates({ studioOrigin, previewing }) reloads
the page in the browser after each save. Setting up the preview address and the whole flow is on
Preview.
What’s next
Section titled “What’s next”Was this page helpful?
Either answer opens a short issue on GitHub, so you can say what worked or what was missing.
Colophon home · the product, its blog and how to try it.