@contentful/experiences-core 1.35.0-dev-20250312T0909-245a333.0 → 1.35.0-prerelease-20250414T1325-5725f29.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.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- import md5 from 'md5';
2
1
  import { z, ZodIssueCode } from 'zod';
2
+ import { omit, isArray, uniqBy } from 'lodash-es';
3
+ import md5 from 'md5';
3
4
  import { BLOCKS } from '@contentful/rich-text-types';
4
- import { isArray, omit, uniqBy } from 'lodash-es';
5
5
 
6
6
  const INCOMING_EVENTS = {
7
7
  RequestEditorMode: 'requestEditorMode',
@@ -151,514 +151,173 @@ const isStructureWithRelativeHeight = (componentId, height) => {
151
151
  return isContentfulStructureComponent(componentId) && !height?.toString().endsWith('px');
152
152
  };
153
153
 
154
- const findOutermostCoordinates = (first, second) => {
155
- return {
156
- top: Math.min(first.top, second.top),
157
- right: Math.max(first.right, second.right),
158
- bottom: Math.max(first.bottom, second.bottom),
159
- left: Math.min(first.left, second.left),
160
- };
161
- };
162
- const getElementCoordinates = (element) => {
163
- const rect = element.getBoundingClientRect();
164
- /**
165
- * If element does not have children, or element has it's own width or height,
166
- * return the element's coordinates.
167
- */
168
- if (element.children.length === 0 || rect.width !== 0 || rect.height !== 0) {
169
- return rect;
170
- }
171
- const rects = [];
172
- /**
173
- * If element has children, or element does not have it's own width and height,
174
- * we find the cordinates of the children, and assume the outermost coordinates of the children
175
- * as the coordinate of the element.
176
- *
177
- * E.g child1 => {top: 2, bottom: 3, left: 4, right: 6} & child2 => {top: 1, bottom: 8, left: 12, right: 24}
178
- * The final assumed coordinates of the element would be => { top: 1, right: 24, bottom: 8, left: 4 }
179
- */
180
- for (const child of element.children) {
181
- const childRect = getElementCoordinates(child);
182
- if (childRect.width !== 0 || childRect.height !== 0) {
183
- const { top, right, bottom, left } = childRect;
184
- rects.push({ top, right, bottom, left });
185
- }
186
- }
187
- if (rects.length === 0) {
188
- return rect;
189
- }
190
- const { top, right, bottom, left } = rects.reduce(findOutermostCoordinates);
191
- return DOMRect.fromRect({
192
- x: left,
193
- y: top,
194
- height: bottom - top,
195
- width: right - left,
196
- });
197
- };
198
-
199
- class ParseError extends Error {
200
- constructor(message) {
201
- super(message);
202
- }
203
- }
204
- const isValidJsonObject = (s) => {
205
- try {
206
- const result = JSON.parse(s);
207
- if ('object' !== typeof result) {
208
- return false;
209
- }
210
- return true;
211
- }
212
- catch (e) {
213
- return false;
214
- }
215
- };
216
- const doesMismatchMessageSchema = (event) => {
217
- try {
218
- tryParseMessage(event);
219
- return false;
220
- }
221
- catch (e) {
222
- if (e instanceof ParseError) {
223
- return e.message;
224
- }
225
- throw e;
226
- }
227
- };
228
- const tryParseMessage = (event) => {
229
- if (!event.data) {
230
- throw new ParseError('Field event.data is missing');
231
- }
232
- if ('string' !== typeof event.data) {
233
- throw new ParseError(`Field event.data must be a string, instead of '${typeof event.data}'`);
234
- }
235
- if (!isValidJsonObject(event.data)) {
236
- throw new ParseError('Field event.data must be a valid JSON object serialized as string');
237
- }
238
- const eventData = JSON.parse(event.data);
239
- if (!eventData.source) {
240
- throw new ParseError(`Field eventData.source must be equal to 'composability-app'`);
241
- }
242
- if ('composability-app' !== eventData.source) {
243
- throw new ParseError(`Field eventData.source must be equal to 'composability-app', instead of '${eventData.source}'`);
244
- }
245
- // check eventData.eventType
246
- const supportedEventTypes = Object.values(INCOMING_EVENTS);
247
- if (!supportedEventTypes.includes(eventData.eventType)) {
248
- // Expected message: This message is handled in the EntityStore to store fetched entities
249
- if (eventData.eventType !== PostMessageMethods.REQUESTED_ENTITIES) {
250
- throw new ParseError(`Field eventData.eventType must be one of the supported values: [${supportedEventTypes.join(', ')}]`);
251
- }
252
- }
253
- return eventData;
154
+ // These styles get added to every component, user custom or contentful provided
155
+ const builtInStyles = {
156
+ cfVerticalAlignment: {
157
+ validations: {
158
+ in: [
159
+ {
160
+ value: 'start',
161
+ displayName: 'Align left',
162
+ },
163
+ {
164
+ value: 'center',
165
+ displayName: 'Align center',
166
+ },
167
+ {
168
+ value: 'end',
169
+ displayName: 'Align right',
170
+ },
171
+ ],
172
+ },
173
+ type: 'Text',
174
+ group: 'style',
175
+ description: 'The vertical alignment of the section',
176
+ defaultValue: 'center',
177
+ displayName: 'Vertical alignment',
178
+ },
179
+ cfHorizontalAlignment: {
180
+ validations: {
181
+ in: [
182
+ {
183
+ value: 'start',
184
+ displayName: 'Align top',
185
+ },
186
+ {
187
+ value: 'center',
188
+ displayName: 'Align center',
189
+ },
190
+ {
191
+ value: 'end',
192
+ displayName: 'Align bottom',
193
+ },
194
+ ],
195
+ },
196
+ type: 'Text',
197
+ group: 'style',
198
+ description: 'The horizontal alignment of the section',
199
+ defaultValue: 'center',
200
+ displayName: 'Horizontal alignment',
201
+ },
202
+ cfVisibility: {
203
+ displayName: 'Visibility toggle',
204
+ type: 'Boolean',
205
+ group: 'style',
206
+ defaultValue: true,
207
+ description: 'The visibility of the component',
208
+ },
209
+ cfMargin: {
210
+ displayName: 'Margin',
211
+ type: 'Text',
212
+ group: 'style',
213
+ description: 'The margin of the section',
214
+ defaultValue: '0 0 0 0',
215
+ },
216
+ cfPadding: {
217
+ displayName: 'Padding',
218
+ type: 'Text',
219
+ group: 'style',
220
+ description: 'The padding of the section',
221
+ defaultValue: '0 0 0 0',
222
+ },
223
+ cfBackgroundColor: {
224
+ displayName: 'Background color',
225
+ type: 'Text',
226
+ group: 'style',
227
+ description: 'The background color of the section',
228
+ defaultValue: 'rgba(0, 0, 0, 0)',
229
+ },
230
+ cfWidth: {
231
+ displayName: 'Width',
232
+ type: 'Text',
233
+ group: 'style',
234
+ description: 'The width of the section',
235
+ defaultValue: '100%',
236
+ },
237
+ cfHeight: {
238
+ displayName: 'Height',
239
+ type: 'Text',
240
+ group: 'style',
241
+ description: 'The height of the section',
242
+ defaultValue: 'fit-content',
243
+ },
244
+ cfMaxWidth: {
245
+ displayName: 'Max width',
246
+ type: 'Text',
247
+ group: 'style',
248
+ description: 'The max-width of the section',
249
+ defaultValue: 'none',
250
+ },
251
+ cfFlexDirection: {
252
+ displayName: 'Direction',
253
+ type: 'Text',
254
+ group: 'style',
255
+ description: 'The orientation of the section',
256
+ defaultValue: 'column',
257
+ },
258
+ cfFlexReverse: {
259
+ displayName: 'Reverse Direction',
260
+ type: 'Boolean',
261
+ group: 'style',
262
+ description: 'Toggle the flex direction to be reversed',
263
+ defaultValue: false,
264
+ },
265
+ cfFlexWrap: {
266
+ displayName: 'Wrap objects',
267
+ type: 'Text',
268
+ group: 'style',
269
+ description: 'Wrap objects',
270
+ defaultValue: 'nowrap',
271
+ },
272
+ cfBorder: {
273
+ displayName: 'Border',
274
+ type: 'Text',
275
+ group: 'style',
276
+ description: 'The border of the section',
277
+ defaultValue: '0px solid rgba(0, 0, 0, 0)',
278
+ },
279
+ cfGap: {
280
+ displayName: 'Gap',
281
+ type: 'Text',
282
+ group: 'style',
283
+ description: 'The spacing between the elements of the section',
284
+ defaultValue: '0px',
285
+ },
286
+ cfHyperlink: {
287
+ displayName: 'URL',
288
+ type: 'Hyperlink',
289
+ defaultValue: '',
290
+ validations: {
291
+ format: 'URL',
292
+ bindingSourceType: ['entry', 'experience', 'manual'],
293
+ },
294
+ description: 'hyperlink for section or container',
295
+ },
296
+ cfOpenInNewTab: {
297
+ displayName: 'URL behaviour',
298
+ type: 'Boolean',
299
+ defaultValue: false,
300
+ description: 'Open in new tab',
301
+ },
254
302
  };
255
- const validateExperienceBuilderConfig = ({ locale, mode, }) => {
256
- if (mode === StudioCanvasMode.EDITOR || mode === StudioCanvasMode.READ_ONLY) {
257
- return;
258
- }
259
- if (!locale) {
260
- throw new Error('Parameter "locale" is required for experience builder initialization outside of editor mode');
261
- }
262
- };
263
-
264
- const transformVisibility = (value) => {
265
- if (value === false) {
266
- return {
267
- display: 'none !important',
268
- };
269
- }
270
- // Don't explicitly set anything when visible to not overwrite values like `grid` or `flex`.
271
- return {};
272
- };
273
- // Keep this for backwards compatibility - deleting this would be a breaking change
274
- // because existing components on a users experience will have the width value as fill
275
- // rather than 100%
276
- const transformFill = (value) => (value === 'fill' ? '100%' : value);
277
- const transformGridColumn = (span) => {
278
- if (!span) {
279
- return {};
280
- }
281
- return {
282
- gridColumn: `span ${span}`,
283
- };
284
- };
285
- const transformBorderStyle = (value) => {
286
- if (!value)
287
- return {};
288
- const parts = value.split(' ');
289
- // Just accept the passed value
290
- if (parts.length < 3)
291
- return { border: value };
292
- const [borderSize, borderStyle, ...borderColorParts] = parts;
293
- const borderColor = borderColorParts.join(' ');
294
- return {
295
- border: `${borderSize} ${borderStyle} ${borderColor}`,
296
- };
297
- };
298
- const transformAlignment = (cfHorizontalAlignment, cfVerticalAlignment, cfFlexDirection = 'column') => cfFlexDirection === 'row'
299
- ? {
300
- alignItems: cfHorizontalAlignment,
301
- justifyContent: cfVerticalAlignment === 'center' ? `safe ${cfVerticalAlignment}` : cfVerticalAlignment,
302
- }
303
- : {
304
- alignItems: cfVerticalAlignment,
305
- justifyContent: cfHorizontalAlignment === 'center'
306
- ? `safe ${cfHorizontalAlignment}`
307
- : cfHorizontalAlignment,
308
- };
309
- const transformBackgroundImage = (cfBackgroundImageUrl, cfBackgroundImageOptions) => {
310
- const matchBackgroundSize = (scaling) => {
311
- if ('fill' === scaling)
312
- return 'cover';
313
- if ('fit' === scaling)
314
- return 'contain';
315
- };
316
- const matchBackgroundPosition = (alignment) => {
317
- if (!alignment || 'string' !== typeof alignment) {
318
- return;
319
- }
320
- let [horizontalAlignment, verticalAlignment] = alignment.trim().split(/\s+/, 2);
321
- // Special case for handling single values
322
- // for backwards compatibility with single values 'right','left', 'center', 'top','bottom'
323
- if (horizontalAlignment && !verticalAlignment) {
324
- const singleValue = horizontalAlignment;
325
- switch (singleValue) {
326
- case 'left':
327
- horizontalAlignment = 'left';
328
- verticalAlignment = 'center';
329
- break;
330
- case 'right':
331
- horizontalAlignment = 'right';
332
- verticalAlignment = 'center';
333
- break;
334
- case 'center':
335
- horizontalAlignment = 'center';
336
- verticalAlignment = 'center';
337
- break;
338
- case 'top':
339
- horizontalAlignment = 'center';
340
- verticalAlignment = 'top';
341
- break;
342
- case 'bottom':
343
- horizontalAlignment = 'center';
344
- verticalAlignment = 'bottom';
345
- break;
346
- // just fall down to the normal validation logic for horiz and vert
347
- }
348
- }
349
- const isHorizontalValid = ['left', 'right', 'center'].includes(horizontalAlignment);
350
- const isVerticalValid = ['top', 'bottom', 'center'].includes(verticalAlignment);
351
- horizontalAlignment = isHorizontalValid ? horizontalAlignment : 'left';
352
- verticalAlignment = isVerticalValid ? verticalAlignment : 'top';
353
- return `${horizontalAlignment} ${verticalAlignment}`;
354
- };
355
- if (!cfBackgroundImageUrl) {
356
- return;
357
- }
358
- let backgroundImage;
359
- let backgroundImageSet;
360
- if (typeof cfBackgroundImageUrl === 'string') {
361
- backgroundImage = `url(${cfBackgroundImageUrl})`;
362
- }
363
- else {
364
- const imgSet = cfBackgroundImageUrl.srcSet?.join(',');
365
- backgroundImage = `url(${cfBackgroundImageUrl.url})`;
366
- backgroundImageSet = `image-set(${imgSet})`;
367
- }
368
- return {
369
- backgroundImage,
370
- backgroundImage2: backgroundImageSet,
371
- backgroundRepeat: cfBackgroundImageOptions?.scaling === 'tile' ? 'repeat' : 'no-repeat',
372
- backgroundPosition: matchBackgroundPosition(cfBackgroundImageOptions?.alignment),
373
- backgroundSize: matchBackgroundSize(cfBackgroundImageOptions?.scaling),
374
- };
375
- };
376
-
377
- const toCSSAttribute = (key) => {
378
- let val = key.replace(/[A-Z]/g, (m) => '-' + m.toLowerCase());
379
- // Remove the number from the end of the key to allow for overrides on style properties
380
- val = val.replace(/\d+$/, '');
381
- return val;
382
- };
383
- /**
384
- * Turns a list of CSSProperties into a joined CSS string that can be
385
- * used for <style> tags. Per default it creates a minimized version.
386
- * For editor mode, use the `useWhitespaces` flag to create a more readable version.
387
- *
388
- * @param cssProperties list of CSS properties
389
- * @param useWhitespaces adds whitespaces and newlines between each rule
390
- * @returns a string of CSS rules
391
- */
392
- const stringifyCssProperties = (cssProperties, useWhitespaces = false) => {
393
- const rules = Object.entries(cssProperties)
394
- .filter(([, value]) => value !== undefined)
395
- .map(([key, value]) => useWhitespaces ? `${toCSSAttribute(key)}: ${value};` : `${toCSSAttribute(key)}:${value};`);
396
- return rules.join(useWhitespaces ? '\n' : '');
397
- };
398
- const buildStyleTag = ({ styles, nodeId }) => {
399
- const generatedStyles = stringifyCssProperties(styles, true);
400
- const className = `cfstyles-${nodeId ? nodeId : md5(generatedStyles)}`;
401
- const styleRule = `.${className}{ ${generatedStyles} }`;
402
- return [className, styleRule];
403
- };
404
- /**
405
- * Takes plain design values and transforms them into CSS properties. Undefined values will
406
- * be filtered out.
407
- *
408
- * **Example Input**
409
- * ```
410
- * values = {
411
- * cfVisibility: 'visible',
412
- * cfMargin: '10px',
413
- * cfFlexReverse: true,
414
- * cfImageOptions: { objectFit: 'cover' },
415
- * // ...
416
- * }
417
- * ```
418
- * **Example Output**
419
- * ```
420
- * cssProperties = {
421
- * margin: '10px',
422
- * flexDirection: 'row-reverse',
423
- * objectFit: 'cover',
424
- * // ...
425
- * }
426
- * ```
427
- */
428
- const buildCfStyles = (values) => {
429
- const cssProperties = {
430
- boxSizing: 'border-box',
431
- ...transformVisibility(values.cfVisibility),
432
- margin: values.cfMargin,
433
- padding: values.cfPadding,
434
- backgroundColor: values.cfBackgroundColor,
435
- width: transformFill(values.cfWidth || values.cfImageOptions?.width),
436
- height: transformFill(values.cfHeight || values.cfImageOptions?.height),
437
- maxWidth: values.cfMaxWidth,
438
- ...transformGridColumn(values.cfColumnSpan),
439
- ...transformBorderStyle(values.cfBorder),
440
- borderRadius: values.cfBorderRadius,
441
- gap: values.cfGap,
442
- ...transformAlignment(values.cfHorizontalAlignment, values.cfVerticalAlignment, values.cfFlexDirection),
443
- flexDirection: values.cfFlexReverse && values.cfFlexDirection
444
- ? `${values.cfFlexDirection}-reverse`
445
- : values.cfFlexDirection,
446
- flexWrap: values.cfFlexWrap,
447
- ...transformBackgroundImage(values.cfBackgroundImageUrl, values.cfBackgroundImageOptions),
448
- fontSize: values.cfFontSize,
449
- fontWeight: values.cfTextBold ? 'bold' : values.cfFontWeight,
450
- fontStyle: values.cfTextItalic ? 'italic' : undefined,
451
- textDecoration: values.cfTextUnderline ? 'underline' : undefined,
452
- lineHeight: values.cfLineHeight,
453
- letterSpacing: values.cfLetterSpacing,
454
- color: values.cfTextColor,
455
- textAlign: values.cfTextAlign,
456
- textTransform: values.cfTextTransform,
457
- objectFit: values.cfImageOptions?.objectFit,
458
- objectPosition: values.cfImageOptions?.objectPosition,
459
- };
460
- const cssPropertiesWithoutUndefined = Object.fromEntries(Object.entries(cssProperties).filter(([, value]) => value !== undefined));
461
- return cssPropertiesWithoutUndefined;
462
- };
463
- /**
464
- * **Only meant to be used in editor mode!**
465
- *
466
- * If the node is an empty structure component with a relative height (e.g. '100%'),
467
- * it might render with a zero height. In this case, add a min height of 80px to ensure
468
- * that child nodes can be added via drag & drop.
469
- */
470
- const addMinHeightForEmptyStructures = (cssProperties, node) => {
471
- if (!node.children.length &&
472
- isStructureWithRelativeHeight(node.definitionId, cssProperties.height)) {
473
- return {
474
- ...cssProperties,
475
- minHeight: EMPTY_CONTAINER_HEIGHT,
476
- };
477
- }
478
- return cssProperties;
479
- };
480
- /**
481
- * Container/section default behavior:
482
- * Default height => height: EMPTY_CONTAINER_HEIGHT
483
- * If a container component has children => height: 'fit-content'
484
- */
485
- const calculateNodeDefaultHeight = ({ blockId, children, value, }) => {
486
- if (!blockId || !isContentfulStructureComponent(blockId) || value !== 'auto') {
487
- return value;
488
- }
489
- if (children.length) {
490
- return '100%';
491
- }
492
- return EMPTY_CONTAINER_HEIGHT;
493
- };
494
-
495
- // These styles get added to every component, user custom or contentful provided
496
- const builtInStyles = {
497
- cfVerticalAlignment: {
303
+ const optionalBuiltInStyles = {
304
+ cfFontSize: {
305
+ displayName: 'Font Size',
306
+ type: 'Text',
307
+ group: 'style',
308
+ description: 'The font size of the element',
309
+ defaultValue: '16px',
310
+ },
311
+ cfFontWeight: {
498
312
  validations: {
499
313
  in: [
500
314
  {
501
- value: 'start',
502
- displayName: 'Align left',
315
+ value: '400',
316
+ displayName: 'Normal',
503
317
  },
504
318
  {
505
- value: 'center',
506
- displayName: 'Align center',
507
- },
508
- {
509
- value: 'end',
510
- displayName: 'Align right',
511
- },
512
- ],
513
- },
514
- type: 'Text',
515
- group: 'style',
516
- description: 'The vertical alignment of the section',
517
- defaultValue: 'center',
518
- displayName: 'Vertical alignment',
519
- },
520
- cfHorizontalAlignment: {
521
- validations: {
522
- in: [
523
- {
524
- value: 'start',
525
- displayName: 'Align top',
526
- },
527
- {
528
- value: 'center',
529
- displayName: 'Align center',
530
- },
531
- {
532
- value: 'end',
533
- displayName: 'Align bottom',
534
- },
535
- ],
536
- },
537
- type: 'Text',
538
- group: 'style',
539
- description: 'The horizontal alignment of the section',
540
- defaultValue: 'center',
541
- displayName: 'Horizontal alignment',
542
- },
543
- cfVisibility: {
544
- displayName: 'Visibility toggle',
545
- type: 'Boolean',
546
- group: 'style',
547
- defaultValue: true,
548
- description: 'The visibility of the component',
549
- },
550
- cfMargin: {
551
- displayName: 'Margin',
552
- type: 'Text',
553
- group: 'style',
554
- description: 'The margin of the section',
555
- defaultValue: '0 0 0 0',
556
- },
557
- cfPadding: {
558
- displayName: 'Padding',
559
- type: 'Text',
560
- group: 'style',
561
- description: 'The padding of the section',
562
- defaultValue: '0 0 0 0',
563
- },
564
- cfBackgroundColor: {
565
- displayName: 'Background color',
566
- type: 'Text',
567
- group: 'style',
568
- description: 'The background color of the section',
569
- defaultValue: 'rgba(0, 0, 0, 0)',
570
- },
571
- cfWidth: {
572
- displayName: 'Width',
573
- type: 'Text',
574
- group: 'style',
575
- description: 'The width of the section',
576
- defaultValue: '100%',
577
- },
578
- cfHeight: {
579
- displayName: 'Height',
580
- type: 'Text',
581
- group: 'style',
582
- description: 'The height of the section',
583
- defaultValue: 'fit-content',
584
- },
585
- cfMaxWidth: {
586
- displayName: 'Max width',
587
- type: 'Text',
588
- group: 'style',
589
- description: 'The max-width of the section',
590
- defaultValue: 'none',
591
- },
592
- cfFlexDirection: {
593
- displayName: 'Direction',
594
- type: 'Text',
595
- group: 'style',
596
- description: 'The orientation of the section',
597
- defaultValue: 'column',
598
- },
599
- cfFlexReverse: {
600
- displayName: 'Reverse Direction',
601
- type: 'Boolean',
602
- group: 'style',
603
- description: 'Toggle the flex direction to be reversed',
604
- defaultValue: false,
605
- },
606
- cfFlexWrap: {
607
- displayName: 'Wrap objects',
608
- type: 'Text',
609
- group: 'style',
610
- description: 'Wrap objects',
611
- defaultValue: 'nowrap',
612
- },
613
- cfBorder: {
614
- displayName: 'Border',
615
- type: 'Text',
616
- group: 'style',
617
- description: 'The border of the section',
618
- defaultValue: '0px solid rgba(0, 0, 0, 0)',
619
- },
620
- cfGap: {
621
- displayName: 'Gap',
622
- type: 'Text',
623
- group: 'style',
624
- description: 'The spacing between the elements of the section',
625
- defaultValue: '0px',
626
- },
627
- cfHyperlink: {
628
- displayName: 'URL',
629
- type: 'Hyperlink',
630
- defaultValue: '',
631
- validations: {
632
- format: 'URL',
633
- bindingSourceType: ['entry', 'experience', 'manual'],
634
- },
635
- description: 'hyperlink for section or container',
636
- },
637
- cfOpenInNewTab: {
638
- displayName: 'URL behaviour',
639
- type: 'Boolean',
640
- defaultValue: false,
641
- description: 'Open in new tab',
642
- },
643
- };
644
- const optionalBuiltInStyles = {
645
- cfFontSize: {
646
- displayName: 'Font Size',
647
- type: 'Text',
648
- group: 'style',
649
- description: 'The font size of the element',
650
- defaultValue: '16px',
651
- },
652
- cfFontWeight: {
653
- validations: {
654
- in: [
655
- {
656
- value: '400',
657
- displayName: 'Normal',
658
- },
659
- {
660
- value: '500',
661
- displayName: 'Medium',
319
+ value: '500',
320
+ displayName: 'Medium',
662
321
  },
663
322
  {
664
323
  value: '600',
@@ -1506,143 +1165,814 @@ z.object({
1506
1165
  })),
1507
1166
  });
1508
1167
 
1509
- var CodeNames;
1510
- (function (CodeNames) {
1511
- CodeNames["Type"] = "type";
1512
- CodeNames["Required"] = "required";
1513
- CodeNames["Unexpected"] = "unexpected";
1514
- CodeNames["Regex"] = "regex";
1515
- CodeNames["In"] = "in";
1516
- CodeNames["Size"] = "size";
1517
- CodeNames["Custom"] = "custom";
1518
- })(CodeNames || (CodeNames = {}));
1519
- const convertInvalidType = (issue) => {
1520
- const name = issue.received === 'undefined' ? CodeNames.Required : CodeNames.Type;
1521
- const details = issue.received === 'undefined'
1522
- ? `The property "${issue.path.slice(-1)}" is required here`
1523
- : `The type of "${issue.path.slice(-1)}" is incorrect, expected type: ${issue.expected}`;
1524
- return {
1525
- details: details,
1526
- name: name,
1527
- path: issue.path,
1528
- value: issue.received.toString(),
1168
+ var CodeNames;
1169
+ (function (CodeNames) {
1170
+ CodeNames["Type"] = "type";
1171
+ CodeNames["Required"] = "required";
1172
+ CodeNames["Unexpected"] = "unexpected";
1173
+ CodeNames["Regex"] = "regex";
1174
+ CodeNames["In"] = "in";
1175
+ CodeNames["Size"] = "size";
1176
+ CodeNames["Custom"] = "custom";
1177
+ })(CodeNames || (CodeNames = {}));
1178
+ const convertInvalidType = (issue) => {
1179
+ const name = issue.received === 'undefined' ? CodeNames.Required : CodeNames.Type;
1180
+ const details = issue.received === 'undefined'
1181
+ ? `The property "${issue.path.slice(-1)}" is required here`
1182
+ : `The type of "${issue.path.slice(-1)}" is incorrect, expected type: ${issue.expected}`;
1183
+ return {
1184
+ details: details,
1185
+ name: name,
1186
+ path: issue.path,
1187
+ value: issue.received.toString(),
1188
+ };
1189
+ };
1190
+ const convertUnrecognizedKeys = (issue) => {
1191
+ const missingProperties = issue.keys.map((k) => `"${k}"`).join(', ');
1192
+ return {
1193
+ details: issue.keys.length > 1
1194
+ ? `The properties ${missingProperties} are not expected`
1195
+ : `The property ${missingProperties} is not expected`,
1196
+ name: CodeNames.Unexpected,
1197
+ path: issue.path,
1198
+ };
1199
+ };
1200
+ const convertInvalidString = (issue) => {
1201
+ return {
1202
+ details: issue.message || 'Invalid string',
1203
+ name: issue.validation === 'regex' ? CodeNames.Regex : CodeNames.Unexpected,
1204
+ path: issue.path,
1205
+ };
1206
+ };
1207
+ const convertInvalidEnumValue = (issue) => {
1208
+ return {
1209
+ details: issue.message || 'Value must be one of expected values',
1210
+ name: CodeNames.In,
1211
+ path: issue.path,
1212
+ value: issue.received.toString(),
1213
+ expected: issue.options,
1214
+ };
1215
+ };
1216
+ const convertInvalidLiteral = (issue) => {
1217
+ return {
1218
+ details: issue.message || 'Value must be one of expected values',
1219
+ name: CodeNames.In,
1220
+ path: issue.path,
1221
+ value: issue.received,
1222
+ expected: [issue.expected],
1223
+ };
1224
+ };
1225
+ const convertTooBig = (issue) => {
1226
+ return {
1227
+ details: issue.message || `Size should be at most ${issue.maximum}`,
1228
+ name: CodeNames.Size,
1229
+ path: issue.path,
1230
+ max: issue.maximum,
1231
+ };
1232
+ };
1233
+ const convertTooSmall = (issue) => {
1234
+ return {
1235
+ details: issue.message || `Size should be at least ${issue.minimum}`,
1236
+ name: CodeNames.Size,
1237
+ path: issue.path,
1238
+ min: issue.minimum,
1239
+ };
1240
+ };
1241
+ const defaultConversion = (issue) => {
1242
+ return {
1243
+ details: issue.message || 'An unexpected error occurred',
1244
+ name: CodeNames.Custom,
1245
+ path: issue.path.map(String),
1246
+ };
1247
+ };
1248
+ const zodToContentfulError = (issue) => {
1249
+ switch (issue.code) {
1250
+ case ZodIssueCode.invalid_type:
1251
+ return convertInvalidType(issue);
1252
+ case ZodIssueCode.unrecognized_keys:
1253
+ return convertUnrecognizedKeys(issue);
1254
+ case ZodIssueCode.invalid_enum_value:
1255
+ return convertInvalidEnumValue(issue);
1256
+ case ZodIssueCode.invalid_string:
1257
+ return convertInvalidString(issue);
1258
+ case ZodIssueCode.too_small:
1259
+ return convertTooSmall(issue);
1260
+ case ZodIssueCode.too_big:
1261
+ return convertTooBig(issue);
1262
+ case ZodIssueCode.invalid_literal:
1263
+ return convertInvalidLiteral(issue);
1264
+ default:
1265
+ return defaultConversion(issue);
1266
+ }
1267
+ };
1268
+
1269
+ const validateBreakpointsDefinition = (breakpoints) => {
1270
+ const result = z
1271
+ .array(BreakpointSchema)
1272
+ .superRefine(breakpointsRefinement)
1273
+ .safeParse(breakpoints);
1274
+ if (!result.success) {
1275
+ return {
1276
+ success: false,
1277
+ errors: result.error.issues.map(zodToContentfulError),
1278
+ };
1279
+ }
1280
+ return { success: true };
1281
+ };
1282
+
1283
+ let breakpointsRegistry = [];
1284
+ /**
1285
+ * Register custom breakpoints
1286
+ * @param breakpoints - [{[key:string]: string}]
1287
+ * @returns void
1288
+ */
1289
+ const defineBreakpoints = (breakpoints) => {
1290
+ Object.assign(breakpointsRegistry, breakpoints);
1291
+ };
1292
+ const runBreakpointsValidation = () => {
1293
+ if (!breakpointsRegistry.length)
1294
+ return;
1295
+ const validation = validateBreakpointsDefinition(breakpointsRegistry);
1296
+ if (!validation.success) {
1297
+ throw new Error(`Invalid breakpoints definition. Failed with errors: \n${JSON.stringify(validation.errors, null, 2)}`);
1298
+ }
1299
+ };
1300
+ // Used in the tests to get a breakpoint registration
1301
+ const getBreakpointRegistration = (id) => breakpointsRegistry.find((breakpoint) => breakpoint.id === id);
1302
+ // Used in the tests to reset the registry
1303
+ const resetBreakpointsRegistry = () => {
1304
+ breakpointsRegistry = [];
1305
+ };
1306
+
1307
+ const MEDIA_QUERY_REGEXP = /(<|>)(\d{1,})(px|cm|mm|in|pt|pc)$/;
1308
+ const toCSSMediaQuery = ({ query }) => {
1309
+ if (query === '*')
1310
+ return undefined;
1311
+ const match = query.match(MEDIA_QUERY_REGEXP);
1312
+ if (!match)
1313
+ return undefined;
1314
+ const [, operator, value, unit] = match;
1315
+ if (operator === '<') {
1316
+ const maxScreenWidth = Number(value) - 1;
1317
+ return `(max-width: ${maxScreenWidth}${unit})`;
1318
+ }
1319
+ else if (operator === '>') {
1320
+ const minScreenWidth = Number(value) + 1;
1321
+ return `(min-width: ${minScreenWidth}${unit})`;
1322
+ }
1323
+ return undefined;
1324
+ };
1325
+ // Remove this helper when upgrading to TypeScript 5.0 - https://github.com/microsoft/TypeScript/issues/48829
1326
+ const findLast = (array, predicate) => {
1327
+ return array.reverse().find(predicate);
1328
+ };
1329
+ // Initialise media query matchers. This won't include the always matching fallback breakpoint.
1330
+ const mediaQueryMatcher = (breakpoints) => {
1331
+ const mediaQueryMatches = {};
1332
+ const mediaQueryMatchers = breakpoints
1333
+ .map((breakpoint) => {
1334
+ const cssMediaQuery = toCSSMediaQuery(breakpoint);
1335
+ if (!cssMediaQuery)
1336
+ return undefined;
1337
+ if (typeof window === 'undefined')
1338
+ return undefined;
1339
+ const mediaQueryMatcher = window.matchMedia(cssMediaQuery);
1340
+ mediaQueryMatches[breakpoint.id] = mediaQueryMatcher.matches;
1341
+ return { id: breakpoint.id, signal: mediaQueryMatcher };
1342
+ })
1343
+ .filter((matcher) => !!matcher);
1344
+ return [mediaQueryMatchers, mediaQueryMatches];
1345
+ };
1346
+ const getActiveBreakpointIndex = (breakpoints, mediaQueryMatches, fallbackBreakpointIndex) => {
1347
+ // The breakpoints are ordered (desktop-first: descending by screen width)
1348
+ const breakpointsWithMatches = breakpoints.map(({ id }, index) => ({
1349
+ id,
1350
+ index,
1351
+ // The fallback breakpoint with wildcard query will always match
1352
+ isMatch: mediaQueryMatches[id] ?? index === fallbackBreakpointIndex,
1353
+ }));
1354
+ // Find the last breakpoint in the list that matches (desktop-first: the narrowest one)
1355
+ const mostSpecificIndex = findLast(breakpointsWithMatches, ({ isMatch }) => isMatch)?.index;
1356
+ return mostSpecificIndex ?? fallbackBreakpointIndex;
1357
+ };
1358
+ const getFallbackBreakpointIndex = (breakpoints) => {
1359
+ // We assume that there will be a single breakpoint which uses the wildcard query.
1360
+ // If there is none, we just take the first one in the list.
1361
+ return Math.max(breakpoints.findIndex(({ query }) => query === '*'), 0);
1362
+ };
1363
+ const builtInStylesWithDesignTokens = [
1364
+ 'cfMargin',
1365
+ 'cfPadding',
1366
+ 'cfGap',
1367
+ 'cfWidth',
1368
+ 'cfHeight',
1369
+ 'cfBackgroundColor',
1370
+ 'cfBorder',
1371
+ 'cfBorderRadius',
1372
+ 'cfFontSize',
1373
+ 'cfLineHeight',
1374
+ 'cfLetterSpacing',
1375
+ 'cfTextColor',
1376
+ 'cfMaxWidth',
1377
+ ];
1378
+ const isValidBreakpointValue = (value) => {
1379
+ return value !== undefined && value !== null && value !== '';
1380
+ };
1381
+ const getValueForBreakpoint = (valuesByBreakpoint, breakpoints, activeBreakpointIndex, fallbackBreakpointIndex, variableName, resolveDesignTokens = true) => {
1382
+ const eventuallyResolveDesignTokens = (value) => {
1383
+ // For some built-in design properties, we support design tokens
1384
+ if (builtInStylesWithDesignTokens.includes(variableName)) {
1385
+ return getDesignTokenRegistration(value, variableName);
1386
+ }
1387
+ // For all other properties, we just return the breakpoint-specific value
1388
+ return value;
1389
+ };
1390
+ if (valuesByBreakpoint instanceof Object) {
1391
+ // Assume that the values are sorted by media query to apply the cascading CSS logic
1392
+ for (let index = activeBreakpointIndex; index >= 0; index--) {
1393
+ const breakpointId = breakpoints[index]?.id;
1394
+ if (isValidBreakpointValue(valuesByBreakpoint[breakpointId])) {
1395
+ // If the value is defined, we use it and stop the breakpoints cascade
1396
+ if (resolveDesignTokens) {
1397
+ return eventuallyResolveDesignTokens(valuesByBreakpoint[breakpointId]);
1398
+ }
1399
+ return valuesByBreakpoint[breakpointId];
1400
+ }
1401
+ }
1402
+ const fallbackBreakpointId = breakpoints[fallbackBreakpointIndex]?.id;
1403
+ if (isValidBreakpointValue(valuesByBreakpoint[fallbackBreakpointId])) {
1404
+ if (resolveDesignTokens) {
1405
+ return eventuallyResolveDesignTokens(valuesByBreakpoint[fallbackBreakpointId]);
1406
+ }
1407
+ return valuesByBreakpoint[fallbackBreakpointId];
1408
+ }
1409
+ }
1410
+ else {
1411
+ // Old design properties did not support breakpoints, keep for backward compatibility
1412
+ return valuesByBreakpoint;
1413
+ }
1414
+ };
1415
+
1416
+ const CF_DEBUG_KEY = 'cf_debug';
1417
+ class DebugLogger {
1418
+ constructor() {
1419
+ // Public methods for logging
1420
+ this.error = this.logger('error');
1421
+ this.warn = this.logger('warn');
1422
+ this.log = this.logger('log');
1423
+ this.debug = this.logger('debug');
1424
+ if (typeof localStorage === 'undefined') {
1425
+ this.enabled = false;
1426
+ return;
1427
+ }
1428
+ // Default to checking localStorage for the debug mode on initialization if in browser
1429
+ this.enabled = localStorage.getItem(CF_DEBUG_KEY) === 'true';
1430
+ }
1431
+ static getInstance() {
1432
+ if (this.instance === null) {
1433
+ this.instance = new DebugLogger();
1434
+ }
1435
+ return this.instance;
1436
+ }
1437
+ getEnabled() {
1438
+ return this.enabled;
1439
+ }
1440
+ setEnabled(enabled) {
1441
+ this.enabled = enabled;
1442
+ if (typeof localStorage === 'undefined') {
1443
+ return;
1444
+ }
1445
+ if (enabled) {
1446
+ localStorage.setItem(CF_DEBUG_KEY, 'true');
1447
+ }
1448
+ else {
1449
+ localStorage.removeItem(CF_DEBUG_KEY);
1450
+ }
1451
+ }
1452
+ // Log method for different levels (error, warn, log)
1453
+ logger(level) {
1454
+ return (...args) => {
1455
+ if (this.enabled) {
1456
+ console[level]('[cf-experiences-sdk]', ...args);
1457
+ }
1458
+ };
1459
+ }
1460
+ }
1461
+ DebugLogger.instance = null;
1462
+ const debug = DebugLogger.getInstance();
1463
+ const enableDebug = () => {
1464
+ debug.setEnabled(true);
1465
+ console.log('Debug mode enabled');
1466
+ };
1467
+ const disableDebug = () => {
1468
+ debug.setEnabled(false);
1469
+ console.log('Debug mode disabled');
1470
+ };
1471
+
1472
+ const findOutermostCoordinates = (first, second) => {
1473
+ return {
1474
+ top: Math.min(first.top, second.top),
1475
+ right: Math.max(first.right, second.right),
1476
+ bottom: Math.max(first.bottom, second.bottom),
1477
+ left: Math.min(first.left, second.left),
1478
+ };
1479
+ };
1480
+ const getElementCoordinates = (element) => {
1481
+ const rect = element.getBoundingClientRect();
1482
+ /**
1483
+ * If element does not have children, or element has it's own width or height,
1484
+ * return the element's coordinates.
1485
+ */
1486
+ if (element.children.length === 0 || rect.width !== 0 || rect.height !== 0) {
1487
+ return rect;
1488
+ }
1489
+ const rects = [];
1490
+ /**
1491
+ * If element has children, or element does not have it's own width and height,
1492
+ * we find the cordinates of the children, and assume the outermost coordinates of the children
1493
+ * as the coordinate of the element.
1494
+ *
1495
+ * E.g child1 => {top: 2, bottom: 3, left: 4, right: 6} & child2 => {top: 1, bottom: 8, left: 12, right: 24}
1496
+ * The final assumed coordinates of the element would be => { top: 1, right: 24, bottom: 8, left: 4 }
1497
+ */
1498
+ for (const child of element.children) {
1499
+ const childRect = getElementCoordinates(child);
1500
+ if (childRect.width !== 0 || childRect.height !== 0) {
1501
+ const { top, right, bottom, left } = childRect;
1502
+ rects.push({ top, right, bottom, left });
1503
+ }
1504
+ }
1505
+ if (rects.length === 0) {
1506
+ return rect;
1507
+ }
1508
+ const { top, right, bottom, left } = rects.reduce(findOutermostCoordinates);
1509
+ return DOMRect.fromRect({
1510
+ x: left,
1511
+ y: top,
1512
+ height: bottom - top,
1513
+ width: right - left,
1514
+ });
1515
+ };
1516
+
1517
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1518
+ const isLinkToAsset = (variable) => {
1519
+ if (!variable)
1520
+ return false;
1521
+ if (typeof variable !== 'object')
1522
+ return false;
1523
+ return (variable.sys?.linkType === 'Asset' &&
1524
+ typeof variable.sys?.id === 'string' &&
1525
+ !!variable.sys?.id &&
1526
+ variable.sys?.type === 'Link');
1527
+ };
1528
+
1529
+ const isLink = (maybeLink) => {
1530
+ if (maybeLink === null)
1531
+ return false;
1532
+ if (typeof maybeLink !== 'object')
1533
+ return false;
1534
+ const link = maybeLink;
1535
+ return Boolean(link.sys?.id) && link.sys?.type === 'Link';
1536
+ };
1537
+
1538
+ /**
1539
+ * Localizes the provided entry or asset to match the regular format of CDA/CPA entities.
1540
+ * Note that this function does not apply a fallback to the default locale nor does it check
1541
+ * the content type for the localization setting of each field.
1542
+ * It will simply resolve each field to the requested locale.
1543
+ *
1544
+ * If the entity is already localized, it will return the entity as is.
1545
+ *
1546
+ * @example
1547
+ * ```
1548
+ * const multiLocaleEntry = { fields: { title: { 'en-US': 'Hello' } } };
1549
+ * const localizedEntry = localizeEntity(multiLocaleEntry, 'en-US');
1550
+ * console.log(localizedEntry.fields.title); // 'Hello'
1551
+ * ```
1552
+ */
1553
+ function localizeEntity(entity, locale) {
1554
+ if (!entity || !entity.fields) {
1555
+ throw new Error('Invalid entity provided');
1556
+ }
1557
+ if (entity.sys.locale) {
1558
+ return entity;
1559
+ }
1560
+ const cloned = structuredClone(entity);
1561
+ // Set the requested locale as entry locale
1562
+ cloned.sys.locale = locale;
1563
+ for (const key in cloned.fields) {
1564
+ cloned.fields[key] = cloned.fields[key][locale];
1565
+ }
1566
+ return cloned;
1567
+ }
1568
+
1569
+ /**
1570
+ * This module encapsulates format of the path to a deep reference.
1571
+ */
1572
+ const parseDataSourcePathIntoFieldset = (path) => {
1573
+ const parsedPath = parseDeepPath(path);
1574
+ if (null === parsedPath) {
1575
+ throw new Error(`Cannot parse path '${path}' as deep path`);
1576
+ }
1577
+ return parsedPath.fields.map((field) => [null, field, '~locale']);
1578
+ };
1579
+ /**
1580
+ * Parse path into components, supports L1 references (one reference follow) atm.
1581
+ * @param path from data source. eg. `/uuid123/fields/image/~locale/fields/file/~locale`
1582
+ * eg. `/uuid123/fields/file/~locale/fields/title/~locale`
1583
+ * @returns
1584
+ */
1585
+ const parseDataSourcePathWithL1DeepBindings = (path) => {
1586
+ const parsedPath = parseDeepPath(path);
1587
+ if (null === parsedPath) {
1588
+ throw new Error(`Cannot parse path '${path}' as deep path`);
1589
+ }
1590
+ return {
1591
+ key: parsedPath.key,
1592
+ field: parsedPath.fields[0],
1593
+ referentField: parsedPath.fields[1],
1594
+ };
1595
+ };
1596
+ /**
1597
+ * Detects if paths is valid deep-path, like:
1598
+ * - /gV6yKXp61hfYrR7rEyKxY/fields/mainStory/~locale/fields/cover/~locale/fields/title/~locale
1599
+ * or regular, like:
1600
+ * - /6J8eA60yXwdm5eyUh9fX6/fields/mainStory/~locale
1601
+ * @returns
1602
+ */
1603
+ const isDeepPath = (deepPathCandidate) => {
1604
+ const deepPathParsed = parseDeepPath(deepPathCandidate);
1605
+ if (!deepPathParsed) {
1606
+ return false;
1607
+ }
1608
+ return deepPathParsed.fields.length > 1;
1609
+ };
1610
+ const parseDeepPath = (deepPathCandidate) => {
1611
+ // ALGORITHM:
1612
+ // We start with deep path in form:
1613
+ // /uuid123/fields/mainStory/~locale/fields/cover/~locale/fields/title/~locale
1614
+ // First turn string into array of segments
1615
+ // ['', 'uuid123', 'fields', 'mainStory', '~locale', 'fields', 'cover', '~locale', 'fields', 'title', '~locale']
1616
+ // Then group segments into intermediate represenatation - chunks, where each non-initial chunk starts with 'fields'
1617
+ // [
1618
+ // [ "", "uuid123" ],
1619
+ // [ "fields", "mainStory", "~locale" ],
1620
+ // [ "fields", "cover", "~locale" ],
1621
+ // [ "fields", "title", "~locale" ]
1622
+ // ]
1623
+ // Then check "initial" chunk for corretness
1624
+ // Then check all "field-leading" chunks for correctness
1625
+ const isValidInitialChunk = (initialChunk) => {
1626
+ // must have start with '' and have at least 2 segments, second non-empty
1627
+ // eg. /-_432uuid123123
1628
+ return /^\/([^/^~]+)$/.test(initialChunk.join('/'));
1629
+ };
1630
+ const isValidFieldChunk = (fieldChunk) => {
1631
+ // must start with 'fields' and have at least 3 segments, second non-empty and last segment must be '~locale'
1632
+ // eg. fields/-32234mainStory/~locale
1633
+ return /^fields\/[^/^~]+\/~locale$/.test(fieldChunk.join('/'));
1634
+ };
1635
+ const deepPathSegments = deepPathCandidate.split('/');
1636
+ const chunks = chunkSegments(deepPathSegments, { startNextChunkOnElementEqualTo: 'fields' });
1637
+ if (chunks.length <= 1) {
1638
+ return null; // malformed path, even regular paths have at least 2 chunks
1639
+ }
1640
+ else if (chunks.length === 2) {
1641
+ return null; // deep paths have at least 3 chunks
1642
+ }
1643
+ // With 3+ chunks we can now check for deep path correctness
1644
+ const [initialChunk, ...fieldChunks] = chunks;
1645
+ if (!isValidInitialChunk(initialChunk)) {
1646
+ return null;
1647
+ }
1648
+ if (!fieldChunks.every(isValidFieldChunk)) {
1649
+ return null;
1650
+ }
1651
+ return {
1652
+ key: initialChunk[1], // pick uuid from initial chunk ['','uuid123'],
1653
+ fields: fieldChunks.map((fieldChunk) => fieldChunk[1]), // pick only fieldName eg. from ['fields','mainStory', '~locale'] we pick `mainStory`
1654
+ };
1655
+ };
1656
+ const chunkSegments = (segments, { startNextChunkOnElementEqualTo }) => {
1657
+ const chunks = [];
1658
+ let currentChunk = [];
1659
+ const isSegmentBeginningOfChunk = (segment) => segment === startNextChunkOnElementEqualTo;
1660
+ const excludeEmptyChunks = (chunk) => chunk.length > 0;
1661
+ for (let i = 0; i < segments.length; i++) {
1662
+ const isInitialElement = i === 0;
1663
+ const segment = segments[i];
1664
+ if (isInitialElement) {
1665
+ currentChunk = [segment];
1666
+ }
1667
+ else if (isSegmentBeginningOfChunk(segment)) {
1668
+ chunks.push(currentChunk);
1669
+ currentChunk = [segment];
1670
+ }
1671
+ else {
1672
+ currentChunk.push(segment);
1673
+ }
1674
+ }
1675
+ chunks.push(currentChunk);
1676
+ return chunks.filter(excludeEmptyChunks);
1677
+ };
1678
+ const lastPathNamedSegmentEq = (path, expectedName) => {
1679
+ // `/key123/fields/featureImage/~locale/fields/file/~locale`
1680
+ // ['', 'key123', 'fields', 'featureImage', '~locale', 'fields', 'file', '~locale']
1681
+ const segments = path.split('/');
1682
+ if (segments.length < 2) {
1683
+ console.warn(`[experiences-sdk-react] Attempting to check whether last named segment of the path (${path}) equals to '${expectedName}', but the path doesn't have enough segments.`);
1684
+ return false;
1685
+ }
1686
+ const secondLast = segments[segments.length - 2]; // skipping trailing '~locale'
1687
+ return secondLast === expectedName;
1688
+ };
1689
+
1690
+ const resolveHyperlinkPattern = (pattern, entry, locale) => {
1691
+ if (!entry || !locale)
1692
+ return null;
1693
+ const variables = {
1694
+ entry,
1695
+ locale,
1529
1696
  };
1697
+ return buildTemplate({ template: pattern, context: variables });
1530
1698
  };
1531
- const convertUnrecognizedKeys = (issue) => {
1532
- const missingProperties = issue.keys.map((k) => `"${k}"`).join(', ');
1533
- return {
1534
- details: issue.keys.length > 1
1535
- ? `The properties ${missingProperties} are not expected`
1536
- : `The property ${missingProperties} is not expected`,
1537
- name: CodeNames.Unexpected,
1538
- path: issue.path,
1539
- };
1699
+ function getValue(obj, path) {
1700
+ return path
1701
+ .replace(/\[/g, '.')
1702
+ .replace(/\]/g, '')
1703
+ .split('.')
1704
+ .reduce((o, k) => (o || {})[k], obj);
1705
+ }
1706
+ function addLocale(str, locale) {
1707
+ const fieldsIndicator = 'fields';
1708
+ const fieldsIndex = str.indexOf(fieldsIndicator);
1709
+ if (fieldsIndex !== -1) {
1710
+ const dotIndex = str.indexOf('.', fieldsIndex + fieldsIndicator.length + 1); // +1 for '.'
1711
+ if (dotIndex !== -1) {
1712
+ return str.slice(0, dotIndex + 1) + locale + '.' + str.slice(dotIndex + 1);
1713
+ }
1714
+ }
1715
+ return str;
1716
+ }
1717
+ function getTemplateValue(ctx, path) {
1718
+ const pathWithLocale = addLocale(path, ctx.locale);
1719
+ const retrievedValue = getValue(ctx, pathWithLocale);
1720
+ return typeof retrievedValue === 'object' && retrievedValue !== null
1721
+ ? retrievedValue[ctx.locale]
1722
+ : retrievedValue;
1723
+ }
1724
+ function buildTemplate({ template, context, }) {
1725
+ const localeVariable = /{\s*locale\s*}/g;
1726
+ // e.g. "{ page.sys.id }"
1727
+ const variables = /{\s*([\S]+?)\s*}/g;
1728
+ return (template
1729
+ // first replace the locale pattern
1730
+ .replace(localeVariable, context.locale)
1731
+ // then resolve the remaining variables
1732
+ .replace(variables, (_, path) => {
1733
+ const fallback = path + '_NOT_FOUND';
1734
+ const value = getTemplateValue(context, path) ?? fallback;
1735
+ // using _.result didn't gave proper results so we run our own version of it
1736
+ return String(typeof value === 'function' ? value() : value);
1737
+ }));
1738
+ }
1739
+
1740
+ const stylesToKeep = ['cfImageAsset'];
1741
+ const stylesToRemove = CF_STYLE_ATTRIBUTES.filter((style) => !stylesToKeep.includes(style));
1742
+ const propsToRemove = ['cfHyperlink', 'cfOpenInNewTab', 'cfSsrClassName'];
1743
+ const sanitizeNodeProps = (nodeProps) => {
1744
+ return omit(nodeProps, stylesToRemove, propsToRemove);
1540
1745
  };
1541
- const convertInvalidString = (issue) => {
1542
- return {
1543
- details: issue.message || 'Invalid string',
1544
- name: issue.validation === 'regex' ? CodeNames.Regex : CodeNames.Unexpected,
1545
- path: issue.path,
1546
- };
1746
+
1747
+ const transformVisibility = (value) => {
1748
+ if (value === false) {
1749
+ return {
1750
+ display: 'none !important',
1751
+ };
1752
+ }
1753
+ // Don't explicitly set anything when visible to not overwrite values like `grid` or `flex`.
1754
+ return {};
1547
1755
  };
1548
- const convertInvalidEnumValue = (issue) => {
1756
+ // Keep this for backwards compatibility - deleting this would be a breaking change
1757
+ // because existing components on a users experience will have the width value as fill
1758
+ // rather than 100%
1759
+ const transformFill = (value) => (value === 'fill' ? '100%' : value);
1760
+ const transformGridColumn = (span) => {
1761
+ if (!span) {
1762
+ return {};
1763
+ }
1549
1764
  return {
1550
- details: issue.message || 'Value must be one of expected values',
1551
- name: CodeNames.In,
1552
- path: issue.path,
1553
- value: issue.received.toString(),
1554
- expected: issue.options,
1765
+ gridColumn: `span ${span}`,
1555
1766
  };
1556
1767
  };
1557
- const convertInvalidLiteral = (issue) => {
1768
+ const transformBorderStyle = (value) => {
1769
+ if (!value)
1770
+ return {};
1771
+ const parts = value.split(' ');
1772
+ // Just accept the passed value
1773
+ if (parts.length < 3)
1774
+ return { border: value };
1775
+ const [borderSize, borderStyle, ...borderColorParts] = parts;
1776
+ const borderColor = borderColorParts.join(' ');
1558
1777
  return {
1559
- details: issue.message || 'Value must be one of expected values',
1560
- name: CodeNames.In,
1561
- path: issue.path,
1562
- value: issue.received,
1563
- expected: [issue.expected],
1778
+ border: `${borderSize} ${borderStyle} ${borderColor}`,
1564
1779
  };
1565
1780
  };
1566
- const convertTooBig = (issue) => {
1567
- return {
1568
- details: issue.message || `Size should be at most ${issue.maximum}`,
1569
- name: CodeNames.Size,
1570
- path: issue.path,
1571
- max: issue.maximum,
1781
+ const transformAlignment = (cfHorizontalAlignment, cfVerticalAlignment, cfFlexDirection = 'column') => cfFlexDirection === 'row'
1782
+ ? {
1783
+ alignItems: cfHorizontalAlignment,
1784
+ justifyContent: cfVerticalAlignment === 'center' ? `safe ${cfVerticalAlignment}` : cfVerticalAlignment,
1785
+ }
1786
+ : {
1787
+ alignItems: cfVerticalAlignment,
1788
+ justifyContent: cfHorizontalAlignment === 'center'
1789
+ ? `safe ${cfHorizontalAlignment}`
1790
+ : cfHorizontalAlignment,
1572
1791
  };
1573
- };
1574
- const convertTooSmall = (issue) => {
1792
+ const transformBackgroundImage = (cfBackgroundImageUrl, cfBackgroundImageOptions) => {
1793
+ const matchBackgroundSize = (scaling) => {
1794
+ if ('fill' === scaling)
1795
+ return 'cover';
1796
+ if ('fit' === scaling)
1797
+ return 'contain';
1798
+ };
1799
+ const matchBackgroundPosition = (alignment) => {
1800
+ if (!alignment || 'string' !== typeof alignment) {
1801
+ return;
1802
+ }
1803
+ let [horizontalAlignment, verticalAlignment] = alignment.trim().split(/\s+/, 2);
1804
+ // Special case for handling single values
1805
+ // for backwards compatibility with single values 'right','left', 'center', 'top','bottom'
1806
+ if (horizontalAlignment && !verticalAlignment) {
1807
+ const singleValue = horizontalAlignment;
1808
+ switch (singleValue) {
1809
+ case 'left':
1810
+ horizontalAlignment = 'left';
1811
+ verticalAlignment = 'center';
1812
+ break;
1813
+ case 'right':
1814
+ horizontalAlignment = 'right';
1815
+ verticalAlignment = 'center';
1816
+ break;
1817
+ case 'center':
1818
+ horizontalAlignment = 'center';
1819
+ verticalAlignment = 'center';
1820
+ break;
1821
+ case 'top':
1822
+ horizontalAlignment = 'center';
1823
+ verticalAlignment = 'top';
1824
+ break;
1825
+ case 'bottom':
1826
+ horizontalAlignment = 'center';
1827
+ verticalAlignment = 'bottom';
1828
+ break;
1829
+ // just fall down to the normal validation logic for horiz and vert
1830
+ }
1831
+ }
1832
+ const isHorizontalValid = ['left', 'right', 'center'].includes(horizontalAlignment);
1833
+ const isVerticalValid = ['top', 'bottom', 'center'].includes(verticalAlignment);
1834
+ horizontalAlignment = isHorizontalValid ? horizontalAlignment : 'left';
1835
+ verticalAlignment = isVerticalValid ? verticalAlignment : 'top';
1836
+ return `${horizontalAlignment} ${verticalAlignment}`;
1837
+ };
1838
+ if (!cfBackgroundImageUrl) {
1839
+ return;
1840
+ }
1841
+ let backgroundImage;
1842
+ let backgroundImageSet;
1843
+ if (typeof cfBackgroundImageUrl === 'string') {
1844
+ backgroundImage = `url(${cfBackgroundImageUrl})`;
1845
+ }
1846
+ else {
1847
+ const imgSet = cfBackgroundImageUrl.srcSet?.join(',');
1848
+ backgroundImage = `url(${cfBackgroundImageUrl.url})`;
1849
+ backgroundImageSet = `image-set(${imgSet})`;
1850
+ }
1575
1851
  return {
1576
- details: issue.message || `Size should be at least ${issue.minimum}`,
1577
- name: CodeNames.Size,
1578
- path: issue.path,
1579
- min: issue.minimum,
1852
+ backgroundImage,
1853
+ backgroundImage2: backgroundImageSet,
1854
+ backgroundRepeat: cfBackgroundImageOptions?.scaling === 'tile' ? 'repeat' : 'no-repeat',
1855
+ backgroundPosition: matchBackgroundPosition(cfBackgroundImageOptions?.alignment),
1856
+ backgroundSize: matchBackgroundSize(cfBackgroundImageOptions?.scaling),
1580
1857
  };
1581
1858
  };
1582
- const defaultConversion = (issue) => {
1583
- return {
1584
- details: issue.message || 'An unexpected error occurred',
1585
- name: CodeNames.Custom,
1586
- path: issue.path.map(String),
1859
+
1860
+ const toCSSAttribute = (key) => {
1861
+ let val = key.replace(/[A-Z]/g, (m) => '-' + m.toLowerCase());
1862
+ // Remove the number from the end of the key to allow for overrides on style properties
1863
+ val = val.replace(/\d+$/, '');
1864
+ return val;
1865
+ };
1866
+ /**
1867
+ * Turns a list of CSSProperties into a joined CSS string that can be
1868
+ * used for <style> tags. Per default it creates a minimized version.
1869
+ * For editor mode, use the `useWhitespaces` flag to create a more readable version.
1870
+ *
1871
+ * @param cssProperties list of CSS properties
1872
+ * @param useWhitespaces adds whitespaces and newlines between each rule
1873
+ * @returns a string of CSS rules
1874
+ */
1875
+ const stringifyCssProperties = (cssProperties, useWhitespaces = false) => {
1876
+ const rules = Object.entries(cssProperties)
1877
+ .filter(([, value]) => value !== undefined)
1878
+ .map(([key, value]) => useWhitespaces ? `${toCSSAttribute(key)}: ${value};` : `${toCSSAttribute(key)}:${value};`);
1879
+ return rules.join(useWhitespaces ? '\n' : '');
1880
+ };
1881
+ const buildStyleTag = ({ styles, nodeId }) => {
1882
+ const generatedStyles = stringifyCssProperties(styles, true);
1883
+ const className = `cfstyles-${nodeId ? nodeId : md5(generatedStyles)}`;
1884
+ const styleRule = `.${className}{ ${generatedStyles} }`;
1885
+ return [className, styleRule];
1886
+ };
1887
+ /**
1888
+ * Takes plain design values and transforms them into CSS properties. Undefined values will
1889
+ * be filtered out.
1890
+ *
1891
+ * **Example Input**
1892
+ * ```
1893
+ * values = {
1894
+ * cfVisibility: 'visible',
1895
+ * cfMargin: '10px',
1896
+ * cfFlexReverse: true,
1897
+ * cfImageOptions: { objectFit: 'cover' },
1898
+ * // ...
1899
+ * }
1900
+ * ```
1901
+ * **Example Output**
1902
+ * ```
1903
+ * cssProperties = {
1904
+ * margin: '10px',
1905
+ * flexDirection: 'row-reverse',
1906
+ * objectFit: 'cover',
1907
+ * // ...
1908
+ * }
1909
+ * ```
1910
+ */
1911
+ const buildCfStyles = (values) => {
1912
+ const cssProperties = {
1913
+ boxSizing: 'border-box',
1914
+ ...transformVisibility(values.cfVisibility),
1915
+ margin: values.cfMargin,
1916
+ padding: values.cfPadding,
1917
+ backgroundColor: values.cfBackgroundColor,
1918
+ width: transformFill(values.cfWidth || values.cfImageOptions?.width),
1919
+ height: transformFill(values.cfHeight || values.cfImageOptions?.height),
1920
+ maxWidth: values.cfMaxWidth,
1921
+ ...transformGridColumn(values.cfColumnSpan),
1922
+ ...transformBorderStyle(values.cfBorder),
1923
+ borderRadius: values.cfBorderRadius,
1924
+ gap: values.cfGap,
1925
+ ...transformAlignment(values.cfHorizontalAlignment, values.cfVerticalAlignment, values.cfFlexDirection),
1926
+ flexDirection: values.cfFlexReverse && values.cfFlexDirection
1927
+ ? `${values.cfFlexDirection}-reverse`
1928
+ : values.cfFlexDirection,
1929
+ flexWrap: values.cfFlexWrap,
1930
+ ...transformBackgroundImage(values.cfBackgroundImageUrl, values.cfBackgroundImageOptions),
1931
+ fontSize: values.cfFontSize,
1932
+ fontWeight: values.cfTextBold ? 'bold' : values.cfFontWeight,
1933
+ fontStyle: values.cfTextItalic ? 'italic' : undefined,
1934
+ textDecoration: values.cfTextUnderline ? 'underline' : undefined,
1935
+ lineHeight: values.cfLineHeight,
1936
+ letterSpacing: values.cfLetterSpacing,
1937
+ color: values.cfTextColor,
1938
+ textAlign: values.cfTextAlign,
1939
+ textTransform: values.cfTextTransform,
1940
+ objectFit: values.cfImageOptions?.objectFit,
1941
+ objectPosition: values.cfImageOptions?.objectPosition,
1587
1942
  };
1943
+ const cssPropertiesWithoutUndefined = Object.fromEntries(Object.entries(cssProperties).filter(([, value]) => value !== undefined));
1944
+ return cssPropertiesWithoutUndefined;
1588
1945
  };
1589
- const zodToContentfulError = (issue) => {
1590
- switch (issue.code) {
1591
- case ZodIssueCode.invalid_type:
1592
- return convertInvalidType(issue);
1593
- case ZodIssueCode.unrecognized_keys:
1594
- return convertUnrecognizedKeys(issue);
1595
- case ZodIssueCode.invalid_enum_value:
1596
- return convertInvalidEnumValue(issue);
1597
- case ZodIssueCode.invalid_string:
1598
- return convertInvalidString(issue);
1599
- case ZodIssueCode.too_small:
1600
- return convertTooSmall(issue);
1601
- case ZodIssueCode.too_big:
1602
- return convertTooBig(issue);
1603
- case ZodIssueCode.invalid_literal:
1604
- return convertInvalidLiteral(issue);
1605
- default:
1606
- return defaultConversion(issue);
1607
- }
1608
- };
1609
-
1610
- const validateBreakpointsDefinition = (breakpoints) => {
1611
- const result = z
1612
- .array(BreakpointSchema)
1613
- .superRefine(breakpointsRefinement)
1614
- .safeParse(breakpoints);
1615
- if (!result.success) {
1946
+ /**
1947
+ * **Only meant to be used in editor mode!**
1948
+ *
1949
+ * If the node is an empty structure component with a relative height (e.g. '100%'),
1950
+ * it might render with a zero height. In this case, add a min height of 80px to ensure
1951
+ * that child nodes can be added via drag & drop.
1952
+ */
1953
+ const addMinHeightForEmptyStructures = (cssProperties, node) => {
1954
+ if (!node.children.length &&
1955
+ isStructureWithRelativeHeight(node.definitionId, cssProperties.height)) {
1616
1956
  return {
1617
- success: false,
1618
- errors: result.error.issues.map(zodToContentfulError),
1957
+ ...cssProperties,
1958
+ minHeight: EMPTY_CONTAINER_HEIGHT,
1619
1959
  };
1620
1960
  }
1621
- return { success: true };
1961
+ return cssProperties;
1622
1962
  };
1623
-
1624
- let breakpointsRegistry = [];
1625
1963
  /**
1626
- * Register custom breakpoints
1627
- * @param breakpoints - [{[key:string]: string}]
1628
- * @returns void
1964
+ * Container/section default behavior:
1965
+ * Default height => height: EMPTY_CONTAINER_HEIGHT
1966
+ * If a container component has children => height: 'fit-content'
1629
1967
  */
1630
- const defineBreakpoints = (breakpoints) => {
1631
- Object.assign(breakpointsRegistry, breakpoints);
1632
- };
1633
- const runBreakpointsValidation = () => {
1634
- if (!breakpointsRegistry.length)
1635
- return;
1636
- const validation = validateBreakpointsDefinition(breakpointsRegistry);
1637
- if (!validation.success) {
1638
- throw new Error(`Invalid breakpoints definition. Failed with errors: \n${JSON.stringify(validation.errors, null, 2)}`);
1968
+ const calculateNodeDefaultHeight = ({ blockId, children, value, }) => {
1969
+ if (!blockId || !isContentfulStructureComponent(blockId) || value !== 'auto') {
1970
+ return value;
1639
1971
  }
1640
- };
1641
- // Used in the tests to get a breakpoint registration
1642
- const getBreakpointRegistration = (id) => breakpointsRegistry.find((breakpoint) => breakpoint.id === id);
1643
- // Used in the tests to reset the registry
1644
- const resetBreakpointsRegistry = () => {
1645
- breakpointsRegistry = [];
1972
+ if (children.length) {
1973
+ return '100%';
1974
+ }
1975
+ return EMPTY_CONTAINER_HEIGHT;
1646
1976
  };
1647
1977
 
1648
1978
  const detachExperienceStyles = (experience) => {
@@ -2428,138 +2758,30 @@ function getArrayValue(entryOrAsset, path, entityStore) {
2428
2758
  return undefined;
2429
2759
  }
2430
2760
  });
2431
- return result;
2432
- }
2433
-
2434
- const transformBoundContentValue = (variables, entityStore, binding, resolveDesignValue, variableName, variableType, path) => {
2435
- const entityOrAsset = entityStore.getEntryOrAsset(binding, path);
2436
- if (!entityOrAsset)
2437
- return;
2438
- switch (variableType) {
2439
- case 'Media':
2440
- // If we bound a normal entry field to the media variable we just return the bound value
2441
- if (entityOrAsset.sys.type === 'Entry') {
2442
- return getBoundValue(entityOrAsset, path);
2443
- }
2444
- return transformMedia(entityOrAsset, variables, resolveDesignValue, variableName, path);
2445
- case 'RichText':
2446
- return transformRichText(entityOrAsset, entityStore, path);
2447
- case 'Array':
2448
- return getArrayValue(entityOrAsset, path, entityStore);
2449
- case 'Link':
2450
- return getResolvedEntryFromLink(entityOrAsset, path, entityStore);
2451
- default:
2452
- return getBoundValue(entityOrAsset, path);
2453
- }
2454
- };
2455
-
2456
- const getDataFromTree = (tree) => {
2457
- let dataSource = {};
2458
- let unboundValues = {};
2459
- const queue = [...tree.root.children];
2460
- while (queue.length) {
2461
- const node = queue.shift();
2462
- if (!node) {
2463
- continue;
2464
- }
2465
- dataSource = { ...dataSource, ...node.data.dataSource };
2466
- unboundValues = { ...unboundValues, ...node.data.unboundValues };
2467
- if (node.children.length) {
2468
- queue.push(...node.children);
2469
- }
2470
- }
2471
- return {
2472
- dataSource,
2473
- unboundValues,
2474
- };
2475
- };
2476
- /**
2477
- * Gets calculates the index to drop the dragged component based on the mouse position
2478
- * @returns {InsertionData} a object containing a node that will become a parent for dragged component and index at which it must be inserted
2479
- */
2480
- const getInsertionData = ({ dropReceiverParentNode, dropReceiverNode, flexDirection, isMouseAtTopBorder, isMouseAtBottomBorder, isMouseInLeftHalf, isMouseInUpperHalf, isOverTopIndicator, isOverBottomIndicator, }) => {
2481
- const APPEND_INSIDE = dropReceiverNode.children.length;
2482
- const PREPEND_INSIDE = 0;
2483
- if (isMouseAtTopBorder || isMouseAtBottomBorder) {
2484
- const indexOfSectionInParentChildren = dropReceiverParentNode.children.findIndex((n) => n.data.id === dropReceiverNode.data.id);
2485
- const APPEND_OUTSIDE = indexOfSectionInParentChildren + 1;
2486
- const PREPEND_OUTSIDE = indexOfSectionInParentChildren;
2487
- return {
2488
- // when the mouse is around the border we want to drop the new component as a new section onto the root node
2489
- node: dropReceiverParentNode,
2490
- index: isMouseAtBottomBorder ? APPEND_OUTSIDE : PREPEND_OUTSIDE,
2491
- };
2492
- }
2493
- // if over one of the section indicators
2494
- if (isOverTopIndicator || isOverBottomIndicator) {
2495
- const indexOfSectionInParentChildren = dropReceiverParentNode.children.findIndex((n) => n.data.id === dropReceiverNode.data.id);
2496
- const APPEND_OUTSIDE = indexOfSectionInParentChildren + 1;
2497
- const PREPEND_OUTSIDE = indexOfSectionInParentChildren;
2498
- return {
2499
- // when the mouse is around the border we want to drop the new component as a new section onto the root node
2500
- node: dropReceiverParentNode,
2501
- index: isOverBottomIndicator ? APPEND_OUTSIDE : PREPEND_OUTSIDE,
2502
- };
2503
- }
2504
- if (flexDirection === undefined || flexDirection === 'row') {
2505
- return {
2506
- node: dropReceiverNode,
2507
- index: isMouseInLeftHalf ? PREPEND_INSIDE : APPEND_INSIDE,
2508
- };
2509
- }
2510
- else {
2511
- return {
2512
- node: dropReceiverNode,
2513
- index: isMouseInUpperHalf ? PREPEND_INSIDE : APPEND_INSIDE,
2514
- };
2515
- }
2516
- };
2517
- const generateRandomId = (letterCount) => {
2518
- const LETTERS = 'abcdefghijklmnopqvwxyzABCDEFGHIJKLMNOPQVWXYZ';
2519
- const NUMS = '0123456789';
2520
- const ALNUM = NUMS + LETTERS;
2521
- const times = (n, callback) => Array.from({ length: n }, callback);
2522
- const random = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
2523
- return times(letterCount, () => ALNUM[random(0, ALNUM.length - 1)]).join('');
2524
- };
2525
- const checkIsAssemblyNode = ({ componentId, usedComponents, }) => {
2526
- if (!usedComponents?.length)
2527
- return false;
2528
- return usedComponents.some((usedComponent) => usedComponent.sys.id === componentId);
2529
- };
2530
- /** @deprecated use `checkIsAssemblyNode` instead. Will be removed with SDK v5. */
2531
- const checkIsAssembly = checkIsAssemblyNode;
2532
- /**
2533
- * This check assumes that the entry is already ensured to be an experience, i.e. the
2534
- * content type of the entry is an experience type with the necessary annotations.
2535
- **/
2536
- const checkIsAssemblyEntry = (entry) => {
2537
- return Boolean(entry.fields?.componentSettings);
2538
- };
2539
- const checkIsAssemblyDefinition = (component) => component?.category === ASSEMBLY_DEFAULT_CATEGORY;
2540
- function parseCSSValue(input) {
2541
- const regex = /^(\d+(\.\d+)?)(px|em|rem)$/;
2542
- const match = input.match(regex);
2543
- if (match) {
2544
- return {
2545
- value: parseFloat(match[1]),
2546
- unit: match[3],
2547
- };
2548
- }
2549
- return null;
2550
- }
2551
- function getTargetValueInPixels(targetWidthObject) {
2552
- switch (targetWidthObject.unit) {
2553
- case 'px':
2554
- return targetWidthObject.value;
2555
- case 'em':
2556
- return targetWidthObject.value * 16;
2557
- case 'rem':
2558
- return targetWidthObject.value * 16;
2761
+ return result;
2762
+ }
2763
+
2764
+ const transformBoundContentValue = (variables, entityStore, binding, resolveDesignValue, variableName, variableType, path) => {
2765
+ const entityOrAsset = entityStore.getEntryOrAsset(binding, path);
2766
+ if (!entityOrAsset)
2767
+ return;
2768
+ switch (variableType) {
2769
+ case 'Media':
2770
+ // If we bound a normal entry field to the media variable we just return the bound value
2771
+ if (entityOrAsset.sys.type === 'Entry') {
2772
+ return getBoundValue(entityOrAsset, path);
2773
+ }
2774
+ return transformMedia(entityOrAsset, variables, resolveDesignValue, variableName, path);
2775
+ case 'RichText':
2776
+ return transformRichText(entityOrAsset, entityStore, path);
2777
+ case 'Array':
2778
+ return getArrayValue(entityOrAsset, path, entityStore);
2779
+ case 'Link':
2780
+ return getResolvedEntryFromLink(entityOrAsset, path, entityStore);
2559
2781
  default:
2560
- return targetWidthObject.value;
2782
+ return getBoundValue(entityOrAsset, path);
2561
2783
  }
2562
- }
2784
+ };
2563
2785
 
2564
2786
  const isExperienceEntry = (entry) => {
2565
2787
  return (entry?.sys?.type === 'Entry' &&
@@ -2571,368 +2793,177 @@ const isExperienceEntry = (entry) => {
2571
2793
  typeof entry.fields.componentTree.schemaVersion === 'string');
2572
2794
  };
2573
2795
 
2574
- const MEDIA_QUERY_REGEXP = /(<|>)(\d{1,})(px|cm|mm|in|pt|pc)$/;
2575
- const toCSSMediaQuery = ({ query }) => {
2576
- if (query === '*')
2577
- return undefined;
2578
- const match = query.match(MEDIA_QUERY_REGEXP);
2579
- if (!match)
2580
- return undefined;
2581
- const [, operator, value, unit] = match;
2582
- if (operator === '<') {
2583
- const maxScreenWidth = Number(value) - 1;
2584
- return `(max-width: ${maxScreenWidth}${unit})`;
2585
- }
2586
- else if (operator === '>') {
2587
- const minScreenWidth = Number(value) + 1;
2588
- return `(min-width: ${minScreenWidth}${unit})`;
2589
- }
2590
- return undefined;
2591
- };
2592
- // Remove this helper when upgrading to TypeScript 5.0 - https://github.com/microsoft/TypeScript/issues/48829
2593
- const findLast = (array, predicate) => {
2594
- return array.reverse().find(predicate);
2595
- };
2596
- // Initialise media query matchers. This won't include the always matching fallback breakpoint.
2597
- const mediaQueryMatcher = (breakpoints) => {
2598
- const mediaQueryMatches = {};
2599
- const mediaQueryMatchers = breakpoints
2600
- .map((breakpoint) => {
2601
- const cssMediaQuery = toCSSMediaQuery(breakpoint);
2602
- if (!cssMediaQuery)
2603
- return undefined;
2604
- if (typeof window === 'undefined')
2605
- return undefined;
2606
- const mediaQueryMatcher = window.matchMedia(cssMediaQuery);
2607
- mediaQueryMatches[breakpoint.id] = mediaQueryMatcher.matches;
2608
- return { id: breakpoint.id, signal: mediaQueryMatcher };
2609
- })
2610
- .filter((matcher) => !!matcher);
2611
- return [mediaQueryMatchers, mediaQueryMatches];
2612
- };
2613
- const getActiveBreakpointIndex = (breakpoints, mediaQueryMatches, fallbackBreakpointIndex) => {
2614
- // The breakpoints are ordered (desktop-first: descending by screen width)
2615
- const breakpointsWithMatches = breakpoints.map(({ id }, index) => ({
2616
- id,
2617
- index,
2618
- // The fallback breakpoint with wildcard query will always match
2619
- isMatch: mediaQueryMatches[id] ?? index === fallbackBreakpointIndex,
2620
- }));
2621
- // Find the last breakpoint in the list that matches (desktop-first: the narrowest one)
2622
- const mostSpecificIndex = findLast(breakpointsWithMatches, ({ isMatch }) => isMatch)?.index;
2623
- return mostSpecificIndex ?? fallbackBreakpointIndex;
2624
- };
2625
- const getFallbackBreakpointIndex = (breakpoints) => {
2626
- // We assume that there will be a single breakpoint which uses the wildcard query.
2627
- // If there is none, we just take the first one in the list.
2628
- return Math.max(breakpoints.findIndex(({ query }) => query === '*'), 0);
2629
- };
2630
- const builtInStylesWithDesignTokens = [
2631
- 'cfMargin',
2632
- 'cfPadding',
2633
- 'cfGap',
2634
- 'cfWidth',
2635
- 'cfHeight',
2636
- 'cfBackgroundColor',
2637
- 'cfBorder',
2638
- 'cfBorderRadius',
2639
- 'cfFontSize',
2640
- 'cfLineHeight',
2641
- 'cfLetterSpacing',
2642
- 'cfTextColor',
2643
- 'cfMaxWidth',
2644
- ];
2645
- const isValidBreakpointValue = (value) => {
2646
- return value !== undefined && value !== null && value !== '';
2647
- };
2648
- const getValueForBreakpoint = (valuesByBreakpoint, breakpoints, activeBreakpointIndex, fallbackBreakpointIndex, variableName, resolveDesignTokens = true) => {
2649
- const eventuallyResolveDesignTokens = (value) => {
2650
- // For some built-in design properties, we support design tokens
2651
- if (builtInStylesWithDesignTokens.includes(variableName)) {
2652
- return getDesignTokenRegistration(value, variableName);
2653
- }
2654
- // For all other properties, we just return the breakpoint-specific value
2655
- return value;
2656
- };
2657
- if (valuesByBreakpoint instanceof Object) {
2658
- // Assume that the values are sorted by media query to apply the cascading CSS logic
2659
- for (let index = activeBreakpointIndex; index >= 0; index--) {
2660
- const breakpointId = breakpoints[index]?.id;
2661
- if (isValidBreakpointValue(valuesByBreakpoint[breakpointId])) {
2662
- // If the value is defined, we use it and stop the breakpoints cascade
2663
- if (resolveDesignTokens) {
2664
- return eventuallyResolveDesignTokens(valuesByBreakpoint[breakpointId]);
2665
- }
2666
- return valuesByBreakpoint[breakpointId];
2667
- }
2796
+ const getDataFromTree = (tree) => {
2797
+ let dataSource = {};
2798
+ let unboundValues = {};
2799
+ const queue = [...tree.root.children];
2800
+ while (queue.length) {
2801
+ const node = queue.shift();
2802
+ if (!node) {
2803
+ continue;
2668
2804
  }
2669
- const fallbackBreakpointId = breakpoints[fallbackBreakpointIndex]?.id;
2670
- if (isValidBreakpointValue(valuesByBreakpoint[fallbackBreakpointId])) {
2671
- if (resolveDesignTokens) {
2672
- return eventuallyResolveDesignTokens(valuesByBreakpoint[fallbackBreakpointId]);
2673
- }
2674
- return valuesByBreakpoint[fallbackBreakpointId];
2805
+ dataSource = { ...dataSource, ...node.data.dataSource };
2806
+ unboundValues = { ...unboundValues, ...node.data.unboundValues };
2807
+ if (node.children.length) {
2808
+ queue.push(...node.children);
2675
2809
  }
2676
2810
  }
2677
- else {
2678
- // Old design properties did not support breakpoints, keep for backward compatibility
2679
- return valuesByBreakpoint;
2680
- }
2681
- };
2682
-
2683
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2684
- const isLinkToAsset = (variable) => {
2685
- if (!variable)
2686
- return false;
2687
- if (typeof variable !== 'object')
2688
- return false;
2689
- return (variable.sys?.linkType === 'Asset' &&
2690
- typeof variable.sys?.id === 'string' &&
2691
- !!variable.sys?.id &&
2692
- variable.sys?.type === 'Link');
2693
- };
2694
-
2695
- const isLink = (maybeLink) => {
2696
- if (maybeLink === null)
2697
- return false;
2698
- if (typeof maybeLink !== 'object')
2699
- return false;
2700
- const link = maybeLink;
2701
- return Boolean(link.sys?.id) && link.sys?.type === 'Link';
2702
- };
2703
-
2704
- /**
2705
- * This module encapsulates format of the path to a deep reference.
2706
- */
2707
- const parseDataSourcePathIntoFieldset = (path) => {
2708
- const parsedPath = parseDeepPath(path);
2709
- if (null === parsedPath) {
2710
- throw new Error(`Cannot parse path '${path}' as deep path`);
2711
- }
2712
- return parsedPath.fields.map((field) => [null, field, '~locale']);
2713
- };
2714
- /**
2715
- * Parse path into components, supports L1 references (one reference follow) atm.
2716
- * @param path from data source. eg. `/uuid123/fields/image/~locale/fields/file/~locale`
2717
- * eg. `/uuid123/fields/file/~locale/fields/title/~locale`
2718
- * @returns
2719
- */
2720
- const parseDataSourcePathWithL1DeepBindings = (path) => {
2721
- const parsedPath = parseDeepPath(path);
2722
- if (null === parsedPath) {
2723
- throw new Error(`Cannot parse path '${path}' as deep path`);
2724
- }
2725
2811
  return {
2726
- key: parsedPath.key,
2727
- field: parsedPath.fields[0],
2728
- referentField: parsedPath.fields[1],
2812
+ dataSource,
2813
+ unboundValues,
2729
2814
  };
2730
2815
  };
2731
2816
  /**
2732
- * Detects if paths is valid deep-path, like:
2733
- * - /gV6yKXp61hfYrR7rEyKxY/fields/mainStory/~locale/fields/cover/~locale/fields/title/~locale
2734
- * or regular, like:
2735
- * - /6J8eA60yXwdm5eyUh9fX6/fields/mainStory/~locale
2736
- * @returns
2817
+ * Gets calculates the index to drop the dragged component based on the mouse position
2818
+ * @returns {InsertionData} a object containing a node that will become a parent for dragged component and index at which it must be inserted
2737
2819
  */
2738
- const isDeepPath = (deepPathCandidate) => {
2739
- const deepPathParsed = parseDeepPath(deepPathCandidate);
2740
- if (!deepPathParsed) {
2741
- return false;
2742
- }
2743
- return deepPathParsed.fields.length > 1;
2744
- };
2745
- const parseDeepPath = (deepPathCandidate) => {
2746
- // ALGORITHM:
2747
- // We start with deep path in form:
2748
- // /uuid123/fields/mainStory/~locale/fields/cover/~locale/fields/title/~locale
2749
- // First turn string into array of segments
2750
- // ['', 'uuid123', 'fields', 'mainStory', '~locale', 'fields', 'cover', '~locale', 'fields', 'title', '~locale']
2751
- // Then group segments into intermediate represenatation - chunks, where each non-initial chunk starts with 'fields'
2752
- // [
2753
- // [ "", "uuid123" ],
2754
- // [ "fields", "mainStory", "~locale" ],
2755
- // [ "fields", "cover", "~locale" ],
2756
- // [ "fields", "title", "~locale" ]
2757
- // ]
2758
- // Then check "initial" chunk for corretness
2759
- // Then check all "field-leading" chunks for correctness
2760
- const isValidInitialChunk = (initialChunk) => {
2761
- // must have start with '' and have at least 2 segments, second non-empty
2762
- // eg. /-_432uuid123123
2763
- return /^\/([^/^~]+)$/.test(initialChunk.join('/'));
2764
- };
2765
- const isValidFieldChunk = (fieldChunk) => {
2766
- // must start with 'fields' and have at least 3 segments, second non-empty and last segment must be '~locale'
2767
- // eg. fields/-32234mainStory/~locale
2768
- return /^fields\/[^/^~]+\/~locale$/.test(fieldChunk.join('/'));
2769
- };
2770
- const deepPathSegments = deepPathCandidate.split('/');
2771
- const chunks = chunkSegments(deepPathSegments, { startNextChunkOnElementEqualTo: 'fields' });
2772
- if (chunks.length <= 1) {
2773
- return null; // malformed path, even regular paths have at least 2 chunks
2820
+ const getInsertionData = ({ dropReceiverParentNode, dropReceiverNode, flexDirection, isMouseAtTopBorder, isMouseAtBottomBorder, isMouseInLeftHalf, isMouseInUpperHalf, isOverTopIndicator, isOverBottomIndicator, }) => {
2821
+ const APPEND_INSIDE = dropReceiverNode.children.length;
2822
+ const PREPEND_INSIDE = 0;
2823
+ if (isMouseAtTopBorder || isMouseAtBottomBorder) {
2824
+ const indexOfSectionInParentChildren = dropReceiverParentNode.children.findIndex((n) => n.data.id === dropReceiverNode.data.id);
2825
+ const APPEND_OUTSIDE = indexOfSectionInParentChildren + 1;
2826
+ const PREPEND_OUTSIDE = indexOfSectionInParentChildren;
2827
+ return {
2828
+ // when the mouse is around the border we want to drop the new component as a new section onto the root node
2829
+ node: dropReceiverParentNode,
2830
+ index: isMouseAtBottomBorder ? APPEND_OUTSIDE : PREPEND_OUTSIDE,
2831
+ };
2774
2832
  }
2775
- else if (chunks.length === 2) {
2776
- return null; // deep paths have at least 3 chunks
2833
+ // if over one of the section indicators
2834
+ if (isOverTopIndicator || isOverBottomIndicator) {
2835
+ const indexOfSectionInParentChildren = dropReceiverParentNode.children.findIndex((n) => n.data.id === dropReceiverNode.data.id);
2836
+ const APPEND_OUTSIDE = indexOfSectionInParentChildren + 1;
2837
+ const PREPEND_OUTSIDE = indexOfSectionInParentChildren;
2838
+ return {
2839
+ // when the mouse is around the border we want to drop the new component as a new section onto the root node
2840
+ node: dropReceiverParentNode,
2841
+ index: isOverBottomIndicator ? APPEND_OUTSIDE : PREPEND_OUTSIDE,
2842
+ };
2777
2843
  }
2778
- // With 3+ chunks we can now check for deep path correctness
2779
- const [initialChunk, ...fieldChunks] = chunks;
2780
- if (!isValidInitialChunk(initialChunk)) {
2781
- return null;
2844
+ if (flexDirection === undefined || flexDirection === 'row') {
2845
+ return {
2846
+ node: dropReceiverNode,
2847
+ index: isMouseInLeftHalf ? PREPEND_INSIDE : APPEND_INSIDE,
2848
+ };
2782
2849
  }
2783
- if (!fieldChunks.every(isValidFieldChunk)) {
2784
- return null;
2850
+ else {
2851
+ return {
2852
+ node: dropReceiverNode,
2853
+ index: isMouseInUpperHalf ? PREPEND_INSIDE : APPEND_INSIDE,
2854
+ };
2785
2855
  }
2786
- return {
2787
- key: initialChunk[1], // pick uuid from initial chunk ['','uuid123'],
2788
- fields: fieldChunks.map((fieldChunk) => fieldChunk[1]), // pick only fieldName eg. from ['fields','mainStory', '~locale'] we pick `mainStory`
2789
- };
2790
2856
  };
2791
- const chunkSegments = (segments, { startNextChunkOnElementEqualTo }) => {
2792
- const chunks = [];
2793
- let currentChunk = [];
2794
- const isSegmentBeginningOfChunk = (segment) => segment === startNextChunkOnElementEqualTo;
2795
- const excludeEmptyChunks = (chunk) => chunk.length > 0;
2796
- for (let i = 0; i < segments.length; i++) {
2797
- const isInitialElement = i === 0;
2798
- const segment = segments[i];
2799
- if (isInitialElement) {
2800
- currentChunk = [segment];
2801
- }
2802
- else if (isSegmentBeginningOfChunk(segment)) {
2803
- chunks.push(currentChunk);
2804
- currentChunk = [segment];
2805
- }
2806
- else {
2807
- currentChunk.push(segment);
2808
- }
2809
- }
2810
- chunks.push(currentChunk);
2811
- return chunks.filter(excludeEmptyChunks);
2857
+ const generateRandomId = (letterCount) => {
2858
+ const LETTERS = 'abcdefghijklmnopqvwxyzABCDEFGHIJKLMNOPQVWXYZ';
2859
+ const NUMS = '0123456789';
2860
+ const ALNUM = NUMS + LETTERS;
2861
+ const times = (n, callback) => Array.from({ length: n }, callback);
2862
+ const random = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
2863
+ return times(letterCount, () => ALNUM[random(0, ALNUM.length - 1)]).join('');
2812
2864
  };
2813
- const lastPathNamedSegmentEq = (path, expectedName) => {
2814
- // `/key123/fields/featureImage/~locale/fields/file/~locale`
2815
- // ['', 'key123', 'fields', 'featureImage', '~locale', 'fields', 'file', '~locale']
2816
- const segments = path.split('/');
2817
- if (segments.length < 2) {
2818
- console.warn(`[experiences-sdk-react] Attempting to check whether last named segment of the path (${path}) equals to '${expectedName}', but the path doesn't have enough segments.`);
2865
+ const checkIsAssemblyNode = ({ componentId, usedComponents, }) => {
2866
+ if (!usedComponents?.length)
2819
2867
  return false;
2820
- }
2821
- const secondLast = segments[segments.length - 2]; // skipping trailing '~locale'
2822
- return secondLast === expectedName;
2868
+ return usedComponents.some((usedComponent) => usedComponent.sys.id === componentId);
2823
2869
  };
2824
-
2825
- const resolveHyperlinkPattern = (pattern, entry, locale) => {
2826
- if (!entry || !locale)
2827
- return null;
2828
- const variables = {
2829
- entry,
2830
- locale,
2831
- };
2832
- return buildTemplate({ template: pattern, context: variables });
2870
+ /** @deprecated use `checkIsAssemblyNode` instead. Will be removed with SDK v5. */
2871
+ const checkIsAssembly = checkIsAssemblyNode;
2872
+ /**
2873
+ * This check assumes that the entry is already ensured to be an experience, i.e. the
2874
+ * content type of the entry is an experience type with the necessary annotations.
2875
+ **/
2876
+ const checkIsAssemblyEntry = (entry) => {
2877
+ return Boolean(entry.fields?.componentSettings);
2833
2878
  };
2834
- function getValue(obj, path) {
2835
- return path
2836
- .replace(/\[/g, '.')
2837
- .replace(/\]/g, '')
2838
- .split('.')
2839
- .reduce((o, k) => (o || {})[k], obj);
2840
- }
2841
- function addLocale(str, locale) {
2842
- const fieldsIndicator = 'fields';
2843
- const fieldsIndex = str.indexOf(fieldsIndicator);
2844
- if (fieldsIndex !== -1) {
2845
- const dotIndex = str.indexOf('.', fieldsIndex + fieldsIndicator.length + 1); // +1 for '.'
2846
- if (dotIndex !== -1) {
2847
- return str.slice(0, dotIndex + 1) + locale + '.' + str.slice(dotIndex + 1);
2848
- }
2879
+ const checkIsAssemblyDefinition = (component) => component?.category === ASSEMBLY_DEFAULT_CATEGORY;
2880
+ function parseCSSValue(input) {
2881
+ const regex = /^(\d+(\.\d+)?)(px|em|rem)$/;
2882
+ const match = input.match(regex);
2883
+ if (match) {
2884
+ return {
2885
+ value: parseFloat(match[1]),
2886
+ unit: match[3],
2887
+ };
2849
2888
  }
2850
- return str;
2851
- }
2852
- function getTemplateValue(ctx, path) {
2853
- const pathWithLocale = addLocale(path, ctx.locale);
2854
- const retrievedValue = getValue(ctx, pathWithLocale);
2855
- return typeof retrievedValue === 'object' && retrievedValue !== null
2856
- ? retrievedValue[ctx.locale]
2857
- : retrievedValue;
2889
+ return null;
2858
2890
  }
2859
- function buildTemplate({ template, context, }) {
2860
- const localeVariable = /{\s*locale\s*}/g;
2861
- // e.g. "{ page.sys.id }"
2862
- const variables = /{\s*([\S]+?)\s*}/g;
2863
- return (template
2864
- // first replace the locale pattern
2865
- .replace(localeVariable, context.locale)
2866
- // then resolve the remaining variables
2867
- .replace(variables, (_, path) => {
2868
- const fallback = path + '_NOT_FOUND';
2869
- const value = getTemplateValue(context, path) ?? fallback;
2870
- // using _.result didn't gave proper results so we run our own version of it
2871
- return String(typeof value === 'function' ? value() : value);
2872
- }));
2891
+ function getTargetValueInPixels(targetWidthObject) {
2892
+ switch (targetWidthObject.unit) {
2893
+ case 'px':
2894
+ return targetWidthObject.value;
2895
+ case 'em':
2896
+ return targetWidthObject.value * 16;
2897
+ case 'rem':
2898
+ return targetWidthObject.value * 16;
2899
+ default:
2900
+ return targetWidthObject.value;
2901
+ }
2873
2902
  }
2874
2903
 
2875
- const stylesToKeep = ['cfImageAsset'];
2876
- const stylesToRemove = CF_STYLE_ATTRIBUTES.filter((style) => !stylesToKeep.includes(style));
2877
- const propsToRemove = ['cfHyperlink', 'cfOpenInNewTab', 'cfSsrClassName'];
2878
- const sanitizeNodeProps = (nodeProps) => {
2879
- return omit(nodeProps, stylesToRemove, propsToRemove);
2880
- };
2881
-
2882
- const CF_DEBUG_KEY = 'cf_debug';
2883
- class DebugLogger {
2884
- constructor() {
2885
- // Public methods for logging
2886
- this.error = this.logger('error');
2887
- this.warn = this.logger('warn');
2888
- this.log = this.logger('log');
2889
- this.debug = this.logger('debug');
2890
- if (typeof localStorage === 'undefined') {
2891
- this.enabled = false;
2892
- return;
2893
- }
2894
- // Default to checking localStorage for the debug mode on initialization if in browser
2895
- this.enabled = localStorage.getItem(CF_DEBUG_KEY) === 'true';
2904
+ class ParseError extends Error {
2905
+ constructor(message) {
2906
+ super(message);
2896
2907
  }
2897
- static getInstance() {
2898
- if (this.instance === null) {
2899
- this.instance = new DebugLogger();
2908
+ }
2909
+ const isValidJsonObject = (s) => {
2910
+ try {
2911
+ const result = JSON.parse(s);
2912
+ if ('object' !== typeof result) {
2913
+ return false;
2900
2914
  }
2901
- return this.instance;
2915
+ return true;
2902
2916
  }
2903
- getEnabled() {
2904
- return this.enabled;
2917
+ catch (e) {
2918
+ return false;
2905
2919
  }
2906
- setEnabled(enabled) {
2907
- this.enabled = enabled;
2908
- if (typeof localStorage === 'undefined') {
2909
- return;
2910
- }
2911
- if (enabled) {
2912
- localStorage.setItem(CF_DEBUG_KEY, 'true');
2913
- }
2914
- else {
2915
- localStorage.removeItem(CF_DEBUG_KEY);
2920
+ };
2921
+ const doesMismatchMessageSchema = (event) => {
2922
+ try {
2923
+ tryParseMessage(event);
2924
+ return false;
2925
+ }
2926
+ catch (e) {
2927
+ if (e instanceof ParseError) {
2928
+ return e.message;
2916
2929
  }
2930
+ throw e;
2917
2931
  }
2918
- // Log method for different levels (error, warn, log)
2919
- logger(level) {
2920
- return (...args) => {
2921
- if (this.enabled) {
2922
- console[level]('[cf-experiences-sdk]', ...args);
2923
- }
2924
- };
2932
+ };
2933
+ const tryParseMessage = (event) => {
2934
+ if (!event.data) {
2935
+ throw new ParseError('Field event.data is missing');
2925
2936
  }
2926
- }
2927
- DebugLogger.instance = null;
2928
- const debug = DebugLogger.getInstance();
2929
- const enableDebug = () => {
2930
- debug.setEnabled(true);
2931
- console.log('Debug mode enabled');
2937
+ if ('string' !== typeof event.data) {
2938
+ throw new ParseError(`Field event.data must be a string, instead of '${typeof event.data}'`);
2939
+ }
2940
+ if (!isValidJsonObject(event.data)) {
2941
+ throw new ParseError('Field event.data must be a valid JSON object serialized as string');
2942
+ }
2943
+ const eventData = JSON.parse(event.data);
2944
+ if (!eventData.source) {
2945
+ throw new ParseError(`Field eventData.source must be equal to 'composability-app'`);
2946
+ }
2947
+ if ('composability-app' !== eventData.source) {
2948
+ throw new ParseError(`Field eventData.source must be equal to 'composability-app', instead of '${eventData.source}'`);
2949
+ }
2950
+ // check eventData.eventType
2951
+ const supportedEventTypes = Object.values(INCOMING_EVENTS);
2952
+ if (!supportedEventTypes.includes(eventData.eventType)) {
2953
+ // Expected message: This message is handled in the EntityStore to store fetched entities
2954
+ if (eventData.eventType !== PostMessageMethods.REQUESTED_ENTITIES) {
2955
+ throw new ParseError(`Field eventData.eventType must be one of the supported values: [${supportedEventTypes.join(', ')}]`);
2956
+ }
2957
+ }
2958
+ return eventData;
2932
2959
  };
2933
- const disableDebug = () => {
2934
- debug.setEnabled(false);
2935
- console.log('Debug mode disabled');
2960
+ const validateExperienceBuilderConfig = ({ locale, mode, }) => {
2961
+ if (mode === StudioCanvasMode.EDITOR || mode === StudioCanvasMode.READ_ONLY) {
2962
+ return;
2963
+ }
2964
+ if (!locale) {
2965
+ throw new Error('Parameter "locale" is required for experience builder initialization outside of editor mode');
2966
+ }
2936
2967
  };
2937
2968
 
2938
2969
  const sendMessage = (eventType, data) => {
@@ -3454,6 +3485,9 @@ function createExperience(options) {
3454
3485
  }
3455
3486
  else {
3456
3487
  const { experienceEntry, referencedAssets, referencedEntries, locale } = options;
3488
+ if ([experienceEntry, ...referencedAssets, ...referencedEntries].some(isNotLocalized)) {
3489
+ throw new Error('Some of the provided content is not localized. Please localize every entity before passing it to this function.');
3490
+ }
3457
3491
  if (!isExperienceEntry(experienceEntry)) {
3458
3492
  throw new Error('Provided entry is not experience entry');
3459
3493
  }
@@ -3467,21 +3501,30 @@ function createExperience(options) {
3467
3501
  };
3468
3502
  }
3469
3503
  }
3504
+ const isNotLocalized = (entity) => {
3505
+ return !entity.sys.locale;
3506
+ };
3470
3507
 
3508
+ /**
3509
+ * Fetches an experience entry by its slug or id. Throws an error if there are multiple
3510
+ * entries with the same slug. Additionally, it resolves all nested pattern entries inside `fields.usedComponents`.
3511
+ * @param options.client - Instantiated client from the Contentful SDK. If this is using the `withAllLocales` modifier, you may not provide a specific locale.
3512
+ * @param options.locale - Provide a locale if your experience contains custom localized fields. Otherwise, it will fallback to the default locale.
3513
+ * @param options.experienceTypeId - id of the content type associated with the experience
3514
+ * @param options.identifier - identifying condition to find the correct experience entry
3515
+ *
3516
+ */
3471
3517
  const fetchExperienceEntry = async ({ client, experienceTypeId, locale, identifier, }) => {
3472
3518
  if (!client) {
3473
3519
  throw new Error('Failed to fetch experience entities. Required "client" parameter was not provided');
3474
3520
  }
3475
- if (!locale) {
3476
- throw new Error('Failed to fetch experience entities. Required "locale" parameter was not provided');
3477
- }
3478
3521
  if (!experienceTypeId) {
3479
3522
  throw new Error('Failed to fetch experience entities. Required "experienceTypeId" parameter was not provided');
3480
3523
  }
3481
- if (!identifier.slug && !identifier.id) {
3524
+ if (!('slug' in identifier) && !('id' in identifier)) {
3482
3525
  throw new Error(`Failed to fetch experience entities. At least one identifier must be provided. Received: ${JSON.stringify(identifier)}`);
3483
3526
  }
3484
- const filter = identifier.slug ? { 'fields.slug': identifier.slug } : { 'sys.id': identifier.id };
3527
+ const filter = 'slug' in identifier ? { 'fields.slug': identifier.slug } : { 'sys.id': identifier.id };
3485
3528
  const entries = await client.getEntries({
3486
3529
  content_type: experienceTypeId,
3487
3530
  locale,
@@ -3746,13 +3789,18 @@ const fetchAllAssets = async ({ client, ids, locale, skip = 0, limit = 100, resp
3746
3789
  }
3747
3790
  };
3748
3791
 
3792
+ /**
3793
+ * Fetches all entries and assets from the `dataSource` of the given experience entry. This will
3794
+ * also consider deep references that are not listed explicitly but linked through deep binding paths.
3795
+ * @param options.client - Instantiated client from the Contentful SDK. If this is using the `withAllLocales` modifier, you may not provide a specific locale.
3796
+ * @param options.experienceEntry - Localized experience entry. To localize a multi locale entry, use the `localizeEntity` function.
3797
+ * @param options.locale - Retrieve a specific localized version of the referenced entities. Otherwise, it will fallback to the default locale.
3798
+ * @returns object with a list of `entries` and a list of `assets`
3799
+ */
3749
3800
  const fetchReferencedEntities = async ({ client, experienceEntry, locale, }) => {
3750
3801
  if (!client) {
3751
3802
  throw new Error('Failed to fetch experience entities. Required "client" parameter was not provided');
3752
3803
  }
3753
- if (!locale) {
3754
- throw new Error('Failed to fetch experience entities. Required "locale" parameter was not provided');
3755
- }
3756
3804
  if (!isExperienceEntry(experienceEntry)) {
3757
3805
  throw new Error('Failed to fetch experience entities. Provided "experienceEntry" does not match experience entry schema');
3758
3806
  }
@@ -3864,7 +3912,8 @@ const handleError$1 = (generalMessage, error) => {
3864
3912
  throw Error(message);
3865
3913
  };
3866
3914
  /**
3867
- * Fetches an experience object by its slug
3915
+ * Fetches an experience entry by its slug and additionally fetches all its references to return
3916
+ * an initilized experience instance.
3868
3917
  * @param {FetchBySlugParams} options - options to fetch the experience
3869
3918
  */
3870
3919
  async function fetchBySlug({ client, experienceTypeId, slug, localeCode, isEditorMode, }) {
@@ -3872,6 +3921,9 @@ async function fetchBySlug({ client, experienceTypeId, slug, localeCode, isEdito
3872
3921
  if (isEditorMode)
3873
3922
  return;
3874
3923
  let experienceEntry = undefined;
3924
+ if (!localeCode) {
3925
+ throw new Error('Failed to fetch by slug. Required "localeCode" parameter was not provided');
3926
+ }
3875
3927
  try {
3876
3928
  experienceEntry = await fetchExperienceEntry({
3877
3929
  client,
@@ -3918,7 +3970,8 @@ const handleError = (generalMessage, error) => {
3918
3970
  throw Error(message);
3919
3971
  };
3920
3972
  /**
3921
- * Fetches an experience object by its id
3973
+ * Fetches an experience entry by its id and additionally fetches all its references to return
3974
+ * an initilized experience instance.
3922
3975
  * @param {FetchByIdParams} options - options to fetch the experience
3923
3976
  */
3924
3977
  async function fetchById({ client, experienceTypeId, id, localeCode, isEditorMode, }) {
@@ -3926,6 +3979,9 @@ async function fetchById({ client, experienceTypeId, id, localeCode, isEditorMod
3926
3979
  if (isEditorMode)
3927
3980
  return;
3928
3981
  let experienceEntry = undefined;
3982
+ if (!localeCode) {
3983
+ throw new Error('Failed to fetch by id. Required "localeCode" parameter was not provided');
3984
+ }
3929
3985
  try {
3930
3986
  experienceEntry = await fetchExperienceEntry({
3931
3987
  client,
@@ -3963,5 +4019,5 @@ async function fetchById({ client, experienceTypeId, id, localeCode, isEditorMod
3963
4019
  }
3964
4020
  }
3965
4021
 
3966
- export { DebugLogger, DeepReference, EditorModeEntityStore, EntityStore, EntityStoreBase, MEDIA_QUERY_REGEXP, VisualEditorMode, addLocale, addMinHeightForEmptyStructures, breakpointsRegistry, buildCfStyles, buildStyleTag, buildTemplate, builtInStyles, calculateNodeDefaultHeight, checkIsAssembly, checkIsAssemblyDefinition, checkIsAssemblyEntry, checkIsAssemblyNode, columnsBuiltInStyles, containerBuiltInStyles, createExperience, debug, defineBreakpoints, defineDesignTokens, designTokensRegistry, detachExperienceStyles, disableDebug, dividerBuiltInStyles, doesMismatchMessageSchema, enableDebug, fetchAllAssets, fetchAllEntries, fetchById, fetchBySlug, findOutermostCoordinates, flattenDesignTokenRegistry, gatherDeepReferencesFromExperienceEntry, gatherDeepReferencesFromTree, generateRandomId, getActiveBreakpointIndex, getBreakpointRegistration, getDataFromTree, getDesignTokenRegistration, getElementCoordinates, getFallbackBreakpointIndex, getInsertionData, getTargetValueInPixels, getTemplateValue, getValueForBreakpoint, indexByBreakpoint, isCfStyleAttribute, isComponentAllowedOnRoot, isContentfulComponent, isContentfulStructureComponent, isDeepPath, isExperienceEntry, isLink, isLinkToAsset, isPatternComponent, isStructureWithRelativeHeight, isValidBreakpointValue, lastPathNamedSegmentEq, maybePopulateDesignTokenValue, mediaQueryMatcher, optionalBuiltInStyles, parseCSSValue, parseDataSourcePathIntoFieldset, parseDataSourcePathWithL1DeepBindings, resetBreakpointsRegistry, resetDesignTokenRegistry, resolveBackgroundImageBinding, resolveHyperlinkPattern, runBreakpointsValidation, sanitizeNodeProps, sectionBuiltInStyles, sendMessage, singleColumnBuiltInStyles, stringifyCssProperties, toCSSAttribute, toMediaQuery, transformBoundContentValue, tryParseMessage, validateExperienceBuilderConfig };
4022
+ export { DebugLogger, DeepReference, EditorModeEntityStore, EntityStore, EntityStoreBase, MEDIA_QUERY_REGEXP, VisualEditorMode, addLocale, addMinHeightForEmptyStructures, breakpointsRegistry, buildCfStyles, buildStyleTag, buildTemplate, builtInStyles, calculateNodeDefaultHeight, checkIsAssembly, checkIsAssemblyDefinition, checkIsAssemblyEntry, checkIsAssemblyNode, columnsBuiltInStyles, containerBuiltInStyles, createExperience, debug, defineBreakpoints, defineDesignTokens, designTokensRegistry, detachExperienceStyles, disableDebug, dividerBuiltInStyles, doesMismatchMessageSchema, enableDebug, fetchAllAssets, fetchAllEntries, fetchById, fetchBySlug, fetchExperienceEntry, fetchReferencedEntities, findOutermostCoordinates, flattenDesignTokenRegistry, gatherDeepReferencesFromExperienceEntry, gatherDeepReferencesFromTree, generateRandomId, getActiveBreakpointIndex, getBreakpointRegistration, getDataFromTree, getDesignTokenRegistration, getElementCoordinates, getFallbackBreakpointIndex, getInsertionData, getTargetValueInPixels, getTemplateValue, getValueForBreakpoint, indexByBreakpoint, isCfStyleAttribute, isComponentAllowedOnRoot, isContentfulComponent, isContentfulStructureComponent, isDeepPath, isExperienceEntry, isLink, isLinkToAsset, isPatternComponent, isStructureWithRelativeHeight, isValidBreakpointValue, lastPathNamedSegmentEq, localizeEntity, maybePopulateDesignTokenValue, mediaQueryMatcher, optionalBuiltInStyles, parseCSSValue, parseDataSourcePathIntoFieldset, parseDataSourcePathWithL1DeepBindings, resetBreakpointsRegistry, resetDesignTokenRegistry, resolveBackgroundImageBinding, resolveHyperlinkPattern, runBreakpointsValidation, sanitizeNodeProps, sectionBuiltInStyles, sendMessage, singleColumnBuiltInStyles, stringifyCssProperties, toCSSAttribute, toMediaQuery, transformBoundContentValue, tryParseMessage, validateExperienceBuilderConfig };
3967
4023
  //# sourceMappingURL=index.js.map