@dotcms/client 0.0.1-beta.9 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +565 -153
  2. package/index.cjs.js +1418 -741
  3. package/index.esm.js +1418 -732
  4. package/internal.cjs.d.ts +1 -0
  5. package/internal.cjs.default.js +1 -0
  6. package/internal.cjs.js +85 -0
  7. package/internal.cjs.mjs +2 -0
  8. package/internal.esm.d.ts +1 -0
  9. package/internal.esm.js +83 -0
  10. package/package.json +14 -17
  11. package/src/index.d.ts +1 -8
  12. package/src/internal.d.ts +1 -0
  13. package/src/lib/client/client.d.ts +1 -29
  14. package/src/lib/client/content/builders/collection/collection.d.ts +1 -1
  15. package/src/lib/client/content/content-api.d.ts +3 -6
  16. package/src/lib/client/content/shared/types.d.ts +1 -42
  17. package/src/lib/client/navigation/navigation-api.d.ts +3 -20
  18. package/src/lib/client/page/page-api.d.ts +14 -84
  19. package/src/lib/utils/graphql/transforms.d.ts +2 -13
  20. package/src/lib/utils/index.d.ts +0 -1
  21. package/next.cjs.d.ts +0 -1
  22. package/next.cjs.default.js +0 -1
  23. package/next.cjs.js +0 -553
  24. package/next.cjs.mjs +0 -2
  25. package/next.esm.d.ts +0 -1
  26. package/next.esm.js +0 -551
  27. package/src/lib/client/models/types.d.ts +0 -516
  28. package/src/lib/deprecated/editor/listeners/listeners.d.ts +0 -45
  29. package/src/lib/deprecated/editor/models/client.model.d.ts +0 -111
  30. package/src/lib/deprecated/editor/models/editor.model.d.ts +0 -62
  31. package/src/lib/deprecated/editor/models/inline-event.model.d.ts +0 -9
  32. package/src/lib/deprecated/editor/models/listeners.model.d.ts +0 -55
  33. package/src/lib/deprecated/editor/sdk-editor-vtl.d.ts +0 -1
  34. package/src/lib/deprecated/editor/sdk-editor.d.ts +0 -92
  35. package/src/lib/deprecated/editor/utils/editor.utils.d.ts +0 -159
  36. package/src/lib/deprecated/editor/utils/traditional-vtl.utils.d.ts +0 -4
  37. package/src/lib/deprecated/sdk-js-client.d.ts +0 -276
  38. package/src/lib/utils/page/common-utils.d.ts +0 -33
  39. package/src/next.d.ts +0 -1
  40. package/src/types.d.ts +0 -2
  41. package/transforms.cjs.js +0 -1145
  42. package/transforms.esm.js +0 -1139
  43. package/types.cjs.d.ts +0 -1
  44. package/types.cjs.default.js +0 -1
  45. package/types.cjs.js +0 -2
  46. package/types.cjs.mjs +0 -2
  47. package/types.esm.d.ts +0 -1
  48. package/types.esm.js +0 -1
package/README.md CHANGED
@@ -1,258 +1,670 @@
1
- # dotCMS API Client - `@dotcms/client`
1
+ # dotCMS Client SDK
2
2
 
3
- The `@dotcms/client` is a JavaScript/TypeScript library for interacting with a dotCMS instance. It allows you to easily fetch pages, content, and navigation information in JSON format, as well as to make complex queries on content collections.
3
+ The `@dotcms/client` is a powerful JavaScript/TypeScript SDK designed to simplify the integration of dotCMS content into your applications. Whether building dynamic websites or content-driven apps, this SDK offers an intuitive API for seamless and type-safe content retrieval, enabling you to create engaging experiences effortlessly by accessing and displaying content from dotCMS.
4
4
 
5
- This client library provides a streamlined, promise-based interface to fetch pages and navigation API.
5
+ ### When to Use It:
6
6
 
7
- ## Features
7
+ - Building headless frontends that need dotCMS content
8
+ - Building content-driven apps that need to access dotCMS content
9
+ - Developing multi-language or personalized experiences
10
+ - Implementing dynamic navigation and page structures
8
11
 
9
- - Easy-to-use methods to interact with [dotCMS pages](https://www.dotcms.com/docs/latest/page-rest-api-layout-as-a-service-laas) and the [Navigation API](https://www.dotcms.com/docs/latest/navigation-rest-api).
10
- - Support for custom actions to communicate with the dotCMS page editor.
11
- - Comprehensive TypeScript typings for better development experience.
12
+ ### Key Benefits:
12
13
 
13
- # dotCMS API Client
14
+ - **Simplified Development**: Write less code with intuitive methods and builders
15
+ - **Type Safety**: Built-in TypeScript definitions prevent runtime errors
16
+ - **Universal Compatibility**: Works in both browser and Node.js environments
17
+ - **Security First**: Handles authentication and requests securely
18
+ - **Developer Experience**: Rich autocompletion and documentation
14
19
 
15
- ## Installation
20
+ ## Table of Contents
16
21
 
17
- To get started, install the client via npm or yarn:
22
+ - [Prerequisites & Setup](#prerequisites--setup)
23
+ - [Get a dotCMS Environment](#get-a-dotcms-environment)
24
+ - [Create a dotCMS API Key](#create-a-dotcms-api-key)
25
+ - [Installation](#installation)
26
+ - [Quickstart](#quickstart)
27
+ - [Example Projects](#example-projects)
28
+ - [Key Concepts](#key-concepts)
29
+ - [Choosing the Right Method](#choosing-the-right-method)
30
+ - [Start with `page.get()`: The One-Request Solution](#start-with-pageget-the-one-request-solution)
31
+ - [API Reference](#api-reference)
32
+ - [Client Initialization](#client-initialization)
33
+ - [client.page.get(): Fetching Page Content](#clientpageget-fetching-page-content)
34
+ - [client.navigation.get(): Fetching Navigation Structure](#clientnavigationget-fetching-navigation-structure)
35
+ - [client.content.getCollection(): Fetching Content Collections](#clientcontentgetcollection-fetching-content-collections)
36
+ - [Using the SDK with TypeScript](#using-the-sdk-with-typescript)
37
+ - [Usage Example](#usage-example)
38
+ - [How to Enable Page Editing in dotCMS](#how-to-enable-page-editing-in-dotcms)
39
+ - [Use an Official SDK](#use-an-official-sdk)
40
+ - [⚠️ Advanced Only: Custom UVE Integration](#advanced-only-custom-uve-integration)
41
+ - [dotCMS Support](#dotcms-support)
42
+ - [How To Contribute](#how-to-contribute)
43
+ - [Licensing Information](#licensing-information)
18
44
 
19
- ```bash
20
- npm install @dotcms/client
21
- ```
45
+ ## Prerequisites & Setup
46
+
47
+ ### Get a dotCMS Environment
48
+
49
+ #### Version Compatibility
50
+
51
+ - **Recommended**: dotCMS Evergreen
52
+ - **Minimum**: dotCMS v25.05
53
+ - **Best Experience**: Latest Evergreen release
54
+
55
+ #### Environment Setup
56
+
57
+ **For Production Use:**
58
+
59
+ - ☁️ [Cloud hosting options](https://www.dotcms.com/pricing) - managed solutions with SLA
60
+ - 🛠️ [Self-hosted options](https://dev.dotcms.com/docs/current-releases) - deploy on your infrastructure
61
+
62
+ **For Testing & Development:**
63
+
64
+ - 🧑🏻‍💻 [dotCMS demo site](https://demo.dotcms.com/dotAdmin/#/public/login) - perfect for trying out the SDK
65
+ - 📘 [Learn how to use the demo site](https://dev.dotcms.com/docs/demo-site)
66
+ - 📝 Read-only access, ideal for building proof-of-concepts
67
+
68
+ **For Local Development:**
69
+
70
+ - 🐳 [Docker setup guide](https://github.com/dotCMS/core/tree/main/docker/docker-compose-examples/single-node-demo-site)
71
+ - 💻 [Local installation guide](https://dev.dotcms.com/docs/quick-start-guide)
72
+
73
+ ### Create a dotCMS API Key
74
+
75
+ > [!TIP]
76
+ > Make sure your API Token has read-only permissions for Pages, Folders, Assets, and Content. Using a key with minimal permissions follows security best practices.
77
+
78
+ This integration requires an API Key with read-only permissions for security best practices:
22
79
 
23
- Or using Yarn:
80
+ 1. Go to the **dotCMS admin panel**.
81
+ 2. Click on **System** > **Users**.
82
+ 3. Select the user you want to create the API Key for.
83
+ 4. Go to **API Access Key** and generate a new key.
84
+
85
+ For detailed instructions, please refer to the [dotCMS API Documentation - Read-only token](https://dev.dotcms.com/docs/rest-api-authentication#ReadOnlyToken).
86
+
87
+ ### Installation
88
+
89
+ Install the SDK and required dependencies:
24
90
 
25
91
  ```bash
26
- yarn add @dotcms/client
92
+ npm install @dotcms/client@latest @dotcms/types@latest
27
93
  ```
28
94
 
29
- ## Usage
95
+ > [!TIP]
96
+ > If you are working with pure JavaScript, you can avoid installing the `@dotcms/types` package.
30
97
 
31
- `@dotcms/client` supports both ES modules and CommonJS. You can import it using either syntax:
98
+ ## Quickstart: Basic Setup Example
32
99
 
33
- ### ES Modules
100
+ Here's a basic setup of the dotCMS Client SDK to help you get started:
34
101
 
35
- ```javascript
36
- import { DotCmsClient } from '@dotcms/client';
37
- ```
102
+ ```typescript
103
+ import { createDotCMSClient } from '@dotcms/client';
38
104
 
39
- ### CommonJS
105
+ // Create a client instance
106
+ const client = createDotCMSClient({
107
+ dotcmsUrl: 'https://your-dotcms-instance.com',
108
+ authToken: 'your-auth-token', // Optional for public content
109
+ siteId: 'your-site-id' // Optional site identifier
110
+ });
40
111
 
41
- ```javascript
42
- const { DotCmsClient } = require('@dotcms/client');
112
+ // Start using the client!
113
+ const { pageAsset } = await client.page.get('/about-us');
114
+ console.log(pageAsset.page.title);
43
115
  ```
44
116
 
45
- ### Initialization
117
+ ### Full-Stack Example Projects Using the SDK
118
+
119
+ While there isn't a dedicated example project specifically for the client SDK, you can see it in action within these full-stack examples:
120
+
121
+ - [Next.js Example](https://github.com/dotCMS/core/tree/main/examples/nextjs) - Modern React-based SSR implementation
122
+ - [Angular Example](https://github.com/dotCMS/core/tree/main/examples/angular) - Enterprise Angular implementation
123
+ - [Astro Example](https://github.com/dotCMS/core/tree/main/examples/astro) - Astro implementation
124
+
125
+ These examples demonstrate how to use the client SDK as part of a complete web application.
126
+
127
+ ## Key Concepts
128
+
129
+ | Term | Description | Documentation |
130
+ | ------------ | ----------------------------------------------------- | ------------------------------------------------------------------------------ |
131
+ | `pageAsset` | The page data structure containing layout and content | [Page API](https://dev.dotcms.com/docs/page-rest-api-layout-as-a-service-laas) |
132
+ | `contentlet` | A single piece of content in dotCMS | [Content API](https://dev.dotcms.com/docs/content) |
133
+ | `collection` | A group of contentlets of the same type | [Content API](https://dev.dotcms.com/docs/search) |
134
+ | `graphql` | Query language used to extend API responses | [GraphQL](https://dev.dotcms.com/docs/graphql) |
135
+
136
+ ## Choosing the Right Method
137
+
138
+ The dotCMS Client SDK provides three core methods for fetching data. Use this quick guide to decide which one is best for your use case:
139
+
140
+ | Method | Use When You Need... | Best For |
141
+ | -------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
142
+ | [`client.page.get()`](#clientpageget-fetching-page-content) | A full page with layout, containers, and related content | **Rendering entire pages** with a single request. Ideal for headless setups, SSR/SSG frameworks, and cases where you want everything—page structure, content, and navigation—tied to a URL path. |
143
+ | [`client.content.getCollection()`](#clientcontentgetcollection-fetching-content-collections) | A filtered list of content items from a specific content type | Populating dynamic blocks, lists, search results, widgets, or reusable components. |
144
+ | [`client.navigation.get()`](#clientnavigationget-fetching-navigation-structure) | Only the site's navigation structure (folders and links) | Standalone menus or use cases where navigation is needed outside of page context. |
46
145
 
47
- First, initialize the client with your dotCMS instance details.
146
+ ### Start with `page.get()`: The One-Request Solution
48
147
 
49
- ```javascript
50
- const client = DotCmsClient.init({
148
+ For most use cases, `client.page.get()` is all you need. It lets you retrieve:
149
+
150
+ - The full page layout
151
+ - Related content
152
+ - Navigation structure
153
+
154
+ All in a single request using GraphQL.
155
+
156
+ Only use `content.getCollection()` or `navigation.get()` if you have advanced needs, like real-time data fetching or building custom dynamic components.
157
+
158
+ > 🔍 **For an example of how to bundle content and navigation in one `page.get()` call,** see the [advanced usage](#fetching-additional-content-with-graphql) section under `client.page.get()`.
159
+
160
+ ## API Reference
161
+
162
+ ### createDotCMSClient: Client Initialization
163
+
164
+ The `createDotCMSClient` function is the first step in using the dotCMS Client SDK. It allows you to create a new client instance with your dotCMS configuration.
165
+
166
+ | Option | Type | Required | Description |
167
+ | ---------------- | -------------- | -------- | ------------------------------------------------------------- |
168
+ | `dotcmsUrl` | string | ✅ | Your dotCMS instance URL |
169
+ | `authToken` | string | ✅ | Authentication token |
170
+ | `siteId` | string | ❌ | Site identifier (falls back to default site if not specified) |
171
+ | `requestOptions` | RequestOptions | ❌ | Additional fetch options |
172
+
173
+ #### Initialization Example
174
+
175
+ ```typescript
176
+ import { createDotCMSClient } from '@dotcms/client';
177
+
178
+ const client = createDotCMSClient({
51
179
  dotcmsUrl: 'https://your-dotcms-instance.com',
52
180
  authToken: 'your-auth-token',
53
- siteId: 'your-site-id'
181
+ siteId: 'your-site-id',
182
+ requestOptions: {
183
+ headers: { 'Custom-Header': 'value' },
184
+ cache: 'default'
185
+ }
54
186
  });
55
187
  ```
56
188
 
57
- ### Fetching a Page
189
+ ### client.page.get(): Fetching Page Content
58
190
 
59
- You can retrieve the elements of any page in your dotCMS system in JSON format using the `client.page.get()` method.
191
+ The `client.page.get()` method is your primary way to retrieve page content from dotCMS using the SDK. It abstracts away the complexity of raw REST or GraphQL calls, letting you fetch structured page data with just a single method.
60
192
 
61
- ```javascript
62
- const pageData = await client.page.get({
63
- path: '/your-page-path',
64
- language_id: 1,
65
- personaId: 'optional-persona-id'
66
- });
193
+ #### Why Use `page.get()`?
194
+
195
+ - Fetch everything needed to render a page with one call
196
+ - Avoid building multiple API queries manually
197
+ - Type-safe, customizable, and extensible with GraphQL
198
+ - Works with dotCMS content localization and personalization out of the box
199
+
200
+ #### Basic Usage
201
+
202
+ Here's the simplest way to fetch a page by its URL:
203
+
204
+ ```ts
205
+ const { pageAsset } = await client.page.get('/about-us');
206
+ console.log(pageAsset.page.title);
67
207
  ```
68
208
 
69
- ### Fetching Navigation
209
+ You can now render this content or pass it to your components.
70
210
 
71
- Retrieve the dotCMS file and folder tree to get information about the navigation structure.
211
+ #### Customizing the Request
72
212
 
73
- ```javascript
74
- const navData = await client.nav.get({
75
- path: '/',
76
- depth: 2,
77
- languageId: 1
213
+ You can customize the request to fetch different languages, rendering modes, or user personas:
214
+
215
+ ```ts
216
+ const { pageAsset } = await client.page.get('/about-us', {
217
+ languageId: '2',
218
+ fireRules: true,
219
+ personaId: '1234'
78
220
  });
79
221
  ```
80
222
 
81
- ### Fetching a Collection of Content
223
+ #### Bundling Content and Navigation in One Request
224
+
225
+ You can also pull in related content, like blog posts or navigation menus, using the `graphql` option:
226
+
227
+ ```ts
228
+ const { pageAsset, content } = await client.page.get('/about-us', {
229
+ graphql: {
230
+ page: `
231
+ title
232
+ vanityUrl {
233
+ url
234
+ }
235
+ `,
236
+ content: {
237
+ blogPosts: `
238
+ BlogCollection(limit: 3) {
239
+ title
240
+ urlTitle
241
+ }
242
+ `,
243
+ navigation: `
244
+ DotNavigation(uri: "/", depth: 2) {
245
+ href
246
+ title
247
+ children {
248
+ href
249
+ title
250
+ }
251
+ }
252
+ `
253
+ }
254
+ }
255
+ });
256
+ ```
257
+
258
+ #### Request Options
259
+
260
+ The `page.get()` method accepts an optional second argument of type [`DotCMSPageRequestParams`](https://github.com/dotCMS/core/blob/6e003eb697554ea9636a1fec59bc0fa020b84390/core-web/libs/sdk/types/src/lib/client/public.ts#L5-L54). This lets you customize how the page is fetched. Common options include:
261
+
262
+ | Option | Type | Description |
263
+ | ------------ | ---------------- | ------------------------------------------------ |
264
+ | `languageId` | string \| number | Language version of the page |
265
+ | `mode` | string | Rendering mode: `LIVE`, `PREVIEW_MODE`, etc. |
266
+ | `personaId` | string | Personalize content based on persona ID |
267
+ | `graphql` | DotCMSGraphQLParams | GraphQL options for extending the response |
268
+ | `fireRules` | boolean | Whether to trigger page rules |
269
+
270
+ The `graphql` option allows you to customize the page and content data returned. It accepts:
271
+
272
+ | Property | Type | Description |
273
+ | ----------- | -------- | ----------------------------------------------------- |
274
+ | `page` | string | GraphQL partial query that will be automatically wrapped with the page context. (you don't need to include the `page(url:"/")` wrapper in your query) |
275
+ | `content` | object | Named queries to fetch additional content |
276
+ | `fragments` | string[] | GraphQL fragments that can be reused across queries |
277
+ | `variables` | object | Variables to pass into the GraphQL queries |
278
+
279
+ > 💡 See [`DotCMSPageRequestParams`](https://github.com/dotCMS/core/blob/6e003eb697554ea9636a1fec59bc0fa020b84390/core-web/libs/sdk/types/src/lib/client/public.ts#L5-L54) for a full list of supported options.
280
+
281
+ #### Method Signature
282
+
283
+ ```ts
284
+ get<T extends DotCMSExtendedPageResponse = DotCMSPageResponse>(
285
+ url: string,
286
+ options?: DotCMSPageRequestParams
287
+ ): Promise<DotCMSComposedPageResponse<T>>;
288
+ ```
289
+
290
+ ### client.navigation.get(): Fetching Navigation Structure
82
291
 
83
- The `getCollection` method allows you to fetch a collection of content items (sometimes called "contentlets") using a builder pattern for complex queries.
292
+ The `client.navigation.get()` method fetches a structured view of a site's file and folder hierarchy from dotCMS. It's useful for building menus and navigation UIs.
84
293
 
85
294
  #### Basic Usage
86
295
 
87
- Heres a simple example to fetch content from a collection:
296
+ Here's the simplest way to fetch the root-level navigation:
88
297
 
89
- ```typescript
90
- import { DotCmsClient } from '@dotcms/client';
298
+ ```ts
299
+ const nav = await client.navigation.get('/');
300
+ console.log(nav);
301
+ ```
91
302
 
92
- const client = DotCmsClient.init({
93
- dotcmsUrl: 'https://your-dotcms-instance.com',
94
- authToken: 'your-auth-token'
95
- });
303
+ #### Customizing the Request
96
304
 
97
- const collectionResponse = await client.content
98
- .getCollection('Blog') // Collection name
99
- .limit(10) // Limit results to 10 items
100
- .page(1) // Fetch the first page
101
- .fetch(); // Execute the query
305
+ You can tailor the navigation structure using optional parameters:
102
306
 
103
- console.log(collectionResponse.contentlets);
307
+ ```ts
308
+ const nav = await client.navigation.get('/', {
309
+ depth: 2,
310
+ languageId: 1
311
+ });
104
312
  ```
105
313
 
106
- #### Sorting Content
314
+ #### Request Options
107
315
 
108
- You can sort the content by any field in ascending or descending order:
316
+ The `navigation.get()` method accepts an optional second argument with the following parameters:
109
317
 
110
- ```typescript
111
- const sortedResponse = await client.content
112
- .getCollection('Blog')
113
- .sortBy([{ field: 'title', order: 'asc' }]) // Sort by title in ascending order
114
- .fetch();
318
+ | Option | Type | Description |
319
+ | ------------ | ------ | ------------------------------------------ |
320
+ | `depth` | number | Number of child levels to include |
321
+ | `languageId` | number | Language ID for localized navigation names |
322
+
323
+ > 💡 For typical use cases, setting `depth: 2` will include top-level navigation and one level of children.
324
+
325
+ #### Method Signature
326
+
327
+ ```ts
328
+ get(
329
+ uri: string,
330
+ options?: {
331
+ depth?: number;
332
+ languageId?: number;
333
+ }
334
+ ): Promise<DotCMSNavigationItem[]>;
115
335
  ```
116
336
 
117
- #### Filtering by Language
337
+ #### Why Use `navigation.get()`?
118
338
 
119
- If you need to filter content by language, you can specify the `language` parameter:
339
+ - Build dynamic menus and site trees with minimal configuration
340
+ - Avoid manual parsing or custom REST calls
341
+ - Support localized navigation out of the box
342
+ - Easily control navigation depth for responsive and nested UIs
120
343
 
121
- ```typescript
122
- const languageFilteredResponse = await client.content
123
- .getCollection('Blog')
124
- .language(2) // Filter by language ID (e.g., 2)
125
- .fetch();
344
+ ### client.content.getCollection(): Fetching Content Collections
345
+
346
+ The `client.content.getCollection()` method allows you to query and retrieve a collection of content items of a specific type from dotCMS. It uses a builder pattern so you can fluently compose queries with filters, pagination, sorting, and more.
347
+
348
+ #### Why Use `getCollection()`?
349
+
350
+ - Query exactly the content you need
351
+ - Chain filters, sorting, and pagination cleanly
352
+ - Works great for lists, search results, or dynamic components
353
+ - Fully type-safe when used with TypeScript interfaces
354
+
355
+ #### Basic Usage
356
+
357
+ Here's how to fetch the first 10 items from the "Blog" content type:
358
+
359
+ ```ts
360
+ const blogs = await client.content.getCollection('Blog').limit(10).page(1);
126
361
  ```
127
362
 
128
- #### Using Complex Queries
363
+ #### Filtering and Querying Content
129
364
 
130
- You can build more complex queries using the query builder. For example, filter by `author` and `title`:
365
+ You can apply query filters using a fluent builder pattern:
131
366
 
132
- ```typescript
133
- const complexQueryResponse = await client.content
367
+ ```ts
368
+ const filtered = await client.content
134
369
  .getCollection('Blog')
135
- .query((qb) => qb.field('author').equals('John Doe').and().field('title').equals('Hello World'))
136
- .fetch();
370
+ .query((qb) => qb.field('title').equals('dotCMS*'))
371
+ .limit(5)
372
+ .sortBy([{ field: 'publishDate', direction: 'desc' }]);
137
373
  ```
138
374
 
139
- #### Fetching Draft Content
375
+ The table below outlines the builder pattern's methods:
376
+
377
+ | QueryBuilder Method | Type | Result | Explanation |
378
+ |------------------------|-------------|--------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
379
+ | `.field('foo')` | Field | `foo:{bar}` | Defines a [field name](https://dev.dotcms.com/docs/field-properties#VariableNames) to query, awaiting a value to be supplied via the `.equals()` method. Multiple such assignments can be made if joined together via operator methods such as `or()`. |
380
+ | `.excludeField('foo')` | Field | `-foo:{bar}` | Defines a field name to exclude from the query, awaiting a value to be supplied via the `.equals()` method, or several combined through operators. |
381
+ | `.equals('bar')` | Assignment | `{foo:}bar` | Supplies a value to a preceding field method. Multiple `.equals()` calls may be joined through operator methods. |
382
+ | `.raw('foo')` | Raw | `foo` | Adds raw input as output to the query; requires use of Lucene syntax directly. |
383
+ | `.and()` | Operator | ` AND ` | Joins two query clauses — whether assignments or field/assignment pairs — such that results will be returned when both halves apply. |
384
+ | `.or()` | Operator | ` OR ` | Joins two query clauses such that results will be returned when at least one half applies. |
385
+ | `.not()` | Operator | ` NOT ` | Unary operator; query will return only results where the subsequent clause does not apply. |
386
+ | `.build()` | Constructor | *n/a* | Outputs query string. |
387
+
388
+ The following example displays all of the builder class's methods, generating a complex Lucene query:
389
+
390
+ ```js
391
+ let queryBuilder = new QueryBuilder();
392
+ const myQuery = queryBuilder
393
+ .field('contentType')
394
+ .equals('Blog')
395
+ .or()
396
+ .equals('Activity')
397
+ .excludeField('conhost')
398
+ .equals('my-super-cool-site')
399
+ .field('languageId')
400
+ .equals('2') // spanish
401
+ .and()
402
+ .field('deleted')
403
+ .equals('false')
404
+ .raw('+summary:Snowboard')
405
+ .not()
406
+ .equals('Swiss Alps')
407
+ .build();
408
+ ```
140
409
 
141
- To only fetch draft content, use the `draft()` method:
410
+ The above `myQuery` variable will have the following value:
411
+ > +contentType:Blog OR Activity -conhost:my-super-cool-site +languageId:2 AND +deleted:false +summary:Snowboard NOT "Swiss Alps"
142
412
 
143
- ```typescript
144
- const draftContentResponse = await client.content
145
- .getCollection('Blog')
146
- .draft() // Fetch only drafts content
147
- .fetch();
413
+ For additional examples, see the [specification page](src/lib/client/content/builders/query/query.spec.ts), or the examples below.
414
+
415
+ #### Search and Paginate Product Results by Title and Price
416
+
417
+ ```ts
418
+ const searchResults = await client.content
419
+ .getCollection('Product')
420
+ .query((qb) => qb.field('title').equals('Book*'))
421
+ .sortBy([{ field: 'price', order: 'asc' }])
422
+ .limit(10)
423
+ .page(2);
424
+
425
+ console.log(searchResults);
148
426
  ```
149
427
 
150
- #### Setting Depth for Relationships
428
+ #### Localized Query with Conditional Status Filtering
151
429
 
152
- To fetch content with a specific relationship depth, use the `depth()` method:
430
+ ```ts
431
+ const events = await client.content
432
+ .getCollection('Event')
433
+ .query((qb) => qb.field('status').equals('Live').or().equals('Scheduled').build())
434
+ .language(2) // e.g., French
435
+ .limit(5);
153
436
 
154
- ```typescript
155
- const depthResponse = await client.content
156
- .getCollection('Blog')
157
- .depth(2) // Fetch related content up to depth 2
158
- .fetch();
437
+ console.log(events);
159
438
  ```
160
439
 
161
- #### Combining Multiple Methods
440
+ #### Raw Search + Sorting + Pagination
162
441
 
163
- You can combine multiple methods to build more complex queries. For example, limit results, sort them, and filter by author:
442
+ ```ts
443
+ const images = await client.content
444
+ .getCollection('Image')
445
+ .query('+title:vacation*')
446
+ .sortBy([{ field: 'publishDate', order: 'desc' }])
447
+ .limit(10)
448
+ .page(1);
164
449
 
165
- ```typescript
166
- const combinedResponse = await client.content
167
- .getCollection('Blog')
168
- .limit(5)
169
- .page(2)
170
- .sortBy([{ field: 'title', order: 'asc' }])
171
- .query((qb) => qb.field('author').equals('John Doe'))
172
- .depth(1)
173
- .fetch();
450
+ console.log(images);
174
451
  ```
175
452
 
176
- ## Error Handling Example
453
+ #### Available Builder Methods
454
+
455
+ The builder returned by `getCollection()` supports the following methods:
456
+
457
+ | Method | Arguments | Description |
458
+ | ------------ | ----------------------------- | ------------------------------------------------------------------------- |
459
+ | `query()` | `string` \| `BuildQuery` | Filter content using query builder or raw query |
460
+ | `limit()` | `number` | Set number of items to return |
461
+ | `page()` | `number` | Set which page of results to fetch |
462
+ | `sortBy()` | `SortBy[]` | Sort by one or more fields |
463
+ | `render()` | None | Enable server-side rendering of widgets |
464
+ | `draft()` | None | Retrieve draft content |
465
+ | `variant()` | `string` | Filter content by variant ID |
466
+ | `depth()` | `number` | Set depth of related content |
467
+ | `language()` | `number \| string` | Set content language |
468
+ | `then()` | `OnFullfilled<T>, OnRejected` | Handle promise fulfillment or rejection. Not needed if using async/await. |
469
+
470
+ #### Method Signature
471
+
472
+ ```ts
473
+ getCollection<T = DotCMSBasicContentlet>(
474
+ contentType: string
475
+ ): CollectionBuilder<T>;
476
+ ```
477
+
478
+ ## Using the SDK with TypeScript
479
+
480
+ As mentioned earlier, dotCMS provides a rich set of types provided by the `@dotcms/types@latest` package. These types can be leveraged to ensure proper typing for your page and content data, enhancing type safety and developer experience.
481
+
482
+ ### Defining Page Response Types
177
483
 
178
- To handle errors gracefully, you can use a `try-catch` block around your API calls. Here’s an example:
484
+ You can use these types to define interfaces for your content and page structures, ensuring that your application benefits from TypeScript's type-checking capabilities:
179
485
 
180
486
  ```typescript
181
- try {
182
- const pageData = await client.page.get({
183
- path: '/your-page-path',
184
- languageId: 1
185
- });
186
- } catch (error) {
187
- console.error('Failed to fetch page data:', error);
487
+ // Import the base DotCMS types
488
+ import { DotCMSPageAsset, DotCMSBasicContentlet } from '@dotcms/types';
489
+
490
+ // Define the page structure by extending the base DotCMSPageAsset
491
+ interface AboutUsPage extends DotCMSPageAsset {
492
+ vanityUrl: {
493
+ url: string;
494
+ };
495
+ }
496
+
497
+ // Define interfaces for your content types
498
+ interface BlogPost extends DotCMSBasicContentlet {
499
+ title: string;
500
+ identifier: string;
501
+ urlTitle: string;
502
+ blogContent: {
503
+ json: string;
504
+ };
505
+ }
506
+
507
+ interface TeamMember {
508
+ name: string;
509
+ position: string;
510
+ bio?: string;
511
+ }
512
+
513
+ // Define the content response structure
514
+ interface AboutUsContent {
515
+ blogPosts: BlogPost[];
516
+ teamMembers: TeamMember[];
188
517
  }
518
+
519
+ // Use the type parameters to get fully typed responses
520
+ const response = await client.page.get<{ pageAsset: AboutUsPage; content: AboutUsContent }>(
521
+ '/about-us',
522
+ {
523
+ languageId: '1',
524
+ fireRules: true,
525
+ graphql: {
526
+ page: `
527
+ title
528
+ pageId
529
+ vanityUrl {
530
+ url
531
+ }
532
+ `,
533
+ content: {
534
+ blogPosts: `
535
+ BlogCollection(limit: 3) {
536
+ title
537
+ identifier
538
+ ...blogFragment
539
+ }
540
+ `,
541
+ teamMembers: `
542
+ TeamMemberCollection(limit: 5) {
543
+ name
544
+ position
545
+ bio
546
+ }
547
+ `
548
+ },
549
+ fragments: [
550
+ `
551
+ fragment blogFragment on Blog {
552
+ urlTitle
553
+ blogContent {
554
+ json
555
+ }
556
+ }
557
+ `
558
+ ]
559
+ }
560
+ }
561
+ );
562
+
563
+ const { pageAsset, content } = response;
564
+
565
+ // Now you get full TypeScript support
566
+ console.log(pageAsset.vanityUrl.url); // TypeScript knows this exists
567
+ console.log(content.blogPosts[0].title); // TypeScript knows this exists
568
+ console.log(content.teamMembers[0].position); // TypeScript knows this exists
189
569
  ```
190
570
 
191
- This ensures that any errors that occur during the fetch (e.g., network issues, invalid paths, etc.) are caught and logged properly.
571
+ ### Defining Content Response Types
192
572
 
193
- ## Pagination
573
+ You can define interfaces for your content types to get full type safety:
194
574
 
195
- When fetching large collections of content, pagination is key to managing the number of results returned:
575
+ ```ts
576
+ import { DotCMSBasicContentlet } from '@dotcms/types';
196
577
 
197
- ```typescript
198
- const paginatedResponse = await client.content
199
- .getCollection('Blog')
200
- .limit(10) // Limit to 10 items per page
201
- .page(2) // Get the second page of results
202
- .fetch();
578
+ interface BlogPost extends DotCMSBasicContentlet {
579
+ title: string;
580
+ publishDate: string;
581
+ author: string;
582
+ blogContent: {
583
+ json: string;
584
+ };
585
+ urlTitle: string;
586
+ tags: string[];
587
+ }
588
+
589
+ const response = await client.content.getCollection<BlogPost>('Blog');
590
+
591
+ response.contentlets.forEach((post) => {
592
+ console.log(post.title); // Type-safe access
593
+ console.log(post.author);
594
+ console.log(post.tags.join(', '));
595
+ });
203
596
  ```
204
597
 
205
- ## API Reference
598
+ ## How to Enable Page Editing in dotCMS
599
+
600
+ By default, the `@dotcms/client` SDK is **read-only**. It's designed to fetch content from dotCMS—pages, navigation, and collections—but it doesn't make pages editable in the dotCMS backend.
601
+
602
+ To make your pages editable using the dotCMS **Universal Visual Editor (UVE)**, you'll need to pair this SDK with one of our supported front-end integrations.
603
+
604
+ ### Use an Official SDK:
605
+
606
+ If you're using a modern JavaScript framework like React or Angular, we strongly recommend starting with one of our official UVE integrations. These pair the `@dotcms/client` SDK with framework-specific tooling for the Universal Visual Editor:
206
607
 
207
- Detailed documentation of the `@dotcms/client` methods, parameters, and types can be found below:
608
+ * 🧩 **React SDK**: [`@dotcms/react`](https://github.com/dotCMS/core/tree/main/core-web/libs/sdk/react)
609
+ * 🧩 **Angular SDK**: [`@dotcms/angular`](https://github.com/dotCMS/core/tree/main/core-web/libs/sdk/angular)
208
610
 
209
- ### `DotCmsClient.init(config: ClientConfig): DotCmsClient`
611
+ You can also see them in action within our full-stack examples:
210
612
 
211
- Initializes the dotCMS client with the specified configuration.
613
+ * [Next.js Example](https://github.com/dotCMS/core/tree/main/examples/nextjs)
614
+ * [Angular Example](https://github.com/dotCMS/core/tree/main/examples/angular)
615
+ * [Astro Example](https://github.com/dotCMS/core/tree/main/examples/astro)
212
616
 
213
- ### `DotCmsClient.page.get(options: PageApiOptions): Promise<unknown>`
617
+ These integrations come pre-wired with everything you need to:
214
618
 
215
- Retrieves the specified page's elements from your dotCMS system in JSON format.
619
+ * Enable editable pages inside dotCMS using the UVE
620
+ * Render layouts and content containers
621
+ * Fetch page and content data using `@dotcms/client`
216
622
 
217
- ### `DotCmsClient.nav.get(options: NavApiOptions): Promise<unknown>`
623
+ ### ⚠️ Advanced Only: Custom UVE Integration
218
624
 
219
- Retrieves information about the dotCMS file and folder tree.
625
+ If you’re building with a framework we don’t yet support, you can build your own UVE integration using the low-level [`@dotcms/uve`](https://github.com/dotCMS/core/tree/main/core-web/libs/sdk/uve) package.
220
626
 
221
- ### `DotCmsClient.content.getCollection(contentType: string): CollectionBuilder<T>`
627
+ > **This is not a recommended path.**
628
+ >
629
+ > Custom UVE implementations are complex, require a deep understanding of dotCMS internals, and are not actively supported.
630
+ >
631
+ > This route is intended only for advanced use cases, such as wiring up layout rendering, editable regions, and UVE behavior manually.
222
632
 
223
- Creates a builder to filter and fetches a collection of content items for a specific content type.
633
+ That said, if you’re experienced and want to explore it, you can [review the `@dotcms/uve` source and docs here](https://github.com/dotCMS/core/tree/main/core-web/libs/sdk/uve).
224
634
 
225
- #### Parameters
635
+ ## dotCMS Support
226
636
 
227
- `contentType` (string): The content type to retrieve.
637
+ We offer multiple channels to get help with the dotCMS Client SDK:
228
638
 
229
- #### Returns
639
+ - **GitHub Issues**: For bug reports and feature requests, please [open an issue](https://github.com/dotCMS/core/issues/new/choose) in the GitHub repository.
640
+ - **Community Forum**: Join our [community discussions](https://community.dotcms.com/) to ask questions and share solutions.
641
+ - **Stack Overflow**: Use the tag `dotcms-client` when posting questions.
230
642
 
231
- `CollectionBuilder<T>`: A builder instance for chaining filters and executing the query.
643
+ When reporting issues, please include:
232
644
 
233
- ## Contributing
645
+ - SDK version you're using
646
+ - dotCMS version
647
+ - Minimal reproduction steps
648
+ - Expected vs. actual behavior
234
649
 
235
- GitHub pull requests are the preferred method to contribute code to dotCMS. Before any pull requests can be accepted, an automated tool will ask you to agree to the [dotCMS Contributor's Agreement](https://gist.github.com/wezell/85ef45298c48494b90d92755b583acb3).
650
+ Enterprise customers can access premium support through the [dotCMS Support Portal](https://dev.dotcms.com/docs/help).
236
651
 
237
- ## Licensing
652
+ ## How To Contribute
238
653
 
239
- dotCMS comes in multiple editions and as such is dual licensed. The dotCMS Community Edition is licensed under the GPL 3.0 and is freely available for download, customization and deployment for use within organizations of all stripes. dotCMS Enterprise Editions (EE) adds a number of enterprise features and is available via a supported, indemnified commercial license from dotCMS. For the differences between the editions, see [the feature page](http://dotcms.com/cms-platform/features).
654
+ GitHub pull requests are the preferred method to contribute code to dotCMS. We welcome contributions to the DotCMS UVE SDK! If you'd like to contribute, please follow these steps:
240
655
 
241
- ## Support
656
+ 1. Fork the repository [dotCMS/core](https://github.com/dotCMS/core)
657
+ 2. Create a feature branch (`git checkout -b feature/amazing-feature`)
658
+ 3. Commit your changes (`git commit -m 'Add some amazing feature'`)
659
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
660
+ 5. Open a Pull Request
242
661
 
243
- If you need help or have any questions, please [open an issue](https://github.com/dotCMS/core/issues/new/choose) in the GitHub repository.
662
+ Please ensure your code follows the existing style and includes appropriate tests.
244
663
 
245
- ## Documentation
664
+ ## Licensing Information
246
665
 
247
- Always refer to the official [dotCMS documentation](https://www.dotcms.com/docs/latest/) for comprehensive guides and API references.
666
+ dotCMS comes in multiple editions and as such is dual-licensed. The dotCMS Community Edition is licensed under the GPL 3.0 and is freely available for download, customization, and deployment for use within organizations of all stripes. dotCMS Enterprise Editions (EE) adds several enterprise features and is available via a supported, indemnified commercial license from dotCMS. For the differences between the editions, see [the feature page](http://www.dotcms.com/cms-platform/features).
248
667
 
249
- ## Getting Help
668
+ This SDK is part of dotCMS's dual-licensed platform (GPL 3.0 for Community, commercial license for Enterprise).
250
669
 
251
- | Source | Location |
252
- | --------------- | ------------------------------------------------------------------- |
253
- | Installation | [Installation](https://dotcms.com/docs/latest/installation) |
254
- | Documentation | [Documentation](https://dotcms.com/docs/latest/table-of-contents) |
255
- | Videos | [Helpful Videos](http://dotcms.com/videos/) |
256
- | Forums/Listserv | [via Google Groups](https://groups.google.com/forum/#!forum/dotCMS) |
257
- | Twitter | @dotCMS |
258
- | Main Site | [dotCMS.com](https://dotcms.com/) |
670
+ [Learn more ](https://www.dotcms.com)at [dotcms.com](https://www.dotcms.com).