@uniformdev/canvas 12.2.1-alpha.59 → 13.0.1-alpha.133

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.
@@ -1,96 +1,5 @@
1
1
  import Pusher from 'pusher-js';
2
2
 
3
- /** Shape of the GET response from /api/v1/canvas-definitions */
4
- declare type ComponentDefinitionAPIResponse = {
5
- componentDefinitions: Array<ComponentDefinition>;
6
- };
7
- /** Shape of the PUT request body for /api/v1/canvas-definitions */
8
- declare type ComponentDefinitionAPIPutRequest = {
9
- componentDefinition: CreatingComponentDefinition;
10
- projectId: string;
11
- };
12
- /** Shape of the DELETE request body for /api/v1/canvas-definitions */
13
- declare type ComponentDefinitionAPIDeleteRequest = {
14
- /** Public ID of the component definition to delete */
15
- componentId: string;
16
- /** Project ID that the component definition lives on */
17
- projectId: string;
18
- };
19
- /** Query parameter options for GET /api/v1/canvas-definitions */
20
- declare type ComponentDefinitionListAPIOptions = {
21
- /** Limit list to one result by ID (response remains an array) */
22
- componentId?: string;
23
- /** Number of records to skip */
24
- offset?: number;
25
- /** Max number of records to return (defaults to 100) */
26
- limit?: number;
27
- projectId: string;
28
- };
29
- /** The definition of a component parameter */
30
- declare type ComponentDefinitionParameter<TConfig = unknown> = {
31
- /** Public ID of the parameter (used in code). Do not change after creation. */
32
- id: string;
33
- /** Friendly name of the parameter */
34
- name: string;
35
- /** Type name of the parameter (provided by a Uniform integration) */
36
- type: string;
37
- /** The configuration object for the type (type-specific) */
38
- typeConfig?: TConfig;
39
- };
40
- /** The definition of a component variant */
41
- declare type ComponentDefinitionVariant = {
42
- /** Public ID of the variant (used in code). Do not change after creation. */
43
- id: string;
44
- /** Friendly name of the variant */
45
- name: string;
46
- };
47
- /** The definition of a named component slot that can contain other components */
48
- declare type ComponentDefinitionSlot = {
49
- /** Public ID of the slot (used in code). Do not change after creation. */
50
- id: string;
51
- /** Friendly name of the slot */
52
- name: string;
53
- /** Whether this slot inherits its allowed components from the parent slot it lives in. If true, allowedComponents is irrelevant. */
54
- inheritAllowedComponents: boolean;
55
- /** A list of component definition public IDs that are allowed in this named slot */
56
- allowedComponents: Array<string>;
57
- /** Minimum valid number of components in this slot */
58
- minComponents?: number;
59
- /** Maximum valid number of components in this slot */
60
- maxComponents?: number;
61
- };
62
- /** Defines a component type that can live on a Composition */
63
- declare type ComponentDefinition = {
64
- /** Public ID of the component (used in code). Do not change after creation. */
65
- id: string;
66
- /** Friendly name of the component definition */
67
- name: string;
68
- /** Icon name for the component definition (e.g. 'screen') */
69
- icon: string;
70
- /**
71
- * The public ID of the parameter whose value should be used to create a display title for this component in the UI.
72
- * The parameter type must support being used as a title parameter for this to work.
73
- */
74
- titleParameter?: string | null;
75
- /** Whether this component type can be the root of a composition. If false, this component is only used within slots on other components. */
76
- canBeComposition?: boolean;
77
- /** The parameters for this component. Parameters are key-value pairs that can be anything from text values to links to CMS entries. */
78
- parameters?: Array<ComponentDefinitionParameter>;
79
- /** The named slots for this component; placement areas where arrays of other components can be added. */
80
- slots?: Array<ComponentDefinitionSlot>;
81
- /** Named variants for this component; enables creation of visual variants that use the same parameter data/ */
82
- variants?: Array<ComponentDefinitionVariant>;
83
- /** Created date string for this definition */
84
- created?: string;
85
- /** Modified date string for this definition */
86
- modified?: string;
87
- };
88
- /** Defines a component type that can live on a Composition, when it is being created or updated */
89
- declare type CreatingComponentDefinition = Omit<Partial<ComponentDefinition>, 'created' | 'modified' | 'id' | 'name'> & {
90
- id: string;
91
- name: string;
92
- };
93
-
94
3
  /** @deprecated use CANVAS_DRAFT_STATE and CANVAS_PUBLISHED_STATE instead */
95
4
  declare type CompositionFetchState = 'preview' | 'published' | number;
96
5
  /** The GET response from /api/v1/canvas when `component` or `slug` params are specified */
@@ -196,6 +105,128 @@ declare type RootComponentInstance = ComponentInstance & {
196
105
  _name?: string;
197
106
  };
198
107
 
108
+ /** Shape of the GET response from /api/v1/canvas-definitions */
109
+ declare type ComponentDefinitionAPIResponse = {
110
+ componentDefinitions: Array<ComponentDefinition>;
111
+ };
112
+ /** Shape of the PUT request body for /api/v1/canvas-definitions */
113
+ declare type ComponentDefinitionAPIPutRequest = {
114
+ componentDefinition: CreatingComponentDefinition;
115
+ projectId: string;
116
+ };
117
+ /** Shape of the DELETE request body for /api/v1/canvas-definitions */
118
+ declare type ComponentDefinitionAPIDeleteRequest = {
119
+ /** Public ID of the component definition to delete */
120
+ componentId: string;
121
+ /** Project ID that the component definition lives on */
122
+ projectId: string;
123
+ };
124
+ /** Query parameter options for GET /api/v1/canvas-definitions */
125
+ declare type ComponentDefinitionListAPIOptions = {
126
+ /** Limit list to one result by ID (response remains an array) */
127
+ componentId?: string;
128
+ /** Number of records to skip */
129
+ offset?: number;
130
+ /** Max number of records to return (defaults to 100) */
131
+ limit?: number;
132
+ projectId: string;
133
+ };
134
+ /** The definition of a component parameter */
135
+ declare type ComponentDefinitionParameter<TConfig = unknown> = {
136
+ /** Public ID of the parameter (used in code). Do not change after creation. */
137
+ id: string;
138
+ /** Friendly name of the parameter */
139
+ name: string;
140
+ /** Type name of the parameter (provided by a Uniform integration) */
141
+ type: string;
142
+ /** The configuration object for the type (type-specific) */
143
+ typeConfig?: TConfig;
144
+ };
145
+ /** The definition of a component variant */
146
+ declare type ComponentDefinitionVariant = {
147
+ /** Public ID of the variant (used in code). Do not change after creation. */
148
+ id: string;
149
+ /** Friendly name of the variant */
150
+ name: string;
151
+ };
152
+ /** The definition of a component slug */
153
+ declare type ComponentDefinitionSlugSettings = {
154
+ /**
155
+ * Is slug required
156
+ * no: slug is optional
157
+ * yes: slug is required
158
+ * disabled: slug is disabled and will not be shown in the editor
159
+ * @default no
160
+ */
161
+ required?: 'no' | 'yes' | 'disabled';
162
+ /** Slug uniqueness configuration.
163
+ * no = no unique constraint
164
+ * local = must be unique within this component type
165
+ * global = must be unique across all component types
166
+ * @default no
167
+ */
168
+ unique?: 'no' | 'local' | 'global';
169
+ /** Regular expression slugs must match */
170
+ regularExpression?: string;
171
+ /**
172
+ * Custom error message when regular expression validation fails.
173
+ * Has no effect if `regularExpression` is not set.
174
+ */
175
+ regularExpressionMessage?: string;
176
+ };
177
+ /** The definition of a named component slot that can contain other components */
178
+ declare type ComponentDefinitionSlot = {
179
+ /** Public ID of the slot (used in code). Do not change after creation. */
180
+ id: string;
181
+ /** Friendly name of the slot */
182
+ name: string;
183
+ /** Whether this slot inherits its allowed components from the parent slot it lives in. If true, allowedComponents is irrelevant. */
184
+ inheritAllowedComponents: boolean;
185
+ /** A list of component definition public IDs that are allowed in this named slot */
186
+ allowedComponents: Array<string>;
187
+ /** Minimum valid number of components in this slot */
188
+ minComponents?: number;
189
+ /** Maximum valid number of components in this slot */
190
+ maxComponents?: number;
191
+ };
192
+ /** Defines a component type that can live on a Composition */
193
+ declare type ComponentDefinition = {
194
+ /** Public ID of the component (used in code). Do not change after creation. */
195
+ id: string;
196
+ /** Friendly name of the component definition */
197
+ name: string;
198
+ /** Icon name for the component definition (e.g. 'screen') */
199
+ icon: string;
200
+ /**
201
+ * The public ID of the parameter whose value should be used to create a display title for this component in the UI.
202
+ * The parameter type must support being used as a title parameter for this to work.
203
+ */
204
+ titleParameter?: string | null;
205
+ /** Whether this component type can be the root of a composition. If false, this component is only used within slots on other components. */
206
+ canBeComposition?: boolean;
207
+ /** The parameters for this component. Parameters are key-value pairs that can be anything from text values to links to CMS entries. */
208
+ parameters?: Array<ComponentDefinitionParameter>;
209
+ /** The named slots for this component; placement areas where arrays of other components can be added. */
210
+ slots?: Array<ComponentDefinitionSlot>;
211
+ /** Default component instance value */
212
+ defaults?: ComponentInstance | null;
213
+ /** Named variants for this component; enables creation of visual variants that use the same parameter data/ */
214
+ variants?: Array<ComponentDefinitionVariant>;
215
+ /** Setting for slug validation */
216
+ slugSettings?: ComponentDefinitionSlugSettings;
217
+ /** Created date string for this definition */
218
+ created?: string;
219
+ /** Updated date string for this definition */
220
+ updated?: string;
221
+ /** Modified date string for this definition */
222
+ modified?: string;
223
+ };
224
+ /** Defines a component type that can live on a Composition, when it is being created or updated */
225
+ declare type CreatingComponentDefinition = Omit<Partial<ComponentDefinition>, 'created' | 'modified' | 'id' | 'name'> & {
226
+ id: string;
227
+ name: string;
228
+ };
229
+
199
230
  /**
200
231
  * Pusher-js is large (80k) and not tree shakable so it is always bundled if directly referenced,
201
232
  * when it's only needed during preview mode. To avoid bundling it for all, we use an old-school
@@ -221,4 +252,4 @@ declare global {
221
252
  */
222
253
  declare function createEventBus(): Promise<PreviewEventBus | undefined>;
223
254
 
224
- export { ComponentInstance as C, PreviewEventBus as P, RootComponentInstance as R, ComponentParameter as a, CompositionAPIOptions as b, CompositionListAPIResponse as c, CompositionAPIResponse as d, CompositionAPIPutRequest as e, CompositionAPIDeleteRequest as f, ComponentDefinitionListAPIOptions as g, ComponentDefinitionAPIResponse as h, ComponentDefinitionAPIPutRequest as i, ComponentDefinitionAPIDeleteRequest as j, ComponentDefinitionParameter as k, ComponentDefinitionVariant as l, ComponentDefinitionSlot as m, ComponentDefinition as n, CreatingComponentDefinition as o, CompositionFetchState as p, ChannelSubscription as q, createEventBus as r };
255
+ export { ComponentInstance as C, PreviewEventBus as P, RootComponentInstance as R, ComponentParameter as a, CompositionAPIOptions as b, CompositionListAPIResponse as c, CompositionAPIResponse as d, CompositionAPIPutRequest as e, CompositionAPIDeleteRequest as f, ComponentDefinitionListAPIOptions as g, ComponentDefinitionAPIResponse as h, ComponentDefinitionAPIPutRequest as i, ComponentDefinitionAPIDeleteRequest as j, ComponentDefinitionParameter as k, ComponentDefinitionVariant as l, ComponentDefinitionSlugSettings as m, ComponentDefinitionSlot as n, ComponentDefinition as o, CreatingComponentDefinition as p, CompositionFetchState as q, ChannelSubscription as r, createEventBus as s };
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { C as ComponentInstance, a as ComponentParameter, b as CompositionAPIOptions, c as CompositionListAPIResponse, d as CompositionAPIResponse, e as CompositionAPIPutRequest, f as CompositionAPIDeleteRequest, g as ComponentDefinitionListAPIOptions, h as ComponentDefinitionAPIResponse, i as ComponentDefinitionAPIPutRequest, j as ComponentDefinitionAPIDeleteRequest, P as PreviewEventBus } from './createEventBus-ada6f4ff';
2
- export { q as ChannelSubscription, n as ComponentDefinition, j as ComponentDefinitionAPIDeleteRequest, i as ComponentDefinitionAPIPutRequest, h as ComponentDefinitionAPIResponse, g as ComponentDefinitionListAPIOptions, k as ComponentDefinitionParameter, m as ComponentDefinitionSlot, l as ComponentDefinitionVariant, C as ComponentInstance, a as ComponentParameter, f as CompositionAPIDeleteRequest, b as CompositionAPIOptions, e as CompositionAPIPutRequest, d as CompositionAPIResponse, p as CompositionFetchState, c as CompositionListAPIResponse, o as CreatingComponentDefinition, P as PreviewEventBus, R as RootComponentInstance, r as createEventBus } from './createEventBus-ada6f4ff';
1
+ import { C as ComponentInstance, a as ComponentParameter, b as CompositionAPIOptions, c as CompositionListAPIResponse, d as CompositionAPIResponse, e as CompositionAPIPutRequest, f as CompositionAPIDeleteRequest, g as ComponentDefinitionListAPIOptions, h as ComponentDefinitionAPIResponse, i as ComponentDefinitionAPIPutRequest, j as ComponentDefinitionAPIDeleteRequest, P as PreviewEventBus } from './createEventBus-ca90547e';
2
+ export { r as ChannelSubscription, o as ComponentDefinition, j as ComponentDefinitionAPIDeleteRequest, i as ComponentDefinitionAPIPutRequest, h as ComponentDefinitionAPIResponse, g as ComponentDefinitionListAPIOptions, k as ComponentDefinitionParameter, n as ComponentDefinitionSlot, m as ComponentDefinitionSlugSettings, l as ComponentDefinitionVariant, C as ComponentInstance, a as ComponentParameter, f as CompositionAPIDeleteRequest, b as CompositionAPIOptions, e as CompositionAPIPutRequest, d as CompositionAPIResponse, q as CompositionFetchState, c as CompositionListAPIResponse, p as CreatingComponentDefinition, P as PreviewEventBus, R as RootComponentInstance, s as createEventBus } from './createEventBus-ca90547e';
3
3
  import { Options } from 'p-throttle';
4
4
  import { Options as Options$1 } from 'p-retry';
5
- import { PersonalizableListItem } from '@uniformdev/optimize-tracker-common';
5
+ import { PersonalizedVariant, TestVariant } from '@uniformdev/context';
6
6
  import 'pusher-js';
7
7
 
8
8
  declare type EnhancerContext = {
@@ -238,7 +238,7 @@ declare function enhance<TContext extends EnhancerContext = EnhancerContext>({ c
238
238
  * Composes several enhancers into a synchronous chain. Can be used to modify the output of an enhancer.
239
239
  * NOTE: only the first enhancer in the chain may use batching (completeAll()).
240
240
  */
241
- declare const compose: (input: ComponentParameterEnhancer<any, any>, ...composers: ReadonlyArray<ComponentParameterEnhancer<any, any> | ComponentParameterEnhancerFunction<any>>) => ComponentParameterEnhancer<any, any>;
241
+ declare const compose: (input: ComponentParameterEnhancer<any, any> | ComponentParameterEnhancerFunction<any>, ...composers: ReadonlyArray<ComponentParameterEnhancer<any, any> | ComponentParameterEnhancerFunction<any>>) => ComponentParameterEnhancer<any, any>;
242
242
 
243
243
  declare type LimitPolicy = <ReturnValue>(func: () => Promise<ReturnValue>) => Promise<ReturnValue>;
244
244
  declare function createLimitPolicy({ throttle, retry, }: {
@@ -313,8 +313,14 @@ declare const CANVAS_TEST_SLOT = "test";
313
313
  declare const CANVAS_LOCALIZATION_SLOT = "localized";
314
314
  /** Constant for a draft composition state. Subject to change. */
315
315
  declare const CANVAS_DRAFT_STATE = 0;
316
- /** Constatnt for a published composition state. Subject to change. */
316
+ /** Constant for a published composition state. Subject to change. */
317
317
  declare const CANVAS_PUBLISHED_STATE = 64;
318
+ /** Public ID of the Uniform Context personalization parameter on Canvas components */
319
+ declare const CANVAS_PERSONALIZATION_PARAM = "$pzCrit";
320
+ /** Public ID of the Uniform Context test variant parameter on Canvas components */
321
+ declare const CANVAS_TEST_VARIANT_PARAM = "$tstVrnt";
322
+ /** Public ID of the Uniform Context enrichment tag parameter on Canvas components */
323
+ declare const CANVAS_ENRICHMENT_TAG_PARAM = "$enr";
318
324
 
319
325
  /** Determines if a given Canvas component type is a system-defined type */
320
326
  declare const isSystemComponentDefinition: (componentType: string) => boolean;
@@ -323,7 +329,13 @@ declare const isSystemComponentDefinition: (componentType: string) => boolean;
323
329
  * Converts components in a slot into personalized variations (based on each component's intent tag in Canvas) suitable to pass to a personalize component
324
330
  * Useful when implementing custom personalization settings for Canvas components.
325
331
  */
326
- declare function mapSlotToPersonalizedVariations(slot: ComponentInstance[] | undefined): Array<ComponentInstance & PersonalizableListItem>;
332
+ declare function mapSlotToPersonalizedVariations(slot: ComponentInstance[] | undefined): Array<ComponentInstance & PersonalizedVariant>;
333
+
334
+ /**
335
+ * Converts components in a slot into test variations (based on each component's Context tag in Canvas) suitable to pass to a personalize component
336
+ * Useful when implementing custom test settings for Canvas components.
337
+ */
338
+ declare function mapSlotToTestVariations(slot: ComponentInstance[] | undefined): Array<ComponentInstance & TestVariant>;
327
339
 
328
340
  declare function getChannelName(projectId: string, compositionId: string, state: number): string;
329
341
 
@@ -352,4 +364,4 @@ declare function localize({ composition, locale, }: {
352
364
  }) => string | undefined);
353
365
  }): void;
354
366
 
355
- export { BatchEnhancer, BatchEntry, CANVAS_DRAFT_STATE, CANVAS_INTENT_TAG_PARAM, CANVAS_LOCALE_TAG_PARAM, CANVAS_LOCALIZATION_SLOT, CANVAS_LOCALIZATION_TYPE, CANVAS_PERSONALIZE_SLOT, CANVAS_PERSONALIZE_TYPE, CANVAS_PUBLISHED_STATE, CANVAS_TEST_SLOT, CANVAS_TEST_TYPE, CanvasClient, CanvasClientError, CanvasClientOptions, ChildEnhancerBuilder, ComponentEnhancer, ComponentEnhancerFunction, ComponentEnhancerOptions, ComponentLocationReference, ComponentParameterEnhancer, ComponentParameterEnhancerFunction, ComponentParameterEnhancerOptions, EnhancerBuilder, EnhancerContext, EnhancerError, EventNames, LimitPolicy, SubscribeToCompositionOptions, UniqueBatchEntries, UnsubscribeCallback, compose, createBatchEnhancer, createLimitPolicy, enhance, extractLocales, getChannelName, getComponentPath, isSystemComponentDefinition, localize, mapSlotToPersonalizedVariations, nullLimitPolicy, subscribeToComposition, walkComponentTree };
367
+ export { BatchEnhancer, BatchEntry, CANVAS_DRAFT_STATE, CANVAS_ENRICHMENT_TAG_PARAM, CANVAS_INTENT_TAG_PARAM, CANVAS_LOCALE_TAG_PARAM, CANVAS_LOCALIZATION_SLOT, CANVAS_LOCALIZATION_TYPE, CANVAS_PERSONALIZATION_PARAM, CANVAS_PERSONALIZE_SLOT, CANVAS_PERSONALIZE_TYPE, CANVAS_PUBLISHED_STATE, CANVAS_TEST_SLOT, CANVAS_TEST_TYPE, CANVAS_TEST_VARIANT_PARAM, CanvasClient, CanvasClientError, CanvasClientOptions, ChildEnhancerBuilder, ComponentEnhancer, ComponentEnhancerFunction, ComponentEnhancerOptions, ComponentLocationReference, ComponentParameterEnhancer, ComponentParameterEnhancerFunction, ComponentParameterEnhancerOptions, EnhancerBuilder, EnhancerContext, EnhancerError, EventNames, LimitPolicy, SubscribeToCompositionOptions, UniqueBatchEntries, UnsubscribeCallback, compose, createBatchEnhancer, createLimitPolicy, enhance, extractLocales, getChannelName, getComponentPath, isSystemComponentDefinition, localize, mapSlotToPersonalizedVariations, mapSlotToTestVariations, nullLimitPolicy, subscribeToComposition, walkComponentTree };
package/dist/index.esm.js CHANGED
@@ -1,4 +1,4 @@
1
- import{a as L,b as l,c as k,d as M,e as j,f as F,g as P,h as v,i as g,j as $,k as N,l as A,m as U,n as z}from"./chunk-Y7BBT5AF.mjs";function u(o,e){let n=[{ancestorsAndSelf:[{component:o,parentSlot:void 0,parentSlotIndex:void 0}]}];do{let t=n.pop();if(!t)continue;let r=t.ancestorsAndSelf[0];e(r.component,t.ancestorsAndSelf,{replaceComponent:i=>{Object.assign(r.component,i),["parameters","variant","slots","data","_pattern","_patternError"].forEach(s=>{i[s]||delete r.component[s]})},removeComponent:()=>{let{parentSlot:i,parentSlotIndex:c}=t.ancestorsAndSelf[0],s=t.ancestorsAndSelf[1];if(i&&typeof c!="undefined")s.component.slots[i].splice(c,1);else throw new Error("Unable to delete composition.")},insertAfter:i=>{let c=Array.isArray(i)?i:[i],{parentSlot:s,parentSlotIndex:p}=t.ancestorsAndSelf[0],m=t.ancestorsAndSelf[1];if(s&&typeof p!="undefined")m.component.slots[s].splice(p+1,0,...c);else throw new Error("Unable to insert after a component not in a slot.")}});let a=r.component.slots;if(a){let i=Object.keys(a);for(let c=i.length-1;c>=0;c--){let s=i[c],p=a[s];for(let m=p.length-1;m>=0;m--)n.push({ancestorsAndSelf:[{component:p[m],parentSlot:s,parentSlotIndex:m},...t.ancestorsAndSelf]})}}}while(n.length>0)}function f(o){let e=[];for(let n=o.length-1;n>=0;n--){let{parentSlot:t,parentSlotIndex:r}=o[n];t&&r!==void 0&&e.push(`${t}[${r}]`)}return`.${e.join(".")}`}var b=class{constructor(e,n){this.groups=e.reduce((t,r)=>{var i;let a=n(r.args);return t[a]=(i=t[a])!=null?i:[],t[a].push(r),t},{})}resolveKey(e,n){this.groups[e].forEach(t=>t.resolve(n))}resolveRemaining(e){Object.keys(this.groups).forEach(n=>{this.groups[n].forEach(t=>{t.isCompleted||t.resolve(e)})})}};var y=class{constructor(){this._paramMatches=Array();this._dataMatches=new Map}parameter(e){return this._paramMatches.push({enhancer:this._resolveParameterEnhancer(e)}),this}parameterName(e,n){return(Array.isArray(e)?e:[e]).forEach(r=>this._paramMatches.push({name:r,enhancer:this._resolveParameterEnhancer(n)})),this}parameterType(e,n){return(Array.isArray(e)?e:[e]).forEach(r=>this._paramMatches.push({type:r,enhancer:this._resolveParameterEnhancer(n)})),this}data(e,n){if(this._dataMatches.has(e))throw new Error(`${e} enhancer data key has been used more than once. This will cause data loss.`);return this._dataMatches.set(e,typeof n=="function"?{enhanceOne:n}:n),this}resolveParameterEnhancer(e,n){var t;return(t=this._paramMatches.find(r=>r.name&&r.name===e||r.type&&r.type===n.type||!r.type&&!r.name))==null?void 0:t.enhancer}resolveComponentEnhancers(){return this._dataMatches}_resolveParameterEnhancer(e){return typeof e=="function"?{enhanceOne:e}:e}},_=class{constructor(){this._componentIndex={};this._rootBuilder=new y}parameter(e){return this._rootBuilder.parameter(e),this}parameterName(e,n){return this._rootBuilder.parameterName(e,n),this}parameterType(e,n){return this._rootBuilder.parameterType(e,n),this}data(e,n){return this._rootBuilder.data(e,n),this}component(e,n){return(Array.isArray(e)?e:[e]).forEach(r=>{this._componentIndex[r]=this._componentIndex[r]||new y,n(this._componentIndex[r])}),this}resolveParameterEnhancer(e,n,t){let r=this._componentIndex[e.type];if(r){let a=r.resolveParameterEnhancer(n,t);if(a)return a}return this._rootBuilder.resolveParameterEnhancer(n,t)}resolveComponentEnhancers(e){let n=this._rootBuilder.resolveComponentEnhancers(),t=this._componentIndex[e.type];if(t){n=new Map(n);for(let[r,a]of t.resolveComponentEnhancers())n.set(r,a)}return n}};var w=class{constructor(e,n,t){this._resolve=e;this._reject=n;this.args=t;this._isCompleted=!1}resolve(e){this._resolve(e),this._isCompleted=!0}reject(e){this._reject(e),this._isCompleted=!0}get isCompleted(){return this._isCompleted}};function Q({handleBatch:o,shouldQueue:e,limitPolicy:n}){let t=[];return{enhanceOne:async i=>{if(!e||e(i))return new Promise((c,s)=>{t.push(new w(c,s,i))})},completeAll:async()=>{if(t.length>0){try{await o(t)}catch(c){t.forEach(s=>s.reject(c))}if(t.some(c=>!c.isCompleted))throw new Error("The completeAll() function failed to resolve or reject all promises in the batch!")}let i=t.length;return t=[],i},limitPolicy:n}}async function Z({composition:o,enhancers:e,context:n,onErrors:t=r=>{throw new Error(r.map(a=>`${a.message}
1
+ import{d as p,e as k,f as d,g as F,h as V,i as N,j as U,k as v,l as z,m as x,n as W,o as H,p as T,q as Q,r as K,s as w,t as _,u as Z}from"./chunk-IFTDQQUZ.mjs";p();p();function y(o,e){let t=[{ancestorsAndSelf:[{component:o,parentSlot:void 0,parentSlotIndex:void 0}]}];do{let n=t.pop();if(!n)continue;let r=n.ancestorsAndSelf[0];e(r.component,n.ancestorsAndSelf,{replaceComponent:i=>{Object.assign(r.component,i),["parameters","variant","slots","data","_pattern","_patternError"].forEach(s=>{i[s]||delete r.component[s]})},removeComponent:()=>{let{parentSlot:i,parentSlotIndex:c}=n.ancestorsAndSelf[0],s=n.ancestorsAndSelf[1];if(i&&typeof c!="undefined")s.component.slots[i].splice(c,1);else throw new Error("Unable to delete composition.")},insertAfter:i=>{let c=Array.isArray(i)?i:[i],{parentSlot:s,parentSlotIndex:m}=n.ancestorsAndSelf[0],l=n.ancestorsAndSelf[1];if(s&&typeof m!="undefined")l.component.slots[s].splice(m+1,0,...c);else throw new Error("Unable to insert after a component not in a slot.")}});let a=r.component.slots;if(a){let i=Object.keys(a);for(let c=i.length-1;c>=0;c--){let s=i[c],m=a[s];for(let l=m.length-1;l>=0;l--)t.push({ancestorsAndSelf:[{component:m[l],parentSlot:s,parentSlotIndex:l},...n.ancestorsAndSelf]})}}}while(t.length>0)}function E(o){let e=[];for(let t=o.length-1;t>=0;t--){let{parentSlot:n,parentSlotIndex:r}=o[t];n&&r!==void 0&&e.push(`${n}[${r}]`)}return`.${e.join(".")}`}p();var S=class{constructor(e,t){this.groups=e.reduce((n,r)=>{var i;let a=t(r.args);return n[a]=(i=n[a])!=null?i:[],n[a].push(r),n},{})}resolveKey(e,t){this.groups[e].forEach(n=>n.resolve(t))}resolveRemaining(e){Object.keys(this.groups).forEach(t=>{this.groups[t].forEach(n=>{n.isCompleted||n.resolve(e)})})}};p();var P=class{constructor(){this._paramMatches=Array();this._dataMatches=new Map}parameter(e){return this._paramMatches.push({enhancer:this._resolveParameterEnhancer(e)}),this}parameterName(e,t){return(Array.isArray(e)?e:[e]).forEach(r=>this._paramMatches.push({name:r,enhancer:this._resolveParameterEnhancer(t)})),this}parameterType(e,t){return(Array.isArray(e)?e:[e]).forEach(r=>this._paramMatches.push({type:r,enhancer:this._resolveParameterEnhancer(t)})),this}data(e,t){if(this._dataMatches.has(e))throw new Error(`${e} enhancer data key has been used more than once. This will cause data loss.`);return this._dataMatches.set(e,typeof t=="function"?{enhanceOne:t}:t),this}resolveParameterEnhancer(e,t){var n;return(n=this._paramMatches.find(r=>r.name&&r.name===e||r.type&&r.type===t.type||!r.type&&!r.name))==null?void 0:n.enhancer}resolveComponentEnhancers(){return this._dataMatches}_resolveParameterEnhancer(e){return typeof e=="function"?{enhanceOne:e}:e}},B=class{constructor(){this._componentIndex={};this._rootBuilder=new P}parameter(e){return this._rootBuilder.parameter(e),this}parameterName(e,t){return this._rootBuilder.parameterName(e,t),this}parameterType(e,t){return this._rootBuilder.parameterType(e,t),this}data(e,t){return this._rootBuilder.data(e,t),this}component(e,t){return(Array.isArray(e)?e:[e]).forEach(r=>{this._componentIndex[r]=this._componentIndex[r]||new P,t(this._componentIndex[r])}),this}resolveParameterEnhancer(e,t,n){let r=this._componentIndex[e.type];if(r){let a=r.resolveParameterEnhancer(t,n);if(a)return a}return this._rootBuilder.resolveParameterEnhancer(t,n)}resolveComponentEnhancers(e){let t=this._rootBuilder.resolveComponentEnhancers(),n=this._componentIndex[e.type];if(n){t=new Map(t);for(let[r,a]of n.resolveComponentEnhancers())t.set(r,a)}return t}};p();var b=class{constructor(e,t,n){this._resolve=e;this._reject=t;this.args=n;this._isCompleted=!1}resolve(e){this._resolve(e),this._isCompleted=!0}reject(e){this._reject(e),this._isCompleted=!0}get isCompleted(){return this._isCompleted}};function Y({handleBatch:o,shouldQueue:e,limitPolicy:t}){let n=[];return{enhanceOne:async i=>{if(!e||e(i))return new Promise((c,s)=>{n.push(new b(c,s,i))})},completeAll:async()=>{if(n.length>0){try{await o(n)}catch(c){n.forEach(s=>s.reject(c))}if(n.some(c=>!c.isCompleted))throw new Error("The completeAll() function failed to resolve or reject all promises in the batch!")}let i=n.length;return n=[],i},limitPolicy:t}}p();async function te({composition:o,enhancers:e,context:t,onErrors:n=r=>{throw new Error(r.map(a=>`${a.message}
2
2
  ${typeof a.error=="object"&&"stack"in a.error?a.error.stack:a.error}`).join(`
3
3
 
4
- `))}}){let r=[],a=new Set,i=new Set;u(o,(s,p)=>{var h;Object.entries((h=s.parameters)!=null?h:{}).forEach(([C,E])=>{let d=e.resolveParameterEnhancer(s,C,E);d&&(i.add(d),r.push(R(s,p,C,E,d,n)))});let m=e.resolveComponentEnhancers(s);r.push(I(s,p,m,n)),a.add(m)}),r.push(...Array.from(a).flatMap(s=>Array.from(s).map(async([,p])=>{var m;try{p.completeAll&&await((m=p.limitPolicy)!=null?m:l)(()=>p.completeAll())}catch(h){return{error:h,message:"Batch component enhancer failed. Individual failed components should receive their own rejections."}}}))),r.push(...Array.from(i).map(async s=>{var p;try{s.completeAll&&await((p=s.limitPolicy)!=null?p:l)(()=>s.completeAll())}catch(m){return{error:m,message:"Batch parameter enhancer failed. Individual failed parameters should receive their own rejections."}}}));let c=(await Promise.all(r)).flatMap(s=>Array.isArray(s)?s:[s]).filter(s=>s);c.length&&t(c)}async function I(o,e,n,t){return n.size&&(o.data={}),await Promise.all(Array.from(n).map(async([r,a])=>{var i;try{let s=await(a.completeAll?l:(i=a.limitPolicy)!=null?i:l)(async()=>a.enhanceOne({component:o,context:t}));s!=null&&(o.data[r]=s)}catch(c){let s=`Component ${f(e)} (type: ${o.type}): data.${r} enhancer threw exception. Data key will not be present.`;return delete o.data[r],{message:s,error:c}}}))}async function R(o,e,n,t,r,a){var i;try{let s=await(r.completeAll?l:(i=r.limitPolicy)!=null?i:l)(async()=>r.enhanceOne({parameter:t,parameterName:n,component:o,context:a}));s===null?delete o.parameters[n]:typeof s=="undefined"?o.parameters[n]={...t,value:t.value}:o.parameters[n]={...t,value:s}}catch(c){let s=`Component ${f(e)} (type: ${o.type}): enhancing parameter ${n} (type: ${t.type}) threw exception. Parameter will be removed.`;return delete o.parameters[n],{message:s,error:c}}}var J=(o,...e)=>({enhanceOne:t=>{let r=o.enhanceOne(t);for(let a of e){let i=S(r)?r:Promise.resolve(r),c="enhanceOne"in a?a.enhanceOne:a;r=i.then(s=>c({...t,parameter:{type:t.parameter.type,value:s}}))}return r},completeAll:()=>{var t,r;for(let a of e)if("completeAll"in a)throw new Error("Only the first enhancer in a compose chain can use the completeAll function (batching)");return(r=(t=o.completeAll)==null?void 0:t.call(o))!=null?r:Promise.resolve(0)}});function S(o){return!!o&&(typeof o=="object"||typeof o=="function")&&typeof o.then=="function"}var ee=o=>o.startsWith("$");function re(o){return o?o.map(e=>{var n,t;return{...e,intentTag:(t=(n=e.parameters)==null?void 0:n[v])==null?void 0:t.value}}):[]}var T="https://js.pusher.com/7.0.3/pusher.min.js";async function B(){if(!(typeof document=="undefined"||typeof window=="undefined"))return window.Pusher?window.Pusher:new Promise((o,e)=>{let n=setTimeout(()=>{window.Pusher&&o(window.Pusher),e(`Unable to load pusher.js; Uniform Canvas live preview disabled. Consider adding <script src="${T}"><\/script> manually.`)},5e3),t=document.createElement("script");t.src=T,t.addEventListener("load",()=>{clearTimeout(n),o(window.Pusher)}),document.head.appendChild(t)})}async function ae(){let o=await B();if(!o)return;let e=window.__UNIFORM_EVENT_BUS__;if(!e){let n=new o("7b5f5abd160fea549ffe",{cluster:"mt1"});n.connect(),console.log("[canvas] \u{1F525} preview connected"),e=window.__UNIFORM_EVENT_BUS__={subscribe:t=>{let r=n.subscribe(t);return{unsubscribe:()=>n.unsubscribe(t),addEventHandler:(a,i)=>(r.bind(a,i),()=>r.unbind(a,i))}}}}return e}function x(o,e,n){return`${o}.${e}@${n}`}function pe({projectId:o,compositionId:e,compositionState:n=0,eventBus:{subscribe:t},callback:r,event:a="updated"}){let i=x(o,e,n),c=t(i),s=c.addEventHandler(a,r);return()=>{s(),c.unsubscribe()}}function O({component:o}){var t;let e={},n=(t=o.slots)==null?void 0:t[A];return n==null||n.forEach(r=>{var i;let a=(i=r.parameters)==null?void 0:i[g];(a==null?void 0:a.value)&&typeof a.value=="string"&&(e[a.value]=e[a.value]||[],e[a.value].push(r))}),e}function ue({composition:o,locale:e}){u(o,(n,t,r)=>{if(n.type===P){let a=O({component:n}),i=typeof e=="string"?e:e({component:n,locales:a}),c;if(i&&(c=a[i]),c==null?void 0:c.length){let[s,...p]=c;r.replaceComponent(s),p.length&&r.insertAfter(p)}else r.removeComponent()}})}export{w as BatchEntry,U as CANVAS_DRAFT_STATE,v as CANVAS_INTENT_TAG_PARAM,g as CANVAS_LOCALE_TAG_PARAM,A as CANVAS_LOCALIZATION_SLOT,P as CANVAS_LOCALIZATION_TYPE,$ as CANVAS_PERSONALIZE_SLOT,j as CANVAS_PERSONALIZE_TYPE,z as CANVAS_PUBLISHED_STATE,N as CANVAS_TEST_SLOT,F as CANVAS_TEST_TYPE,M as CanvasClient,k as CanvasClientError,y as ChildEnhancerBuilder,_ as EnhancerBuilder,b as UniqueBatchEntries,J as compose,Q as createBatchEnhancer,ae as createEventBus,L as createLimitPolicy,Z as enhance,O as extractLocales,x as getChannelName,f as getComponentPath,ee as isSystemComponentDefinition,ue as localize,re as mapSlotToPersonalizedVariations,l as nullLimitPolicy,pe as subscribeToComposition,u as walkComponentTree};
4
+ `))}}){let r=[],a=new Set,i=new Set;y(o,(s,m)=>{var f;Object.entries((f=s.parameters)!=null?f:{}).forEach(([A,g])=>{let C=e.resolveParameterEnhancer(s,A,g);C&&(i.add(C),r.push(M(s,m,A,g,C,t)))});let l=e.resolveComponentEnhancers(s);r.push(O(s,m,l,t)),a.add(l)}),r.push(...Array.from(a).flatMap(s=>Array.from(s).map(async([,m])=>{var l;try{m.completeAll&&await((l=m.limitPolicy)!=null?l:d)(()=>m.completeAll())}catch(f){return{error:f,message:"Batch component enhancer failed. Individual failed components should receive their own rejections."}}}))),r.push(...Array.from(i).map(async s=>{var m;try{s.completeAll&&await((m=s.limitPolicy)!=null?m:d)(()=>s.completeAll())}catch(l){return{error:l,message:"Batch parameter enhancer failed. Individual failed parameters should receive their own rejections."}}}));let c=(await Promise.all(r)).flatMap(s=>Array.isArray(s)?s:[s]).filter(s=>s);c.length&&n(c)}async function O(o,e,t,n){return t.size&&(o.data={}),await Promise.all(Array.from(t).map(async([r,a])=>{var i;try{let s=await(a.completeAll?d:(i=a.limitPolicy)!=null?i:d)(async()=>a.enhanceOne({component:o,context:n}));s!=null&&(o.data[r]=s)}catch(c){let s=`Component ${E(e)} (type: ${o.type}): data.${r} enhancer threw exception. Data key will not be present.`;return delete o.data[r],{message:s,error:c}}}))}async function M(o,e,t,n,r,a){var i;try{let s=await(r.completeAll?d:(i=r.limitPolicy)!=null?i:d)(async()=>r.enhanceOne({parameter:n,parameterName:t,component:o,context:a}));s===null?delete o.parameters[t]:typeof s=="undefined"?o.parameters[t]={...n,value:n.value}:o.parameters[t]={...n,value:s}}catch(c){let s=`Component ${E(e)} (type: ${o.type}): enhancing parameter ${t} (type: ${n.type}) threw exception. Parameter will be removed.`;return delete o.parameters[t],{message:s,error:c}}}p();var oe=(o,...e)=>({enhanceOne:n=>{let r="enhanceOne"in o?o.enhanceOne(n):o(n);for(let a of e){let i=L(r)?r:Promise.resolve(r),c="enhanceOne"in a?a.enhanceOne:a;r=i.then(s=>c({...n,parameter:{type:n.parameter.type,value:s}}))}return r},completeAll:async()=>{var n,r;for(let a of e)if("completeAll"in a)throw new Error("Only the first enhancer in a compose chain can use the completeAll function (batching)");return(r="completeAll"in o?(n=o.completeAll)==null?void 0:n.call(o):0)!=null?r:0}});function L(o){return!!o&&(typeof o=="object"||typeof o=="function")&&typeof o.then=="function"}p();var se=o=>o.startsWith("$");p();function pe(o){return o?o.map((e,t)=>{var a,i;let n=(i=(a=e.parameters)==null?void 0:a[w])==null?void 0:i.value,r="testId"in e?e.testId:`pz-${t}-${e.type}`;return{...e,id:r,pz:n}}):[]}p();function he(o){return o?o.map((e,t)=>{var a,i,c;let n=(i=(a=e.parameters)==null?void 0:a[_])==null?void 0:i.value,r=(c=n==null?void 0:n.id)!=null?c:"testId"in e?e.testId:`ab-${t}-${e.type}`;return{...e,id:r}}):[]}p();var I="https://js.pusher.com/7.0.3/pusher.min.js";async function $(){if(!(typeof document=="undefined"||typeof window=="undefined"))return window.Pusher?window.Pusher:new Promise((o,e)=>{let t=setTimeout(()=>{window.Pusher&&o(window.Pusher),e(`Unable to load pusher.js; Uniform Canvas live preview disabled. Consider adding <script src="${I}"><\/script> manually.`)},5e3),n=document.createElement("script");n.src=I,n.addEventListener("load",()=>{clearTimeout(t),o(window.Pusher)}),document.head.appendChild(n)})}async function de(){let o=await $();if(!o)return;let e=window.__UNIFORM_EVENT_BUS__;if(!e){let t=new o("7b5f5abd160fea549ffe",{cluster:"mt1"});t.connect(),console.log("[canvas] \u{1F525} preview connected"),e=window.__UNIFORM_EVENT_BUS__={subscribe:n=>{let r=t.subscribe(n);return{unsubscribe:()=>t.unsubscribe(n),addEventHandler:(a,i)=>(r.bind(a,i),()=>r.unbind(a,i))}}}}return e}p();function R(o,e,t){return`${o}.${e}@${t}`}p();function Ee({projectId:o,compositionId:e,compositionState:t=0,eventBus:{subscribe:n},callback:r,event:a="updated"}){let i=R(o,e,t),c=n(i),s=c.addEventHandler(a,r);return()=>{s(),c.unsubscribe()}}p();function j({component:o}){var n;let e={},t=(n=o.slots)==null?void 0:n[T];return t==null||t.forEach(r=>{var i;let a=(i=r.parameters)==null?void 0:i[x];(a==null?void 0:a.value)&&typeof a.value=="string"&&(e[a.value]=e[a.value]||[],e[a.value].push(r))}),e}function ve({composition:o,locale:e}){y(o,(t,n,r)=>{if(t.type===v){let a=j({component:t}),i=typeof e=="string"?e:e({component:t,locales:a}),c;if(i&&(c=a[i]),c!=null&&c.length){let[s,...m]=c;r.replaceComponent(s),m.length&&r.insertAfter(m)}else r.removeComponent()}})}export{b as BatchEntry,Q as CANVAS_DRAFT_STATE,Z as CANVAS_ENRICHMENT_TAG_PARAM,z as CANVAS_INTENT_TAG_PARAM,x as CANVAS_LOCALE_TAG_PARAM,T as CANVAS_LOCALIZATION_SLOT,v as CANVAS_LOCALIZATION_TYPE,w as CANVAS_PERSONALIZATION_PARAM,W as CANVAS_PERSONALIZE_SLOT,N as CANVAS_PERSONALIZE_TYPE,K as CANVAS_PUBLISHED_STATE,H as CANVAS_TEST_SLOT,U as CANVAS_TEST_TYPE,_ as CANVAS_TEST_VARIANT_PARAM,V as CanvasClient,F as CanvasClientError,P as ChildEnhancerBuilder,B as EnhancerBuilder,S as UniqueBatchEntries,oe as compose,Y as createBatchEnhancer,de as createEventBus,k as createLimitPolicy,te as enhance,j as extractLocales,R as getChannelName,E as getComponentPath,se as isSystemComponentDefinition,ve as localize,pe as mapSlotToPersonalizedVariations,he as mapSlotToTestVariations,d as nullLimitPolicy,Ee as subscribeToComposition,y as walkComponentTree};
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- var $=Object.create;var y=Object.defineProperty;var M=Object.getOwnPropertyDescriptor;var V=Object.getOwnPropertyNames;var D=Object.getPrototypeOf,F=Object.prototype.hasOwnProperty;var _=r=>y(r,"__esModule",{value:!0});var z=(r,e)=>{_(r);for(var n in e)y(r,n,{get:e[n],enumerable:!0})},H=(r,e,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of V(e))!F.call(r,t)&&t!=="default"&&y(r,t,{get:()=>e[t],enumerable:!(n=M(e,t))||n.enumerable});return r},S=r=>H(_(y(r!=null?$(D(r)):{},"default",r&&r.__esModule&&"default"in r?{get:()=>r.default,enumerable:!0}:{value:r,enumerable:!0})),r);z(exports,{BatchEntry:()=>A,CANVAS_DRAFT_STATE:()=>ne,CANVAS_INTENT_TAG_PARAM:()=>I,CANVAS_LOCALE_TAG_PARAM:()=>T,CANVAS_LOCALIZATION_SLOT:()=>x,CANVAS_LOCALIZATION_TYPE:()=>v,CANVAS_PERSONALIZE_SLOT:()=>X,CANVAS_PERSONALIZE_TYPE:()=>Y,CANVAS_PUBLISHED_STATE:()=>te,CANVAS_TEST_SLOT:()=>ee,CANVAS_TEST_TYPE:()=>Q,CanvasClient:()=>N,CanvasClientError:()=>f,ChildEnhancerBuilder:()=>E,EnhancerBuilder:()=>L,UniqueBatchEntries:()=>O,compose:()=>J,createBatchEnhancer:()=>q,createEventBus:()=>se,createLimitPolicy:()=>g,enhance:()=>K,extractLocales:()=>U,getChannelName:()=>w,getComponentPath:()=>C,isSystemComponentDefinition:()=>oe,localize:()=>ce,mapSlotToPersonalizedVariations:()=>re,nullLimitPolicy:()=>h,subscribeToComposition:()=>ae,walkComponentTree:()=>d});function d(r,e){let n=[{ancestorsAndSelf:[{component:r,parentSlot:void 0,parentSlotIndex:void 0}]}];do{let t=n.pop();if(!t)continue;let o=t.ancestorsAndSelf[0];e(o.component,t.ancestorsAndSelf,{replaceComponent:s=>{Object.assign(o.component,s),["parameters","variant","slots","data","_pattern","_patternError"].forEach(a=>{s[a]||delete o.component[a]})},removeComponent:()=>{let{parentSlot:s,parentSlotIndex:c}=t.ancestorsAndSelf[0],a=t.ancestorsAndSelf[1];if(s&&typeof c!="undefined")a.component.slots[s].splice(c,1);else throw new Error("Unable to delete composition.")},insertAfter:s=>{let c=Array.isArray(s)?s:[s],{parentSlot:a,parentSlotIndex:p}=t.ancestorsAndSelf[0],m=t.ancestorsAndSelf[1];if(a&&typeof p!="undefined")m.component.slots[a].splice(p+1,0,...c);else throw new Error("Unable to insert after a component not in a slot.")}});let i=o.component.slots;if(i){let s=Object.keys(i);for(let c=s.length-1;c>=0;c--){let a=s[c],p=i[a];for(let m=p.length-1;m>=0;m--)n.push({ancestorsAndSelf:[{component:p[m],parentSlot:a,parentSlotIndex:m},...t.ancestorsAndSelf]})}}}while(n.length>0)}function C(r){let e=[];for(let n=r.length-1;n>=0;n--){let{parentSlot:t,parentSlotIndex:o}=r[n];t&&o!==void 0&&e.push(`${t}[${o}]`)}return`.${e.join(".")}`}var O=class{constructor(e,n){this.groups=e.reduce((t,o)=>{var s;let i=n(o.args);return t[i]=(s=t[i])!=null?s:[],t[i].push(o),t},{})}resolveKey(e,n){this.groups[e].forEach(t=>t.resolve(n))}resolveRemaining(e){Object.keys(this.groups).forEach(n=>{this.groups[n].forEach(t=>{t.isCompleted||t.resolve(e)})})}};var E=class{constructor(){this._paramMatches=Array();this._dataMatches=new Map}parameter(e){return this._paramMatches.push({enhancer:this._resolveParameterEnhancer(e)}),this}parameterName(e,n){return(Array.isArray(e)?e:[e]).forEach(o=>this._paramMatches.push({name:o,enhancer:this._resolveParameterEnhancer(n)})),this}parameterType(e,n){return(Array.isArray(e)?e:[e]).forEach(o=>this._paramMatches.push({type:o,enhancer:this._resolveParameterEnhancer(n)})),this}data(e,n){if(this._dataMatches.has(e))throw new Error(`${e} enhancer data key has been used more than once. This will cause data loss.`);return this._dataMatches.set(e,typeof n=="function"?{enhanceOne:n}:n),this}resolveParameterEnhancer(e,n){var t;return(t=this._paramMatches.find(o=>o.name&&o.name===e||o.type&&o.type===n.type||!o.type&&!o.name))==null?void 0:t.enhancer}resolveComponentEnhancers(){return this._dataMatches}_resolveParameterEnhancer(e){return typeof e=="function"?{enhanceOne:e}:e}},L=class{constructor(){this._componentIndex={};this._rootBuilder=new E}parameter(e){return this._rootBuilder.parameter(e),this}parameterName(e,n){return this._rootBuilder.parameterName(e,n),this}parameterType(e,n){return this._rootBuilder.parameterType(e,n),this}data(e,n){return this._rootBuilder.data(e,n),this}component(e,n){return(Array.isArray(e)?e:[e]).forEach(o=>{this._componentIndex[o]=this._componentIndex[o]||new E,n(this._componentIndex[o])}),this}resolveParameterEnhancer(e,n,t){let o=this._componentIndex[e.type];if(o){let i=o.resolveParameterEnhancer(n,t);if(i)return i}return this._rootBuilder.resolveParameterEnhancer(n,t)}resolveComponentEnhancers(e){let n=this._rootBuilder.resolveComponentEnhancers(),t=this._componentIndex[e.type];if(t){n=new Map(n);for(let[o,i]of t.resolveComponentEnhancers())n.set(o,i)}return n}};var A=class{constructor(e,n,t){this._resolve=e;this._reject=n;this.args=t;this._isCompleted=!1}resolve(e){this._resolve(e),this._isCompleted=!0}reject(e){this._reject(e),this._isCompleted=!0}get isCompleted(){return this._isCompleted}};function q({handleBatch:r,shouldQueue:e,limitPolicy:n}){let t=[];return{enhanceOne:async s=>{if(!e||e(s))return new Promise((c,a)=>{t.push(new A(c,a,s))})},completeAll:async()=>{if(t.length>0){try{await r(t)}catch(c){t.forEach(a=>a.reject(c))}if(t.some(c=>!c.isCompleted))throw new Error("The completeAll() function failed to resolve or reject all promises in the batch!")}let s=t.length;return t=[],s},limitPolicy:n}}var j=S(require("p-throttle")),B=S(require("p-retry"));function g({throttle:r={interval:1e3,limit:10},retry:e={retries:1,factor:1.66}}){let n=r?(0,j.default)(r):null;return function(o){let i=async()=>await o();if(n&&(i=n(i)),e){let s=i;i=()=>(0,B.default)(s,e)}return i()}}var h=async r=>await r();async function K({composition:r,enhancers:e,context:n,onErrors:t=o=>{throw new Error(o.map(i=>`${i.message}
1
+ var M=Object.create;var y=Object.defineProperty;var F=Object.getOwnPropertyDescriptor;var D=Object.getOwnPropertyNames;var z=Object.getPrototypeOf,H=Object.prototype.hasOwnProperty;var S=r=>y(r,"__esModule",{value:!0});var K=(r,e)=>{for(var n in e)y(r,n,{get:e[n],enumerable:!0})},O=(r,e,n,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of D(e))!H.call(r,o)&&(n||o!=="default")&&y(r,o,{get:()=>e[o],enumerable:!(t=F(e,o))||t.enumerable});return r},L=(r,e)=>O(S(y(r!=null?M(z(r)):{},"default",!e&&r&&r.__esModule?{get:()=>r.default,enumerable:!0}:{value:r,enumerable:!0})),r),q=(r=>(e,n)=>r&&r.get(e)||(n=O(S({}),e,1),r&&r.set(e,n),n))(typeof WeakMap!="undefined"?new WeakMap:0);var he={};K(he,{BatchEntry:()=>E,CANVAS_DRAFT_STATE:()=>be,CANVAS_ENRICHMENT_TAG_PARAM:()=>re,CANVAS_INTENT_TAG_PARAM:()=>ne,CANVAS_LOCALE_TAG_PARAM:()=>T,CANVAS_LOCALIZATION_SLOT:()=>v,CANVAS_LOCALIZATION_TYPE:()=>I,CANVAS_PERSONALIZATION_PARAM:()=>x,CANVAS_PERSONALIZE_SLOT:()=>te,CANVAS_PERSONALIZE_TYPE:()=>X,CANVAS_PUBLISHED_STATE:()=>Se,CANVAS_TEST_SLOT:()=>oe,CANVAS_TEST_TYPE:()=>ee,CANVAS_TEST_VARIANT_PARAM:()=>R,CanvasClient:()=>$,CanvasClientError:()=>f,ChildEnhancerBuilder:()=>A,EnhancerBuilder:()=>j,UniqueBatchEntries:()=>N,compose:()=>W,createBatchEnhancer:()=>Z,createEventBus:()=>pe,createLimitPolicy:()=>g,enhance:()=>G,extractLocales:()=>k,getChannelName:()=>w,getComponentPath:()=>C,isSystemComponentDefinition:()=>ie,localize:()=>le,mapSlotToPersonalizedVariations:()=>se,mapSlotToTestVariations:()=>ae,nullLimitPolicy:()=>h,subscribeToComposition:()=>me,walkComponentTree:()=>d});function d(r,e){let n=[{ancestorsAndSelf:[{component:r,parentSlot:void 0,parentSlotIndex:void 0}]}];do{let t=n.pop();if(!t)continue;let o=t.ancestorsAndSelf[0];e(o.component,t.ancestorsAndSelf,{replaceComponent:s=>{Object.assign(o.component,s),["parameters","variant","slots","data","_pattern","_patternError"].forEach(a=>{s[a]||delete o.component[a]})},removeComponent:()=>{let{parentSlot:s,parentSlotIndex:c}=t.ancestorsAndSelf[0],a=t.ancestorsAndSelf[1];if(s&&typeof c!="undefined")a.component.slots[s].splice(c,1);else throw new Error("Unable to delete composition.")},insertAfter:s=>{let c=Array.isArray(s)?s:[s],{parentSlot:a,parentSlotIndex:p}=t.ancestorsAndSelf[0],l=t.ancestorsAndSelf[1];if(a&&typeof p!="undefined")l.component.slots[a].splice(p+1,0,...c);else throw new Error("Unable to insert after a component not in a slot.")}});let i=o.component.slots;if(i){let s=Object.keys(i);for(let c=s.length-1;c>=0;c--){let a=s[c],p=i[a];for(let l=p.length-1;l>=0;l--)n.push({ancestorsAndSelf:[{component:p[l],parentSlot:a,parentSlotIndex:l},...t.ancestorsAndSelf]})}}}while(n.length>0)}function C(r){let e=[];for(let n=r.length-1;n>=0;n--){let{parentSlot:t,parentSlotIndex:o}=r[n];t&&o!==void 0&&e.push(`${t}[${o}]`)}return`.${e.join(".")}`}var N=class{constructor(e,n){this.groups=e.reduce((t,o)=>{var s;let i=n(o.args);return t[i]=(s=t[i])!=null?s:[],t[i].push(o),t},{})}resolveKey(e,n){this.groups[e].forEach(t=>t.resolve(n))}resolveRemaining(e){Object.keys(this.groups).forEach(n=>{this.groups[n].forEach(t=>{t.isCompleted||t.resolve(e)})})}};var A=class{constructor(){this._paramMatches=Array();this._dataMatches=new Map}parameter(e){return this._paramMatches.push({enhancer:this._resolveParameterEnhancer(e)}),this}parameterName(e,n){return(Array.isArray(e)?e:[e]).forEach(o=>this._paramMatches.push({name:o,enhancer:this._resolveParameterEnhancer(n)})),this}parameterType(e,n){return(Array.isArray(e)?e:[e]).forEach(o=>this._paramMatches.push({type:o,enhancer:this._resolveParameterEnhancer(n)})),this}data(e,n){if(this._dataMatches.has(e))throw new Error(`${e} enhancer data key has been used more than once. This will cause data loss.`);return this._dataMatches.set(e,typeof n=="function"?{enhanceOne:n}:n),this}resolveParameterEnhancer(e,n){var t;return(t=this._paramMatches.find(o=>o.name&&o.name===e||o.type&&o.type===n.type||!o.type&&!o.name))==null?void 0:t.enhancer}resolveComponentEnhancers(){return this._dataMatches}_resolveParameterEnhancer(e){return typeof e=="function"?{enhanceOne:e}:e}},j=class{constructor(){this._componentIndex={};this._rootBuilder=new A}parameter(e){return this._rootBuilder.parameter(e),this}parameterName(e,n){return this._rootBuilder.parameterName(e,n),this}parameterType(e,n){return this._rootBuilder.parameterType(e,n),this}data(e,n){return this._rootBuilder.data(e,n),this}component(e,n){return(Array.isArray(e)?e:[e]).forEach(o=>{this._componentIndex[o]=this._componentIndex[o]||new A,n(this._componentIndex[o])}),this}resolveParameterEnhancer(e,n,t){let o=this._componentIndex[e.type];if(o){let i=o.resolveParameterEnhancer(n,t);if(i)return i}return this._rootBuilder.resolveParameterEnhancer(n,t)}resolveComponentEnhancers(e){let n=this._rootBuilder.resolveComponentEnhancers(),t=this._componentIndex[e.type];if(t){n=new Map(n);for(let[o,i]of t.resolveComponentEnhancers())n.set(o,i)}return n}};var E=class{constructor(e,n,t){this._resolve=e;this._reject=n;this.args=t;this._isCompleted=!1}resolve(e){this._resolve(e),this._isCompleted=!0}reject(e){this._reject(e),this._isCompleted=!0}get isCompleted(){return this._isCompleted}};function Z({handleBatch:r,shouldQueue:e,limitPolicy:n}){let t=[];return{enhanceOne:async s=>{if(!e||e(s))return new Promise((c,a)=>{t.push(new E(c,a,s))})},completeAll:async()=>{if(t.length>0){try{await r(t)}catch(c){t.forEach(a=>a.reject(c))}if(t.some(c=>!c.isCompleted))throw new Error("The completeAll() function failed to resolve or reject all promises in the batch!")}let s=t.length;return t=[],s},limitPolicy:n}}var B=L(require("p-throttle")),V=L(require("p-retry"));function g({throttle:r={interval:1e3,limit:10},retry:e={retries:1,factor:1.66}}){let n=r?(0,B.default)(r):null;return function(o){let i=async()=>await o();if(n&&(i=n(i)),e){let s=i;i=()=>(0,V.default)(s,e)}return i()}}var h=async r=>await r();async function G({composition:r,enhancers:e,context:n,onErrors:t=o=>{throw new Error(o.map(i=>`${i.message}
2
2
  ${typeof i.error=="object"&&"stack"in i.error?i.error.stack:i.error}`).join(`
3
3
 
4
- `))}}){let o=[],i=new Set,s=new Set;d(r,(a,p)=>{var u;Object.entries((u=a.parameters)!=null?u:{}).forEach(([R,b])=>{let P=e.resolveParameterEnhancer(a,R,b);P&&(s.add(P),o.push(Z(a,p,R,b,P,n)))});let m=e.resolveComponentEnhancers(a);o.push(G(a,p,m,n)),i.add(m)}),o.push(...Array.from(i).flatMap(a=>Array.from(a).map(async([,p])=>{var m;try{p.completeAll&&await((m=p.limitPolicy)!=null?m:h)(()=>p.completeAll())}catch(u){return{error:u,message:"Batch component enhancer failed. Individual failed components should receive their own rejections."}}}))),o.push(...Array.from(s).map(async a=>{var p;try{a.completeAll&&await((p=a.limitPolicy)!=null?p:h)(()=>a.completeAll())}catch(m){return{error:m,message:"Batch parameter enhancer failed. Individual failed parameters should receive their own rejections."}}}));let c=(await Promise.all(o)).flatMap(a=>Array.isArray(a)?a:[a]).filter(a=>a);c.length&&t(c)}async function G(r,e,n,t){return n.size&&(r.data={}),await Promise.all(Array.from(n).map(async([o,i])=>{var s;try{let a=await(i.completeAll?h:(s=i.limitPolicy)!=null?s:h)(async()=>i.enhanceOne({component:r,context:t}));a!=null&&(r.data[o]=a)}catch(c){let a=`Component ${C(e)} (type: ${r.type}): data.${o} enhancer threw exception. Data key will not be present.`;return delete r.data[o],{message:a,error:c}}}))}async function Z(r,e,n,t,o,i){var s;try{let a=await(o.completeAll?h:(s=o.limitPolicy)!=null?s:h)(async()=>o.enhanceOne({parameter:t,parameterName:n,component:r,context:i}));a===null?delete r.parameters[n]:typeof a=="undefined"?r.parameters[n]={...t,value:t.value}:r.parameters[n]={...t,value:a}}catch(c){let a=`Component ${C(e)} (type: ${r.type}): enhancing parameter ${n} (type: ${t.type}) threw exception. Parameter will be removed.`;return delete r.parameters[n],{message:a,error:c}}}var J=(r,...e)=>({enhanceOne:t=>{let o=r.enhanceOne(t);for(let i of e){let s=W(o)?o:Promise.resolve(o),c="enhanceOne"in i?i.enhanceOne:i;o=s.then(a=>c({...t,parameter:{type:t.parameter.type,value:a}}))}return o},completeAll:()=>{var t,o;for(let i of e)if("completeAll"in i)throw new Error("Only the first enhancer in a compose chain can use the completeAll function (batching)");return(o=(t=r.completeAll)==null?void 0:t.call(r))!=null?o:Promise.resolve(0)}});function W(r){return!!r&&(typeof r=="object"||typeof r=="function")&&typeof r.then=="function"}var f=class extends Error{constructor(e,n,t,o,i){super(`${e}
5
- ${o}${i?" "+i:""} (${n} ${t})`);this.errorMessage=e;this.fetchMethod=n;this.fetchUri=t;this.statusCode=o;this.statusText=i;Object.setPrototypeOf(this,f.prototype)}},N=class{constructor(e){var n,t,o,i,s,c;if(!e.apiKey&&!e.bearerToken)throw new Error("You must provide an API key or a bearer token");this.options={...e,fetch:(n=e.fetch)!=null?n:fetch,apiHost:(t=e.apiHost)!=null?t:"https://uniform.app",apiKey:(o=e.apiKey)!=null?o:null,projectId:(i=e.projectId)!=null?i:null,bearerToken:(s=e.bearerToken)!=null?s:null,limitPolicy:(c=e.limitPolicy)!=null?c:g({})}}async getCompositionList(e){let{projectId:n}=this.options,t=this.createUrl("/api/v1/canvas",{...e,projectId:n});return await this.apiClient(t)}async getCompositionBySlug(e){let{projectId:n}=this.options,t=this.createUrl("/api/v1/canvas",{...e,projectId:n});return await this.apiClient(t)}async getCompositionById(e){let{projectId:n}=this.options,t=this.createUrl("/api/v1/canvas",{...e,projectId:n});return await this.apiClient(t)}async updateComposition(e){let n=this.createUrl("/api/v1/canvas");await this.apiClient(n,{method:"PUT",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}async removeComposition(e){let n=this.createUrl("/api/v1/canvas");await this.apiClient(n,{method:"DELETE",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}async getComponentDefinitions(e){let{projectId:n}=this.options,t=this.createUrl("/api/v1/canvas-definitions",{...e,projectId:n});return await this.apiClient(t)}async updateComponentDefinition(e){let n=this.createUrl("/api/v1/canvas-definitions");await this.apiClient(n,{method:"PUT",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}async removeComponentDefinition(e){let n=this.createUrl("/api/v1/canvas-definitions");await this.apiClient(n,{method:"DELETE",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}async apiClient(e,n){return this.options.limitPolicy(async()=>{var i;let t=this.options.apiKey?{"x-api-key":this.options.apiKey}:{Authorization:`Bearer ${this.options.bearerToken}`},o=await fetch(e.toString(),{...n,headers:{...n==null?void 0:n.headers,...t}});if(!o.ok){let s="";try{let c=await o.text();try{let a=JSON.parse(c);a.errorMessage?s=Array.isArray(a.errorMessage)?a.errorMessage.join(", "):a.errorMessage:s=c}catch(a){s=c}}catch(c){s="General error"}throw new f(s,(i=n==null?void 0:n.method)!=null?i:"GET",e.toString(),o.status)}return(n==null?void 0:n.expectNoContent)?null:await o.json()})}createUrl(e,n){let t=new URL(`${this.options.apiHost}${e}`);return Object.entries(n!=null?n:{}).forEach(([o,i])=>{var s;typeof i!==void 0&&i!==null&&t.searchParams.append(o,(s=i==null?void 0:i.toString())!=null?s:"")}),t}};var Y="$personalization",Q="$test",v="$localization",I="intentTag",T="locale",X="pz",ee="test",x="localized",ne=0,te=64;var oe=r=>r.startsWith("$");function re(r){return r?r.map(e=>{var n,t;return{...e,intentTag:(t=(n=e.parameters)==null?void 0:n[I])==null?void 0:t.value}}):[]}var k="https://js.pusher.com/7.0.3/pusher.min.js";async function ie(){if(!(typeof document=="undefined"||typeof window=="undefined"))return window.Pusher?window.Pusher:new Promise((r,e)=>{let n=setTimeout(()=>{window.Pusher&&r(window.Pusher),e(`Unable to load pusher.js; Uniform Canvas live preview disabled. Consider adding <script src="${k}"><\/script> manually.`)},5e3),t=document.createElement("script");t.src=k,t.addEventListener("load",()=>{clearTimeout(n),r(window.Pusher)}),document.head.appendChild(t)})}async function se(){let r=await ie();if(!r)return;let e=window.__UNIFORM_EVENT_BUS__;if(!e){let n=new r("7b5f5abd160fea549ffe",{cluster:"mt1"});n.connect(),console.log("[canvas] \u{1F525} preview connected"),e=window.__UNIFORM_EVENT_BUS__={subscribe:t=>{let o=n.subscribe(t);return{unsubscribe:()=>n.unsubscribe(t),addEventHandler:(i,s)=>(o.bind(i,s),()=>o.unbind(i,s))}}}}return e}function w(r,e,n){return`${r}.${e}@${n}`}function ae({projectId:r,compositionId:e,compositionState:n=0,eventBus:{subscribe:t},callback:o,event:i="updated"}){let s=w(r,e,n),c=t(s),a=c.addEventHandler(i,o);return()=>{a(),c.unsubscribe()}}function U({component:r}){var t;let e={},n=(t=r.slots)==null?void 0:t[x];return n==null||n.forEach(o=>{var s;let i=(s=o.parameters)==null?void 0:s[T];(i==null?void 0:i.value)&&typeof i.value=="string"&&(e[i.value]=e[i.value]||[],e[i.value].push(o))}),e}function ce({composition:r,locale:e}){d(r,(n,t,o)=>{if(n.type===v){let i=U({component:n}),s=typeof e=="string"?e:e({component:n,locales:i}),c;if(s&&(c=i[s]),c==null?void 0:c.length){let[a,...p]=c;o.replaceComponent(a),p.length&&o.insertAfter(p)}else o.removeComponent()}})}0&&(module.exports={BatchEntry,CANVAS_DRAFT_STATE,CANVAS_INTENT_TAG_PARAM,CANVAS_LOCALE_TAG_PARAM,CANVAS_LOCALIZATION_SLOT,CANVAS_LOCALIZATION_TYPE,CANVAS_PERSONALIZE_SLOT,CANVAS_PERSONALIZE_TYPE,CANVAS_PUBLISHED_STATE,CANVAS_TEST_SLOT,CANVAS_TEST_TYPE,CanvasClient,CanvasClientError,ChildEnhancerBuilder,EnhancerBuilder,UniqueBatchEntries,compose,createBatchEnhancer,createEventBus,createLimitPolicy,enhance,extractLocales,getChannelName,getComponentPath,isSystemComponentDefinition,localize,mapSlotToPersonalizedVariations,nullLimitPolicy,subscribeToComposition,walkComponentTree});
4
+ `))}}){let o=[],i=new Set,s=new Set;d(r,(a,p)=>{var u;Object.entries((u=a.parameters)!=null?u:{}).forEach(([_,b])=>{let P=e.resolveParameterEnhancer(a,_,b);P&&(s.add(P),o.push(J(a,p,_,b,P,n)))});let l=e.resolveComponentEnhancers(a);o.push(Y(a,p,l,n)),i.add(l)}),o.push(...Array.from(i).flatMap(a=>Array.from(a).map(async([,p])=>{var l;try{p.completeAll&&await((l=p.limitPolicy)!=null?l:h)(()=>p.completeAll())}catch(u){return{error:u,message:"Batch component enhancer failed. Individual failed components should receive their own rejections."}}}))),o.push(...Array.from(s).map(async a=>{var p;try{a.completeAll&&await((p=a.limitPolicy)!=null?p:h)(()=>a.completeAll())}catch(l){return{error:l,message:"Batch parameter enhancer failed. Individual failed parameters should receive their own rejections."}}}));let c=(await Promise.all(o)).flatMap(a=>Array.isArray(a)?a:[a]).filter(a=>a);c.length&&t(c)}async function Y(r,e,n,t){return n.size&&(r.data={}),await Promise.all(Array.from(n).map(async([o,i])=>{var s;try{let a=await(i.completeAll?h:(s=i.limitPolicy)!=null?s:h)(async()=>i.enhanceOne({component:r,context:t}));a!=null&&(r.data[o]=a)}catch(c){let a=`Component ${C(e)} (type: ${r.type}): data.${o} enhancer threw exception. Data key will not be present.`;return delete r.data[o],{message:a,error:c}}}))}async function J(r,e,n,t,o,i){var s;try{let a=await(o.completeAll?h:(s=o.limitPolicy)!=null?s:h)(async()=>o.enhanceOne({parameter:t,parameterName:n,component:r,context:i}));a===null?delete r.parameters[n]:typeof a=="undefined"?r.parameters[n]={...t,value:t.value}:r.parameters[n]={...t,value:a}}catch(c){let a=`Component ${C(e)} (type: ${r.type}): enhancing parameter ${n} (type: ${t.type}) threw exception. Parameter will be removed.`;return delete r.parameters[n],{message:a,error:c}}}var W=(r,...e)=>({enhanceOne:t=>{let o="enhanceOne"in r?r.enhanceOne(t):r(t);for(let i of e){let s=Q(o)?o:Promise.resolve(o),c="enhanceOne"in i?i.enhanceOne:i;o=s.then(a=>c({...t,parameter:{type:t.parameter.type,value:a}}))}return o},completeAll:async()=>{var t,o;for(let i of e)if("completeAll"in i)throw new Error("Only the first enhancer in a compose chain can use the completeAll function (batching)");return(o="completeAll"in r?(t=r.completeAll)==null?void 0:t.call(r):0)!=null?o:0}});function Q(r){return!!r&&(typeof r=="object"||typeof r=="function")&&typeof r.then=="function"}var f=class extends Error{constructor(e,n,t,o,i){super(`${e}
5
+ ${o}${i?" "+i:""} (${n} ${t})`);this.errorMessage=e;this.fetchMethod=n;this.fetchUri=t;this.statusCode=o;this.statusText=i;Object.setPrototypeOf(this,f.prototype)}},$=class{constructor(e){var t,o,i,s,c;if(!e.apiKey&&!e.bearerToken)throw new Error("You must provide an API key or a bearer token");let n=e.fetch;if(!n)if(typeof window!="undefined")n=window.fetch.bind(window);else if(typeof fetch!="undefined")n=fetch;else throw new Error("You must provide or polyfill a fetch implementation when not in a browser");this.options={...e,fetch:n,apiHost:(t=e.apiHost)!=null?t:"https://uniform.app",apiKey:(o=e.apiKey)!=null?o:null,projectId:(i=e.projectId)!=null?i:null,bearerToken:(s=e.bearerToken)!=null?s:null,limitPolicy:(c=e.limitPolicy)!=null?c:g({})}}async getCompositionList(e){let{projectId:n}=this.options,t=this.createUrl("/api/v1/canvas",{...e,projectId:n});return await this.apiClient(t)}async getCompositionBySlug(e){let{projectId:n}=this.options,t=this.createUrl("/api/v1/canvas",{...e,projectId:n});return await this.apiClient(t)}async getCompositionById(e){let{projectId:n}=this.options,t=this.createUrl("/api/v1/canvas",{...e,projectId:n});return await this.apiClient(t)}async updateComposition(e){let n=this.createUrl("/api/v1/canvas");await this.apiClient(n,{method:"PUT",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}async removeComposition(e){let n=this.createUrl("/api/v1/canvas");await this.apiClient(n,{method:"DELETE",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}async getComponentDefinitions(e){let{projectId:n}=this.options,t=this.createUrl("/api/v1/canvas-definitions",{...e,projectId:n});return await this.apiClient(t)}async updateComponentDefinition(e){let n=this.createUrl("/api/v1/canvas-definitions");await this.apiClient(n,{method:"PUT",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}async removeComponentDefinition(e){let n=this.createUrl("/api/v1/canvas-definitions");await this.apiClient(n,{method:"DELETE",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}async apiClient(e,n){return this.options.limitPolicy(async()=>{var i;let t=this.options.apiKey?{"x-api-key":this.options.apiKey}:{Authorization:`Bearer ${this.options.bearerToken}`},o=await this.options.fetch(e.toString(),{...n,headers:{...n==null?void 0:n.headers,...t}});if(!o.ok){let s="";try{let c=await o.text();try{let a=JSON.parse(c);a.errorMessage?s=Array.isArray(a.errorMessage)?a.errorMessage.join(", "):a.errorMessage:s=c}catch(a){s=c}}catch(c){s="General error"}throw new f(s,(i=n==null?void 0:n.method)!=null?i:"GET",e.toString(),o.status)}return n!=null&&n.expectNoContent?null:await o.json()})}createUrl(e,n){let t=new URL(`${this.options.apiHost}${e}`);return Object.entries(n!=null?n:{}).forEach(([o,i])=>{var s;typeof i!==void 0&&i!==null&&t.searchParams.append(o,(s=i==null?void 0:i.toString())!=null?s:"")}),t}};var X="$personalization",ee="$test",I="$localization",ne="intentTag",T="locale",te="pz",oe="test",v="localized",be=0,Se=64,x="$pzCrit",R="$tstVrnt",re="$enr";var ie=r=>r.startsWith("$");function se(r){return r?r.map((e,n)=>{var i,s;let t=(s=(i=e.parameters)==null?void 0:i[x])==null?void 0:s.value,o="testId"in e?e.testId:`pz-${n}-${e.type}`;return{...e,id:o,pz:t}}):[]}function ae(r){return r?r.map((e,n)=>{var i,s,c;let t=(s=(i=e.parameters)==null?void 0:i[R])==null?void 0:s.value,o=(c=t==null?void 0:t.id)!=null?c:"testId"in e?e.testId:`ab-${n}-${e.type}`;return{...e,id:o}}):[]}var U="https://js.pusher.com/7.0.3/pusher.min.js";async function ce(){if(!(typeof document=="undefined"||typeof window=="undefined"))return window.Pusher?window.Pusher:new Promise((r,e)=>{let n=setTimeout(()=>{window.Pusher&&r(window.Pusher),e(`Unable to load pusher.js; Uniform Canvas live preview disabled. Consider adding <script src="${U}"><\/script> manually.`)},5e3),t=document.createElement("script");t.src=U,t.addEventListener("load",()=>{clearTimeout(n),r(window.Pusher)}),document.head.appendChild(t)})}async function pe(){let r=await ce();if(!r)return;let e=window.__UNIFORM_EVENT_BUS__;if(!e){let n=new r("7b5f5abd160fea549ffe",{cluster:"mt1"});n.connect(),console.log("[canvas] \u{1F525} preview connected"),e=window.__UNIFORM_EVENT_BUS__={subscribe:t=>{let o=n.subscribe(t);return{unsubscribe:()=>n.unsubscribe(t),addEventHandler:(i,s)=>(o.bind(i,s),()=>o.unbind(i,s))}}}}return e}function w(r,e,n){return`${r}.${e}@${n}`}function me({projectId:r,compositionId:e,compositionState:n=0,eventBus:{subscribe:t},callback:o,event:i="updated"}){let s=w(r,e,n),c=t(s),a=c.addEventHandler(i,o);return()=>{a(),c.unsubscribe()}}function k({component:r}){var t;let e={},n=(t=r.slots)==null?void 0:t[v];return n==null||n.forEach(o=>{var s;let i=(s=o.parameters)==null?void 0:s[T];(i==null?void 0:i.value)&&typeof i.value=="string"&&(e[i.value]=e[i.value]||[],e[i.value].push(o))}),e}function le({composition:r,locale:e}){d(r,(n,t,o)=>{if(n.type===I){let i=k({component:n}),s=typeof e=="string"?e:e({component:n,locales:i}),c;if(s&&(c=i[s]),c!=null&&c.length){let[a,...p]=c;o.replaceComponent(a),p.length&&o.insertAfter(p)}else o.removeComponent()}})}module.exports=q(he);0&&(module.exports={BatchEntry,CANVAS_DRAFT_STATE,CANVAS_ENRICHMENT_TAG_PARAM,CANVAS_INTENT_TAG_PARAM,CANVAS_LOCALE_TAG_PARAM,CANVAS_LOCALIZATION_SLOT,CANVAS_LOCALIZATION_TYPE,CANVAS_PERSONALIZATION_PARAM,CANVAS_PERSONALIZE_SLOT,CANVAS_PERSONALIZE_TYPE,CANVAS_PUBLISHED_STATE,CANVAS_TEST_SLOT,CANVAS_TEST_TYPE,CANVAS_TEST_VARIANT_PARAM,CanvasClient,CanvasClientError,ChildEnhancerBuilder,EnhancerBuilder,UniqueBatchEntries,compose,createBatchEnhancer,createEventBus,createLimitPolicy,enhance,extractLocales,getChannelName,getComponentPath,isSystemComponentDefinition,localize,mapSlotToPersonalizedVariations,mapSlotToTestVariations,nullLimitPolicy,subscribeToComposition,walkComponentTree});
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import{a as L,b as l,c as k,d as M,e as j,f as F,g as P,h as v,i as g,j as $,k as N,l as A,m as U,n as z}from"./chunk-Y7BBT5AF.mjs";function u(o,e){let n=[{ancestorsAndSelf:[{component:o,parentSlot:void 0,parentSlotIndex:void 0}]}];do{let t=n.pop();if(!t)continue;let r=t.ancestorsAndSelf[0];e(r.component,t.ancestorsAndSelf,{replaceComponent:i=>{Object.assign(r.component,i),["parameters","variant","slots","data","_pattern","_patternError"].forEach(s=>{i[s]||delete r.component[s]})},removeComponent:()=>{let{parentSlot:i,parentSlotIndex:c}=t.ancestorsAndSelf[0],s=t.ancestorsAndSelf[1];if(i&&typeof c!="undefined")s.component.slots[i].splice(c,1);else throw new Error("Unable to delete composition.")},insertAfter:i=>{let c=Array.isArray(i)?i:[i],{parentSlot:s,parentSlotIndex:p}=t.ancestorsAndSelf[0],m=t.ancestorsAndSelf[1];if(s&&typeof p!="undefined")m.component.slots[s].splice(p+1,0,...c);else throw new Error("Unable to insert after a component not in a slot.")}});let a=r.component.slots;if(a){let i=Object.keys(a);for(let c=i.length-1;c>=0;c--){let s=i[c],p=a[s];for(let m=p.length-1;m>=0;m--)n.push({ancestorsAndSelf:[{component:p[m],parentSlot:s,parentSlotIndex:m},...t.ancestorsAndSelf]})}}}while(n.length>0)}function f(o){let e=[];for(let n=o.length-1;n>=0;n--){let{parentSlot:t,parentSlotIndex:r}=o[n];t&&r!==void 0&&e.push(`${t}[${r}]`)}return`.${e.join(".")}`}var b=class{constructor(e,n){this.groups=e.reduce((t,r)=>{var i;let a=n(r.args);return t[a]=(i=t[a])!=null?i:[],t[a].push(r),t},{})}resolveKey(e,n){this.groups[e].forEach(t=>t.resolve(n))}resolveRemaining(e){Object.keys(this.groups).forEach(n=>{this.groups[n].forEach(t=>{t.isCompleted||t.resolve(e)})})}};var y=class{constructor(){this._paramMatches=Array();this._dataMatches=new Map}parameter(e){return this._paramMatches.push({enhancer:this._resolveParameterEnhancer(e)}),this}parameterName(e,n){return(Array.isArray(e)?e:[e]).forEach(r=>this._paramMatches.push({name:r,enhancer:this._resolveParameterEnhancer(n)})),this}parameterType(e,n){return(Array.isArray(e)?e:[e]).forEach(r=>this._paramMatches.push({type:r,enhancer:this._resolveParameterEnhancer(n)})),this}data(e,n){if(this._dataMatches.has(e))throw new Error(`${e} enhancer data key has been used more than once. This will cause data loss.`);return this._dataMatches.set(e,typeof n=="function"?{enhanceOne:n}:n),this}resolveParameterEnhancer(e,n){var t;return(t=this._paramMatches.find(r=>r.name&&r.name===e||r.type&&r.type===n.type||!r.type&&!r.name))==null?void 0:t.enhancer}resolveComponentEnhancers(){return this._dataMatches}_resolveParameterEnhancer(e){return typeof e=="function"?{enhanceOne:e}:e}},_=class{constructor(){this._componentIndex={};this._rootBuilder=new y}parameter(e){return this._rootBuilder.parameter(e),this}parameterName(e,n){return this._rootBuilder.parameterName(e,n),this}parameterType(e,n){return this._rootBuilder.parameterType(e,n),this}data(e,n){return this._rootBuilder.data(e,n),this}component(e,n){return(Array.isArray(e)?e:[e]).forEach(r=>{this._componentIndex[r]=this._componentIndex[r]||new y,n(this._componentIndex[r])}),this}resolveParameterEnhancer(e,n,t){let r=this._componentIndex[e.type];if(r){let a=r.resolveParameterEnhancer(n,t);if(a)return a}return this._rootBuilder.resolveParameterEnhancer(n,t)}resolveComponentEnhancers(e){let n=this._rootBuilder.resolveComponentEnhancers(),t=this._componentIndex[e.type];if(t){n=new Map(n);for(let[r,a]of t.resolveComponentEnhancers())n.set(r,a)}return n}};var w=class{constructor(e,n,t){this._resolve=e;this._reject=n;this.args=t;this._isCompleted=!1}resolve(e){this._resolve(e),this._isCompleted=!0}reject(e){this._reject(e),this._isCompleted=!0}get isCompleted(){return this._isCompleted}};function Q({handleBatch:o,shouldQueue:e,limitPolicy:n}){let t=[];return{enhanceOne:async i=>{if(!e||e(i))return new Promise((c,s)=>{t.push(new w(c,s,i))})},completeAll:async()=>{if(t.length>0){try{await o(t)}catch(c){t.forEach(s=>s.reject(c))}if(t.some(c=>!c.isCompleted))throw new Error("The completeAll() function failed to resolve or reject all promises in the batch!")}let i=t.length;return t=[],i},limitPolicy:n}}async function Z({composition:o,enhancers:e,context:n,onErrors:t=r=>{throw new Error(r.map(a=>`${a.message}
1
+ import{d as p,e as k,f as d,g as F,h as V,i as N,j as U,k as v,l as z,m as x,n as W,o as H,p as T,q as Q,r as K,s as w,t as _,u as Z}from"./chunk-IFTDQQUZ.mjs";p();p();function y(o,e){let t=[{ancestorsAndSelf:[{component:o,parentSlot:void 0,parentSlotIndex:void 0}]}];do{let n=t.pop();if(!n)continue;let r=n.ancestorsAndSelf[0];e(r.component,n.ancestorsAndSelf,{replaceComponent:i=>{Object.assign(r.component,i),["parameters","variant","slots","data","_pattern","_patternError"].forEach(s=>{i[s]||delete r.component[s]})},removeComponent:()=>{let{parentSlot:i,parentSlotIndex:c}=n.ancestorsAndSelf[0],s=n.ancestorsAndSelf[1];if(i&&typeof c!="undefined")s.component.slots[i].splice(c,1);else throw new Error("Unable to delete composition.")},insertAfter:i=>{let c=Array.isArray(i)?i:[i],{parentSlot:s,parentSlotIndex:m}=n.ancestorsAndSelf[0],l=n.ancestorsAndSelf[1];if(s&&typeof m!="undefined")l.component.slots[s].splice(m+1,0,...c);else throw new Error("Unable to insert after a component not in a slot.")}});let a=r.component.slots;if(a){let i=Object.keys(a);for(let c=i.length-1;c>=0;c--){let s=i[c],m=a[s];for(let l=m.length-1;l>=0;l--)t.push({ancestorsAndSelf:[{component:m[l],parentSlot:s,parentSlotIndex:l},...n.ancestorsAndSelf]})}}}while(t.length>0)}function E(o){let e=[];for(let t=o.length-1;t>=0;t--){let{parentSlot:n,parentSlotIndex:r}=o[t];n&&r!==void 0&&e.push(`${n}[${r}]`)}return`.${e.join(".")}`}p();var S=class{constructor(e,t){this.groups=e.reduce((n,r)=>{var i;let a=t(r.args);return n[a]=(i=n[a])!=null?i:[],n[a].push(r),n},{})}resolveKey(e,t){this.groups[e].forEach(n=>n.resolve(t))}resolveRemaining(e){Object.keys(this.groups).forEach(t=>{this.groups[t].forEach(n=>{n.isCompleted||n.resolve(e)})})}};p();var P=class{constructor(){this._paramMatches=Array();this._dataMatches=new Map}parameter(e){return this._paramMatches.push({enhancer:this._resolveParameterEnhancer(e)}),this}parameterName(e,t){return(Array.isArray(e)?e:[e]).forEach(r=>this._paramMatches.push({name:r,enhancer:this._resolveParameterEnhancer(t)})),this}parameterType(e,t){return(Array.isArray(e)?e:[e]).forEach(r=>this._paramMatches.push({type:r,enhancer:this._resolveParameterEnhancer(t)})),this}data(e,t){if(this._dataMatches.has(e))throw new Error(`${e} enhancer data key has been used more than once. This will cause data loss.`);return this._dataMatches.set(e,typeof t=="function"?{enhanceOne:t}:t),this}resolveParameterEnhancer(e,t){var n;return(n=this._paramMatches.find(r=>r.name&&r.name===e||r.type&&r.type===t.type||!r.type&&!r.name))==null?void 0:n.enhancer}resolveComponentEnhancers(){return this._dataMatches}_resolveParameterEnhancer(e){return typeof e=="function"?{enhanceOne:e}:e}},B=class{constructor(){this._componentIndex={};this._rootBuilder=new P}parameter(e){return this._rootBuilder.parameter(e),this}parameterName(e,t){return this._rootBuilder.parameterName(e,t),this}parameterType(e,t){return this._rootBuilder.parameterType(e,t),this}data(e,t){return this._rootBuilder.data(e,t),this}component(e,t){return(Array.isArray(e)?e:[e]).forEach(r=>{this._componentIndex[r]=this._componentIndex[r]||new P,t(this._componentIndex[r])}),this}resolveParameterEnhancer(e,t,n){let r=this._componentIndex[e.type];if(r){let a=r.resolveParameterEnhancer(t,n);if(a)return a}return this._rootBuilder.resolveParameterEnhancer(t,n)}resolveComponentEnhancers(e){let t=this._rootBuilder.resolveComponentEnhancers(),n=this._componentIndex[e.type];if(n){t=new Map(t);for(let[r,a]of n.resolveComponentEnhancers())t.set(r,a)}return t}};p();var b=class{constructor(e,t,n){this._resolve=e;this._reject=t;this.args=n;this._isCompleted=!1}resolve(e){this._resolve(e),this._isCompleted=!0}reject(e){this._reject(e),this._isCompleted=!0}get isCompleted(){return this._isCompleted}};function Y({handleBatch:o,shouldQueue:e,limitPolicy:t}){let n=[];return{enhanceOne:async i=>{if(!e||e(i))return new Promise((c,s)=>{n.push(new b(c,s,i))})},completeAll:async()=>{if(n.length>0){try{await o(n)}catch(c){n.forEach(s=>s.reject(c))}if(n.some(c=>!c.isCompleted))throw new Error("The completeAll() function failed to resolve or reject all promises in the batch!")}let i=n.length;return n=[],i},limitPolicy:t}}p();async function te({composition:o,enhancers:e,context:t,onErrors:n=r=>{throw new Error(r.map(a=>`${a.message}
2
2
  ${typeof a.error=="object"&&"stack"in a.error?a.error.stack:a.error}`).join(`
3
3
 
4
- `))}}){let r=[],a=new Set,i=new Set;u(o,(s,p)=>{var h;Object.entries((h=s.parameters)!=null?h:{}).forEach(([C,E])=>{let d=e.resolveParameterEnhancer(s,C,E);d&&(i.add(d),r.push(R(s,p,C,E,d,n)))});let m=e.resolveComponentEnhancers(s);r.push(I(s,p,m,n)),a.add(m)}),r.push(...Array.from(a).flatMap(s=>Array.from(s).map(async([,p])=>{var m;try{p.completeAll&&await((m=p.limitPolicy)!=null?m:l)(()=>p.completeAll())}catch(h){return{error:h,message:"Batch component enhancer failed. Individual failed components should receive their own rejections."}}}))),r.push(...Array.from(i).map(async s=>{var p;try{s.completeAll&&await((p=s.limitPolicy)!=null?p:l)(()=>s.completeAll())}catch(m){return{error:m,message:"Batch parameter enhancer failed. Individual failed parameters should receive their own rejections."}}}));let c=(await Promise.all(r)).flatMap(s=>Array.isArray(s)?s:[s]).filter(s=>s);c.length&&t(c)}async function I(o,e,n,t){return n.size&&(o.data={}),await Promise.all(Array.from(n).map(async([r,a])=>{var i;try{let s=await(a.completeAll?l:(i=a.limitPolicy)!=null?i:l)(async()=>a.enhanceOne({component:o,context:t}));s!=null&&(o.data[r]=s)}catch(c){let s=`Component ${f(e)} (type: ${o.type}): data.${r} enhancer threw exception. Data key will not be present.`;return delete o.data[r],{message:s,error:c}}}))}async function R(o,e,n,t,r,a){var i;try{let s=await(r.completeAll?l:(i=r.limitPolicy)!=null?i:l)(async()=>r.enhanceOne({parameter:t,parameterName:n,component:o,context:a}));s===null?delete o.parameters[n]:typeof s=="undefined"?o.parameters[n]={...t,value:t.value}:o.parameters[n]={...t,value:s}}catch(c){let s=`Component ${f(e)} (type: ${o.type}): enhancing parameter ${n} (type: ${t.type}) threw exception. Parameter will be removed.`;return delete o.parameters[n],{message:s,error:c}}}var J=(o,...e)=>({enhanceOne:t=>{let r=o.enhanceOne(t);for(let a of e){let i=S(r)?r:Promise.resolve(r),c="enhanceOne"in a?a.enhanceOne:a;r=i.then(s=>c({...t,parameter:{type:t.parameter.type,value:s}}))}return r},completeAll:()=>{var t,r;for(let a of e)if("completeAll"in a)throw new Error("Only the first enhancer in a compose chain can use the completeAll function (batching)");return(r=(t=o.completeAll)==null?void 0:t.call(o))!=null?r:Promise.resolve(0)}});function S(o){return!!o&&(typeof o=="object"||typeof o=="function")&&typeof o.then=="function"}var ee=o=>o.startsWith("$");function re(o){return o?o.map(e=>{var n,t;return{...e,intentTag:(t=(n=e.parameters)==null?void 0:n[v])==null?void 0:t.value}}):[]}var T="https://js.pusher.com/7.0.3/pusher.min.js";async function B(){if(!(typeof document=="undefined"||typeof window=="undefined"))return window.Pusher?window.Pusher:new Promise((o,e)=>{let n=setTimeout(()=>{window.Pusher&&o(window.Pusher),e(`Unable to load pusher.js; Uniform Canvas live preview disabled. Consider adding <script src="${T}"><\/script> manually.`)},5e3),t=document.createElement("script");t.src=T,t.addEventListener("load",()=>{clearTimeout(n),o(window.Pusher)}),document.head.appendChild(t)})}async function ae(){let o=await B();if(!o)return;let e=window.__UNIFORM_EVENT_BUS__;if(!e){let n=new o("7b5f5abd160fea549ffe",{cluster:"mt1"});n.connect(),console.log("[canvas] \u{1F525} preview connected"),e=window.__UNIFORM_EVENT_BUS__={subscribe:t=>{let r=n.subscribe(t);return{unsubscribe:()=>n.unsubscribe(t),addEventHandler:(a,i)=>(r.bind(a,i),()=>r.unbind(a,i))}}}}return e}function x(o,e,n){return`${o}.${e}@${n}`}function pe({projectId:o,compositionId:e,compositionState:n=0,eventBus:{subscribe:t},callback:r,event:a="updated"}){let i=x(o,e,n),c=t(i),s=c.addEventHandler(a,r);return()=>{s(),c.unsubscribe()}}function O({component:o}){var t;let e={},n=(t=o.slots)==null?void 0:t[A];return n==null||n.forEach(r=>{var i;let a=(i=r.parameters)==null?void 0:i[g];(a==null?void 0:a.value)&&typeof a.value=="string"&&(e[a.value]=e[a.value]||[],e[a.value].push(r))}),e}function ue({composition:o,locale:e}){u(o,(n,t,r)=>{if(n.type===P){let a=O({component:n}),i=typeof e=="string"?e:e({component:n,locales:a}),c;if(i&&(c=a[i]),c==null?void 0:c.length){let[s,...p]=c;r.replaceComponent(s),p.length&&r.insertAfter(p)}else r.removeComponent()}})}export{w as BatchEntry,U as CANVAS_DRAFT_STATE,v as CANVAS_INTENT_TAG_PARAM,g as CANVAS_LOCALE_TAG_PARAM,A as CANVAS_LOCALIZATION_SLOT,P as CANVAS_LOCALIZATION_TYPE,$ as CANVAS_PERSONALIZE_SLOT,j as CANVAS_PERSONALIZE_TYPE,z as CANVAS_PUBLISHED_STATE,N as CANVAS_TEST_SLOT,F as CANVAS_TEST_TYPE,M as CanvasClient,k as CanvasClientError,y as ChildEnhancerBuilder,_ as EnhancerBuilder,b as UniqueBatchEntries,J as compose,Q as createBatchEnhancer,ae as createEventBus,L as createLimitPolicy,Z as enhance,O as extractLocales,x as getChannelName,f as getComponentPath,ee as isSystemComponentDefinition,ue as localize,re as mapSlotToPersonalizedVariations,l as nullLimitPolicy,pe as subscribeToComposition,u as walkComponentTree};
4
+ `))}}){let r=[],a=new Set,i=new Set;y(o,(s,m)=>{var f;Object.entries((f=s.parameters)!=null?f:{}).forEach(([A,g])=>{let C=e.resolveParameterEnhancer(s,A,g);C&&(i.add(C),r.push(M(s,m,A,g,C,t)))});let l=e.resolveComponentEnhancers(s);r.push(O(s,m,l,t)),a.add(l)}),r.push(...Array.from(a).flatMap(s=>Array.from(s).map(async([,m])=>{var l;try{m.completeAll&&await((l=m.limitPolicy)!=null?l:d)(()=>m.completeAll())}catch(f){return{error:f,message:"Batch component enhancer failed. Individual failed components should receive their own rejections."}}}))),r.push(...Array.from(i).map(async s=>{var m;try{s.completeAll&&await((m=s.limitPolicy)!=null?m:d)(()=>s.completeAll())}catch(l){return{error:l,message:"Batch parameter enhancer failed. Individual failed parameters should receive their own rejections."}}}));let c=(await Promise.all(r)).flatMap(s=>Array.isArray(s)?s:[s]).filter(s=>s);c.length&&n(c)}async function O(o,e,t,n){return t.size&&(o.data={}),await Promise.all(Array.from(t).map(async([r,a])=>{var i;try{let s=await(a.completeAll?d:(i=a.limitPolicy)!=null?i:d)(async()=>a.enhanceOne({component:o,context:n}));s!=null&&(o.data[r]=s)}catch(c){let s=`Component ${E(e)} (type: ${o.type}): data.${r} enhancer threw exception. Data key will not be present.`;return delete o.data[r],{message:s,error:c}}}))}async function M(o,e,t,n,r,a){var i;try{let s=await(r.completeAll?d:(i=r.limitPolicy)!=null?i:d)(async()=>r.enhanceOne({parameter:n,parameterName:t,component:o,context:a}));s===null?delete o.parameters[t]:typeof s=="undefined"?o.parameters[t]={...n,value:n.value}:o.parameters[t]={...n,value:s}}catch(c){let s=`Component ${E(e)} (type: ${o.type}): enhancing parameter ${t} (type: ${n.type}) threw exception. Parameter will be removed.`;return delete o.parameters[t],{message:s,error:c}}}p();var oe=(o,...e)=>({enhanceOne:n=>{let r="enhanceOne"in o?o.enhanceOne(n):o(n);for(let a of e){let i=L(r)?r:Promise.resolve(r),c="enhanceOne"in a?a.enhanceOne:a;r=i.then(s=>c({...n,parameter:{type:n.parameter.type,value:s}}))}return r},completeAll:async()=>{var n,r;for(let a of e)if("completeAll"in a)throw new Error("Only the first enhancer in a compose chain can use the completeAll function (batching)");return(r="completeAll"in o?(n=o.completeAll)==null?void 0:n.call(o):0)!=null?r:0}});function L(o){return!!o&&(typeof o=="object"||typeof o=="function")&&typeof o.then=="function"}p();var se=o=>o.startsWith("$");p();function pe(o){return o?o.map((e,t)=>{var a,i;let n=(i=(a=e.parameters)==null?void 0:a[w])==null?void 0:i.value,r="testId"in e?e.testId:`pz-${t}-${e.type}`;return{...e,id:r,pz:n}}):[]}p();function he(o){return o?o.map((e,t)=>{var a,i,c;let n=(i=(a=e.parameters)==null?void 0:a[_])==null?void 0:i.value,r=(c=n==null?void 0:n.id)!=null?c:"testId"in e?e.testId:`ab-${t}-${e.type}`;return{...e,id:r}}):[]}p();var I="https://js.pusher.com/7.0.3/pusher.min.js";async function $(){if(!(typeof document=="undefined"||typeof window=="undefined"))return window.Pusher?window.Pusher:new Promise((o,e)=>{let t=setTimeout(()=>{window.Pusher&&o(window.Pusher),e(`Unable to load pusher.js; Uniform Canvas live preview disabled. Consider adding <script src="${I}"><\/script> manually.`)},5e3),n=document.createElement("script");n.src=I,n.addEventListener("load",()=>{clearTimeout(t),o(window.Pusher)}),document.head.appendChild(n)})}async function de(){let o=await $();if(!o)return;let e=window.__UNIFORM_EVENT_BUS__;if(!e){let t=new o("7b5f5abd160fea549ffe",{cluster:"mt1"});t.connect(),console.log("[canvas] \u{1F525} preview connected"),e=window.__UNIFORM_EVENT_BUS__={subscribe:n=>{let r=t.subscribe(n);return{unsubscribe:()=>t.unsubscribe(n),addEventHandler:(a,i)=>(r.bind(a,i),()=>r.unbind(a,i))}}}}return e}p();function R(o,e,t){return`${o}.${e}@${t}`}p();function Ee({projectId:o,compositionId:e,compositionState:t=0,eventBus:{subscribe:n},callback:r,event:a="updated"}){let i=R(o,e,t),c=n(i),s=c.addEventHandler(a,r);return()=>{s(),c.unsubscribe()}}p();function j({component:o}){var n;let e={},t=(n=o.slots)==null?void 0:n[T];return t==null||t.forEach(r=>{var i;let a=(i=r.parameters)==null?void 0:i[x];(a==null?void 0:a.value)&&typeof a.value=="string"&&(e[a.value]=e[a.value]||[],e[a.value].push(r))}),e}function ve({composition:o,locale:e}){y(o,(t,n,r)=>{if(t.type===v){let a=j({component:t}),i=typeof e=="string"?e:e({component:t,locales:a}),c;if(i&&(c=a[i]),c!=null&&c.length){let[s,...m]=c;r.replaceComponent(s),m.length&&r.insertAfter(m)}else r.removeComponent()}})}export{b as BatchEntry,Q as CANVAS_DRAFT_STATE,Z as CANVAS_ENRICHMENT_TAG_PARAM,z as CANVAS_INTENT_TAG_PARAM,x as CANVAS_LOCALE_TAG_PARAM,T as CANVAS_LOCALIZATION_SLOT,v as CANVAS_LOCALIZATION_TYPE,w as CANVAS_PERSONALIZATION_PARAM,W as CANVAS_PERSONALIZE_SLOT,N as CANVAS_PERSONALIZE_TYPE,K as CANVAS_PUBLISHED_STATE,H as CANVAS_TEST_SLOT,U as CANVAS_TEST_TYPE,_ as CANVAS_TEST_VARIANT_PARAM,V as CanvasClient,F as CanvasClientError,P as ChildEnhancerBuilder,B as EnhancerBuilder,S as UniqueBatchEntries,oe as compose,Y as createBatchEnhancer,de as createEventBus,k as createLimitPolicy,te as enhance,j as extractLocales,R as getChannelName,E as getComponentPath,se as isSystemComponentDefinition,ve as localize,pe as mapSlotToPersonalizedVariations,he as mapSlotToTestVariations,d as nullLimitPolicy,Ee as subscribeToComposition,y as walkComponentTree};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uniformdev/canvas",
3
- "version": "12.2.1-alpha.59+ee5a4745",
3
+ "version": "13.0.1-alpha.133+5e32ce3cd",
4
4
  "description": "Common functionality and types for Uniform Canvas",
5
5
  "license": "SEE LICENSE IN LICENSE.txt",
6
6
  "main": "./dist/index.js",
@@ -31,45 +31,23 @@
31
31
  },
32
32
  "sideEffects": false,
33
33
  "scripts": {
34
- "build": "tsup",
34
+ "build": "tsup --minify",
35
35
  "dev": "tsup --watch",
36
36
  "clean": "rimraf dist",
37
37
  "test": "jest --maxWorkers=1",
38
38
  "lint": "eslint \"src/**/*.{js,ts,tsx}\"",
39
- "format": "prettier --write \"src/**/*.{js,ts,tsx}\"",
40
- "ci:verify": "run-p lint test",
41
- "ci:build": "tsup --minify --clean"
39
+ "format": "prettier --write \"src/**/*.{js,ts,tsx}\""
42
40
  },
43
41
  "devDependencies": {
44
- "@types/diff": "5.0.1",
45
- "@types/jest": "27.0.3",
46
- "@types/js-yaml": "4.0.4",
47
- "@types/lodash.isequalwith": "4.4.6",
48
- "@types/node": "16.7.1",
49
- "@types/yargs": "17.0.5",
50
- "@uniformdev/cli": "^12.2.1-alpha.59+ee5a4745",
51
- "eslint": "7.32.0",
52
- "eslint-plugin-react": "7.27.1",
53
- "eslint-plugin-react-hooks": "4.3.0",
54
- "jest": "27.3.1",
55
- "npm-run-all": "4.1.5",
56
- "pusher-js": "7.0.3",
57
- "rimraf": "3.0.2",
58
- "ts-jest": "27.0.7",
59
- "tsup": "5.7.2",
60
- "yargs": "17.2.1"
61
- },
62
- "peerDependencies": {
63
- "yargs": "^17.0.1"
42
+ "@types/retry": "^0.12.1",
43
+ "@types/yargs": "17.0.10",
44
+ "@uniformdev/cli": "^13.0.1-alpha.133+5e32ce3cd",
45
+ "pusher-js": "7.0.6",
46
+ "yargs": "17.4.0"
64
47
  },
65
48
  "dependencies": {
66
- "@uniformdev/optimize-common": "^12.2.1-alpha.59+ee5a4745",
67
- "@uniformdev/optimize-tracker-common": "^12.2.1-alpha.59+ee5a4745",
68
- "chalk": "^4.1.2",
69
- "diff": "^5.0.0",
49
+ "@uniformdev/context": "^13.0.1-alpha.133+5e32ce3cd",
70
50
  "isomorphic-unfetch": "^3.1.0",
71
- "js-yaml": "^4.1.0",
72
- "lodash.isequalwith": "^4.4.0",
73
51
  "p-limit": "^3.1.0",
74
52
  "p-retry": "^4.6.1",
75
53
  "p-throttle": "^4.1.1"
@@ -80,5 +58,5 @@
80
58
  "publishConfig": {
81
59
  "access": "public"
82
60
  },
83
- "gitHead": "ee5a4745535ac342d62ba2472e2a681c9867255b"
61
+ "gitHead": "5e32ce3cd962560af97708369bf4c4c91a0116d1"
84
62
  }
@@ -1,2 +0,0 @@
1
- import m from"p-throttle";import u from"p-retry";function l({throttle:p={interval:1e3,limit:10},retry:e={retries:1,factor:1.66}}){let t=p?m(p):null;return function(s){let i=async()=>await s();if(t&&(i=t(i)),e){let n=i;i=()=>u(n,e)}return i()}}var I=async p=>await p();var c=class extends Error{constructor(e,t,o,s,i){super(`${e}
2
- ${s}${i?" "+i:""} (${t} ${o})`);this.errorMessage=e;this.fetchMethod=t;this.fetchUri=o;this.statusCode=s;this.statusText=i;Object.setPrototypeOf(this,c.prototype)}},h=class{constructor(e){var t,o,s,i,n,r;if(!e.apiKey&&!e.bearerToken)throw new Error("You must provide an API key or a bearer token");this.options={...e,fetch:(t=e.fetch)!=null?t:fetch,apiHost:(o=e.apiHost)!=null?o:"https://uniform.app",apiKey:(s=e.apiKey)!=null?s:null,projectId:(i=e.projectId)!=null?i:null,bearerToken:(n=e.bearerToken)!=null?n:null,limitPolicy:(r=e.limitPolicy)!=null?r:l({})}}async getCompositionList(e){let{projectId:t}=this.options,o=this.createUrl("/api/v1/canvas",{...e,projectId:t});return await this.apiClient(o)}async getCompositionBySlug(e){let{projectId:t}=this.options,o=this.createUrl("/api/v1/canvas",{...e,projectId:t});return await this.apiClient(o)}async getCompositionById(e){let{projectId:t}=this.options,o=this.createUrl("/api/v1/canvas",{...e,projectId:t});return await this.apiClient(o)}async updateComposition(e){let t=this.createUrl("/api/v1/canvas");await this.apiClient(t,{method:"PUT",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}async removeComposition(e){let t=this.createUrl("/api/v1/canvas");await this.apiClient(t,{method:"DELETE",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}async getComponentDefinitions(e){let{projectId:t}=this.options,o=this.createUrl("/api/v1/canvas-definitions",{...e,projectId:t});return await this.apiClient(o)}async updateComponentDefinition(e){let t=this.createUrl("/api/v1/canvas-definitions");await this.apiClient(t,{method:"PUT",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}async removeComponentDefinition(e){let t=this.createUrl("/api/v1/canvas-definitions");await this.apiClient(t,{method:"DELETE",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}async apiClient(e,t){return this.options.limitPolicy(async()=>{var i;let o=this.options.apiKey?{"x-api-key":this.options.apiKey}:{Authorization:`Bearer ${this.options.bearerToken}`},s=await fetch(e.toString(),{...t,headers:{...t==null?void 0:t.headers,...o}});if(!s.ok){let n="";try{let r=await s.text();try{let a=JSON.parse(r);a.errorMessage?n=Array.isArray(a.errorMessage)?a.errorMessage.join(", "):a.errorMessage:n=r}catch(a){n=r}}catch(r){n="General error"}throw new c(n,(i=t==null?void 0:t.method)!=null?i:"GET",e.toString(),s.status)}return(t==null?void 0:t.expectNoContent)?null:await s.json()})}createUrl(e,t){let o=new URL(`${this.options.apiHost}${e}`);return Object.entries(t!=null?t:{}).forEach(([s,i])=>{var n;typeof i!==void 0&&i!==null&&o.searchParams.append(s,(n=i==null?void 0:i.toString())!=null?n:"")}),o}};var T="$personalization",L="$test",g="$localization",S="intentTag",N="locale",j="pz",x="test",E="localized",U=0,b=64;export{l as a,I as b,c,h as d,T as e,L as f,g,S as h,N as i,j,x as k,E as l,U as m,b as n};