@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/next.esm.js DELETED
@@ -1,551 +0,0 @@
1
- import { E as ErrorMessages, _ as __classPrivateFieldGet, g as graphqlToPageEntity, C as Content } from './transforms.esm.js';
2
-
3
- class NavigationClient {
4
- constructor(config, requestOptions) {
5
- this.requestOptions = requestOptions;
6
- this.BASE_URL = `${config?.dotcmsUrl}/api/v1/nav`;
7
- }
8
- /**
9
- * Retrieves information about the dotCMS file and folder tree.
10
- * @param {NavigationApiOptions} options - The options for the Navigation API call. Defaults to `{ depth: 0, path: '/', languageId: 1 }`.
11
- * @returns {Promise<unknown>} - A Promise that resolves to the response from the DotCMS API.
12
- * @throws {Error} - Throws an error if the options are not valid.
13
- */
14
- async get(path, params) {
15
- if (!path) {
16
- throw new Error("The 'path' parameter is required for the Navigation API");
17
- }
18
- const navParams = params ? this.mapToBackendParams(params) : {};
19
- const urlParams = new URLSearchParams(navParams).toString();
20
- const parsedPath = path.replace(/^\/+/, '/').replace(/\/+$/, '/');
21
- const url = `${this.BASE_URL}${parsedPath}${urlParams ? `?${urlParams}` : ''}`;
22
- const response = await fetch(url, this.requestOptions);
23
- if (!response.ok) {
24
- throw new Error(`Failed to fetch navigation data: ${response.statusText} - ${response.status}`);
25
- }
26
- return response.json().then((data) => data.entity);
27
- }
28
- mapToBackendParams(params) {
29
- const backendParams = {};
30
- if (params.depth) {
31
- backendParams['depth'] = String(params.depth);
32
- }
33
- if (params.languageId) {
34
- backendParams['language_id'] = String(params.languageId);
35
- }
36
- return backendParams;
37
- }
38
- }
39
-
40
- const DEFAULT_PAGE_CONTENTLETS_CONTENT = `
41
- publishDate
42
- inode
43
- identifier
44
- archived
45
- urlMap
46
- urlMap
47
- locked
48
- contentType
49
- creationDate
50
- modDate
51
- title
52
- baseType
53
- working
54
- live
55
- publishUser {
56
- firstName
57
- lastName
58
- }
59
- owner {
60
- lastName
61
- }
62
- conLanguage {
63
- language
64
- languageCode
65
- }
66
- modUser {
67
- firstName
68
- lastName
69
- }
70
- `;
71
- /**
72
- * Builds a GraphQL query for retrieving page content from DotCMS.
73
- *
74
- * @param {string} pageQuery - Custom fragment fields to include in the ClientPage fragment
75
- * @param {string} additionalQueries - Additional GraphQL queries to include in the main query
76
- * @returns {string} Complete GraphQL query string for page content
77
- */
78
- const buildPageQuery = ({ page, fragments, additionalQueries }) => {
79
- if (!page) {
80
- console.warn('No page query provided. The query will be used by fetching all content with _map. This may mean poor performance in the query. We suggest you provide a detailed query on page attribute.');
81
- }
82
- return `
83
- fragment DotCMSPage on DotPage {
84
- publishDate
85
- type
86
- httpsRequired
87
- inode
88
- path
89
- identifier
90
- hasTitleImage
91
- sortOrder
92
- extension
93
- canRead
94
- pageURI
95
- canEdit
96
- archived
97
- friendlyName
98
- workingInode
99
- url
100
- hasLiveVersion
101
- deleted
102
- pageUrl
103
- shortyWorking
104
- mimeType
105
- locked
106
- stInode
107
- contentType
108
- creationDate
109
- liveInode
110
- name
111
- shortyLive
112
- modDate
113
- title
114
- baseType
115
- working
116
- canLock
117
- live
118
- isContentlet
119
- statusIcons
120
- canEdit
121
- canLock
122
- canRead
123
- canEdit
124
- canLock
125
- canRead
126
- conLanguage {
127
- id
128
- language
129
- languageCode
130
- }
131
- template {
132
- drawed
133
- }
134
- containers {
135
- path
136
- identifier
137
- maxContentlets
138
- containerStructures {
139
- id
140
- code
141
- structureId
142
- containerId
143
- contentTypeVar
144
- containerInode
145
- }
146
- containerContentlets {
147
- uuid
148
- contentlets {
149
- ${page ? DEFAULT_PAGE_CONTENTLETS_CONTENT : '_map'}
150
- }
151
- }
152
- }
153
- layout {
154
- header
155
- footer
156
- body {
157
- rows {
158
- columns {
159
- leftOffset
160
- styleClass
161
- width
162
- left
163
- containers {
164
- identifier
165
- uuid
166
- }
167
- }
168
- }
169
- }
170
- }
171
- viewAs {
172
- visitor {
173
- persona {
174
- name
175
- }
176
- }
177
- language {
178
- id
179
- languageCode
180
- countryCode
181
- language
182
- country
183
- }
184
- }
185
- }
186
-
187
- ${page ? ` fragment ClientPage on DotPage { ${page} } ` : ''}
188
-
189
- ${fragments ? fragments.join('\n\n') : ''}
190
-
191
- query PageContent($url: String!, $languageId: String, $mode: String) {
192
- page: page(url: $url, languageId: $languageId, pageMode: $mode) {
193
- ...DotCMSPage
194
- ${page ? '...ClientPage' : ''}
195
- }
196
-
197
- ${additionalQueries}
198
- }
199
- `;
200
- };
201
- /**
202
- * Converts a record of query strings into a single GraphQL query string.
203
- *
204
- * @param {Record<string, string>} queryData - Object containing named query strings
205
- * @returns {string} Combined query string or empty string if no queryData provided
206
- */
207
- function buildQuery(queryData) {
208
- if (!queryData)
209
- return '';
210
- return Object.entries(queryData)
211
- .map(([key, query]) => `${key}: ${query}`)
212
- .join(' ');
213
- }
214
- /**
215
- * Filters response data to include only specified keys.
216
- *
217
- * @param {Record<string, string>} responseData - Original response data object
218
- * @param {string[]} keys - Array of keys to extract from the response data
219
- * @returns {Record<string, string>} New object containing only the specified keys
220
- */
221
- function mapResponseData(responseData, keys) {
222
- return keys.reduce((accumulator, key) => {
223
- if (responseData[key] !== undefined) {
224
- accumulator[key] = responseData[key];
225
- }
226
- return accumulator;
227
- }, {});
228
- }
229
- /**
230
- * Executes a GraphQL query against the DotCMS API.
231
- *
232
- * @param {Object} options - Options for the fetch request
233
- * @param {string} options.body - GraphQL query string
234
- * @param {Record<string, string>} options.headers - HTTP headers for the request
235
- * @returns {Promise<any>} Parsed JSON response from the GraphQL API
236
- * @throws {Error} If the HTTP response is not successful
237
- */
238
- async function fetchGraphQL({ baseURL, body, headers }) {
239
- const url = new URL(baseURL);
240
- url.pathname = '/api/v1/graphql';
241
- const response = await fetch(url.toString(), {
242
- method: 'POST',
243
- body,
244
- headers
245
- });
246
- if (!response.ok) {
247
- const error = {
248
- status: response.status,
249
- message: ErrorMessages[response.status] || response.statusText
250
- };
251
- throw error;
252
- }
253
- return await response.json();
254
- }
255
-
256
- var _PageClient_instances, _PageClient_isGraphQLRequest, _PageClient_getPageFromAPI, _PageClient_getPageFromGraphQL, _PageClient_mapToBackendParams;
257
- /**
258
- * Client for interacting with the DotCMS Page API.
259
- * Provides methods to retrieve and manipulate pages.
260
- */
261
- class PageClient {
262
- /**
263
- * Creates a new PageClient instance.
264
- *
265
- * @param {DotCMSClientConfig} config - Configuration options for the DotCMS client
266
- * @param {RequestOptions} requestOptions - Options for fetch requests including authorization headers
267
- * @example
268
- * ```typescript
269
- * const pageClient = new PageClient(
270
- * {
271
- * dotcmsUrl: 'https://demo.dotcms.com',
272
- * authToken: 'your-auth-token',
273
- * siteId: 'demo.dotcms.com'
274
- * },
275
- * {
276
- * headers: {
277
- * Authorization: 'Bearer your-auth-token'
278
- * }
279
- * }
280
- * );
281
- * ```
282
- */
283
- constructor(config, requestOptions) {
284
- _PageClient_instances.add(this);
285
- this.requestOptions = requestOptions;
286
- this.siteId = config.siteId || '';
287
- this.dotcmsUrl = config.dotcmsUrl;
288
- }
289
- get(url, options) {
290
- if (!options) {
291
- return __classPrivateFieldGet(this, _PageClient_instances, "m", _PageClient_getPageFromAPI).call(this, url);
292
- }
293
- if (__classPrivateFieldGet(this, _PageClient_instances, "m", _PageClient_isGraphQLRequest).call(this, options)) {
294
- return __classPrivateFieldGet(this, _PageClient_instances, "m", _PageClient_getPageFromGraphQL).call(this, url, options);
295
- }
296
- return __classPrivateFieldGet(this, _PageClient_instances, "m", _PageClient_getPageFromAPI).call(this, url, options);
297
- }
298
- }
299
- _PageClient_instances = new WeakSet(), _PageClient_isGraphQLRequest = function _PageClient_isGraphQLRequest(options) {
300
- return 'graphql' in options;
301
- }, _PageClient_getPageFromAPI =
302
- /**
303
- * Retrieves all the elements of a Page in your dotCMS system in JSON format.
304
- *
305
- * @param {string} path - The path of the page to retrieve
306
- * @param {PageRequestParams} params - The options for the Page API call
307
- * @returns {Promise<unknown>} A Promise that resolves to the page data
308
- * @throws {Error} Throws an error if the path parameter is missing or if the fetch request fails
309
- * @example
310
- * ```typescript
311
- * // Get a page with default parameters
312
- * const homePage = await pageClient.get('/');
313
- *
314
- * // Get a page with specific language and mode
315
- * const aboutPage = await pageClient.get('/about-us', {
316
- * languageId: 2,
317
- * mode: 'PREVIEW_MODE'
318
- * });
319
- *
320
- * // Get a page with persona targeting
321
- * const productPage = await pageClient.get('/products', {
322
- * personaId: 'persona-123',
323
- * depth: 2
324
- * });
325
- * ```
326
- */
327
- async function _PageClient_getPageFromAPI(path, params) {
328
- if (!path) {
329
- throw new Error("The 'path' parameter is required for the Page API");
330
- }
331
- const normalizedParams = __classPrivateFieldGet(this, _PageClient_instances, "m", _PageClient_mapToBackendParams).call(this, params || {});
332
- const queryParams = new URLSearchParams(normalizedParams).toString();
333
- // If the path starts with a slash, remove it to avoid double slashes in the final URL
334
- // Because the page path is part of api url path
335
- const pagePath = path.startsWith('/') ? path.slice(1) : path;
336
- const url = `${this.dotcmsUrl}/api/v1/page/json/${pagePath}?${queryParams}`;
337
- const response = await fetch(url, this.requestOptions);
338
- if (!response.ok) {
339
- const error = {
340
- status: response.status,
341
- message: ErrorMessages[response.status] || response.statusText
342
- };
343
- throw error;
344
- }
345
- return response.json().then((data) => data.entity);
346
- }, _PageClient_getPageFromGraphQL =
347
- /**
348
- * Retrieves a personalized page with associated content and navigation.
349
- *
350
- * @param {Object} options - Options for the personalized page request
351
- * @param {string} options.url - The URL of the page to retrieve
352
- * @param {string} options.languageId - The language ID for the page content
353
- * @param {string} options.mode - The rendering mode for the page
354
- * @param {string} options.pageFragment - GraphQL fragment for page data
355
- * @param {Record<string, string>} options.content - Content queries to include
356
- * @param {Record<string, string>} options.nav - Navigation queries to include
357
- * @returns {Promise<Object>} A Promise that resolves to the personalized page data with content and navigation
358
- * @example
359
- * ```typescript
360
- * // Get a personalized page with content and navigation
361
- * const personalizedPage = await pageClient.getPageFromGraphQL({
362
- * url: '/about-us',
363
- * languageId: '1',
364
- * mode: 'LIVE',
365
- * pageFragment: `
366
- * fragment PageFields on Page {
367
- * title
368
- * description
369
- * modDate
370
- * }
371
- * `,
372
- * content: {
373
- * blogs: `
374
- * search(query: "+contentType: blog", limit: 3) {
375
- * title
376
- * ...on Blog {
377
- * author {
378
- * title
379
- * }
380
- * }
381
- }
382
- * nav: {
383
- * mainNav: `
384
- * query MainNav {
385
- * Nav(identifier: "main-nav") {
386
- * title
387
- * items {
388
- * label
389
- * url
390
- * }
391
- * }
392
- * }
393
- * `
394
- * }
395
- * });
396
- * ```
397
- */
398
- async function _PageClient_getPageFromGraphQL(url, options) {
399
- const { languageId = '1', mode = 'LIVE', graphql = {} } = options || {};
400
- const { page, content = {}, variables, fragments } = graphql;
401
- const contentQuery = buildQuery(content);
402
- const completeQuery = buildPageQuery({
403
- page,
404
- fragments,
405
- additionalQueries: contentQuery
406
- });
407
- const requestVariables = {
408
- url,
409
- mode,
410
- languageId,
411
- ...variables
412
- };
413
- const requestHeaders = this.requestOptions.headers;
414
- const requestBody = JSON.stringify({ query: completeQuery, variables: requestVariables });
415
- try {
416
- const { data, errors } = await fetchGraphQL({
417
- baseURL: this.dotcmsUrl,
418
- body: requestBody,
419
- headers: requestHeaders
420
- });
421
- if (errors) {
422
- errors.forEach((error) => {
423
- throw new Error(error.message);
424
- });
425
- }
426
- const pageResponse = graphqlToPageEntity(data);
427
- if (!pageResponse) {
428
- throw new Error('No page data found');
429
- }
430
- const contentResponse = mapResponseData(data, Object.keys(content));
431
- return {
432
- page: pageResponse,
433
- content: contentResponse,
434
- errors
435
- };
436
- }
437
- catch (error) {
438
- const errorMessage = {
439
- error,
440
- message: 'Failed to retrieve page data',
441
- query: completeQuery,
442
- variables: requestVariables
443
- };
444
- throw errorMessage;
445
- }
446
- }, _PageClient_mapToBackendParams = function _PageClient_mapToBackendParams(params) {
447
- const backendParams = {
448
- hostId: params.siteId || this.siteId,
449
- mode: params.mode,
450
- language_id: params.languageId ? String(params.languageId) : undefined,
451
- 'com.dotmarketing.persona.id': params.personaId,
452
- fireRules: params.fireRules ? String(params.fireRules) : undefined,
453
- depth: params.depth ? String(params.depth) : undefined,
454
- publishDate: params.publishDate
455
- };
456
- // Remove undefined values
457
- return Object.fromEntries(Object.entries(backendParams).filter(([_, value]) => value !== undefined));
458
- };
459
-
460
- /**
461
- * Parses a string into a URL object.
462
- *
463
- * @param url - The URL string to parse
464
- * @returns A URL object if parsing is successful, undefined otherwise
465
- */
466
- function parseURL(url) {
467
- try {
468
- return new URL(url);
469
- }
470
- catch {
471
- console.error('Invalid URL:', url);
472
- return undefined;
473
- }
474
- }
475
- /**
476
- * Default configuration for the DotCMS client.
477
- */
478
- const defaultConfig = {
479
- dotcmsUrl: '',
480
- authToken: '',
481
- requestOptions: {}
482
- };
483
- /**
484
- * Client for interacting with the DotCMS REST API.
485
- * Provides access to content, page, and navigation functionality.
486
- */
487
- class DotCMSClient {
488
- /**
489
- * Creates a new DotCMS client instance.
490
- *
491
- * @param config - Configuration options for the client
492
- * @throws Warning if dotcmsUrl is invalid or authToken is missing
493
- */
494
- constructor(config = defaultConfig) {
495
- this.config = config;
496
- this.requestOptions = this.createAuthenticatedRequestOptions(this.config);
497
- // Initialize clients
498
- this.page = new PageClient(this.config, this.requestOptions);
499
- this.nav = new NavigationClient(this.config, this.requestOptions);
500
- this.content = new Content(this.requestOptions, this.config.dotcmsUrl);
501
- }
502
- /**
503
- * Creates request options with authentication headers.
504
- *
505
- * @param config - The client configuration
506
- * @returns Request options with authorization headers
507
- */
508
- createAuthenticatedRequestOptions(config) {
509
- return {
510
- ...config.requestOptions,
511
- headers: {
512
- ...config.requestOptions?.headers,
513
- Authorization: `Bearer ${config.authToken}`
514
- }
515
- };
516
- }
517
- }
518
- /**
519
- * Creates and returns a new DotCMS client instance.
520
- *
521
- * @param config - Configuration options for the client
522
- * @returns A configured DotCMS client instance
523
- * @example
524
- * ```typescript
525
- * const client = dotCMSCreateClient({
526
- * dotcmsUrl: 'https://demo.dotcms.com',
527
- * authToken: 'your-auth-token'
528
- * });
529
- *
530
- * // Use the client to fetch content
531
- * const pages = await client.page.get('/about-us');
532
- * ```
533
- */
534
- const createDotCMSClient = (clientConfig) => {
535
- const { dotcmsUrl, authToken } = clientConfig || {};
536
- const instanceUrl = parseURL(dotcmsUrl)?.origin;
537
- if (!instanceUrl) {
538
- throw new TypeError("Invalid configuration - 'dotcmsUrl' must be a valid URL");
539
- }
540
- if (!authToken) {
541
- throw new TypeError("Invalid configuration - 'authToken' is required");
542
- }
543
- const config = {
544
- ...clientConfig,
545
- authToken,
546
- dotcmsUrl: instanceUrl
547
- };
548
- return new DotCMSClient(config);
549
- };
550
-
551
- export { createDotCMSClient };