@rulecms/widget-angular 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/fesm2022/rulecms-widget-angular.mjs +570 -88
  2. package/fesm2022/rulecms-widget-angular.mjs.map +1 -1
  3. package/lib/fetch/fetch-rule-cms-widget.d.ts +42 -7
  4. package/lib/fetch/fetch-rule-cms-widget.d.ts.map +1 -1
  5. package/lib/helpers/index.d.ts +1 -0
  6. package/lib/helpers/index.d.ts.map +1 -1
  7. package/lib/helpers/with-widget-placeholder-values.d.ts +25 -0
  8. package/lib/helpers/with-widget-placeholder-values.d.ts.map +1 -0
  9. package/lib/id-utils/dev-client-token.d.ts +15 -0
  10. package/lib/id-utils/dev-client-token.d.ts.map +1 -1
  11. package/lib/library-registry/types.d.ts +7 -0
  12. package/lib/library-registry/types.d.ts.map +1 -1
  13. package/lib/project-css-classes/format-project-css-classes-stylesheet.d.ts +13 -1
  14. package/lib/project-css-classes/format-project-css-classes-stylesheet.d.ts.map +1 -1
  15. package/lib/project-css-properties/format-project-css-properties-stylesheet.d.ts.map +1 -1
  16. package/lib/render/breakpoint-variant-render.component.d.ts +2 -1
  17. package/lib/render/breakpoint-variant-render.component.d.ts.map +1 -1
  18. package/lib/render/display-component.component.d.ts +4 -1
  19. package/lib/render/display-component.component.d.ts.map +1 -1
  20. package/lib/render/render-components-for-device.component.d.ts +2 -1
  21. package/lib/render/render-components-for-device.component.d.ts.map +1 -1
  22. package/lib/render/render-components-inner.component.d.ts +4 -1
  23. package/lib/render/render-components-inner.component.d.ts.map +1 -1
  24. package/lib/render/render-components.component.d.ts +2 -1
  25. package/lib/render/render-components.component.d.ts.map +1 -1
  26. package/lib/widget/rule-cms-widget.component.d.ts +33 -2
  27. package/lib/widget/rule-cms-widget.component.d.ts.map +1 -1
  28. package/lib/widget/widget-data.types.d.ts +6 -0
  29. package/lib/widget/widget-data.types.d.ts.map +1 -1
  30. package/lib/widget/widget-selection/build-widget-resolve-request.d.ts +23 -0
  31. package/lib/widget/widget-selection/build-widget-resolve-request.d.ts.map +1 -0
  32. package/lib/widget/widget-selection/get-or-create-anonymous-id.d.ts +11 -0
  33. package/lib/widget/widget-selection/get-or-create-anonymous-id.d.ts.map +1 -0
  34. package/lib/widget/widget-selection/is-widget-resolve-fallback-status.d.ts +8 -0
  35. package/lib/widget/widget-selection/is-widget-resolve-fallback-status.d.ts.map +1 -0
  36. package/lib/widget/widget-selection/normalize-widget-resolve-response.d.ts +16 -0
  37. package/lib/widget/widget-selection/normalize-widget-resolve-response.d.ts.map +1 -0
  38. package/lib/widget/widget-selection/stable-json-stringify.d.ts +8 -0
  39. package/lib/widget/widget-selection/stable-json-stringify.d.ts.map +1 -0
  40. package/lib/widget/widget-selection/to-ruleset-key.d.ts +7 -0
  41. package/lib/widget/widget-selection/to-ruleset-key.d.ts.map +1 -0
  42. package/lib/widget/widget-selection/types.d.ts +78 -0
  43. package/lib/widget/widget-selection/types.d.ts.map +1 -0
  44. package/package.json +1 -1
  45. package/public-api.d.ts +4 -1
  46. package/public-api.d.ts.map +1 -1
@@ -1,5 +1,5 @@
1
1
  import * as i0 from '@angular/core';
2
- import { Injectable, Input, Component, HostBinding, ErrorHandler, Optional, Inject } from '@angular/core';
2
+ import { Injectable, Input, Component, HostBinding, EventEmitter, ErrorHandler, Output, Optional, Inject } from '@angular/core';
3
3
  import { NgComponentOutlet, NgStyle, NgTemplateOutlet } from '@angular/common';
4
4
 
5
5
  /**
@@ -265,6 +265,10 @@ const WIDGET_CACHE_API_ORIGIN = 'https://widget-cache.rulecms.com';
265
265
  const PUBLISHED_WIDGET_API_PATH = '/api/v1/c/widget/get';
266
266
  /** Live draft client API path — no cache; reads the widget table directly. */
267
267
  const DEV_WIDGET_API_PATH = '/api/v1/c/dev/widget/get';
268
+ /** Published ruleset resolve path (POST) — picks a widget by params, returns its payload. */
269
+ const PUBLISHED_WIDGET_RESOLVE_API_PATH = '/api/v1/c/widget/resolve';
270
+ /** Live draft ruleset resolve path (POST) — compiles the draft ruleset in-process. */
271
+ const DEV_WIDGET_RESOLVE_API_PATH = '/api/v1/c/dev/widget/resolve';
268
272
  function isDevClientToken(token) {
269
273
  return typeof token === 'string' && token.startsWith(DEV_CLIENT_TOKEN_PREFIX);
270
274
  }
@@ -292,6 +296,17 @@ function buildWidgetFetchUrl({ publishedKey, token, endpoint, }) {
292
296
  const origin = resolveWidgetApiOrigin(token, endpoint);
293
297
  return `${origin}${apiPath}?${queryParams.toString()}`;
294
298
  }
299
+ /**
300
+ * Builds the ruleset resolve URL. The token, ruleset key and params travel in
301
+ * the POST body, so the URL carries no query string. Development tokens
302
+ * (`dev.…`) hit the draft resolve route; everything else uses the published one.
303
+ */
304
+ function buildWidgetResolveUrl({ token, endpoint, }) {
305
+ const apiPath = isDevClientToken(token)
306
+ ? DEV_WIDGET_RESOLVE_API_PATH
307
+ : PUBLISHED_WIDGET_RESOLVE_API_PATH;
308
+ return `${resolveWidgetApiOrigin(token, endpoint)}${apiPath}`;
309
+ }
295
310
 
296
311
  const getDragItemId = ({ id, prefix }) => {
297
312
  return `${prefix}_${id}`;
@@ -2100,6 +2115,39 @@ function resolveWidgetInstanceProps({ componentProps, ancestorColumnIds, columnI
2100
2115
  return undefined;
2101
2116
  }
2102
2117
 
2118
+ /**
2119
+ * The one key copied from `rulecms-widget`'s `placeholderValues` onto a card.
2120
+ * Must stay the key `r-text` reads (`PLACEHOLDER_VALUES_PROP` in
2121
+ * `@rulecms/source-components-angular`). The renderer copies the value and does
2122
+ * not look inside it.
2123
+ */
2124
+ const WIDGET_PLACEHOLDER_VALUES_KEY = 'placeholderValues';
2125
+ /**
2126
+ * Widget-wide placeholder values for one component instance.
2127
+ *
2128
+ * When the host passed `placeholderValues` on `rulecms-widget`, every instance
2129
+ * receives that object unless its own `componentProps` entry already has the
2130
+ * key. An entry that sets the key wins even when the value is `null` or
2131
+ * otherwise unusable: that is how one Text opts out. Other keys on the entry,
2132
+ * such as `onClick`, stay. The host's entry is not mutated.
2133
+ *
2134
+ * `undefined` means the widget input was omitted, which is the common case and
2135
+ * must not invent a bag.
2136
+ */
2137
+ function withWidgetPlaceholderValues({ widgetInstanceProps, placeholderValues, }) {
2138
+ if (placeholderValues === undefined) {
2139
+ return widgetInstanceProps;
2140
+ }
2141
+ if (widgetInstanceProps != null &&
2142
+ Object.prototype.hasOwnProperty.call(widgetInstanceProps, WIDGET_PLACEHOLDER_VALUES_KEY)) {
2143
+ return widgetInstanceProps;
2144
+ }
2145
+ return {
2146
+ ...widgetInstanceProps,
2147
+ [WIDGET_PLACEHOLDER_VALUES_KEY]: placeholderValues,
2148
+ };
2149
+ }
2150
+
2103
2151
  /**
2104
2152
  * Every component instance in a config, as the `/`-joined column-id path that
2105
2153
  * `componentProps` keys are matched against. Collections contribute their
@@ -2678,11 +2726,13 @@ class DisplayComponentComponent {
2678
2726
  styleProps: componentStyleProps,
2679
2727
  className: cardClassName,
2680
2728
  widgetInstanceProps: this.widgetInstanceProps,
2729
+ pageViewType: this.pageViewType,
2730
+ columnPath: this.columnPath,
2681
2731
  mounts: this.mounts,
2682
2732
  };
2683
2733
  }
2684
2734
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.25", ngImport: i0, type: DisplayComponentComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
2685
- static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "19.2.25", type: DisplayComponentComponent, isStandalone: true, selector: "rulecms-display-component", inputs: { componentType: "componentType", libraryId: "libraryId", componentAttributes: "componentAttributes", components: "components", styleProps: "styleProps", widgetInstanceProps: "widgetInstanceProps", mounts: "mounts" }, host: { styleAttribute: "display: contents" }, usesOnChanges: true, ngImport: i0, template: `
2735
+ static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "19.2.25", type: DisplayComponentComponent, isStandalone: true, selector: "rulecms-display-component", inputs: { componentType: "componentType", libraryId: "libraryId", componentAttributes: "componentAttributes", components: "components", styleProps: "styleProps", widgetInstanceProps: "widgetInstanceProps", pageViewType: "pageViewType", columnPath: "columnPath", mounts: "mounts" }, host: { styleAttribute: "display: contents" }, usesOnChanges: true, ngImport: i0, template: `
2686
2736
  @if (card) {
2687
2737
  @if (needsWrapper) {
2688
2738
  <div [class]="wrapperClass || undefined" [ngStyle]="wrapperStyle">
@@ -2735,6 +2785,10 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImpo
2735
2785
  type: Input
2736
2786
  }], widgetInstanceProps: [{
2737
2787
  type: Input
2788
+ }], pageViewType: [{
2789
+ type: Input
2790
+ }], columnPath: [{
2791
+ type: Input
2738
2792
  }], mounts: [{
2739
2793
  type: Input
2740
2794
  }] } });
@@ -2843,18 +2897,30 @@ class RenderComponentsInnerComponent {
2843
2897
  }
2844
2898
  return collection.collectionRows;
2845
2899
  }
2900
+ get pageViewType() {
2901
+ return this.isComposeMode ? PageViewTypes.Compose : PageViewTypes.RenderedPage;
2902
+ }
2846
2903
  childAncestorIds(columnId) {
2847
2904
  return [...(this.ancestorColumnIds ?? []), columnId];
2848
2905
  }
2906
+ columnPathFor(columnId) {
2907
+ if (this.isComposeMode || !columnId) {
2908
+ return undefined;
2909
+ }
2910
+ return [...(this.ancestorColumnIds ?? []), columnId].join(COMPONENT_PROPS_PATH_SEPARATOR);
2911
+ }
2849
2912
  instanceProps(columnId) {
2850
- return resolveWidgetInstanceProps({
2851
- componentProps: this.componentProps,
2852
- ancestorColumnIds: this.ancestorColumnIds,
2853
- columnId,
2913
+ return withWidgetPlaceholderValues({
2914
+ widgetInstanceProps: resolveWidgetInstanceProps({
2915
+ componentProps: this.componentProps,
2916
+ ancestorColumnIds: this.ancestorColumnIds,
2917
+ columnId,
2918
+ }),
2919
+ placeholderValues: this.isComposeMode ? undefined : this.placeholderValues,
2854
2920
  });
2855
2921
  }
2856
2922
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.25", ngImport: i0, type: RenderComponentsInnerComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
2857
- static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "19.2.25", type: RenderComponentsInnerComponent, isStandalone: true, selector: "rulecms-render-inner", inputs: { displayItemList: "displayItemList", isComposeMode: "isComposeMode", isWithinCollection: "isWithinCollection", widgetCollections: "widgetCollections", showDropContainers: "showDropContainers", reduxDeviceDisplayType: "reduxDeviceDisplayType", plugins: "plugins", deviceDisplayType: "deviceDisplayType", componentProps: "componentProps", mounts: "mounts", ancestorColumnIds: "ancestorColumnIds" }, host: { styleAttribute: "display: contents" }, ngImport: i0, template: `
2923
+ static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "19.2.25", type: RenderComponentsInnerComponent, isStandalone: true, selector: "rulecms-render-inner", inputs: { displayItemList: "displayItemList", isComposeMode: "isComposeMode", isWithinCollection: "isWithinCollection", widgetCollections: "widgetCollections", showDropContainers: "showDropContainers", reduxDeviceDisplayType: "reduxDeviceDisplayType", plugins: "plugins", deviceDisplayType: "deviceDisplayType", componentProps: "componentProps", mounts: "mounts", placeholderValues: "placeholderValues", ancestorColumnIds: "ancestorColumnIds" }, host: { styleAttribute: "display: contents" }, ngImport: i0, template: `
2858
2924
  <ng-template #baseTree>
2859
2925
  <rulecms-embed-vertical
2860
2926
  [displayItemList]="displayItemList"
@@ -2885,6 +2951,7 @@ class RenderComponentsInnerComponent {
2885
2951
  [deviceDisplayType]="deviceDisplayType"
2886
2952
  [componentProps]="componentProps"
2887
2953
  [mounts]="mounts"
2954
+ [placeholderValues]="placeholderValues"
2888
2955
  [ancestorColumnIds]="childAncestorIds(col.id)"
2889
2956
  />
2890
2957
  } @else {
@@ -2895,6 +2962,8 @@ class RenderComponentsInnerComponent {
2895
2962
  [components]="components"
2896
2963
  [styleProps]="columnView(col).styleProps"
2897
2964
  [widgetInstanceProps]="instanceProps(col.id)"
2965
+ [pageViewType]="pageViewType"
2966
+ [columnPath]="columnPathFor(col.id)"
2898
2967
  [mounts]="mounts"
2899
2968
  />
2900
2969
  }
@@ -2924,6 +2993,7 @@ class RenderComponentsInnerComponent {
2924
2993
  [deviceDisplayType]="deviceDisplayType"
2925
2994
  [componentProps]="componentProps"
2926
2995
  [mounts]="mounts"
2996
+ [placeholderValues]="placeholderValues"
2927
2997
  [ancestorColumnIds]="ancestorColumnIds"
2928
2998
  />
2929
2999
  </div>
@@ -2932,7 +3002,7 @@ class RenderComponentsInnerComponent {
2932
3002
  } @else {
2933
3003
  <ng-container *ngTemplateOutlet="baseTree" />
2934
3004
  }
2935
- `, isInline: true, dependencies: [{ kind: "component", type: RenderComponentsInnerComponent, selector: "rulecms-render-inner", inputs: ["displayItemList", "isComposeMode", "isWithinCollection", "widgetCollections", "showDropContainers", "reduxDeviceDisplayType", "plugins", "deviceDisplayType", "componentProps", "mounts", "ancestorColumnIds"] }, { kind: "directive", type: NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }, { kind: "component", type: EmbedInVerticalContainerComponent, selector: "rulecms-embed-vertical", inputs: ["displayItemList", "isComposeMode", "showDropContainers", "isWithinCollection", "deviceDisplayType"] }, { kind: "component", type: EmbedInRowComponent, selector: "rulecms-embed-row", inputs: ["row", "isComposeMode", "showDropContainers", "isWithinCollection", "deviceDisplayType"] }, { kind: "component", type: DisplayComponentComponent, selector: "rulecms-display-component", inputs: ["componentType", "libraryId", "componentAttributes", "components", "styleProps", "widgetInstanceProps", "mounts"] }] }); }
3005
+ `, isInline: true, dependencies: [{ kind: "component", type: RenderComponentsInnerComponent, selector: "rulecms-render-inner", inputs: ["displayItemList", "isComposeMode", "isWithinCollection", "widgetCollections", "showDropContainers", "reduxDeviceDisplayType", "plugins", "deviceDisplayType", "componentProps", "mounts", "placeholderValues", "ancestorColumnIds"] }, { kind: "directive", type: NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }, { kind: "component", type: EmbedInVerticalContainerComponent, selector: "rulecms-embed-vertical", inputs: ["displayItemList", "isComposeMode", "showDropContainers", "isWithinCollection", "deviceDisplayType"] }, { kind: "component", type: EmbedInRowComponent, selector: "rulecms-embed-row", inputs: ["row", "isComposeMode", "showDropContainers", "isWithinCollection", "deviceDisplayType"] }, { kind: "component", type: DisplayComponentComponent, selector: "rulecms-display-component", inputs: ["componentType", "libraryId", "componentAttributes", "components", "styleProps", "widgetInstanceProps", "pageViewType", "columnPath", "mounts"] }] }); }
2936
3006
  }
2937
3007
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImport: i0, type: RenderComponentsInnerComponent, decorators: [{
2938
3008
  type: Component,
@@ -2976,6 +3046,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImpo
2976
3046
  [deviceDisplayType]="deviceDisplayType"
2977
3047
  [componentProps]="componentProps"
2978
3048
  [mounts]="mounts"
3049
+ [placeholderValues]="placeholderValues"
2979
3050
  [ancestorColumnIds]="childAncestorIds(col.id)"
2980
3051
  />
2981
3052
  } @else {
@@ -2986,6 +3057,8 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImpo
2986
3057
  [components]="components"
2987
3058
  [styleProps]="columnView(col).styleProps"
2988
3059
  [widgetInstanceProps]="instanceProps(col.id)"
3060
+ [pageViewType]="pageViewType"
3061
+ [columnPath]="columnPathFor(col.id)"
2989
3062
  [mounts]="mounts"
2990
3063
  />
2991
3064
  }
@@ -3015,6 +3088,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImpo
3015
3088
  [deviceDisplayType]="deviceDisplayType"
3016
3089
  [componentProps]="componentProps"
3017
3090
  [mounts]="mounts"
3091
+ [placeholderValues]="placeholderValues"
3018
3092
  [ancestorColumnIds]="ancestorColumnIds"
3019
3093
  />
3020
3094
  </div>
@@ -3050,6 +3124,8 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImpo
3050
3124
  type: Input
3051
3125
  }], mounts: [{
3052
3126
  type: Input
3127
+ }], placeholderValues: [{
3128
+ type: Input
3053
3129
  }], ancestorColumnIds: [{
3054
3130
  type: Input
3055
3131
  }] } });
@@ -3061,7 +3137,7 @@ class RenderComponentsForDeviceComponent {
3061
3137
  this.showDropContainers = false;
3062
3138
  }
3063
3139
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.25", ngImport: i0, type: RenderComponentsForDeviceComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
3064
- static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "19.2.25", type: RenderComponentsForDeviceComponent, isStandalone: true, selector: "rulecms-render-for-device", inputs: { displayItemList: "displayItemList", isComposeMode: "isComposeMode", isWithinCollection: "isWithinCollection", widgetCollections: "widgetCollections", showDropContainers: "showDropContainers", reduxDeviceDisplayType: "reduxDeviceDisplayType", deviceDisplayType: "deviceDisplayType", plugins: "plugins", componentProps: "componentProps", mounts: "mounts", ancestorColumnIds: "ancestorColumnIds" }, host: { styleAttribute: "display: contents" }, ngImport: i0, template: `
3140
+ static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "19.2.25", type: RenderComponentsForDeviceComponent, isStandalone: true, selector: "rulecms-render-for-device", inputs: { displayItemList: "displayItemList", isComposeMode: "isComposeMode", isWithinCollection: "isWithinCollection", widgetCollections: "widgetCollections", showDropContainers: "showDropContainers", reduxDeviceDisplayType: "reduxDeviceDisplayType", deviceDisplayType: "deviceDisplayType", plugins: "plugins", componentProps: "componentProps", mounts: "mounts", placeholderValues: "placeholderValues", ancestorColumnIds: "ancestorColumnIds" }, host: { styleAttribute: "display: contents" }, ngImport: i0, template: `
3065
3141
  @if (displayItemList?.rows?.length) {
3066
3142
  <rulecms-render-inner
3067
3143
  [displayItemList]="displayItemList"
@@ -3074,10 +3150,11 @@ class RenderComponentsForDeviceComponent {
3074
3150
  [deviceDisplayType]="deviceDisplayType"
3075
3151
  [componentProps]="componentProps"
3076
3152
  [mounts]="mounts"
3153
+ [placeholderValues]="placeholderValues"
3077
3154
  [ancestorColumnIds]="ancestorColumnIds"
3078
3155
  />
3079
3156
  }
3080
- `, isInline: true, dependencies: [{ kind: "component", type: RenderComponentsInnerComponent, selector: "rulecms-render-inner", inputs: ["displayItemList", "isComposeMode", "isWithinCollection", "widgetCollections", "showDropContainers", "reduxDeviceDisplayType", "plugins", "deviceDisplayType", "componentProps", "mounts", "ancestorColumnIds"] }] }); }
3157
+ `, isInline: true, dependencies: [{ kind: "component", type: RenderComponentsInnerComponent, selector: "rulecms-render-inner", inputs: ["displayItemList", "isComposeMode", "isWithinCollection", "widgetCollections", "showDropContainers", "reduxDeviceDisplayType", "plugins", "deviceDisplayType", "componentProps", "mounts", "placeholderValues", "ancestorColumnIds"] }] }); }
3081
3158
  }
3082
3159
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImport: i0, type: RenderComponentsForDeviceComponent, decorators: [{
3083
3160
  type: Component,
@@ -3098,6 +3175,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImpo
3098
3175
  [deviceDisplayType]="deviceDisplayType"
3099
3176
  [componentProps]="componentProps"
3100
3177
  [mounts]="mounts"
3178
+ [placeholderValues]="placeholderValues"
3101
3179
  [ancestorColumnIds]="ancestorColumnIds"
3102
3180
  />
3103
3181
  }
@@ -3128,6 +3206,8 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImpo
3128
3206
  type: Input
3129
3207
  }], mounts: [{
3130
3208
  type: Input
3209
+ }], placeholderValues: [{
3210
+ type: Input
3131
3211
  }], ancestorColumnIds: [{
3132
3212
  type: Input
3133
3213
  }] } });
@@ -3142,7 +3222,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImpo
3142
3222
  class LibraryStylesheetsComponent {
3143
3223
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.25", ngImport: i0, type: LibraryStylesheetsComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
3144
3224
  static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "19.2.25", type: LibraryStylesheetsComponent, isStandalone: true, selector: "rulecms-library-stylesheets", inputs: { stylesheets: "stylesheets" }, host: { styleAttribute: "display: contents" }, ngImport: i0, template: `
3145
- @for (css of stylesheets ?? []; track css) {
3225
+ @for (css of stylesheets ?? []; track $index) {
3146
3226
  <style data-rulecms-library-stylesheet="" [innerText]="css"></style>
3147
3227
  }
3148
3228
  `, isInline: true }); }
@@ -3153,7 +3233,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImpo
3153
3233
  selector: 'rulecms-library-stylesheets',
3154
3234
  standalone: true,
3155
3235
  template: `
3156
- @for (css of stylesheets ?? []; track css) {
3236
+ @for (css of stylesheets ?? []; track $index) {
3157
3237
  <style data-rulecms-library-stylesheet="" [innerText]="css"></style>
3158
3238
  }
3159
3239
  `,
@@ -3178,7 +3258,7 @@ class BreakpointVariantRenderComponent {
3178
3258
  this.variantStyles = buildBreakpointVariantStyles(this.resolvedScopeId);
3179
3259
  }
3180
3260
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.25", ngImport: i0, type: BreakpointVariantRenderComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
3181
- static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "19.2.25", type: BreakpointVariantRenderComponent, isStandalone: true, selector: "rulecms-breakpoint-variants", inputs: { displayItemList: "displayItemList", widgetCollections: "widgetCollections", plugins: "plugins", componentProps: "componentProps", mounts: "mounts", scopeIdInput: "scopeIdInput" }, host: { styleAttribute: "display: contents" }, usesOnChanges: true, ngImport: i0, template: `
3261
+ static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "19.2.25", type: BreakpointVariantRenderComponent, isStandalone: true, selector: "rulecms-breakpoint-variants", inputs: { displayItemList: "displayItemList", widgetCollections: "widgetCollections", plugins: "plugins", componentProps: "componentProps", mounts: "mounts", placeholderValues: "placeholderValues", scopeIdInput: "scopeIdInput" }, host: { styleAttribute: "display: contents" }, usesOnChanges: true, ngImport: i0, template: `
3182
3262
  <rulecms-library-stylesheets [stylesheets]="plugins.sourceComponents?.stylesheets" />
3183
3263
  @if (!divergent) {
3184
3264
  <rulecms-render-for-device
@@ -3192,6 +3272,7 @@ class BreakpointVariantRenderComponent {
3192
3272
  [plugins]="plugins"
3193
3273
  [componentProps]="componentProps"
3194
3274
  [mounts]="mounts"
3275
+ [placeholderValues]="placeholderValues"
3195
3276
  />
3196
3277
  } @else {
3197
3278
  <style [innerText]="variantStyles"></style>
@@ -3208,11 +3289,12 @@ class BreakpointVariantRenderComponent {
3208
3289
  [plugins]="plugins"
3209
3290
  [componentProps]="componentProps"
3210
3291
  [mounts]="mounts"
3292
+ [placeholderValues]="placeholderValues"
3211
3293
  />
3212
3294
  </div>
3213
3295
  }
3214
3296
  }
3215
- `, isInline: true, dependencies: [{ kind: "component", type: RenderComponentsForDeviceComponent, selector: "rulecms-render-for-device", inputs: ["displayItemList", "isComposeMode", "isWithinCollection", "widgetCollections", "showDropContainers", "reduxDeviceDisplayType", "deviceDisplayType", "plugins", "componentProps", "mounts", "ancestorColumnIds"] }, { kind: "component", type: LibraryStylesheetsComponent, selector: "rulecms-library-stylesheets", inputs: ["stylesheets"] }] }); }
3297
+ `, isInline: true, dependencies: [{ kind: "component", type: RenderComponentsForDeviceComponent, selector: "rulecms-render-for-device", inputs: ["displayItemList", "isComposeMode", "isWithinCollection", "widgetCollections", "showDropContainers", "reduxDeviceDisplayType", "deviceDisplayType", "plugins", "componentProps", "mounts", "placeholderValues", "ancestorColumnIds"] }, { kind: "component", type: LibraryStylesheetsComponent, selector: "rulecms-library-stylesheets", inputs: ["stylesheets"] }] }); }
3216
3298
  }
3217
3299
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImport: i0, type: BreakpointVariantRenderComponent, decorators: [{
3218
3300
  type: Component,
@@ -3234,6 +3316,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImpo
3234
3316
  [plugins]="plugins"
3235
3317
  [componentProps]="componentProps"
3236
3318
  [mounts]="mounts"
3319
+ [placeholderValues]="placeholderValues"
3237
3320
  />
3238
3321
  } @else {
3239
3322
  <style [innerText]="variantStyles"></style>
@@ -3250,6 +3333,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImpo
3250
3333
  [plugins]="plugins"
3251
3334
  [componentProps]="componentProps"
3252
3335
  [mounts]="mounts"
3336
+ [placeholderValues]="placeholderValues"
3253
3337
  />
3254
3338
  </div>
3255
3339
  }
@@ -3270,6 +3354,8 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImpo
3270
3354
  type: Input
3271
3355
  }], mounts: [{
3272
3356
  type: Input
3357
+ }], placeholderValues: [{
3358
+ type: Input
3273
3359
  }], scopeIdInput: [{
3274
3360
  type: Input
3275
3361
  }] } });
@@ -3318,7 +3404,7 @@ class RenderComponentsComponent {
3318
3404
  this.deviceDisplayType = resolveDisplayDeviceType(this.phoneQuery?.matches ?? false, this.tabletQuery?.matches ?? false, this.reduxDeviceDisplayType);
3319
3405
  }
3320
3406
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.25", ngImport: i0, type: RenderComponentsComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
3321
- static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "19.2.25", type: RenderComponentsComponent, isStandalone: true, selector: "rulecms-render-components", inputs: { displayItemList: "displayItemList", isComposeMode: "isComposeMode", isWithinCollection: "isWithinCollection", widgetCollections: "widgetCollections", showDropContainers: "showDropContainers", reduxDeviceDisplayType: "reduxDeviceDisplayType", plugins: "plugins", componentProps: "componentProps", mounts: "mounts" }, host: { styleAttribute: "display: contents" }, ngImport: i0, template: `
3407
+ static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "19.2.25", type: RenderComponentsComponent, isStandalone: true, selector: "rulecms-render-components", inputs: { displayItemList: "displayItemList", isComposeMode: "isComposeMode", isWithinCollection: "isWithinCollection", widgetCollections: "widgetCollections", showDropContainers: "showDropContainers", reduxDeviceDisplayType: "reduxDeviceDisplayType", plugins: "plugins", componentProps: "componentProps", mounts: "mounts", placeholderValues: "placeholderValues" }, host: { styleAttribute: "display: contents" }, ngImport: i0, template: `
3322
3408
  @if (!isWithinCollection) {
3323
3409
  <rulecms-library-stylesheets [stylesheets]="plugins.sourceComponents?.stylesheets" />
3324
3410
  }
@@ -3333,8 +3419,9 @@ class RenderComponentsComponent {
3333
3419
  [plugins]="plugins"
3334
3420
  [componentProps]="componentProps"
3335
3421
  [mounts]="mounts"
3422
+ [placeholderValues]="placeholderValues"
3336
3423
  />
3337
- `, isInline: true, dependencies: [{ kind: "component", type: RenderComponentsForDeviceComponent, selector: "rulecms-render-for-device", inputs: ["displayItemList", "isComposeMode", "isWithinCollection", "widgetCollections", "showDropContainers", "reduxDeviceDisplayType", "deviceDisplayType", "plugins", "componentProps", "mounts", "ancestorColumnIds"] }, { kind: "component", type: LibraryStylesheetsComponent, selector: "rulecms-library-stylesheets", inputs: ["stylesheets"] }] }); }
3424
+ `, isInline: true, dependencies: [{ kind: "component", type: RenderComponentsForDeviceComponent, selector: "rulecms-render-for-device", inputs: ["displayItemList", "isComposeMode", "isWithinCollection", "widgetCollections", "showDropContainers", "reduxDeviceDisplayType", "deviceDisplayType", "plugins", "componentProps", "mounts", "placeholderValues", "ancestorColumnIds"] }, { kind: "component", type: LibraryStylesheetsComponent, selector: "rulecms-library-stylesheets", inputs: ["stylesheets"] }] }); }
3338
3425
  }
3339
3426
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImport: i0, type: RenderComponentsComponent, decorators: [{
3340
3427
  type: Component,
@@ -3357,6 +3444,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImpo
3357
3444
  [plugins]="plugins"
3358
3445
  [componentProps]="componentProps"
3359
3446
  [mounts]="mounts"
3447
+ [placeholderValues]="placeholderValues"
3360
3448
  />
3361
3449
  `,
3362
3450
  host: { style: 'display: contents' },
@@ -3382,6 +3470,8 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImpo
3382
3470
  type: Input
3383
3471
  }], mounts: [{
3384
3472
  type: Input
3473
+ }], placeholderValues: [{
3474
+ type: Input
3385
3475
  }] } });
3386
3476
 
3387
3477
  /**
@@ -3418,8 +3508,26 @@ const wrapProjectCssClassesStylesheetInLayer = (css, classLayer) => {
3418
3508
  * `[data-rulecms-published-key="…"]`. `CSS.escape` is not assumed (SSR / Node).
3419
3509
  */
3420
3510
  const escapeCssAttributeValue$2 = (value) => value.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
3421
- /** Escape a class name for use after `.` (`/` → `\/`). */
3422
- const escapeCssClassName = (name) => name.replace(/[^A-Za-z0-9_-]/g, char => `\\${char}`);
3511
+ /**
3512
+ * Escape a class name for use after `.` in a selector. `/` becomes `\/` so
3513
+ * `ring-parity-accent/30` emits as `.ring-parity-accent\/30`.
3514
+ *
3515
+ * A CSS identifier may not *start* with a digit, or with a hyphen followed by a
3516
+ * digit, so a leading digit needs the numeric escape form instead of a
3517
+ * backslash: `2xl:flex` has to emit `.\32 xl\:flex`, because `.2xl\:flex` is a
3518
+ * parse error and the browser drops the whole rule. Tailwind breakpoint
3519
+ * prefixes (`2xl:`) and grid utilities kept in class names hit this.
3520
+ */
3521
+ const escapeCssClassName = (name) => {
3522
+ const escaped = name.replace(/[^A-Za-z0-9_-]/g, char => `\\${char}`);
3523
+ if (/^[0-9]/.test(escaped)) {
3524
+ return `\\3${escaped[0]} ${escaped.slice(1)}`;
3525
+ }
3526
+ if (/^-[0-9]/.test(escaped)) {
3527
+ return `-\\3${escaped[1]} ${escaped.slice(2)}`;
3528
+ }
3529
+ return escaped;
3530
+ };
3423
3531
  const REJECTED_IN_BODY = ['</', '<script', '@import', 'javascript:', 'vbscript:', 'expression('];
3424
3532
  // eslint-disable-next-line no-control-regex -- control characters are what this matches
3425
3533
  const REJECTED_CONTROL_CHARACTERS$2 = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/;
@@ -3483,6 +3591,9 @@ const indentDeclarationBody$1 = (body) => body
3483
3591
  /**
3484
3592
  * Descendant class rules under this widget’s published-key span.
3485
3593
  * Empty / flag-off / unsanitary catalogs return null so the caller omits `<style>`.
3594
+ *
3595
+ * Rules are emitted in catalog order. Two utilities that set the same property
3596
+ * are resolved by source order, so re-sorting here would change which one wins.
3486
3597
  */
3487
3598
  const formatProjectCssClassesStylesheet = (publishedKey, classes, includeClassDefinitions, classLayer) => {
3488
3599
  if (!shouldIncludeClassDefinitionsOnPublishedWidget(includeClassDefinitions)) {
@@ -3495,7 +3606,6 @@ const formatProjectCssClassesStylesheet = (publishedKey, classes, includeClassDe
3495
3606
  }
3496
3607
  const ancestor = `[data-rulecms-published-key="${escapeCssAttributeValue$2(publishedKey)}"]`;
3497
3608
  const css = names
3498
- .sort((left, right) => left.localeCompare(right))
3499
3609
  .map(name => `${ancestor} .${escapeCssClassName(name)} {\n${indentDeclarationBody$1(sanitized[name])}\n}`)
3500
3610
  .join('\n');
3501
3611
  return wrapProjectCssClassesStylesheetInLayer(css, classLayer);
@@ -4165,7 +4275,9 @@ const PROJECT_CSS_PROPERTY_SYNTAX_VALUES = [
4165
4275
  ];
4166
4276
  const PROPERTY_SYNTAX_SET = new Set(PROJECT_CSS_PROPERTY_SYNTAX_VALUES);
4167
4277
  const REJECTED_IN_EMITTED_VALUE$2 = /[{};]/;
4168
- const MAX_PROJECT_CSS_PROPERTIES = 40;
4278
+ // RuleCMS's cap. Below it, the published widget silently drops registrations
4279
+ // the composer renders.
4280
+ const MAX_PROJECT_CSS_PROPERTIES = 200;
4169
4281
  const PROPERTY_INITIAL_VALUE_MAX_LENGTH = 200;
4170
4282
  const isAllowlistedSyntax = (value) => typeof value === 'string' && PROPERTY_SYNTAX_SET.has(value);
4171
4283
  const isSafeInitialValue = (value, syntax) => {
@@ -4732,6 +4844,152 @@ function resolveSourceComponentsPlugin(params) {
4732
4844
  return registry.resolve({ registrations: params.libraries, referenced });
4733
4845
  }
4734
4846
 
4847
+ /**
4848
+ * The draft resolve route wants the bare `ruleset-…` key. Callers may hand us
4849
+ * a published key (`{environmentId}---ruleset-…`) out of habit; strip the
4850
+ * environment prefix so both spellings work with a `dev.` token.
4851
+ */
4852
+ function toRulesetKey(rulesetPublishedKey) {
4853
+ const separatorIndex = rulesetPublishedKey.lastIndexOf(PUBLISHED_KEY_SEPARATOR);
4854
+ return separatorIndex === -1
4855
+ ? rulesetPublishedKey
4856
+ : rulesetPublishedKey.slice(separatorIndex + PUBLISHED_KEY_SEPARATOR.length);
4857
+ }
4858
+
4859
+ const DEFAULT_WIDGET_RESOLVE_CONTENT_TYPE = 'text/plain';
4860
+ /**
4861
+ * Body for the resolve POST. Published tokens send
4862
+ * `{ token, rulesetPublishedKey, params, mode: 'payload' }`; `dev.` tokens hit
4863
+ * the draft route, which wants the bare `rulesetKey` and no `mode`.
4864
+ */
4865
+ function buildWidgetResolveRequestBody({ token, rulesetPublishedKey, params, }) {
4866
+ if (isDevClientToken(token)) {
4867
+ return {
4868
+ token,
4869
+ rulesetKey: toRulesetKey(rulesetPublishedKey),
4870
+ ...(params ? { params } : {}),
4871
+ };
4872
+ }
4873
+ return {
4874
+ token,
4875
+ rulesetPublishedKey,
4876
+ ...(params ? { params } : {}),
4877
+ mode: 'payload',
4878
+ };
4879
+ }
4880
+ /**
4881
+ * `fetch` init for the resolve POST. `Content-Type` is the only header —
4882
+ * `text/plain` keeps the request CORS-simple (no preflight); anything else
4883
+ * would add one, so nothing else is set here.
4884
+ */
4885
+ function buildWidgetResolveRequestInit({ contentType = DEFAULT_WIDGET_RESOLVE_CONTENT_TYPE, ...bodyParams }) {
4886
+ return {
4887
+ method: 'POST',
4888
+ headers: { 'Content-Type': contentType },
4889
+ body: JSON.stringify(buildWidgetResolveRequestBody(bodyParams)),
4890
+ };
4891
+ }
4892
+
4893
+ /** First-party `localStorage` key holding the SDK-generated anonymous id. */
4894
+ const RULECMS_ANONYMOUS_ID_STORAGE_KEY = 'rulecms_anon_id';
4895
+ function generateUuid() {
4896
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
4897
+ return crypto.randomUUID();
4898
+ }
4899
+ // RFC 4122 v4 layout from Math.random — only for engines without crypto.randomUUID.
4900
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (char) => {
4901
+ const nibble = (Math.random() * 16) | 0;
4902
+ return (char === 'x' ? nibble : (nibble & 0x3) | 0x8).toString(16);
4903
+ });
4904
+ }
4905
+ /**
4906
+ * Returns the anonymous id used as `params.anonId` for experiments, minting
4907
+ * and persisting one in `localStorage` on first use. Browser-only: returns
4908
+ * `undefined` outside a window (SSR) so the server never invents an id, and
4909
+ * when storage is unavailable (private mode, blocked third-party context) a
4910
+ * per-page-load id is returned without persisting.
4911
+ */
4912
+ function getOrCreateAnonymousId() {
4913
+ if (typeof window === 'undefined') {
4914
+ return undefined;
4915
+ }
4916
+ try {
4917
+ const existing = window.localStorage.getItem(RULECMS_ANONYMOUS_ID_STORAGE_KEY);
4918
+ if (existing) {
4919
+ return existing;
4920
+ }
4921
+ const created = generateUuid();
4922
+ window.localStorage.setItem(RULECMS_ANONYMOUS_ID_STORAGE_KEY, created);
4923
+ return created;
4924
+ }
4925
+ catch {
4926
+ return generateUuid();
4927
+ }
4928
+ }
4929
+
4930
+ /**
4931
+ * Whether a failed resolve response should be retried through the plain GET of
4932
+ * `fallbackPublishedKey`. Only server-side failures (5xx) qualify: a 4xx means
4933
+ * the request itself is wrong (bad token, unknown ruleset, environment
4934
+ * mismatch), and a fallback widget would just mask that.
4935
+ */
4936
+ function isWidgetResolveFallbackStatus(status) {
4937
+ return status >= 500;
4938
+ }
4939
+
4940
+ function normalizePublishedResolveResponse(body) {
4941
+ if (!body?.success || !body.data) {
4942
+ return null;
4943
+ }
4944
+ const { selection, ...raw } = body.data;
4945
+ return { raw, selection };
4946
+ }
4947
+ function normalizeDevResolveResponse(body, rulesetPublishedKey) {
4948
+ if (!body?.resolution || !body.widget) {
4949
+ return null;
4950
+ }
4951
+ const { resolution, ...raw } = body;
4952
+ const selection = {
4953
+ rulesetPublishedKey,
4954
+ outcome: resolution.outcome,
4955
+ ruleId: resolution.ruleId ?? null,
4956
+ variantId: resolution.variantId ?? null,
4957
+ widgetKey: resolution.widgetKey,
4958
+ widgetPublishedKey: resolution.widgetPublishedKey,
4959
+ };
4960
+ return { raw, selection };
4961
+ }
4962
+ /**
4963
+ * Reduces either resolve response shape to the existing widget payload plus a
4964
+ * `selection`. Published: `{ success, data: { …payload, selection } }`.
4965
+ * Draft (`dev.` token): unwrapped `{ resolution, widget, childCollections, …css }`.
4966
+ * Returns `null` when the body is not a successful resolve.
4967
+ */
4968
+ function normalizeWidgetResolveResponse({ token, rulesetPublishedKey, body, }) {
4969
+ return isDevClientToken(token)
4970
+ ? normalizeDevResolveResponse(body, rulesetPublishedKey)
4971
+ : normalizePublishedResolveResponse(body);
4972
+ }
4973
+
4974
+ /**
4975
+ * `JSON.stringify` with object keys sorted at every depth, so two objects with
4976
+ * the same values serialize identically regardless of insertion order. Used as
4977
+ * the effect dependency for resolve `params`: a fresh `{ b, a }` on every render
4978
+ * must not trigger a refetch when `{ a, b }` was already sent.
4979
+ */
4980
+ function stableJsonStringify(value) {
4981
+ return JSON.stringify(value, (_key, current) => {
4982
+ if (current === null || typeof current !== 'object' || Array.isArray(current)) {
4983
+ return current;
4984
+ }
4985
+ const sorted = {};
4986
+ for (const key of Object.keys(current).sort()) {
4987
+ sorted[key] = current[key];
4988
+ }
4989
+ return sorted;
4990
+ });
4991
+ }
4992
+
4735
4993
  const loadingContainerStyle = {
4736
4994
  display: 'flex',
4737
4995
  justifyContent: 'center',
@@ -4785,11 +5043,19 @@ class RuleCMSWidgetComponent {
4785
5043
  constructor(context, errorHandler) {
4786
5044
  this.context = context;
4787
5045
  this.errorHandler = errorHandler;
5046
+ /**
5047
+ * Staging/production: published key (`{environmentId}---{widgetKey}`).
5048
+ * Development (`dev.` token): the live widget key itself (`widget-...`).
5049
+ * Omit when `rulesetPublishedKey` is set — the ruleset picks the widget.
5050
+ */
5051
+ this.publishedKey = '';
4788
5052
  /**
4789
5053
  * `'client-fetch'` (default) fetches in the browser.
4790
5054
  * `'pre-fetched'` renders `initialData` with CSS breakpoint variants.
4791
5055
  */
4792
5056
  this.mode = 'client-fetch';
5057
+ /** Fires when a ruleset resolve returns a selection. */
5058
+ this.selectionChange = new EventEmitter();
4793
5059
  this.publishedKeyAttribute = RULECMS_PUBLISHED_KEY_ATTRIBUTE;
4794
5060
  this.loadingContainerStyle = loadingContainerStyle;
4795
5061
  this.spinnerContainerStyle = spinnerContainerStyle;
@@ -4797,18 +5063,26 @@ class RuleCMSWidgetComponent {
4797
5063
  this.errorContainerStyle = errorContainerStyle;
4798
5064
  this.errorTitleStyle = errorTitleStyle;
4799
5065
  this.errorMessageStyle = errorMessageStyle;
4800
- this.loading = false;
5066
+ this.loading = true;
4801
5067
  this.error = null;
4802
5068
  this.preparedData = null;
4803
5069
  this.sourceComponentsPlugin = null;
4804
5070
  this.useBreakpointVariants = false;
5071
+ this.selection = null;
5072
+ /** Published key of the widget a ruleset chose, when `publishedKey` was omitted. */
5073
+ this.resolvedPublishedKey = '';
4805
5074
  this.abortController = null;
4806
5075
  this.lastFetchKey = null;
4807
5076
  this.stylesInjected = false;
5077
+ this.fetchGeneration = 0;
4808
5078
  }
4809
5079
  get plugins() {
4810
5080
  return { sourceComponents: this.sourceComponentsPlugin ?? undefined };
4811
5081
  }
5082
+ /** Ruleset mode has no publishedKey; the root then carries the chosen widget's key. */
5083
+ get renderPublishedKey() {
5084
+ return this.publishedKey || this.resolvedPublishedKey;
5085
+ }
4812
5086
  ngOnInit() {
4813
5087
  this.syncFromInputs();
4814
5088
  }
@@ -4871,23 +5145,46 @@ class RuleCMSWidgetComponent {
4871
5145
  componentProps: this.componentProps,
4872
5146
  displayItemList: this.preparedData.displayItemList,
4873
5147
  widgetCollections: this.preparedData.widgetCollections,
4874
- publishedKey: this.publishedKey,
5148
+ publishedKey: this.renderPublishedKey,
4875
5149
  });
4876
5150
  }
4877
5151
  fetchClient() {
4878
5152
  const token = this.token ?? this.context?.token;
4879
5153
  const endpoint = this.endpoint ?? this.context?.endpoint;
4880
- if (!this.publishedKey || !token) {
4881
- this.error = !this.publishedKey
4882
- ? isDevClientToken(token)
4883
- ? 'Widget key is required'
4884
- : 'Published key is required'
4885
- : 'Token is required. Provide it either directly as an input ([token]) or via rulecms-widget-provider.';
5154
+ const isDev = isDevClientToken(token);
5155
+ const rulesetKey = this.rulesetPublishedKey;
5156
+ if ((!this.publishedKey && !rulesetKey) || !token) {
5157
+ if (!this.publishedKey && !rulesetKey) {
5158
+ this.error =
5159
+ rulesetKey !== undefined
5160
+ ? isDev
5161
+ ? 'Ruleset key is required'
5162
+ : 'Ruleset published key is required'
5163
+ : isDev
5164
+ ? 'Widget key is required'
5165
+ : 'Published key is required';
5166
+ }
5167
+ else {
5168
+ this.error =
5169
+ 'Token is required. Provide it either directly as an input ([token]) or via rulecms-widget-provider.';
5170
+ }
4886
5171
  this.preparedData = null;
5172
+ this.loading = false;
4887
5173
  return;
4888
5174
  }
4889
- const fetchKey = `${this.publishedKey}|${token}`;
5175
+ const paramsKey = stableJsonStringify(this.params);
5176
+ const fetchKey = JSON.stringify({
5177
+ publishedKey: this.publishedKey,
5178
+ rulesetPublishedKey: rulesetKey,
5179
+ token,
5180
+ endpoint,
5181
+ paramsKey,
5182
+ anonymousId: this.anonymousId,
5183
+ fallbackPublishedKey: this.fallbackPublishedKey,
5184
+ contentType: this.contentType,
5185
+ });
4890
5186
  if (this.lastFetchKey === fetchKey && this.preparedData) {
5187
+ this.loading = false;
4891
5188
  this.resolveLibraries();
4892
5189
  return;
4893
5190
  }
@@ -4897,31 +5194,91 @@ class RuleCMSWidgetComponent {
4897
5194
  this.lastFetchKey = fetchKey;
4898
5195
  this.loading = true;
4899
5196
  this.error = null;
4900
- const url = buildWidgetFetchUrl({ publishedKey: this.publishedKey, token, endpoint });
4901
- fetch(url, {
4902
- method: 'GET',
4903
- headers: { 'Content-Type': 'application/json' },
4904
- ...(isDevClientToken(token) ? { cache: 'no-store' } : {}),
4905
- signal,
4906
- })
4907
- .then(async (response) => {
4908
- if (response.ok) {
4909
- const data = await response.json();
4910
- if (data.success) {
4911
- this.preparedData = prepareRuleCMSWidgetData(data.data);
4912
- this.error = null;
4913
- this.resolveLibraries();
4914
- this.warnUnmatched();
5197
+ const requestId = ++this.fetchGeneration;
5198
+ const readErrorMessage = async (response) => {
5199
+ const errorData = await response.json().catch(() => ({ error: 'Unknown error' }));
5200
+ return errorData.error || `Request failed with status ${response.status}`;
5201
+ };
5202
+ const getPublishedWidget = async (key) => {
5203
+ const url = buildWidgetFetchUrl({ publishedKey: key, token, endpoint });
5204
+ const response = await fetch(url, {
5205
+ method: 'GET',
5206
+ ...(isDev ? { cache: 'no-store' } : {}),
5207
+ signal,
5208
+ });
5209
+ if (!response.ok) {
5210
+ throw new FetchWidgetMessage(await readErrorMessage(response));
5211
+ }
5212
+ const data = await response.json();
5213
+ if (!data.success) {
5214
+ throw new FetchWidgetMessage('Failed to fetch widget data');
5215
+ }
5216
+ return data.data;
5217
+ };
5218
+ const resolveWidget = async () => {
5219
+ const requestParams = paramsKey ? JSON.parse(paramsKey) : {};
5220
+ if (this.anonymousId === false) {
5221
+ // Host opted out of an anonymous id.
5222
+ }
5223
+ else if (typeof this.anonymousId === 'string') {
5224
+ requestParams.anonId = requestParams.anonId ?? this.anonymousId;
5225
+ }
5226
+ else if (requestParams.anonId == null) {
5227
+ const minted = getOrCreateAnonymousId();
5228
+ if (minted) {
5229
+ requestParams.anonId = minted;
4915
5230
  }
4916
- else {
4917
- this.error = 'Failed to fetch widget data';
4918
- this.preparedData = null;
5231
+ }
5232
+ let response;
5233
+ try {
5234
+ response = await fetch(buildWidgetResolveUrl({ token, endpoint }), {
5235
+ ...buildWidgetResolveRequestInit({
5236
+ token,
5237
+ rulesetPublishedKey: rulesetKey,
5238
+ params: requestParams,
5239
+ contentType: this.contentType,
5240
+ }),
5241
+ signal,
5242
+ });
5243
+ }
5244
+ catch (err) {
5245
+ if (err instanceof DOMException && err.name === 'AbortError') {
5246
+ throw err;
5247
+ }
5248
+ if (this.fallbackPublishedKey) {
5249
+ return { raw: await getPublishedWidget(this.fallbackPublishedKey), selection: null };
4919
5250
  }
5251
+ throw err;
4920
5252
  }
4921
- else {
4922
- const errorData = await response.json().catch(() => ({ error: 'Unknown error' }));
4923
- this.error = errorData.error || `Request failed with status ${response.status}`;
4924
- this.preparedData = null;
5253
+ if (!response.ok) {
5254
+ if (this.fallbackPublishedKey && isWidgetResolveFallbackStatus(response.status)) {
5255
+ return { raw: await getPublishedWidget(this.fallbackPublishedKey), selection: null };
5256
+ }
5257
+ throw new FetchWidgetMessage(await readErrorMessage(response));
5258
+ }
5259
+ const normalized = normalizeWidgetResolveResponse({
5260
+ token,
5261
+ rulesetPublishedKey: rulesetKey,
5262
+ body: await response.json(),
5263
+ });
5264
+ if (!normalized) {
5265
+ throw new FetchWidgetMessage('Failed to fetch widget data');
5266
+ }
5267
+ return { raw: normalized.raw, selection: normalized.selection };
5268
+ };
5269
+ const run = rulesetKey
5270
+ ? resolveWidget()
5271
+ : getPublishedWidget(this.publishedKey).then((raw) => ({ raw, selection: null }));
5272
+ run
5273
+ .then(({ raw, selection }) => {
5274
+ this.preparedData = prepareRuleCMSWidgetData(raw);
5275
+ this.resolvedPublishedKey = raw.widget?.publishedKey ?? '';
5276
+ this.selection = selection;
5277
+ this.error = null;
5278
+ this.resolveLibraries();
5279
+ this.warnUnmatched();
5280
+ if (selection) {
5281
+ this.selectionChange.emit(selection);
4925
5282
  }
4926
5283
  })
4927
5284
  .catch((err) => {
@@ -4929,11 +5286,14 @@ class RuleCMSWidgetComponent {
4929
5286
  return;
4930
5287
  }
4931
5288
  console.error('Error fetching widget:', err);
4932
- this.error = 'Failed to fetch widget';
5289
+ this.error = err instanceof FetchWidgetMessage ? err.message : 'Failed to fetch widget';
4933
5290
  this.preparedData = null;
5291
+ this.selection = null;
4934
5292
  })
4935
5293
  .finally(() => {
4936
- this.loading = false;
5294
+ if (this.fetchGeneration === requestId) {
5295
+ this.loading = false;
5296
+ }
4937
5297
  });
4938
5298
  }
4939
5299
  ensureSpinnerStyles() {
@@ -4950,38 +5310,38 @@ class RuleCMSWidgetComponent {
4950
5310
  this.stylesInjected = true;
4951
5311
  }
4952
5312
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.25", ngImport: i0, type: RuleCMSWidgetComponent, deps: [{ token: RuleCMSWidgetContextService, optional: true }, { token: ErrorHandler, optional: true }], target: i0.ɵɵFactoryTarget.Component }); }
4953
- static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "19.2.25", type: RuleCMSWidgetComponent, isStandalone: true, selector: "rulecms-widget", inputs: { publishedKey: "publishedKey", token: "token", endpoint: "endpoint", mode: "mode", initialData: "initialData", libraries: "libraries", componentProps: "componentProps", mounts: "mounts" }, host: { styleAttribute: "display: contents" }, usesOnChanges: true, ngImport: i0, template: `
4954
- <span [attr.data-rulecms-published-key]="publishedKey" style="display: contents">
5313
+ static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "19.2.25", type: RuleCMSWidgetComponent, isStandalone: true, selector: "rulecms-widget", inputs: { publishedKey: "publishedKey", rulesetPublishedKey: "rulesetPublishedKey", params: "params", anonymousId: "anonymousId", fallbackPublishedKey: "fallbackPublishedKey", contentType: "contentType", token: "token", endpoint: "endpoint", mode: "mode", initialData: "initialData", libraries: "libraries", componentProps: "componentProps", mounts: "mounts", placeholderValues: "placeholderValues" }, outputs: { selectionChange: "selectionChange" }, host: { styleAttribute: "display: contents" }, usesOnChanges: true, ngImport: i0, template: `
5314
+ <span [attr.data-rulecms-published-key]="renderPublishedKey" style="display: contents">
4955
5315
  <rulecms-project-css-fonts-stylesheet
4956
- [publishedKey]="publishedKey"
5316
+ [publishedKey]="renderPublishedKey"
4957
5317
  [fonts]="preparedData?.fontFaces"
4958
5318
  />
4959
5319
  <rulecms-project-css-keyframes-stylesheet
4960
- [publishedKey]="publishedKey"
5320
+ [publishedKey]="renderPublishedKey"
4961
5321
  [keyframes]="preparedData?.keyframes"
4962
5322
  />
4963
5323
  <rulecms-project-css-themes-stylesheet
4964
- [publishedKey]="publishedKey"
5324
+ [publishedKey]="renderPublishedKey"
4965
5325
  [themes]="preparedData?.themes"
4966
5326
  />
4967
5327
  <rulecms-project-css-properties-stylesheet
4968
- [publishedKey]="publishedKey"
5328
+ [publishedKey]="renderPublishedKey"
4969
5329
  [cssProperties]="preparedData?.cssProperties"
4970
5330
  />
4971
5331
  <rulecms-project-css-widget-chrome-stylesheet
4972
- [publishedKey]="publishedKey"
5332
+ [publishedKey]="renderPublishedKey"
4973
5333
  [widgetChrome]="preparedData?.widgetChrome"
4974
5334
  />
4975
5335
  <rulecms-project-css-position-try-stylesheet
4976
- [publishedKey]="publishedKey"
5336
+ [publishedKey]="renderPublishedKey"
4977
5337
  [positionTry]="preparedData?.positionTry"
4978
5338
  />
4979
5339
  <rulecms-project-css-variables-stylesheet
4980
- [publishedKey]="publishedKey"
5340
+ [publishedKey]="renderPublishedKey"
4981
5341
  [variables]="preparedData?.cssVariables"
4982
5342
  />
4983
5343
  <rulecms-project-css-classes-stylesheet
4984
- [publishedKey]="publishedKey"
5344
+ [publishedKey]="renderPublishedKey"
4985
5345
  [classes]="preparedData?.classDefinitions"
4986
5346
  [classLayer]="preparedData?.classLayer"
4987
5347
  />
@@ -5009,6 +5369,7 @@ class RuleCMSWidgetComponent {
5009
5369
  [plugins]="plugins"
5010
5370
  [componentProps]="componentProps"
5011
5371
  [mounts]="mounts"
5372
+ [placeholderValues]="placeholderValues"
5012
5373
  />
5013
5374
  } @else {
5014
5375
  <rulecms-render-components
@@ -5021,11 +5382,12 @@ class RuleCMSWidgetComponent {
5021
5382
  [plugins]="plugins"
5022
5383
  [componentProps]="componentProps"
5023
5384
  [mounts]="mounts"
5385
+ [placeholderValues]="placeholderValues"
5024
5386
  />
5025
5387
  }
5026
5388
  }
5027
5389
  </span>
5028
- `, isInline: true, dependencies: [{ kind: "directive", type: NgStyle, selector: "[ngStyle]", inputs: ["ngStyle"] }, { kind: "component", type: BreakpointVariantRenderComponent, selector: "rulecms-breakpoint-variants", inputs: ["displayItemList", "widgetCollections", "plugins", "componentProps", "mounts", "scopeIdInput"] }, { kind: "component", type: RenderComponentsComponent, selector: "rulecms-render-components", inputs: ["displayItemList", "isComposeMode", "isWithinCollection", "widgetCollections", "showDropContainers", "reduxDeviceDisplayType", "plugins", "componentProps", "mounts"] }, { kind: "component", type: ProjectCssVariablesStylesheetComponent, selector: "rulecms-project-css-variables-stylesheet", inputs: ["publishedKey", "variables"] }, { kind: "component", type: ProjectCssClassesStylesheetComponent, selector: "rulecms-project-css-classes-stylesheet", inputs: ["publishedKey", "classes", "classLayer"] }, { kind: "component", type: ProjectCssFontsStylesheetComponent, selector: "rulecms-project-css-fonts-stylesheet", inputs: ["publishedKey", "fonts", "includeFontFaces"] }, { kind: "component", type: ProjectCssKeyframesStylesheetComponent, selector: "rulecms-project-css-keyframes-stylesheet", inputs: ["publishedKey", "keyframes"] }, { kind: "component", type: ProjectCssThemesStylesheetComponent, selector: "rulecms-project-css-themes-stylesheet", inputs: ["publishedKey", "themes"] }, { kind: "component", type: ProjectCssPropertiesStylesheetComponent, selector: "rulecms-project-css-properties-stylesheet", inputs: ["publishedKey", "cssProperties"] }, { kind: "component", type: ProjectCssWidgetChromeStylesheetComponent, selector: "rulecms-project-css-widget-chrome-stylesheet", inputs: ["publishedKey", "widgetChrome"] }, { kind: "component", type: ProjectCssPositionTryStylesheetComponent, selector: "rulecms-project-css-position-try-stylesheet", inputs: ["publishedKey", "positionTry"] }] }); }
5390
+ `, isInline: true, dependencies: [{ kind: "directive", type: NgStyle, selector: "[ngStyle]", inputs: ["ngStyle"] }, { kind: "component", type: BreakpointVariantRenderComponent, selector: "rulecms-breakpoint-variants", inputs: ["displayItemList", "widgetCollections", "plugins", "componentProps", "mounts", "placeholderValues", "scopeIdInput"] }, { kind: "component", type: RenderComponentsComponent, selector: "rulecms-render-components", inputs: ["displayItemList", "isComposeMode", "isWithinCollection", "widgetCollections", "showDropContainers", "reduxDeviceDisplayType", "plugins", "componentProps", "mounts", "placeholderValues"] }, { kind: "component", type: ProjectCssVariablesStylesheetComponent, selector: "rulecms-project-css-variables-stylesheet", inputs: ["publishedKey", "variables"] }, { kind: "component", type: ProjectCssClassesStylesheetComponent, selector: "rulecms-project-css-classes-stylesheet", inputs: ["publishedKey", "classes", "classLayer"] }, { kind: "component", type: ProjectCssFontsStylesheetComponent, selector: "rulecms-project-css-fonts-stylesheet", inputs: ["publishedKey", "fonts", "includeFontFaces"] }, { kind: "component", type: ProjectCssKeyframesStylesheetComponent, selector: "rulecms-project-css-keyframes-stylesheet", inputs: ["publishedKey", "keyframes"] }, { kind: "component", type: ProjectCssThemesStylesheetComponent, selector: "rulecms-project-css-themes-stylesheet", inputs: ["publishedKey", "themes"] }, { kind: "component", type: ProjectCssPropertiesStylesheetComponent, selector: "rulecms-project-css-properties-stylesheet", inputs: ["publishedKey", "cssProperties"] }, { kind: "component", type: ProjectCssWidgetChromeStylesheetComponent, selector: "rulecms-project-css-widget-chrome-stylesheet", inputs: ["publishedKey", "widgetChrome"] }, { kind: "component", type: ProjectCssPositionTryStylesheetComponent, selector: "rulecms-project-css-position-try-stylesheet", inputs: ["publishedKey", "positionTry"] }] }); }
5029
5391
  }
5030
5392
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImport: i0, type: RuleCMSWidgetComponent, decorators: [{
5031
5393
  type: Component,
@@ -5046,37 +5408,37 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImpo
5046
5408
  ProjectCssPositionTryStylesheetComponent,
5047
5409
  ],
5048
5410
  template: `
5049
- <span [attr.data-rulecms-published-key]="publishedKey" style="display: contents">
5411
+ <span [attr.data-rulecms-published-key]="renderPublishedKey" style="display: contents">
5050
5412
  <rulecms-project-css-fonts-stylesheet
5051
- [publishedKey]="publishedKey"
5413
+ [publishedKey]="renderPublishedKey"
5052
5414
  [fonts]="preparedData?.fontFaces"
5053
5415
  />
5054
5416
  <rulecms-project-css-keyframes-stylesheet
5055
- [publishedKey]="publishedKey"
5417
+ [publishedKey]="renderPublishedKey"
5056
5418
  [keyframes]="preparedData?.keyframes"
5057
5419
  />
5058
5420
  <rulecms-project-css-themes-stylesheet
5059
- [publishedKey]="publishedKey"
5421
+ [publishedKey]="renderPublishedKey"
5060
5422
  [themes]="preparedData?.themes"
5061
5423
  />
5062
5424
  <rulecms-project-css-properties-stylesheet
5063
- [publishedKey]="publishedKey"
5425
+ [publishedKey]="renderPublishedKey"
5064
5426
  [cssProperties]="preparedData?.cssProperties"
5065
5427
  />
5066
5428
  <rulecms-project-css-widget-chrome-stylesheet
5067
- [publishedKey]="publishedKey"
5429
+ [publishedKey]="renderPublishedKey"
5068
5430
  [widgetChrome]="preparedData?.widgetChrome"
5069
5431
  />
5070
5432
  <rulecms-project-css-position-try-stylesheet
5071
- [publishedKey]="publishedKey"
5433
+ [publishedKey]="renderPublishedKey"
5072
5434
  [positionTry]="preparedData?.positionTry"
5073
5435
  />
5074
5436
  <rulecms-project-css-variables-stylesheet
5075
- [publishedKey]="publishedKey"
5437
+ [publishedKey]="renderPublishedKey"
5076
5438
  [variables]="preparedData?.cssVariables"
5077
5439
  />
5078
5440
  <rulecms-project-css-classes-stylesheet
5079
- [publishedKey]="publishedKey"
5441
+ [publishedKey]="renderPublishedKey"
5080
5442
  [classes]="preparedData?.classDefinitions"
5081
5443
  [classLayer]="preparedData?.classLayer"
5082
5444
  />
@@ -5104,6 +5466,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImpo
5104
5466
  [plugins]="plugins"
5105
5467
  [componentProps]="componentProps"
5106
5468
  [mounts]="mounts"
5469
+ [placeholderValues]="placeholderValues"
5107
5470
  />
5108
5471
  } @else {
5109
5472
  <rulecms-render-components
@@ -5116,6 +5479,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImpo
5116
5479
  [plugins]="plugins"
5117
5480
  [componentProps]="componentProps"
5118
5481
  [mounts]="mounts"
5482
+ [placeholderValues]="placeholderValues"
5119
5483
  />
5120
5484
  }
5121
5485
  }
@@ -5131,8 +5495,17 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImpo
5131
5495
  type: Inject,
5132
5496
  args: [ErrorHandler]
5133
5497
  }] }], propDecorators: { publishedKey: [{
5134
- type: Input,
5135
- args: [{ required: true }]
5498
+ type: Input
5499
+ }], rulesetPublishedKey: [{
5500
+ type: Input
5501
+ }], params: [{
5502
+ type: Input
5503
+ }], anonymousId: [{
5504
+ type: Input
5505
+ }], fallbackPublishedKey: [{
5506
+ type: Input
5507
+ }], contentType: [{
5508
+ type: Input
5136
5509
  }], token: [{
5137
5510
  type: Input
5138
5511
  }], endpoint: [{
@@ -5147,8 +5520,24 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImpo
5147
5520
  type: Input
5148
5521
  }], mounts: [{
5149
5522
  type: Input
5523
+ }], placeholderValues: [{
5524
+ type: Input
5525
+ }], selectionChange: [{
5526
+ type: Output
5150
5527
  }] } });
5528
+ class FetchWidgetMessage extends Error {
5529
+ constructor(message) {
5530
+ super(message);
5531
+ this.name = 'FetchWidgetMessage';
5532
+ }
5533
+ }
5151
5534
 
5535
+ /**
5536
+ * How long a published-token GET stays in the in-process cache when the caller
5537
+ * sets no cache policy. Angular has no Next.js `next.revalidate`; this is the
5538
+ * same 60-second default `@rulecms/widget-react` applies on the server.
5539
+ */
5540
+ const DEFAULT_PUBLISHED_WIDGET_CACHE_MS = 60_000;
5152
5541
  class FetchRuleCMSWidgetError extends Error {
5153
5542
  constructor(message, status) {
5154
5543
  super(message);
@@ -5156,31 +5545,124 @@ class FetchRuleCMSWidgetError extends Error {
5156
5545
  this.status = status;
5157
5546
  }
5158
5547
  }
5159
- /** Fetch widget JSON on the server (or at build time) and return render-ready data. */
5160
- async function fetchRuleCMSWidget(params) {
5161
- const { publishedKey, token, endpoint, fetchOptions } = params;
5162
- if (!publishedKey) {
5163
- throw new FetchRuleCMSWidgetError(isDevClientToken(token) ? 'Widget key is required' : 'Published key is required');
5548
+ const publishedWidgetCache = new Map();
5549
+ /** Drops the in-process published-widget cache. Tests call this between cases. */
5550
+ function clearPublishedWidgetFetchCache() {
5551
+ publishedWidgetCache.clear();
5552
+ }
5553
+ function bypassesPublishedCache(fetchOptions) {
5554
+ const cache = fetchOptions?.cache;
5555
+ return cache === 'no-store' || cache === 'reload' || cache === 'no-cache';
5556
+ }
5557
+ function readPublishedCache(url, now) {
5558
+ const entry = publishedWidgetCache.get(url);
5559
+ if (!entry) {
5560
+ return undefined;
5164
5561
  }
5165
- if (!token) {
5166
- throw new FetchRuleCMSWidgetError('Token is required');
5562
+ if (entry.expiresAt <= now) {
5563
+ publishedWidgetCache.delete(url);
5564
+ return undefined;
5167
5565
  }
5566
+ return entry.data;
5567
+ }
5568
+ async function readErrorMessage(response) {
5569
+ const errorData = await response.json().catch(() => ({ error: 'Unknown error' }));
5570
+ return errorData.error || `Request failed with status ${response.status}`;
5571
+ }
5572
+ async function getPublishedWidget({ publishedKey, token, endpoint, fetchOptions, }) {
5168
5573
  const url = buildWidgetFetchUrl({ publishedKey, token, endpoint });
5574
+ const dev = isDevClientToken(token);
5575
+ const now = Date.now();
5576
+ if (!dev && !bypassesPublishedCache(fetchOptions)) {
5577
+ const cached = readPublishedCache(url, now);
5578
+ if (cached) {
5579
+ return cached;
5580
+ }
5581
+ }
5169
5582
  const response = await fetch(url, {
5170
5583
  method: 'GET',
5171
- headers: { 'Content-Type': 'application/json' },
5172
- ...(isDevClientToken(token) ? { cache: 'no-store' } : {}),
5584
+ ...(dev ? { cache: 'no-store' } : {}),
5173
5585
  ...fetchOptions,
5174
5586
  });
5175
5587
  if (!response.ok) {
5176
- const errorData = await response.json().catch(() => ({ error: 'Unknown error' }));
5177
- throw new FetchRuleCMSWidgetError(errorData.error || `Request failed with status ${response.status}`, response.status);
5588
+ throw new FetchRuleCMSWidgetError(await readErrorMessage(response), response.status);
5178
5589
  }
5179
5590
  const data = await response.json();
5180
5591
  if (!data.success) {
5181
5592
  throw new FetchRuleCMSWidgetError('Failed to fetch widget data');
5182
5593
  }
5183
- return prepareRuleCMSWidgetData(data.data);
5594
+ const prepared = prepareRuleCMSWidgetData(data.data);
5595
+ if (!dev && !bypassesPublishedCache(fetchOptions)) {
5596
+ publishedWidgetCache.set(url, {
5597
+ expiresAt: now + DEFAULT_PUBLISHED_WIDGET_CACHE_MS,
5598
+ data: prepared,
5599
+ });
5600
+ }
5601
+ return prepared;
5602
+ }
5603
+ async function resolveWidgetViaRuleset(params) {
5604
+ const { rulesetPublishedKey, params: resolveParams, fallbackPublishedKey, contentType, token, endpoint, fetchOptions } = params;
5605
+ const fallback = () => getPublishedWidget({
5606
+ publishedKey: fallbackPublishedKey,
5607
+ token,
5608
+ endpoint,
5609
+ fetchOptions,
5610
+ });
5611
+ let response;
5612
+ try {
5613
+ response = await fetch(buildWidgetResolveUrl({ token, endpoint }), {
5614
+ ...buildWidgetResolveRequestInit({
5615
+ token,
5616
+ rulesetPublishedKey,
5617
+ params: resolveParams,
5618
+ contentType,
5619
+ }),
5620
+ ...fetchOptions,
5621
+ });
5622
+ }
5623
+ catch (err) {
5624
+ if (fallbackPublishedKey) {
5625
+ return fallback();
5626
+ }
5627
+ throw err;
5628
+ }
5629
+ if (!response.ok) {
5630
+ if (fallbackPublishedKey && isWidgetResolveFallbackStatus(response.status)) {
5631
+ return fallback();
5632
+ }
5633
+ throw new FetchRuleCMSWidgetError(await readErrorMessage(response), response.status);
5634
+ }
5635
+ const normalized = normalizeWidgetResolveResponse({
5636
+ token,
5637
+ rulesetPublishedKey,
5638
+ body: await response.json(),
5639
+ });
5640
+ if (!normalized) {
5641
+ throw new FetchRuleCMSWidgetError('Failed to fetch widget data');
5642
+ }
5643
+ return { ...prepareRuleCMSWidgetData(normalized.raw), selection: normalized.selection };
5644
+ }
5645
+ /**
5646
+ * Fetch widget JSON on the server (or at build time) and return render-ready
5647
+ * data. Pass `publishedKey` for one widget, or `rulesetPublishedKey` + `params`
5648
+ * to let a ruleset choose (the result then carries `selection`).
5649
+ */
5650
+ async function fetchRuleCMSWidget(params) {
5651
+ const { publishedKey, rulesetPublishedKey, token } = params;
5652
+ if (!publishedKey && !rulesetPublishedKey) {
5653
+ const isDev = isDevClientToken(token);
5654
+ if (rulesetPublishedKey !== undefined) {
5655
+ throw new FetchRuleCMSWidgetError(isDev ? 'Ruleset key is required' : 'Ruleset published key is required');
5656
+ }
5657
+ throw new FetchRuleCMSWidgetError(isDev ? 'Widget key is required' : 'Published key is required');
5658
+ }
5659
+ if (!token) {
5660
+ throw new FetchRuleCMSWidgetError('Token is required');
5661
+ }
5662
+ if (params.rulesetPublishedKey) {
5663
+ return resolveWidgetViaRuleset(params);
5664
+ }
5665
+ return getPublishedWidget(params);
5184
5666
  }
5185
5667
 
5186
5668
  /**
@@ -5205,5 +5687,5 @@ async function resolveWidgetLibraries(params) {
5205
5687
  * Generated bundle index. Do not edit.
5206
5688
  */
5207
5689
 
5208
- export { AlignContentTypes, BreakpointVariantRenderComponent, COLLECTION_TYPE_PREFIX, COMPONENT_PROPS_PATH_SEPARATOR, CSS_CLASSES_ATTRIBUTE_NAME, CSS_VARIABLE_NAME_MAX_LENGTH, CSS_VARIABLE_NAME_PATTERN, DEFAULT_BASE_Z_INDEX, DEFAULT_CLOUDINARY_CLOUD_NAME, DEFAULT_LIBRARY_ID, DEFAULT_ROW_GAP, DEV_CLIENT_TOKEN_PREFIX, DEV_WIDGET_API_PATH, DeviceDisplayTypes, DisplayComponentComponent, DisplayItemTypes, DragItemIdPrefixTypes, EMBEDDED_KEY_SEPARATOR, FLEX_LAYOUT_STYLE_KEYS_THAT_DERIVE_DISPLAY, FetchRuleCMSWidgetError, HIDE_WIDGET_ATTRIBUTE_NAME, JustifyContentTypes, POINTER_EVENTS_ATTRIBUTE_NAME, PUBLISHED_KEY_SEPARATOR, PUBLISHED_WIDGET_API_PATH, PageViewTypes, RULECMS_API_ORIGIN, RULECMS_PUBLISHED_KEY_ATTRIBUTE, RenderComponentsComponent, RenderComponentsForDeviceComponent, RenderComponentsInnerComponent, RuleCMSWidgetComponent, RuleCMSWidgetContextService, RuleCMSWidgetProviderComponent, WIDGET_ATTRIBUTES_IGNORED_IN_COMPOSE_MODE, WIDGET_CACHE_API_ORIGIN, Z_INDEX_WIDGET_ATTRIBUTE_NAME, alignContentAllowlist, alignItemsAllowlist, backgroundPositionAllowlist, backgroundRepeatAllowlist, backgroundSizeAllowlist, borderStyleKeywords, boxSpacingSideKeys, boxSpacingStyleAttributeEntries, buildCloudinaryBackgroundUrl, buildOverlayLayerBoxStyles, buildOverlayStackStyles, buildWidgetFetchUrl, collectComponentInstancePaths, collectReferencedLibraryIds, composeSourceComponentsPlugin, createComponentLibraryRegistry, cssAttrArrayKey, defaultPageWidth, deriveDisplayFlexIfNeeded, desktopModeWidth, fetchRuleCMSWidget, findUnmatchedComponentPropsKeys, flexDirectionAllowlist, flexWrapAllowlist, fontFamilyAllowlist, fontStyleAllowlist, fontWeightAllowlist, formatBackgroundImageStyles, formatBorderStyles, formatBoxShadowStyles, formatBoxSpacingStyles, formatCssColorStyles, formatCssColorValue, formatCssEnumStyles, formatCssLengthStyles, formatCssVariable, formatCssVariableStyles, formatLineHeightStyles, formatObjectStyleAttribute, formatOpacityStyles, formatSpacingSideValue, generatePublishedKey, generatePublishedKeyForEmbedded, getCollectionIdForCollectionType, getColumnAttributes, getComponentAttributesAndStyles, getComponentsPluginFromPlugins, getCssVariableFromLeaf, getDefaultDimensionAttributes, getDeviceTypeBasedAttributes, getDragItemId, getDragItemPrefixAndId, getIdAndPrefix, getMergedAttributes, getNameAndInstanceIdFromWidgetKey, getNameFromWidgetKey, getOverlayLayerZIndex, getWidgetKeyForCollection, getWidgetKeyForCollectionWithPrefix, getWidgetKeyForPublishedCollection, getWidgetKeyForPublishedCollectionWithPrefix, hasBoxShadowLeaf, hasDeviceDivergentValues, hasInvalidCssVariable, hasItems, hasOverlayLayers, incrementVersion, isBackgroundImageValue, isBorderStyleValue, isBorderValue, isBoxShadowValue, isBoxSpacingValue, isCloudinaryCloudName, isCloudinaryPublicId, isCloudinaryTransformationString, isCssColorValue, isCssEnumValue, isCssVariableName, isDevClientToken, isLineHeightValue, isOpacityValue, isOverlayLayerEmptyForDevice, isRowHiddenForDevice, isSafeImageUrl, isSpacingSideValue, isWidgetHiddenForDevice, justifyContentAllowlist, normalizeCssClasses, objectStyleAttributeRegistry, overflowAllowlist, phoneModeWidth, pointerEventsAllowlist, prepareRuleCMSWidgetData, resolveBaseZIndex, resolveKey, resolveOverlayLayerPointerEvents, resolveRowStyles, resolveWidgetApiOrigin, resolveWidgetContainerStyles, resolveWidgetInstanceProps, resolveWidgetLibraries, rowBasedPropertiesAreAssigned, spacingKeywords, spacingLengthUnits, tabletModeWidth, textAlignAllowlist, textDecorationAllowlist, textTransformAllowlist, typeHasPrefix, warnUnmatchedComponentProps, widgetBasedPropertiesAreAssigned, widgetDeclaresOwnHeight };
5690
+ export { AlignContentTypes, BreakpointVariantRenderComponent, COLLECTION_TYPE_PREFIX, COMPONENT_PROPS_PATH_SEPARATOR, CSS_CLASSES_ATTRIBUTE_NAME, CSS_VARIABLE_NAME_MAX_LENGTH, CSS_VARIABLE_NAME_PATTERN, DEFAULT_BASE_Z_INDEX, DEFAULT_CLOUDINARY_CLOUD_NAME, DEFAULT_LIBRARY_ID, DEFAULT_PUBLISHED_WIDGET_CACHE_MS, DEFAULT_ROW_GAP, DEV_CLIENT_TOKEN_PREFIX, DEV_WIDGET_API_PATH, DEV_WIDGET_RESOLVE_API_PATH, DeviceDisplayTypes, DisplayComponentComponent, DisplayItemTypes, DragItemIdPrefixTypes, EMBEDDED_KEY_SEPARATOR, FLEX_LAYOUT_STYLE_KEYS_THAT_DERIVE_DISPLAY, FetchRuleCMSWidgetError, HIDE_WIDGET_ATTRIBUTE_NAME, JustifyContentTypes, POINTER_EVENTS_ATTRIBUTE_NAME, PUBLISHED_KEY_SEPARATOR, PUBLISHED_WIDGET_API_PATH, PUBLISHED_WIDGET_RESOLVE_API_PATH, PageViewTypes, RULECMS_ANONYMOUS_ID_STORAGE_KEY, RULECMS_API_ORIGIN, RULECMS_PUBLISHED_KEY_ATTRIBUTE, RenderComponentsComponent, RenderComponentsForDeviceComponent, RenderComponentsInnerComponent, RuleCMSWidgetComponent, RuleCMSWidgetContextService, RuleCMSWidgetProviderComponent, WIDGET_ATTRIBUTES_IGNORED_IN_COMPOSE_MODE, WIDGET_CACHE_API_ORIGIN, WIDGET_PLACEHOLDER_VALUES_KEY, Z_INDEX_WIDGET_ATTRIBUTE_NAME, alignContentAllowlist, alignItemsAllowlist, backgroundPositionAllowlist, backgroundRepeatAllowlist, backgroundSizeAllowlist, borderStyleKeywords, boxSpacingSideKeys, boxSpacingStyleAttributeEntries, buildCloudinaryBackgroundUrl, buildOverlayLayerBoxStyles, buildOverlayStackStyles, buildWidgetFetchUrl, buildWidgetResolveUrl, clearPublishedWidgetFetchCache, collectComponentInstancePaths, collectReferencedLibraryIds, composeSourceComponentsPlugin, createComponentLibraryRegistry, cssAttrArrayKey, defaultPageWidth, deriveDisplayFlexIfNeeded, desktopModeWidth, fetchRuleCMSWidget, findUnmatchedComponentPropsKeys, flexDirectionAllowlist, flexWrapAllowlist, fontFamilyAllowlist, fontStyleAllowlist, fontWeightAllowlist, formatBackgroundImageStyles, formatBorderStyles, formatBoxShadowStyles, formatBoxSpacingStyles, formatCssColorStyles, formatCssColorValue, formatCssEnumStyles, formatCssLengthStyles, formatCssVariable, formatCssVariableStyles, formatLineHeightStyles, formatObjectStyleAttribute, formatOpacityStyles, formatSpacingSideValue, generatePublishedKey, generatePublishedKeyForEmbedded, getCollectionIdForCollectionType, getColumnAttributes, getComponentAttributesAndStyles, getComponentsPluginFromPlugins, getCssVariableFromLeaf, getDefaultDimensionAttributes, getDeviceTypeBasedAttributes, getDragItemId, getDragItemPrefixAndId, getIdAndPrefix, getMergedAttributes, getNameAndInstanceIdFromWidgetKey, getNameFromWidgetKey, getOrCreateAnonymousId, getOverlayLayerZIndex, getWidgetKeyForCollection, getWidgetKeyForCollectionWithPrefix, getWidgetKeyForPublishedCollection, getWidgetKeyForPublishedCollectionWithPrefix, hasBoxShadowLeaf, hasDeviceDivergentValues, hasInvalidCssVariable, hasItems, hasOverlayLayers, incrementVersion, isBackgroundImageValue, isBorderStyleValue, isBorderValue, isBoxShadowValue, isBoxSpacingValue, isCloudinaryCloudName, isCloudinaryPublicId, isCloudinaryTransformationString, isCssColorValue, isCssEnumValue, isCssVariableName, isDevClientToken, isLineHeightValue, isOpacityValue, isOverlayLayerEmptyForDevice, isRowHiddenForDevice, isSafeImageUrl, isSpacingSideValue, isWidgetHiddenForDevice, justifyContentAllowlist, normalizeCssClasses, objectStyleAttributeRegistry, overflowAllowlist, phoneModeWidth, pointerEventsAllowlist, prepareRuleCMSWidgetData, resolveBaseZIndex, resolveKey, resolveOverlayLayerPointerEvents, resolveRowStyles, resolveWidgetApiOrigin, resolveWidgetContainerStyles, resolveWidgetInstanceProps, resolveWidgetLibraries, rowBasedPropertiesAreAssigned, spacingKeywords, spacingLengthUnits, stableJsonStringify, tabletModeWidth, textAlignAllowlist, textDecorationAllowlist, textTransformAllowlist, typeHasPrefix, warnUnmatchedComponentProps, widgetBasedPropertiesAreAssigned, widgetDeclaresOwnHeight, withWidgetPlaceholderValues };
5209
5691
  //# sourceMappingURL=rulecms-widget-angular.mjs.map