@dotcms/client
Version:
Official JavaScript library for interacting with DotCMS REST APIs.
1,444 lines (1,419 loc) • 54.6 kB
JavaScript
import { consola } from 'consola';
import { graphqlToPageEntity } from './internal.esm.js';
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
function __classPrivateFieldGet(receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}
function __classPrivateFieldSet(receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
/**
* Default variant identifier used in the application.
*/
/**
* Fields that should not be formatted when sanitizing the query.
* These fields are essential for maintaining the integrity of the content type.
*/
const CONTENT_TYPE_MAIN_FIELDS = ['live', 'variant', 'contentType', 'languageId'];
/**
* URL endpoint for the content API search functionality.
*/
const CONTENT_API_URL = '/api/content/_search';
/**
* @description
* Sanitizes the query for the given content type.
* It replaces the fields that are not content type fields with the correct format.
* Example: +field: -> +contentTypeVar.field:
*
* @example
*
* ```ts
* const query = '+field: value';
* const contentType = 'contentTypeVar';
* const sanitizedQuery = sanitizeQueryForContentType(query, contentType); // Output: '+contentTypeVar.field: value'
* ```
*
* @export
* @param {string} query - The query string to be sanitized.
* @param {string} contentType - The content type to be used for formatting the fields.
* @returns {string} The sanitized query string.
*/
function sanitizeQueryForContentType(query, contentType) {
return query.replace(/\+([^+:]*?):/g, (original, field) => {
return !CONTENT_TYPE_MAIN_FIELDS.includes(field) // Fields that are not content type fields
? `+${contentType}.${field}:` // Should have this format: +contentTypeVar.field:
: original; // Return the field if it is a content type field
});
}
var _Field_query;
/**
* The `Field` class is used to build a query with a specific field.
* A Lucene Field is a key used to search for a specific value in a document.
*
* @export
* @class Field
*/
class Field {
/**
* Creates an instance of the `Field` class.
*
* @param {string} query - The initial query string.
*/
constructor(query) {
this.query = query;
_Field_query.set(this, '');
__classPrivateFieldSet(this, _Field_query, this.query, "f");
}
/**
* Appends a term to the query that should be included in the search.
*
* @example
* ```typescript
* const field = new Field("+myField");
* field.equals("myValue");
* ```
*
* @param {string} term - The term that should be included in the search.
* @return {Equals} - An instance of `Equals`.
* @memberof Field
*/
equals(term) {
return buildEquals(__classPrivateFieldGet(this, _Field_query, "f"), term);
}
}
_Field_query = new WeakMap();
var _NotOperand_query;
/**
* 'NotOperand' Is a Typescript class that provides the ability to use the NOT operand in the lucene query string.
*
* @export
* @class NotOperand
*/
class NotOperand {
constructor(query) {
this.query = query;
_NotOperand_query.set(this, '');
__classPrivateFieldSet(this, _NotOperand_query, this.query, "f");
}
/**
* This method appends to the query a term that should be included in the search.
*
* @example
* ```typescript
* const notOperand = new NotOperand("+myField");
* notOperand.equals("myValue");
* ```
*
* @param {string} term - The term that should be included in the search.
* @return {*} {Equals} - An instance of Equals.
* @memberof NotOperand
*/
equals(term) {
return buildEquals(__classPrivateFieldGet(this, _NotOperand_query, "f"), term);
}
}
_NotOperand_query = new WeakMap();
var _Operand_query;
/**
* 'Operand' Is a Typescript class that provides the ability to use operands in the lucene query string.}
* An operand is a logical operator used to join two or more conditions in a query.
*
* @export
* @class Operand
*/
class Operand {
constructor(query) {
this.query = query;
_Operand_query.set(this, '');
__classPrivateFieldSet(this, _Operand_query, this.query, "f");
}
/**
* This method appends to the query a term that should be excluded in the search.
*
* Ex: "-myValue"
*
* @param {string} field - The field that should be excluded in the search.
* @return {*} {Field} - An instance of a Lucene Field. A field is a key used to search for a specific value in a document.
* @memberof Operand
*/
excludeField(field) {
return buildExcludeField(__classPrivateFieldGet(this, _Operand_query, "f"), field);
}
/**
* This method appends to the query a field that should be included in the search.
*
* Ex: "+myField:"
*
* @param {string} field - The field that should be included in the search.
* @return {*} {Field} - An instance of a Lucene Field. A field is a key used to search for a specific value in a document.
* @memberof Operand
*/
field(field) {
return buildField(__classPrivateFieldGet(this, _Operand_query, "f"), field);
}
/**
* This method appends to the query a term that should be included in the search.
*
* Ex: myValue or "My value"
*
* @param {string} term - The term that should be included in the search.
* @return {*} {Equals} - An instance of Equals.
* @memberof Operand
*/
equals(term) {
return buildEquals(__classPrivateFieldGet(this, _Operand_query, "f"), term);
}
}
_Operand_query = new WeakMap();
/**
* Enum for common Operands
*
* @export
* @enum {number}
*/
var OPERAND;
(function (OPERAND) {
OPERAND["OR"] = "OR";
OPERAND["AND"] = "AND";
OPERAND["NOT"] = "NOT";
})(OPERAND || (OPERAND = {}));
/**
* This function removes extra spaces from a string.
*
* @example
* ```ts
* sanitizeQuery(" my query "); // Output: "my query"
* ```
*
* @export
* @param {string} str
* @return {*} {string}
*/
function sanitizeQuery(str) {
return str.replace(/\s{2,}/g, ' ').trim();
}
/**
* This function sanitizes a term by adding quotes if it contains spaces.
* In lucene, a term with spaces should be enclosed in quotes.
*
* @example
* ```ts
* sanitizePhrases(`my term`); // Output: `"my term"`
* sanitizePhrases(`myterm`); // Output: `myterm`
* ```
*
* @export
* @param {string} term
* @return {*} {string}
*/
function sanitizePhrases(term) {
return term.includes(' ') ? `'${term}'` : term;
}
/**
* This function builds a term to be used in a lucene query.
* We need to sanitize the term before adding it to the query.
*
* @example
* ```ts
* const equals = buildEquals("+myField: ", "myValue"); // Current query: "+myField: myValue"
* ```
*
* @export
* @param {string} query
* @param {string} term
* @return {*} {Equals}
*/
function buildEquals(query, term) {
const newQuery = query + sanitizePhrases(term);
return new Equals(newQuery);
}
/**
* This function builds a term to be used in a lucene query.
* We need to sanitize the raw query before adding it to the query.
*
* @example
* ```ts
* const query = "+myField: myValue";
* const field = buildRawEquals(query, "-myField2: myValue2"); // Current query: "+myField: myValue -myField2: myValue"
* ```
*
* @export
* @param {string} query
* @param {string} raw
* @return {*} {Equals}
*/
function buildRawEquals(query, raw) {
const newQuery = query + ` ${raw}`;
return new Equals(sanitizeQuery(newQuery));
}
/**
* This function builds a field to be used in a lucene query.
* We need to format the field before adding it to the query.
*
* @example
* ```ts
* const field = buildField("+myField: ", "myValue"); // Current query: "+myField: myValue"
* ```
*
* @export
* @param {string} query
* @param {string} field
* @return {*} {Field}
*/
function buildField(query, field) {
const newQuery = query + ` +${field}:`;
return new Field(newQuery);
}
/**
* This function builds an exclude field to be used in a lucene query.
* We need to format the field before adding it to the query.
*
* @example
* ```ts
* const query = "+myField: myValue";
* const field = buildExcludeField(query, "myField2"); // Current query: "+myField: myValue -myField2:"
* ```
*
* @export
* @param {string} query
* @param {string} field
* @return {*} {Field}
*/
function buildExcludeField(query, field) {
const newQuery = query + ` -${field}:`;
return new Field(newQuery);
}
/**
* This function builds an operand to be used in a lucene query.
* We need to format the operand before adding it to the query.
*
* @example
* <caption>E.g. Using the AND operand</caption>
* ```ts
* const query = "+myField: myValue";
* const field = buildOperand(query, OPERAND.AND); // Current query: "+myField: myValue AND"
* ```
* @example
* <caption>E.g. Using the OR operand</caption>
* ```ts
* const query = "+myField: myValue";
* const field = buildOperand(query, OPERAND.OR); // Current query: "+myField: myValue OR"
* ```
* @export
* @param {string} query
* @param {OPERAND} operand
* @return {*} {Operand}
*/
function buildOperand(query, operand) {
const newQuery = query + ` ${operand} `;
return new Operand(newQuery);
}
/**
* This function builds a NOT operand to be used in a lucene query.
* We need to format the operand before adding it to the query.
*
* @example
* ```ts
* const query = "+myField: myValue";
* const field = buildNotOperand(query); // Current query: "+myField: myValue NOT"
* ```
*
* @export
* @param {string} query
* @return {*} {NotOperand}
*/
function buildNotOperand(query) {
const newQuery = query + ` ${OPERAND.NOT} `;
return new NotOperand(newQuery);
}
var _Equals_query;
/**
* 'Equal' Is a Typescript class that provides the ability to use terms in the lucene query string.
* A term is a value used to search for a specific value in a document. It can be a word or a phrase.
*
* Ex: myValue or "My Value"
*
* @export
* @class Equal
*/
class Equals {
constructor(query) {
this.query = query;
_Equals_query.set(this, '');
__classPrivateFieldSet(this, _Equals_query, this.query, "f");
}
/**
* This method appends to the query a term that should be excluded in the search.
*
* @example
* ```ts
* const equals = new Equals("+myField: myValue");
* equals.excludeField("myField2").equals("myValue2"); // Current query: "+myField: myValue -myField2: myValue2"
* ```
*
* @param {string} field - The field that should be excluded in the search.
* @return {*} {Field} - An instance of a Lucene Field. A field is a key used to search for a specific value in a document.
* @memberof Equal
*/
excludeField(field) {
return buildExcludeField(__classPrivateFieldGet(this, _Equals_query, "f"), field);
}
/**
* This method appends to the query a field that should be included in the search.
*
* @example
* ```ts
* const equals = new Equals("+myField: myValue");
* equals.field("myField2").equals("myValue2"); // Current query: "+myField: myValue +myField2: myValue2"
*```
* @param {string} field - The field that should be included in the search.
* @return {*} {Field} - An instance of a Lucene Field. A field is a key used to search for a specific value in a document.
* @memberof Equal
*/
field(field) {
return buildField(__classPrivateFieldGet(this, _Equals_query, "f"), field);
}
/**
* This method appends to the query an operand to use logic operators in the query.
*
* @example
* @example
* ```ts
* const equals = new Equals("+myField: myValue");
* equals.or().field("myField2").equals("myValue2"); // Current query: "+myField: myValue OR +myField2: myValue2"
* ```
*
* @return {*} {Operand} - An instance of a Lucene Operand. An operand is a logical operator used to combine terms or phrases in a query.
* @memberof Equal
*/
or() {
return buildOperand(__classPrivateFieldGet(this, _Equals_query, "f"), OPERAND.OR);
}
/**
* This method appends to the query an operand to use logic operators in the query.
*
* @example
* ```ts
* const equals = new Equals("+myField: myValue");
* equals.and().field("myField2").equals("myValue2"); // Current query: "+myField: myValue AND +myField2: myValue2"
* ```
*
* @return {*} {Operand} - An instance of a Lucene Operand. An operand is a logical operator used to combine terms or phrases in a query.
* @memberof Equal
*/
and() {
return buildOperand(__classPrivateFieldGet(this, _Equals_query, "f"), OPERAND.AND);
}
/**
* This method appends to the query an operand to use logic operators in the query.
*
* @example
* ```ts
* const equals = new Equals("+myField: myValue");
* equals.not().field("myField").equals("myValue2"); // Current query: "+myField: myValue NOT +myField: myValue2"
* ```
*
* @return {*} {NotOperand} - An instance of a Lucene Not Operand. A not operand is a logical operator used to exclude terms or phrases in a query.
* @memberof Equal
*/
not() {
return buildNotOperand(__classPrivateFieldGet(this, _Equals_query, "f"));
}
/**
* This method allows to pass a raw query string to the query builder.
* This raw query should end in a Lucene Equal.
* This method is useful when you want to append a complex query or an already written query to the query builder.
*
* @example
* ```ts
* // This builds the follow raw query "+myField: value AND (someOtherValue OR anotherValue)"
* const equals = new Equals("+myField: value");
* equals.raw("+myField2: value2"); // Current query: "+myField: value +myField2: anotherValue"
* ```
*
* @param {string} query - A raw query string.
* @return {*} {Equal} - An instance of a Lucene Equal. A term is a value used to search for a specific value in a document.
* @memberof QueryBuilder
*/
raw(query) {
return buildRawEquals(__classPrivateFieldGet(this, _Equals_query, "f"), query);
}
/**
* This method returns the final query string.
*
* @example
* ```ts
* const equals = new Equals("+myField: myValue");
* equals.field("myField2").equals("myValue2").build(); // Returns "+myField: myValue +myField2: myValue2"
* ```
*
* @return {*} {string} - The final query string.
* @memberof Equal
*/
build() {
return sanitizeQuery(__classPrivateFieldGet(this, _Equals_query, "f"));
}
}
_Equals_query = new WeakMap();
var _QueryBuilder_query;
/**
* 'QueryBuilder' Is a Typescript class that provides the ability to build a query string using the Lucene syntax in a more readable way.
* @example
* ```ts
* const qb = new QueryBuilder();
* const query = qb
* .field('contentType')
* .equals('Blog')
* .field('conhost')
* .equals('my-super-cool-site')
* .build(); // Output: `+contentType:Blog +conhost:my-super-cool-site"`
* ```
*
* @example
* ```ts
* const qb = new QueryBuilder();
* const query = qb
* .field('contentType')
* .equals('Blog')
* .field('title')
* .equals('Football')
* .excludeField('summary')
* .equals('Lionel Messi')
* .build(); // Output: `+contentType:Blog +title:Football -summary:"Lionel Messi"`
* ```
* @export
* @class QueryBuilder
*/
class QueryBuilder {
constructor() {
_QueryBuilder_query.set(this, '');
}
/**
* This method appends to the query a field that should be included in the search.
*
* @example
* ```ts
* const qb = new QueryBuilder();
* qb.field("+myField: ", "myValue"); // Current query: "+myField: myValue"
* ```
*
* @param {string} field - The field that should be included in the search.
* @return {*} {Field} - An instance of a Lucene Field. A field is a key used to search for a specific value in a document.
* @memberof QueryBuilder
*/
field(field) {
return buildField(__classPrivateFieldGet(this, _QueryBuilder_query, "f"), field);
}
/**
* This method appends to the query a field that should be excluded from the search.
*
* @example
* ```ts
* const qb = new QueryBuilder();
* qb.excludeField("myField").equals("myValue"); // Current query: "-myField: myValue"
* ```
*
* @param {string} field - The field that should be excluded from the search.
* @return {*} {Field} - An instance of a Lucene Exclude Field. An exclude field is a key used to exclude for a specific value in a document.
* @memberof QueryBuilder
*/
excludeField(field) {
return buildExcludeField(__classPrivateFieldGet(this, _QueryBuilder_query, "f"), field);
}
/**
* This method allows to pass a raw query string to the query builder.
* This raw query should end in Equals.
* This method is useful when you want to append a complex query or an already written query to the query builder.
*
* @example
* ```ts
* const qb = new QueryBuilder();
* qb.raw("+myField: value AND (someOtherValue OR anotherValue)"); // Current query: "+myField: value AND (someOtherValue OR anotherValue)"
* ```
*
* @param {string} query - A raw query string.
* @return {*} {Equals} - An instance of Equals. A term is a value used to search for a specific value in a document.
* @memberof QueryBuilder
*/
raw(query) {
return buildRawEquals(__classPrivateFieldGet(this, _QueryBuilder_query, "f"), query);
}
}
_QueryBuilder_query = new WeakMap();
var _CollectionBuilder_page, _CollectionBuilder_limit, _CollectionBuilder_depth, _CollectionBuilder_render, _CollectionBuilder_sortBy, _CollectionBuilder_contentType, _CollectionBuilder_defaultQuery, _CollectionBuilder_query, _CollectionBuilder_rawQuery, _CollectionBuilder_languageId, _CollectionBuilder_draft, _CollectionBuilder_serverUrl, _CollectionBuilder_requestOptions;
/**
* Creates a Builder to filter and fetch content from the content API for a specific content type.
*
* @export
* @class CollectionBuilder
* @template T Represents the type of the content type to fetch. Defaults to unknown.
*/
class CollectionBuilder {
/**
* Creates an instance of CollectionBuilder.
* @param {ClientOptions} requestOptions Options for the client request.
* @param {string} serverUrl The server URL.
* @param {string} contentType The content type to fetch.
* @memberof CollectionBuilder
*/
constructor(requestOptions, serverUrl, contentType) {
_CollectionBuilder_page.set(this, 1);
_CollectionBuilder_limit.set(this, 10);
_CollectionBuilder_depth.set(this, 0);
_CollectionBuilder_render.set(this, false);
_CollectionBuilder_sortBy.set(this, void 0);
_CollectionBuilder_contentType.set(this, void 0);
_CollectionBuilder_defaultQuery.set(this, void 0);
_CollectionBuilder_query.set(this, void 0);
_CollectionBuilder_rawQuery.set(this, void 0);
_CollectionBuilder_languageId.set(this, 1);
_CollectionBuilder_draft.set(this, false);
_CollectionBuilder_serverUrl.set(this, void 0);
_CollectionBuilder_requestOptions.set(this, void 0);
__classPrivateFieldSet(this, _CollectionBuilder_requestOptions, requestOptions, "f");
__classPrivateFieldSet(this, _CollectionBuilder_serverUrl, serverUrl, "f");
__classPrivateFieldSet(this, _CollectionBuilder_contentType, contentType, "f");
// Build the default query with the contentType field
__classPrivateFieldSet(this, _CollectionBuilder_defaultQuery, new QueryBuilder().field('contentType').equals(__classPrivateFieldGet(this, _CollectionBuilder_contentType, "f")), "f");
}
/**
* Returns the sort query in the format: field order, field order, ...
*
* @readonly
* @private
* @memberof CollectionBuilder
*/
get sort() {
return __classPrivateFieldGet(this, _CollectionBuilder_sortBy, "f")?.map((sort) => `${sort.field} ${sort.order}`).join(',');
}
/**
* Returns the offset for pagination.
*
* @readonly
* @private
* @memberof CollectionBuilder
*/
get offset() {
return __classPrivateFieldGet(this, _CollectionBuilder_limit, "f") * (__classPrivateFieldGet(this, _CollectionBuilder_page, "f") - 1);
}
/**
* Returns the full URL for the content API.
*
* @readonly
* @private
* @memberof CollectionBuilder
*/
get url() {
return `${__classPrivateFieldGet(this, _CollectionBuilder_serverUrl, "f")}${CONTENT_API_URL}`;
}
/**
* Returns the current query built.
*
* @readonly
* @private
* @memberof CollectionBuilder
*/
get currentQuery() {
return __classPrivateFieldGet(this, _CollectionBuilder_query, "f") ?? __classPrivateFieldGet(this, _CollectionBuilder_defaultQuery, "f");
}
/**
* Filters the content by the specified language ID.
*
* @example
* ```typescript
* const client = new DotCMSClient(config);
* const collectionBuilder = client.content.getCollection("Blog");
* collectionBuilder.language(1);
* ```
*
* @param {number | string} languageId The language ID to filter the content by.
* @return {CollectionBuilder} A CollectionBuilder instance.
* @memberof CollectionBuilder
*/
language(languageId) {
__classPrivateFieldSet(this, _CollectionBuilder_languageId, languageId, "f");
return this;
}
/**
* Setting this to true will server side render (using velocity) any widgets that are returned by the content query.
*
* More information here: {@link https://www.dotcms.com/docs/latest/content-api-retrieval-and-querying#ParamsOptional}
*
* @return {CollectionBuilder} A CollectionBuilder instance.
* @memberof CollectionBuilder
*/
render() {
__classPrivateFieldSet(this, _CollectionBuilder_render, true, "f");
return this;
}
/**
* Sorts the content by the specified fields and orders.
*
* @example
* ```typescript
* const client = new DotCMSClient(config);
* const collectionBuilder = client.content.getCollection("Blog");
* const sortBy = [{ field: 'title', order: 'asc' }, { field: 'modDate', order: 'desc' }];
* collectionBuilder("Blog").sortBy(sortBy);
* ```
*
* @param {SortBy[]} sortBy Array of constraints to sort the content by.
* @return {CollectionBuilder} A CollectionBuilder instance.
* @memberof CollectionBuilder
*/
sortBy(sortBy) {
__classPrivateFieldSet(this, _CollectionBuilder_sortBy, sortBy, "f");
return this;
}
/**
* Sets the maximum amount of content to fetch.
*
* @param {number} limit The maximum amount of content to fetch.
* @return {CollectionBuilder} A CollectionBuilder instance.
* @memberof CollectionBuilder
*/
limit(limit) {
__classPrivateFieldSet(this, _CollectionBuilder_limit, limit, "f");
return this;
}
/**
* Sets the page number to fetch.
*
* @param {number} page The page number to fetch.
* @return {CollectionBuilder} A CollectionBuilder instance.
* @memberof CollectionBuilder
*/
page(page) {
__classPrivateFieldSet(this, _CollectionBuilder_page, page, "f");
return this;
}
query(arg) {
if (typeof arg === 'string') {
__classPrivateFieldSet(this, _CollectionBuilder_rawQuery, arg, "f");
return this;
}
if (typeof arg !== 'function') {
throw new Error(`Parameter for query method should be a buildQuery function or a string.\nExample:\nclient.content.getCollection('Activity').query((queryBuilder) => queryBuilder.field('title').equals('Hello World'))\nor\nclient.content.getCollection('Activity').query('+Activity.title:"Hello World"') \nSee documentation for more information.`);
}
const builtQuery = arg(new QueryBuilder());
// This can be use in Javascript so we cannot rely on the type checking
if (builtQuery instanceof Equals) {
__classPrivateFieldSet(this, _CollectionBuilder_query, builtQuery.raw(this.currentQuery.build()), "f");
}
else {
throw new Error('Provided query is not valid. A query should end in an equals method call.\nExample:\n(queryBuilder) => queryBuilder.field("title").equals("Hello World")\nSee documentation for more information.');
}
return this;
}
/**
* Retrieves draft content.
* @example
* ```ts
* const client = new DotCMSClient(config);
* const collectionBuilder = client.content.getCollection("Blog");
* collectionBuilder
* .draft() // This will retrieve draft/working content
* .then((response) => // Your code here })
* .catch((error) => // Your code here })
* ```
*
* @return {CollectionBuilder} A CollectionBuilder instance.
* @memberof CollectionBuilder
*/
draft() {
__classPrivateFieldSet(this, _CollectionBuilder_draft, true, "f");
return this;
}
/**
* Filters the content by a variant ID for [Experiments](https://www.dotcms.com/docs/latest/experiments-and-a-b-testing)
*
* More information here: {@link https://www.dotcms.com/docs/latest/content-api-retrieval-and-querying#ParamsOptional}
*
* @example
* ```ts
* const client = new DotCMSClient(config);
* const collectionBuilder = client.content.getCollection("Blog");
* collectionBuilder
* .variant("YOUR_VARIANT_ID")
* .then((response) => // Your code here })
* .catch((error) => // Your code here })
* ```
*
* @param {string} variantId A string that represents a variant ID.
* @return {CollectionBuilder} A CollectionBuilder instance.
* @memberof CollectionBuilder
*/
variant(variantId) {
__classPrivateFieldSet(this, _CollectionBuilder_query, this.currentQuery.field('variant').equals(variantId), "f");
return this;
}
/**
* Sets the depth of the relationships of the content.
* Specifies the depth of related content to return in the results.
*
* More information here: {@link https://www.dotcms.com/docs/latest/content-api-retrieval-and-querying#ParamsOptional}
*
* @example
* ```ts
* const client = new DotCMSClient(config);
* const collectionBuilder = client.content.getCollection("Blog");
* collectionBuilder
* .depth(1)
* .then((response) => // Your code here })
* .catch((error) => // Your code here })
* ```
*
* @param {number} depth The depth of the relationships of the content.
* @return {CollectionBuilder} A CollectionBuilder instance.
* @memberof CollectionBuilder
*/
depth(depth) {
if (depth < 0 || depth > 3) {
throw new Error('Depth value must be between 0 and 3');
}
__classPrivateFieldSet(this, _CollectionBuilder_depth, depth, "f");
return this;
}
/**
* Executes the fetch and returns a promise that resolves to the content or rejects with an error.
*
* @example
* ```ts
* const client = new DotCMSClient(config);
* const collectionBuilder = client.content.getCollection("Blog");
* collectionBuilder
* .limit(10)
* .then((response) => // Your code here })
* .catch((error) => // Your code here })
* ```
*
* @param {OnFullfilled} [onfulfilled] A callback that is called when the fetch is successful.
* @param {OnRejected} [onrejected] A callback that is called when the fetch fails.
* @return {Promise<GetCollectionResponse<T> | GetCollectionError>} A promise that resolves to the content or rejects with an error.
* @memberof CollectionBuilder
*/
then(onfulfilled, onrejected) {
return this.fetch().then(async (response) => {
const data = await response.json();
if (response.ok) {
const formattedResponse = this.formatResponse(data);
const finalResponse = typeof onfulfilled === 'function'
? onfulfilled(formattedResponse)
: formattedResponse;
return finalResponse;
}
else {
return {
status: response.status,
...data
};
}
}, onrejected);
}
/**
* Formats the response to the desired format.
*
* @private
* @param {GetCollectionRawResponse<T>} data The raw response data.
* @return {GetCollectionResponse<T>} The formatted response.
* @memberof CollectionBuilder
*/
formatResponse(data) {
const contentlets = data.entity.jsonObjectView.contentlets;
const total = data.entity.resultsSize;
const mappedResponse = {
contentlets,
total,
page: __classPrivateFieldGet(this, _CollectionBuilder_page, "f"),
size: contentlets.length
};
return __classPrivateFieldGet(this, _CollectionBuilder_sortBy, "f")
? {
...mappedResponse,
sortedBy: __classPrivateFieldGet(this, _CollectionBuilder_sortBy, "f")
}
: mappedResponse;
}
/**
* Calls the content API to fetch the content.
*
* @private
* @return {Promise<Response>} The fetch response.
* @memberof CollectionBuilder
*/
fetch() {
const finalQuery = this.currentQuery
.field('languageId')
.equals(__classPrivateFieldGet(this, _CollectionBuilder_languageId, "f").toString())
.field('live')
.equals((!__classPrivateFieldGet(this, _CollectionBuilder_draft, "f")).toString())
.build();
const sanitizedQuery = sanitizeQueryForContentType(finalQuery, __classPrivateFieldGet(this, _CollectionBuilder_contentType, "f"));
const query = __classPrivateFieldGet(this, _CollectionBuilder_rawQuery, "f") ? `${sanitizedQuery} ${__classPrivateFieldGet(this, _CollectionBuilder_rawQuery, "f")}` : sanitizedQuery;
return fetch(this.url, {
...__classPrivateFieldGet(this, _CollectionBuilder_requestOptions, "f"),
method: 'POST',
headers: {
...__classPrivateFieldGet(this, _CollectionBuilder_requestOptions, "f").headers,
'Content-Type': 'application/json'
},
body: JSON.stringify({
query,
render: __classPrivateFieldGet(this, _CollectionBuilder_render, "f"),
sort: this.sort,
limit: __classPrivateFieldGet(this, _CollectionBuilder_limit, "f"),
offset: this.offset,
depth: __classPrivateFieldGet(this, _CollectionBuilder_depth, "f")
//userId: This exist but we currently don't use it
//allCategoriesInfo: This exist but we currently don't use it
})
});
}
}
_CollectionBuilder_page = new WeakMap(), _CollectionBuilder_limit = new WeakMap(), _CollectionBuilder_depth = new WeakMap(), _CollectionBuilder_render = new WeakMap(), _CollectionBuilder_sortBy = new WeakMap(), _CollectionBuilder_contentType = new WeakMap(), _CollectionBuilder_defaultQuery = new WeakMap(), _CollectionBuilder_query = new WeakMap(), _CollectionBuilder_rawQuery = new WeakMap(), _CollectionBuilder_languageId = new WeakMap(), _CollectionBuilder_draft = new WeakMap(), _CollectionBuilder_serverUrl = new WeakMap(), _CollectionBuilder_requestOptions = new WeakMap();
var _Content_requestOptions, _Content_serverUrl;
/**
* Creates a builder to filter and fetch a collection of content items.
* @param contentType - The content type to retrieve.
* @returns A CollectionBuilder instance for chaining filters and executing the query.
* @template T - The type of the content items (defaults to unknown).
*
* @example Fetch blog posts with async/await
* ```typescript
* const response = await client.content
* .getCollection<BlogPost>('Blog')
* .limit(10)
* .page(2)
* .sortBy([{ field: 'title', order: 'asc' }])
* .query(q => q.field('author').equals('John Doe'))
* .depth(1)
*
* console.log(response.contentlets);
* ```
*
* @example Fetch blog posts with Promise chain
* ```typescript
* client.content
* .getCollection<BlogPost>('Blog')
* .limit(10)
* .page(2)
* .sortBy([{ field: 'title', order: 'asc' }])
* .query(q => q.field('author').equals('John Doe'))
* .depth(1)
* .then(response => console.log(response.contentlets))
* .catch(error => console.error(error));
* ```
*
* @example Using a custom type
* ```typescript
* interface BlogPost {
* summary: string;
* author: string;
* title: string;
* }
*
* const posts = await client.content
* .getCollection<BlogPost>('Blog')
* .limit(10)
*
* posts.contentlets.forEach(post => {
* console.log(post.title, post.author, post.summary);
* });
* ```
*/
class Content {
/**
* Creates an instance of Content.
* @param {RequestOptions} requestOptions - The options for the client request.
* @param {string} serverUrl - The server URL.
*/
constructor(requestOptions, serverUrl) {
_Content_requestOptions.set(this, void 0);
_Content_serverUrl.set(this, void 0);
__classPrivateFieldSet(this, _Content_requestOptions, requestOptions, "f");
__classPrivateFieldSet(this, _Content_serverUrl, serverUrl, "f");
}
/**
* Takes a content type and returns a builder to filter and fetch the collection.
* @param {string} contentType - The content type to get the collection.
* @return {CollectionBuilder<T>} CollectionBuilder to filter and fetch the collection.
* @template T - Represents the type of the content type to fetch. Defaults to unknown.
* @memberof Content
*
* @example
* ```javascript
* // Using await and async
* const collectionResponse = await client.content
* .getCollection('Blog')
* .limit(10)
* .page(2)
* .sortBy([{ field: 'title', order: 'asc' }])
* .query((queryBuilder) => queryBuilder.field('author').equals('John Doe'))
* .depth(1);
* ```
* @example
* ```javascript
* // Using then and catch
* client.content
* .getCollection('Blog')
* .limit(10)
* .page(2)
* .sortBy([{ field: 'title', order: 'asc' }])
* .query((queryBuilder) => queryBuilder.field('author').equals('John Doe'))
* .depth(1)
* .then((response) => {
* console.log(response.contentlets);
* })
* .catch((error) => {
* console.error(error);
* });
* ```
* @example
* ```typescript
* // Using a specific type for your content
*
* type Blog = {
* summary: string;
* author: string;
* title: string;
* };
*
* client.content
* .getCollection<Blog>('Blog')
* .limit(10)
* .page(2)
* .sortBy([{ field: 'title', order: 'asc' }])
* .query((queryBuilder) => queryBuilder.field('author').equals('John Doe'))
* .depth(1)
* .then((response) => {
* response.contentlets.forEach((blog) => {
* console.log(blog.title);
* console.log(blog.author);
* console.log(blog.summary);
* });
* })
* .catch((error) => {
* console.error(error);
* });
* ```
*
*/
getCollection(contentType) {
return new CollectionBuilder(__classPrivateFieldGet(this, _Content_requestOptions, "f"), __classPrivateFieldGet(this, _Content_serverUrl, "f"), contentType);
}
}
_Content_requestOptions = new WeakMap(), _Content_serverUrl = new WeakMap();
class NavigationClient {
constructor(config, requestOptions) {
this.requestOptions = requestOptions;
this.BASE_URL = `${config?.dotcmsUrl}/api/v1/nav`;
}
/**
* Retrieves information about the dotCMS file and folder tree.
* @param {NavigationApiOptions} options - The options for the Navigation API call. Defaults to `{ depth: 0, path: '/', languageId: 1 }`.
* @returns {Promise<DotCMSNavigationItem[]>} - A Promise that resolves to the response from the DotCMS API.
* @throws {Error} - Throws an error if the options are not valid.
*/
async get(path, params) {
if (!path) {
throw new Error("The 'path' parameter is required for the Navigation API");
}
const navParams = params ? this.mapToBackendParams(params) : {};
const urlParams = new URLSearchParams(navParams).toString();
const parsedPath = path.replace(/^\/+/, '/').replace(/\/+$/, '/');
const url = `${this.BASE_URL}${parsedPath}${urlParams ? `?${urlParams}` : ''}`;
const response = await fetch(url, this.requestOptions);
if (!response.ok) {
throw new Error(`Failed to fetch navigation data: ${response.statusText} - ${response.status}`);
}
return response.json().then((data) => data.entity);
}
mapToBackendParams(params) {
const backendParams = {};
if (params.depth) {
backendParams['depth'] = String(params.depth);
}
if (params.languageId) {
backendParams['language_id'] = String(params.languageId);
}
return backendParams;
}
}
/**
* A record of HTTP status codes and their corresponding error messages.
*
* @type {Record<number, string>}
* @property {string} 401 - Unauthorized. Check the token and try again.
* @property {string} 403 - Forbidden. Check the permissions and try again.
* @property {string} 404 - Not Found. Check the URL and try again.
* @property {string} 500 - Internal Server Error. Try again later.
* @property {string} 502 - Bad Gateway. Try again later.
* @property {string} 503 - Service Unavailable. Try again later.
*/
const ErrorMessages = {
401: 'Unauthorized. Check the token and try again.',
403: 'Forbidden. Check the permissions and try again.',
404: 'Not Found. Check the URL and try again.',
500: 'Internal Server Error. Try again later.',
502: 'Bad Gateway. Try again later.',
503: 'Service Unavailable. Try again later.'
};
const DEFAULT_PAGE_CONTENTLETS_CONTENT = `
publishDate
inode
identifier
archived
urlMap
urlMap
locked
contentType
creationDate
modDate
title
baseType
working
live
publishUser {
firstName
lastName
}
owner {
lastName
}
conLanguage {
language
languageCode
}
modUser {
firstName
lastName
}
`;
/**
* Builds a GraphQL query for retrieving page content from DotCMS.
*
* @param {string} pageQuery - Custom fragment fields to include in the ClientPage fragment
* @param {string} additionalQueries - Additional GraphQL queries to include in the main query
* @returns {string} Complete GraphQL query string for page content
*/
const buildPageQuery = ({ page, fragments, additionalQueries }) => {
if (!page) {
consola.warn("[DotCMS Client]: No page query was found, so we're loading all content using _map. This might slow things down. For better performance, we recommend adding a specific query in the page attribute.");
}
return `
fragment DotCMSPage on DotPage {
publishDate
type
httpsRequired
inode
path
identifier
hasTitleImage
sortOrder
extension
canRead
pageURI
canEdit
archived
friendlyName
workingInode
url
pageURI
hasLiveVersion
deleted
pageUrl
shortyWorking
mimeType
locked
stInode
contentType
creationDate
liveInode
name
shortyLive
modDate
title
baseType
working
canLock
live
isContentlet
statusIcons
canEdit
canLock
canRead
canEdit
canLock
canRead
runningExperimentId
urlContentMap {
_map
}
host {
identifier
hostName
googleMap
archived
contentType
}
vanityUrl {
action
forwardTo
uri
}
conLanguage {
id
language
languageCode
}
template {
drawed
anonymous
theme
identifier
}
containers {
path
identifier
maxContentlets
containerStructures {
id
code
structureId
containerId
contentTypeVar
containerInode
}
containerContentlets {
uuid
contentlets {
${page ? DEFAULT_PAGE_CONTENTLETS_CONTENT : '_map'}
}
}
}
layout {
header
footer
body {
rows {
styleClass
columns {
leftOffset
styleClass
width
left
containers {
identifier
uuid
}
}
}
}
}
viewAs {
visitor {
persona {
modDate
inode
name
identifier
keyTag
photo {
versionPath
}
}
}
persona {
modDate
inode
name
identifier
keyTag
photo {
versionPath
}
}
language {
id
languageCode
countryCode
language
country
}
}
}
${page ? ` fragment ClientPage on DotPage { ${page} } ` : ''}
${fragments ? fragments.join('\n\n') : ''}
query PageContent($url: String!, $languageId: String, $mode: String, $personaId: String, $fireRules: Boolean, $publishDate: String, $siteId: String, $variantName: String) {
page: page(url: $url, languageId: $languageId, pageMode: $mode, persona: $personaId, fireRules: $fireRules, publishDate: $publishDate, site: $siteId, variantName: $variantName) {
...DotCMSPage
${page ? '...ClientPage' : ''}
}
${additionalQueries}
}
`;
};
/**
* Converts a record of query strings into a single GraphQL query string.
*
* @param {Record<string, string>} queryData - Object containing named query strings
* @returns {string} Combined query string or empty string if no queryData provided
*/
function buildQuery(queryData) {
if (!queryData)
return '';
return Object.entries(queryData)
.map(([key, query]) => `${key}: ${query}`)
.join(' ');
}
/**
* Filters response data to include only specified keys.
*
* @param {Record<string, string>} responseData - Original response data object
* @param {string[]} keys - Array of keys to extract from the response data
* @returns {Record<string, string>} New object containing only the specified keys
*/
function mapResponseData(responseData, keys) {
return keys.reduce((accumulator, key) => {
if (responseData[key] !== undefined) {
accumulator[key] = responseData[key];
}
return accumulator;
}, {});
}
/**
* Executes a GraphQL query against the DotCMS API.
*
* @param {Object} options - Options for the fetch request
* @param {string} options.body - GraphQL query string
* @param {Record<string, string>} options.headers - HTTP headers for the request
* @returns {Promise<any>} Parsed JSON response from the GraphQL API
* @throws {Error} If the HTTP response is not successful
*/
async function fetchGraphQL({ baseURL, body, headers }) {
const url = new URL(baseURL);
url.pathname = '/api/v1/graphql';
const response = await fetch(url.toString(), {
method: 'POST',
body,
headers
});
if (!response.ok) {
const error = {
status: response.status,
message: ErrorMessages[response.status] || response.statusText
};
throw error;
}
return await response.json();
}
/**
* Client for interacting with the DotCMS Page API.
* Provides methods to retrieve and manipulate pages.
*/
class PageClient {
/**
* Creates a new PageClient instance.
*
* @param {DotCMSClientConfig} config - Configuration options for the DotCMS client
* @param {RequestOptions} requestOptions - Options for fetch requests including authorization headers
* @example
* ```typescript
* const pageClient = new PageClient(
* {
* dotcmsUrl: 'https://demo.dotcms.com',
* authToken: 'your-auth-token',
* siteId: 'demo.dotcms.com'
* },
* {
* headers: {
* Authorization: 'Bearer your-auth-token'
* }
* }
* );
* ```
*/
constructor(config, requestOptions) {
this.requestOptions = requestOptions;
this.siteId = config.siteId || '';
this.dotcmsUrl = config.dotcmsUrl;
}
/**
* Retrieves a page from DotCMS using GraphQL.
*
* @param {string} url - The URL of the page to retrieve
* @param {DotCMSPageRequestParams} [options] - Options for the request
* @template T - The type of the page and content, defaults to DotCMSBasicPage and Record<string, unknown> | unknown
* @returns {Promise<DotCMSComposedPageResponse<T>>} A Promise that resolves to the page data
*
* @example Using GraphQL
* ```typescript
* const page = await pageClient.get<{ page: MyPageWithBanners; content: { blogPosts: { blogTitle: string } } }>(
* '/index',
* {
* languageId: '1',
* mode: 'LIVE',
* graphql: {
* page: `
* containers {
* containerContentlets {
* contentlets {
* ... on Banner {
* ...bannerFragment
* }
* }
* }
* `,
* content: {
* blogPosts: `
* BlogCollection(limit: 3) {
* ...blogFragment
* }
* `,
* },
* fragments: [
* `
* fragment bannerFragment on Banner {
* caption
* }
* `,
* `
* fragment blogFragment on Blog {
* title
* urlTitle
* }
* `
* ]
* }
* });
* ```
*/
async get(url, options) {
const { languageId = '1', mode = 'LIVE', siteId = this.siteId, fireRules = false, personaId, publishDate, variantName, graphql = {} } = options || {};
const { page, content = {}, variables, fragments } = graphql;
const contentQuery = buildQuery(content);
const completeQuery = buildPageQuery({
page,
fragments,
a