- TypeScript 87.7%
- JavaScript 12.3%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
|
All checks were successful
Publish / Stage release on npmjs.com (push) Successful in 26s
Merge pull request #2: release 4.0.1 |
||
| .github/workflows | ||
| scripts | ||
| specs | ||
| src | ||
| test | ||
| .gitattributes | ||
| .gitignore | ||
| CHANGELOG.md | ||
| LICENSE | ||
| package.json | ||
| README.md | ||
| tsconfig.build.json | ||
| tsconfig.json | ||
| yarn.lock | ||
@ulyxie/cs-rest
Simple authentication and REST calls for OpenText Content Server.
Note
This is a fork of
@kweli/cs-restby Christopher Meyer / Kwe.li GmbH, republished under the@ulyxiescope so that the OpenText Content Server n8n nodes depend on a package we control. MIT licensed; the original copyright notice is retained in LICENSE.From 4.0.0 this fork goes its own way. 3.1.4 was byte-identical to upstream 3.1.4; 4.0.0 is a rewrite: a method for every Content Server REST endpoint, version gating, normalised results, optional modules, and no runtime dependencies. See CHANGELOG.md for what changed and how to migrate.
Features
- Provides a simplified interface for managing authentication with the OpenText Content Server REST API
- Refreshes the
OTCSTickettoken automatically (minimising token expiration errors) - Simplifies POST, PUT, & PATCH requests (since Content Server doesn't support the
application/jsoncontent type) - No runtime dependencies: requests go through Node's own
http/httpsin Node andfetchin Bun and browsers, with axios available as an opt-in transport - Streams uploads and downloads of any size, in every runtime
- Works in Node.js (20.19+), Bun and the browser, as ES modules
- Optional handlers are separate imports, so a browser bundle carries only the parts it uses
Breaking Changes v2
- The
baseURLparameter was renamedbaseUrl.
Installing
Using npm:
npm install @ulyxie/cs-rest
Using yarn:
yarn add @ulyxie/cs-rest
Needs Node.js 20.19 or newer, Bun, or a current browser. The package is ES
modules only; require() works on the Node releases that can load them
(20.19+, 22.12+).
In a web page, without a build step
The package is plain ES modules, so a page can load it straight from a CDN or your own server. Pin the version.
From esm.sh, with no setup:
<script type="module">
import { Session } from "https://esm.sh/@ulyxie/cs-rest@4.0.1";
import "https://esm.sh/@ulyxie/cs-rest@4.0.1/workspaces"; // modules work the same way
const session = new Session({ baseUrl: "https://server/otcs/cs.exe", username, password });
const { result } = await session.nodes.node(2000);
</script>
Or the exact npm files, from jsDelivr, unpkg or your own web server (copy
node_modules/@ulyxie/cs-rest/lib/ onto it). An import map tells the browser
where #platform - the switch between the Node and browser code - lives:
<script type="importmap">
{ "imports": { "#platform": "https://cdn.jsdelivr.net/npm/@ulyxie/cs-rest@4.0.1/lib/platform/browser.js" } }
</script>
<script type="module">
import { Session } from "https://cdn.jsdelivr.net/npm/@ulyxie/cs-rest@4.0.1/lib/index.js";
import "https://cdn.jsdelivr.net/npm/@ulyxie/cs-rest@4.0.1/lib/modules/workspaces.js";
</script>
- Do not use jsDelivr's
/+esmURLs: they bundle each entry point separately, so a module could end up with its own copy ofSessionand never attach to yours. - Either way the browser calls Content Server directly, so the server must
allow the page's origin: Administration > Server Configuration > Configure
Security Parameters > Trusted CORS Domain. A page opened as
file://has the originnull, which cannot be allowed - serve it over HTTP. - Paths for uploads and
download()to disk are Node and Bun only; in a page, upload aFileorBloband read content as aBlobor stream.
Example
Authenticate with a username and password and get the details of a node:
import { Session } from "@ulyxie/cs-rest";
const session = new Session({
baseUrl: "https://.../cs.exe",
username: "Admin",
password: "******",
});
// a Session instance can issue authenticated requests to Content Server
const response = await session.get("/api/v1/nodes/2000");
Authenticate with an OTCSTicket:
const session = new Session({
baseUrl: "https://.../cs.exe",
otcsticket: "<token>",
});
cs-rest API
Requests can be made with the get, post, put, patch, delete, head and options methods on the Session instance. They take a URL relative to baseUrl (or an absolute one), a body for the writes, and { params, headers, responseType, signal }, and resolve with { data, status, statusText, headers }. JSON is parsed; responseType can ask for "text", "arraybuffer", "blob" or "stream" instead.
A status outside 2xx rejects with an HTTPError, which carries the response as error.response - the same shape an axios error had:
import { isHTTPError } from "@ulyxie/cs-rest";
try {
await session.nodes.node(12345);
} catch (e) {
if (isHTTPError(e)) console.log(e.response.status, e.response.data.error);
}
Content Server returns a fresh OTCSTicket with each successful API call. The Session instance automatically retains it for the subsequent request.
POST, PUT, & PATCH
The OpenText Content Server REST API doesn't accept requests that use the application/json content type. This means POST, PUT, & PATCH requests need to use a content type of multipart/form-data, which makes writing a request a little more verbose. For example, to create a new folder:
const formData = new FormData();
formData.append("type", 0);
formData.append("parent_id", 2000);
formDAta.append("name", "My New Folder");
const response = await session.post("api/v2/nodes", formData);
The Session class provides a postForm (also putForm and patchForm) method to simplify this:
const response = await session.postForm("api/v2/nodes", {
type: 0,
parent_id: 2000,
name: "My New Folder",
});
Transports
In Node, requests go through Node's own http / https; in Bun and browsers,
through fetch. Node is the exception because its fetch holds an upload's
whole body in memory before sending it. Every default streams uploads and
downloads.
In Node, pass an agent for a private CA, a proxy or a custom DNS lookup:
import https from "node:https";
const session = new Session({ baseUrl, otcsticket, agent: new https.Agent({ ca: readFileSync("corp-ca.pem") }) });
NODE_EXTRA_CA_CERTS works too, with no code. A proxy takes a proxy agent such
as https-proxy-agent. Or
pass fetch to send through a fetch of your own (in Node, uploads then sit
in memory until sent).
Or send them through axios, for its proxy and agent support or its interceptors. axios is an optional peer dependency - install it yourself:
import axios from "axios";
import { axiosTransport } from "@ulyxie/cs-rest/axios";
const session = new Session({ baseUrl, otcsticket, transport: axiosTransport(axios.create({ httpsAgent })) });
Responses and errors look the same whichever transport sends them. A
transport is just (request) => Promise<response>, so a custom one is a few
lines; see TTransport.
Wrapper
Every operation in the Content Server 26.2 REST API spec has a method, as does
every route the core restapi module of a live 26.1 server registers, including
the undocumented ones. They are grouped into handlers on the Session.
The core handlers are always there:
| Handler | Covers |
|---|---|
session.nodes |
create, copy, move, update, delete, children, content, thumbnails, actions, nicknames, sharing, templates, notifications, reservations |
session.versions |
versions, their content, renditions, thumbnails, promote / lock |
session.categories |
applying and updating categories, inheritance, apply-down, TKL values |
session.permissions |
owner, group, public, Assigned Access and dynamic permissions |
session.members |
users, groups, membership, favorites, sessions, proxies, module assignments |
session.volumes |
volumes, the Recycle Bin |
session.search |
search, regions, slices, facets, display settings |
session.uploads |
Large File Upload |
session.forms |
the Alpaca forms behind each action |
session.server |
server info, privileges, system health, settings |
session.auth |
the current user and session |
The rest are modules. Import one once, anywhere in your app, and its
handler appears on every Session; until then it is left out of your bundle,
and using it throws an error naming the import:
import { Session } from "@ulyxie/cs-rest";
import "@ulyxie/cs-rest/workflow";
const startForm = await session.workflow.start(mapId);
| Import | Adds | Covers |
|---|---|---|
@ulyxie/cs-rest/workflow |
session.workflow |
draft processes, initiating, sending on, status |
@ulyxie/cs-rest/webreports |
session.webreports |
running WebReports, parameters, destinations |
@ulyxie/cs-rest/viewx |
session.viewx |
Intelligent Viewing |
@ulyxie/cs-rest/perspectives |
session.perspectives |
Smart View perspectives |
@ulyxie/cs-rest/reminders |
session.reminders |
follow-ups and reminders |
@ulyxie/cs-rest/signatures |
session.signatures |
DocuSign / Core Signature requests |
@ulyxie/cs-rest/ai |
session.ai |
Content Aviator |
@ulyxie/cs-rest/recman |
session.recman |
Records Management: RM classifications, holds, RSIs, security clearances, cross-references, disposition |
@ulyxie/cs-rest/physical-objects |
session.physicalObjects |
Physical Objects: borrowing, requests, locators, transfers, labels, circulation |
@ulyxie/cs-rest/classifications |
session.classifications |
classification trees |
@ulyxie/cs-rest/video |
session.video |
video comments, clips and conversion |
@ulyxie/cs-rest/wopi |
session.wopi |
Office Online (WOPI): file info, locks, launch, set-up |
@ulyxie/cs-rest/office |
session.office |
Microsoft 365 integration: Outlook items, OneDrive / SharePoint drives, content-type mapping; Extended ECM for Microsoft 365 (Teams, groups, archiving) |
@ulyxie/cs-rest/email |
session.email |
Email management: email properties, settings, metadata query and upgrade |
@ulyxie/cs-rest/forums |
session.forums |
Discussion forums: search, following, full post content |
@ulyxie/cs-rest/notifications |
session.notifications |
The Message Center's messages and preferences, and watching items |
@ulyxie/cs-rest/pulse |
session.pulse |
Pulse: statuses, comments, activity feeds, profiles, presence, collaboration settings |
@ulyxie/cs-rest/regulated |
session.regulated |
Regulated documents: controlled copies and viewing rules, category audit, 21 CFR Part 11 e-signatures |
@ulyxie/cs-rest/salesforce |
session.salesforce |
The Salesforce integration: licence checks, bulk Pulse entries |
@ulyxie/cs-rest/sharepoint-archive |
session.sharePointArchive |
Enterprise Archive for SharePoint: the ArchiveLink filter, orphaned entries |
@ulyxie/cs-rest/sharing |
session.sharing |
Content Sharing: shares and shared items, providers, Core Share settings |
@ulyxie/cs-rest/syndication |
session.syndication |
Syndication: remote sites, syndicating and consolidating content |
@ulyxie/cs-rest/webedit |
session.webedit |
WebEdit: desktop-client options and printing |
@ulyxie/cs-rest/wiki |
session.wiki |
Wikis: pages, links, previews, version comparison, autosave |
@ulyxie/cs-rest/workspaces |
session.workspaces |
Extended ECM business workspaces: listing, creating and reading them, types, members and roles, related workspaces, documents, references, business attachments, business objects and external systems, completeness checks |
@ulyxie/cs-rest/event-action-center |
session.eventActionCenter |
Extended ECM Event Action Center: event definitions, action plans, processing events |
@ulyxie/cs-rest/smart-document-types |
session.smartDocumentTypes |
Extended ECM Smart Document Types, their rules and bots, scheduled bots and jobs |
@ulyxie/cs-rest/government |
session.government |
Extended ECM for Government: inbox, assignments, forwarding, e-files, printing, xdomea |
@ulyxie/cs-rest/admin |
session.admin |
installation, licences, modules, OTDS, cluster and database upgrade |
@ulyxie/cs-rest/rpc |
session.rhcore, session.rpcClient() |
RHCore script calls and the JSON-RPC client |
session.use(Handler) reaches a handler without its getter, and
registerModule(name, Handler) attaches one of your own the same way the
modules do (extend ServiceAbstract, and augment the SessionModules
interface for its type).
Methods for routes OpenText does not document return TUndocumented and say so
in their JSDoc, along with anything about the request that is unverified.
npm run coverage reports which spec operations have a method (-- --missing, -- --skipped for detail).
v1 and v2
A method name says which API generation it calls: unsuffixed methods call
v2, and methods ending in V1 call v1.
await session.nodes.node(2000); // GET /v2/nodes/2000
await session.nodes.nodeV1(2000); // GET /v1/nodes/2000
await session.nodes.ancestorsV1(2000); // v1 only - there is no v2 equivalent
A V1 method with a v2 counterpart is marked @deprecated; one where v1 is the
only generation is not. The few v3 routes a server registers end in V3
(server.statusV3()).
Normalised results
Methods that return a known kind of entity - nodes, versions, members,
volumes, permissions, categories, search results, audit events, renditions,
Alpaca forms, workflows and assignments, and the modules' business
workspaces, WebReports parameters, perspectives, Pulse statuses and more (see
the wiki's Normalised Results page) - also carry
response.result: the same content, read the same way whichever API
generation served it. response.data is still the body exactly as the server
sent it.
const { result: folder } = await session.nodes.node(2000); // v2
const { result: same } = await session.nodes.nodeV1(2000); // v1 - same fields
folder.name === same.name; // true
const { result: page } = await session.nodes.children(2000, { limit: 10 });
page.items; // TNode[]
page.paging; // { page, limit, page_total, total_count, range_min, range_max }
Field names are Content Server's own - v1 and v2 already agree on them; what
differs between the generations is the envelope around them, which is what
result removes. It also corrects the spec where the spec is wrong: the
generated types say single-item responses are arrays at every level, and a real
server sends objects.
The normalisers are exported as normalize for bodies fetched some other way,
e.g. normalize.node((await session.get("api/v2/nodes/2000")).data).
Examples
const folder = await session.nodes.addFolder(2000, "My New Folder");
await session.nodes.move(12345, 2000);
await session.categories.apply(12345, 9830, { "9830_2": "a value" });
await session.permissions.addCustom(12345, { right_id: 1000, permissions: ["see", "see_contents"] });
Uploads accept a path on disk (Node and Bun, streamed rather than read into memory), a
browser File or Blob, or { data, name } for bytes already in memory - the
form to use for a Node Buffer:
await session.nodes.addDocument({ parent_id: 2000, fileHandler: "c:/temp/file.pdf" });
await session.nodes.addDocument({ parent_id: 2000, fileHandler: { data: buffer, name: "file.pdf" } });
// Too big for one request? Send it through Large File Upload instead.
await session.nodes.addDocument({ parent_id: 2000, fileHandler: "c:/temp/huge.iso", largeFile: true });
Content Server versions
specs/ holds the OpenAPI document for every Content Server release from 20.3 to 26.2. Types are generated from the newest; diffing all of them yields, per endpoint, the release it first appeared in. content-server-rest-api-26.1-live.yaml sits alongside them but is not a published spec: it lists every /api route a live 26.1 server registers, including undocumented ones such as /v3/status. The type generator ignores it; the capability generator reads it only to avoid marking an endpoint removed that the server still serves.
That lets a Session be told which release it is talking to, so a call to an endpoint that release does not have fails immediately and says why, instead of returning an opaque Content Server error:
import { Session, CSVersion, isUnsupportedOperationError } from "@ulyxie/cs-rest";
const session = new Session({
baseUrl: "https://.../cs.exe",
otcsticket: "<token>",
version: CSVersion.V22_1, // or the string "22.1"
});
try {
await session.volumes.recycleBin();
} catch (e) {
if (isUnsupportedOperationError(e)) {
// "GET /v2/volumes/recyclebin/nodes is not available on Content Server
// 22.1: it arrived in 22.4."
console.log(e.operation, e.since);
}
}
version defaults to "latest", which gates nothing — omit it and the client behaves exactly as it did before. To branch instead of rejecting, ask first:
if (session.supports("GET /v2/volumes/recyclebin/nodes")) {
// ...
}
Detecting the version
Rather than being told the release, a Session can ask the server for it once. This is opt-in, because it costs a /v1/serverinfo request that a session gating nothing has no use for:
const session = new Session({
baseUrl: "https://.../cs.exe",
otcsticket: "<token>",
detectVersion: true,
});
await session.resolveVersion(); // "26.1", read from the server
Calling resolveVersion() is optional — every handler call awaits it internally, so the first one resolves the release before its gate is checked rather than racing it. Detection happens once and is cached.
Detection never rejects: a server that cannot be reached or read leaves version at whatever it was given and warns, because failing to discover a version is not a reason to fail the call you actually wanted.
Anything that silently changes which release you gate against warns as well, in yellow on a terminal:
| What happened | Warning |
|---|---|
| Server reports a release with no spec here (21.2 and 23.2 shipped without one) | rounded down to the nearest release below, naming it |
| Server is newer than 26.2 | gated as 26.2, and says newer endpoints pass unchecked |
Detection overrode a version you configured |
names both, and how to keep yours |
Release predates 20.3 (16.x numbered itself 16.2.3) |
cannot be placed; gating stays as configured |
Discovering a release when you configured none is not a correction, so that stays quiet. Colour is dropped when output is not a terminal, in browsers, and under NO_COLOR.
The release is also available in full via session.server.infoV1().
Two caveats. The gate reflects what the published specs document, not what a given server actually does: OpenText never published a document for 21.2 or 23.2, so an endpoint attributed to 23.3 may in fact have shipped in 23.2, and since is a lower bound. And an endpoint no spec documents at all is treated as available — the check guards against a knowably-missing endpoint rather than acting as an allowlist.
Both generated files are rebuilt from specs/:
npm run generate:types && npm run generate:capabilities