@picked/client 0.0.70-next.3 → 0.0.70-next.5

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 +1 @@
1
- var e=`Picked-Client`,t=`Picked-Version`;function n(n,r){return{[e]:n,[t]:r}}var r=()=>`0.0.70-next.3`,i=`v1`;function a(e,t){return new URL(`/api/${i}/${t}`,e).toString()}function o(e){return{...n(`sdk`,r()),...e}}async function s(e,t,n,r){let i=a(e,t);return fetch(i,{headers:o(n),signal:r})}async function c(e,t,n,r){let i=a(e,t);return fetch(i,{method:`POST`,headers:{"Content-Type":`application/json`,...o(r)},body:JSON.stringify(n)})}Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return s}});
1
+ var e=`Picked-Client`,t=`Picked-Version`;function n(n,r){return{[e]:n,[t]:r}}var r=()=>`0.0.70-next.5`,i=`v1`;function a(e,t){return new URL(`/api/${i}/${t}`,e).toString()}function o(e){return{...n(`sdk`,r()),...e}}async function s(e,t,n,r){let i=a(e,t);return fetch(i,{headers:o(n),signal:r})}async function c(e,t,n,r){let i=a(e,t);return fetch(i,{method:`POST`,headers:{"Content-Type":`application/json`,...o(r)},body:JSON.stringify(n)})}Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return s}});
@@ -8,7 +8,7 @@ function n(n, r) {
8
8
  }
9
9
  //#endregion
10
10
  //#region src/utils/version.ts
11
- var r = () => "0.0.70-next.3", i = "v1";
11
+ var r = () => "0.0.70-next.5", i = "v1";
12
12
  function a(e, t) {
13
13
  return new URL(`/api/${i}/${t}`, e).toString();
14
14
  }
package/dist/cjs/index.js CHANGED
@@ -1,4 +1,4 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../object-CIkt7Fkr.cjs"),t=require("../rules-logic-CGZIYgAI.cjs"),n=require("../logger-CSTvAyyB.cjs"),r=require("../supports-DBzjGaWD.cjs"),i=require("../dom-CDrHc_j9.cjs"),a=require("../experience-instance-DurC3pE-.cjs"),o=require("../storage-DUw9UJ2h.cjs"),s=require("../api-BQRx-Qnj.cjs"),c=require("../id-Js-62re-.cjs"),l=require("../inert-script-report-ijRHPtcY.cjs");let u=require("effector"),d=require("@withease/factories");var f=(0,u.createDomain)(`experience`),p=(0,d.createFactory)(({client:e,experience:n})=>{let r=f.store(n),o=(0,u.createApi)(r,{merge(e,t){return{...e,...t.experience}}}),s=r.map(e=>({name:e.name,decisionLogic:e.condition,targetSelectors:e.targets,initializeOpenLogic:e.initializeOpen})),c=(0,u.combine)(r,e.components.listStore,(e,t)=>(e.componentName?t.find(t=>t.name===e.componentName):void 0)||t.find(t=>t.name===`experience:${e.id}`)||t.find(e=>e.name===`experience`),{skipVoid:!1}),l=(0,u.combine)(r,e.steps.indexStore,e.conditions.indexStore,(e,t,n)=>{let r=e.nodes.filter(a.u).map(e=>t[e.stepId]).filter(e=>e!==void 0),i=e.nodes.filter(a.l).map(e=>n[e.conditionId]).filter(e=>e!==void 0);return{steps:r,nodes:e.nodes,edges:e.edges,conditions:i}}),d=n.actions??[],p,m=(0,u.attach)({source:s,effect:(t,r)=>{let a=i.i(t.targetSelectors,n.id);a.forEach(({elements:e})=>e.forEach(e=>i.s(e,n.id))),i.t(a,n.id,n.key).forEach(t=>{r?e.experienceInstances.spawn(p,t,r):e.experienceInstances.spawn(p,t)})}}),h=(0,u.attach)({source:(0,u.combine)({preconditionPassed:e.preconditionPassedStore,isUser:e.session.store.map(e=>e.isUser,{skipVoid:!1}),config:s}),effect:async({preconditionPassed:r,isUser:a,config:o})=>{if(!r||!a)return!1;let{decisionLogic:s,targetSelectors:c}=o;return c.length===0||i.i(c,n.id).length<1?!1:s===void 0?!0:t.n(s)?await t.t(e,s)===!0:!0}}),g=(0,u.createEffect)(async()=>{if(!e.contentLoader)return!0;try{await e.contentLoader({id:n.id,key:n.key})}catch{`${n.id}`}return!0}),_=(0,u.createEvent)(),v=(0,u.createEvent)(),y=f.createStore(void 0,{skipVoid:!1}).on(_,(e,t)=>t).on(v,(e,t)=>t);return(0,u.sample)({clock:_,target:h}),(0,u.sample)({clock:h.doneData,source:y,filter:(e,t)=>t,fn:e=>e,target:m}),(0,u.sample)({clock:h.doneData,filter:Boolean,target:g}),(0,u.sample)({clock:v,source:y,fn:e=>e,target:m}),(0,u.sample)({clock:v,target:g}),p={id:n.id,key:n.key,name:n.name,configStore:s,treeStore:l,componentStore:c,actions:d,merge:o.merge,initialiseFx:m,shouldInitialiseFx:h,initialiseRequested:_,initialiseDirectly:v,prepareExperienceContentFx:g},p});function m(e){return(0,d.invoke)(p,e)}var h=(0,d.createFactory)(({client:e})=>{let t=f.store({}),n=(0,u.createApi)(t,{register(e,t){return{...e,[t.id]:t}}}),r=(0,u.createEvent)(),i=(0,u.createEffect)(t=>{n.register(m({client:e,experience:t}))});(0,u.sample)({clock:r,source:t,filter:(e,t)=>e[t.id]!==void 0,fn:(e,t)=>({existing:e[t.id],experience:t})}).watch(({existing:e,experience:t})=>{e?.merge({experience:t,strategy:`override`})}),(0,u.sample)({clock:r,source:t,filter:(e,t)=>e[t.id]===void 0,fn:(e,t)=>t,target:i});let a=t.map(e=>Object.values(e));function o(e){return t.map(t=>t[e],{skipVoid:!1})}function s(e){return t.map(t=>Object.values(t).find(t=>t.key===e)??t[e],{skipVoid:!1})}let c=(0,u.attach)({source:t,effect:(e,t)=>{let n=`key`in t?Object.values(e).find(e=>e.key===t.key):e[t.id];if(!n){`key`in t?`${t.key}`:`${t.id}`;return}let{options:r}=t;r?.bypassCondition?n.initialiseDirectly(r):n.initialiseRequested(r)}});return{register:r,get:o,getById:o,getByKey:s,launch:c,open:(0,u.attach)({source:{experiences:t,instances:e.experienceInstances.listStore},effect:async({experiences:e,instances:t},n)=>{let r=`key`in n?Object.values(e).find(e=>e.key===n.key):e[n.id],i=t.filter(e=>e.experienceId===r?.id);if(i.length>0){for(let e of i)e.open();return}await c(`key`in n?{key:n.key,options:{...n.options,initialiseOpen:!0}}:{id:n.id,options:{...n.options,initialiseOpen:!0}})}}),listStore:a,initialiseExperiencesFx:(0,u.attach)({source:a,effect:e=>{for(let t of e)t.initialiseRequested(void 0)}})}});function g(e){return(0,d.invoke)(h,e)}var _=async e=>{await e.experiences.initialiseExperiencesFx()};function v(e){return(0,u.createEffect)(async()=>{await e()})}var y=(e,t,n)=>{let r=t.name,i=t.setup(e);if(i){let e=n[r]??{};n[r]=Object.freeze({...e,...i})}},b=(0,u.createDomain)(`component`),x=(0,d.createFactory)(({client:e,component:t,name:n})=>({name:n,component:t,frameworkStore:e.frameworks.getByName(t.frameworkName)}));function S(e){return(0,d.invoke)(x,e)}var C=(0,d.createFactory)(({client:e})=>{let t=b.store({}),r=(0,u.createApi)(t,{register(e,t){return{...e,[t.name]:t}}}),i=(0,u.createEvent)();(0,u.sample)({clock:i,source:t,filter:(e,{name:t})=>e[t]!==void 0,fn:(e,{name:t})=>`Component '${t}' already registered. Registering again will override the previous registration.`}).watch(e=>n.t(`warn`,e)),(0,u.sample)({clock:i,fn:({name:t,component:n})=>S({client:e,name:t,component:n}),target:r.register});let a=t.map(e=>Object.values(e));function o(e){return t.map(t=>t[e],{skipVoid:!1})}return{register:i,getByName:o,listStore:a}});function w(e){return(0,d.invoke)(C,e)}var T=(e,t,n)=>{n.register({name:e,component:t})},E=(0,u.createDomain)(`framework`),D=(0,d.createFactory)(e=>{let t=E.store({}),r=(0,u.createApi)(t,{register(e,t){return{...e,[t.name]:t.framework}}}),i=(0,u.createEvent)();(0,u.sample)({clock:i,source:t,filter:(e,{name:t})=>e[t]!==void 0,fn:(e,{name:t})=>`Framework '${t}' already registered. Registering again will override the previous registration.`}).watch(e=>n.t(`warn`,e)),(0,u.sample)({clock:i,target:r.register});let a=t.map(e=>Object.values(e));function o(e){return t.map(t=>t[e],{skipVoid:!1})}return{register:i,getByName:o,listStore:a}});function O(e){return(0,d.invoke)(D,e)}var k=(e,t)=>{t.register({name:e.name,framework:e})},A=(0,d.createFactory)(({client:e})=>{let t=`window`in globalThis,n={location:t?globalThis.location:void 0,document:t?globalThis.document:void 0,sessionStorage:t?globalThis.sessionStorage:void 0,localStorage:t?globalThis.localStorage:void 0};return(0,u.combine)(e.responses.listStore,e.fields.listStore,(t,r)=>Object.freeze({client:e,responses:t,fields:r,...n}))});function ee(e){return(0,d.invoke)(A,e)}function te(e){return typeof e==`number`&&!isNaN(e)}function j(e){return typeof e==`string`}function M(e){return Array.isArray(e)}function N(e){return e instanceof Promise}function P(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.keys(e).length===1}function F(e){if(te(e))return e;let t=parseFloat(`${e}`);return isNaN(t)?0:t}function I(e){return`${e}`}var ne={"==":(e,t)=>e==t,"===":(e,t)=>e===t,"!=":(e,t)=>e!=t,"!==":(e,t)=>e!==t,">":(e,t)=>F(e)>F(t),">=":(e,t)=>F(e)>=F(t),"<":(e,t,n)=>{let r=F(e),i=F(t);if(n===void 0)return r<i;let a=F(n);return r<i&&i<a},"<=":(e,t,n)=>{let r=F(e),i=F(t);if(n===void 0)return r<=i;let a=F(n);return r<=i&&i<=a},"!!":async e=>await R(e),"!":async e=>!await R(e),"%":(e,t)=>F(e)%F(t),log:e=>(console.log(e),e),in:(e,t)=>t?j(t)?t.indexOf(I(e))!==-1:M(t)?t.includes(e):!1:!1,cat:(...e)=>e.map(I).join(``),substr:(e,t,n)=>{let r=I(e),i=F(t);if(n===void 0)return r.substr(i);let a=F(n);if(a<0){let e=r.substr(i);return e.substr(0,e.length+a)}return r.substr(i,a)},"+":(...e)=>e.reduce((e,t)=>F(e)+F(t),0),"*":(...e)=>e.reduce((e,t)=>F(e)*F(t),1),"-":(e,t)=>{let n=F(e);return t===void 0?-n:n-F(t)},"/":(e,t)=>F(e)/F(t),min:(...e)=>Math.min(...e.map(F)),max:(...e)=>Math.max(...e.map(F)),merge:(...e)=>e.reduce((e,t)=>M(t)?e.concat(t):e.concat([t]),[]),var(e,t){let n=arguments.length>1?t:null;if(e===``||e===`.`||e==null)return this;if(typeof e==`number`&&Array.isArray(this))return e>=0&&e<this.length?this[e]:n;let r=I(e);if(r===``||r===`.`)return this;let i=r.split(`.`),a=this;for(let e of i){if(a==null)return n;if(Array.isArray(a)){let t=parseInt(e,10);a=isNaN(t)?a[e]:a[t]}else a=a[e]}return a===void 0?n:a},async missing(...e){let t=M(e[0])?e[0]:e,n=[];for(let e of t){let t=await L({var:e},this);(t===null||t===``)&&n.push(`${e}`)}return n},async missing_some(e,t){let n=await L({missing:t},this);if(!M(n)||!M(t))return[];let r=n.filter(j);return t.filter(j).length-r.length>=F(e)?[]:r},invoke(...e){let[t,...n]=e;return typeof t==`function`?Reflect.apply(t,null,n):null},startsWith:(e,t)=>j(e)&&j(t)&&e.startsWith(t),endsWith:(e,t)=>j(e)&&j(t)&&e.endsWith(t),regexp_matches(e,t){let n=e,r=``;if(M(e)){let[t,i]=e;n=t,r=i}return!j(n)||!j(r)?!1:new RegExp(n,r).test(I(t))},throw(e){throw Error(I(e))}};async function L(e,t){if(!e)return e;if(N(e))return L(await e,t);if(M(e))return Promise.all(e.map(e=>L(e,t)));if(!P(e))return e;let n=re(e),r=n?e[n]??[]:[];switch(M(r)||(r=[r]),n){case`if`:case`?:`:for(let e=0;e<r.length-1;e+=2)if(await R(await L(r[e],t)))return L(r[e+1],t);return r.length%2==1?L(r[r.length-1],t):null;case`and`:{let e=null;for(let n of r)if(e=await L(n,t),!await R(e))return e;return e}case`or`:{let e=null;for(let n of r)if(e=await L(n,t),await R(e))return e;return e}case`map`:{let e=await L(r[0],t);return M(e)?await Promise.all(e.map(e=>L(r[1],e))):[]}case`filter`:{let e=await L(r[0],t);return M(e)?(await Promise.all(e.map(async e=>({item:e,shouldInclude:await R(await L(r[1],e))})))).filter(({shouldInclude:e})=>e).map(({item:e})=>e):[]}case`reduce`:{let e=await L(r[0],t);if(!M(e))return r.length>2?await L(r[2],t):null;let n=r[1],i=r.length>2?await L(r[2],t):null;for(let t of e)i=await L(n,{current:t,accumulator:i});return i}case`all`:{let e=await L(r[0],t);if(!M(e)||e.length===0)return!1;for(let t of e)if(!await R(await L(r[1],t)))return!1;return!0}case`some`:{let e=await L(r[0],t);if(!M(e))return!1;for(let t of e)if(await R(await L(r[1],t)))return!0;return!1}case`none`:{let e=await L(r[0],t);if(!M(e))return!0;for(let t of e)if(await R(await L(r[1],t)))return!1;return!0}case`catch`:try{return await L(r[0],t)}catch(e){return P(e)?await L(e,t):r[1]?await L(r[1],e):e instanceof Error?e.message:e}}let i=await Promise.all(r.map(e=>L(e,t))),a=n?ne[n]:void 0;if(!a)throw Error(`Unrecognized operation ${n}`);return a.apply(t,i)}async function R(e){return N(e)?R(await e):!(Array.isArray(e)&&e.length===0)&&!!e}function re(e){return Object.keys(e)[0]}function z(e,t,n){return new Proxy(Object.create(null),{get(r,i){if(typeof i!=`string`)return;let a=e.find(e=>e.key===i);if(a!==void 0)return async()=>n.has(i)?!1:await L(a.logic,{...t,conditions:z(e,t,new Set(n).add(i))})===!0}})}var ie=(0,d.createFactory)(({client:e})=>(0,u.attach)({source:{stateSnapshot:e.stateSnapshotStore,predicates:e.predicates.listStore,actions:e.actions.listStore,features:e.features.listStore,responses:e.responses.getAllStore,conditions:e.conditions.listStore},effect:async({stateSnapshot:e,predicates:t,actions:n,features:r,responses:i,conditions:a},{rule:o,context:s})=>{let c=t.reduce((t,n)=>(t[n.name]=async(...t)=>await n.predicate({...e,args:t}),t),{}),l=n.reduce((t,n)=>(t[n.key]=async(...t)=>await n.action({...e,args:t},null)??void 0,t),{}),u=r.reduce((e,t)=>(e[t.id]=async()=>{let{bucket:e}=await t.getBucket();return e},e),{}),d={responses:i,location:typeof e.location==`object`?{hash:e.location.hash,host:e.location.host,hostname:e.location.hostname,href:e.location.href,origin:e.location.origin,pathname:e.location.pathname,port:e.location.port,protocol:e.location.protocol,search:e.location.search}:void 0,predicates:c,actions:l,features:u,...s};return await L(o,{...d,conditions:z(a,d,new Set)})}}));function ae(e){return(0,d.invoke)(ie,e)}var oe=6e3,se=o.t(`last_ping`,`global`),ce=async e=>{try{let t=Date.now(),n=o.n.get(se),r=0;if(n.isSet()&&(r=n.json()??0),r&&t-r<oe)return!0;let i={projectId:e.projectId,path:window.location.pathname},a={},c=document.getElementById(`picked_script`)?.dataset.verceltoken;c&&(a[`x-vercel-protection-bypass`]=c);let l=(await s.n(e.apiUrl,`ping`,i,a)).ok;return l&&n.set(t),l}catch{return!1}},B=(0,u.createDomain)(`lifecycle`),le=(0,d.createFactory)(({client:e})=>{let n=B.store(!1),a=(0,u.createStore)(void 0,{skipVoid:!1,domain:B}),o=(0,u.createStore)(void 0,{skipVoid:!1,domain:B}),s=B.store(`idle`),c=B.store([]),l=(0,u.createStore)(void 0,{skipVoid:!1,domain:B}),d=(0,u.createStore)(void 0,{skipVoid:!1,domain:B}),f=(0,u.createEvent)(),p=(0,u.createEvent)(),m=(0,u.createEvent)(),h=(0,u.createEvent)(),g=(0,u.createEvent)(),v=(0,u.createEvent)();c.on(h,(e,t)=>[...e,t]),l.on(g,(e,t)=>t),d.on(v,(e,t)=>t),n.on(p,()=>!0);let y=(0,u.createEffect)(()=>{ce(e)}),b=(0,u.createEffect)(async()=>{await i.r()}),x=(0,u.createEffect)(async()=>{await _(e)}),S=(0,u.attach)({effect:x}),C=(0,u.attach)({source:c,effect:async e=>{for(let t of e)await t()}}),w=(0,u.attach)({source:l,effect:async n=>n===void 0?!0:typeof n==`boolean`?n:await t.t(e,n)===!0}),T=(0,u.attach)({source:d,effect:async n=>n===void 0?!0:typeof n==`boolean`?n:await t.t(e,n)===!0}),E=(0,u.sample)({clock:f,source:s,filter:e=>e===`idle`&&r.i(),fn:()=>void 0});(0,u.sample)({clock:E,fn:()=>`starting`,target:s}),(0,u.sample)({clock:E,target:y}),(0,u.sample)({clock:E,target:C}),(0,u.sample)({clock:E,target:b}),(0,u.sample)({clock:C.done,target:w}),(0,u.sample)({clock:w.doneData,target:a}),(0,u.sample)({clock:T.doneData,target:o}),(0,u.sample)({clock:w.doneData,filter:e=>e,target:T}),(0,u.sample)({clock:T.doneData,target:e.session.setIsUser}),(0,u.sample)({clock:T.doneData,fn:e=>({type:`user_decide`,value:e}),target:e.eventBus}),(0,u.sample)({clock:w.doneData,filter:e=>!e,fn:()=>void 0,target:m}),(0,u.sample)({clock:T.doneData,fn:()=>void 0,target:m}),(0,u.sample)({clock:m,fn:()=>({type:`initialize`}),target:e.eventBus});let D=(0,u.createStore)(!1).on(b.done,()=>!0),O=(0,u.createStore)(!1).on(m,()=>!0),k=(0,u.createStore)(!1).on(S.done,()=>!0),A=(0,u.combine)(a,o,(e,t)=>e===!0&&t===!0);return(0,u.sample)({clock:m,source:A,filter:e=>e,fn:()=>void 0,target:x}),(0,u.sample)({clock:(0,u.combine)(D,O,A,(e,t,n)=>e&&t&&n),filter:e=>e,fn:()=>void 0,target:S}),(0,u.sample)({clock:(0,u.combine)(D,O,A,k,(e,t,n,r)=>e&&t&&(!n||r)),filter:e=>e,fn:()=>void 0,target:p}),(0,u.sample)({clock:p,fn:()=>`ready`,target:s}),(0,u.sample)({clock:p,fn:()=>({type:`ready`}),target:e.eventBus}),(0,u.sample)({clock:p,source:e.session.store,fn:({id:e,isUser:t,identifiers:n})=>({type:`session`,id:e,isUser:t,identifiers:n}),target:e.eventBus}),(0,u.sample)({clock:[C.fail,w.fail,T.fail,x.fail,S.fail,b.fail],fn:()=>`failed`,target:s}),{start:f,readyStore:n,preconditionPassedStore:a,conditionPassedStore:o,lifecycleStageStore:s,registerPluginStartHook:h,setPrecondition:g,setCondition:v}});function ue(e){return(0,d.invoke)(le,e)}var de=(0,u.createDomain)(`predicate`),fe=(0,d.createFactory)(({client:e})=>{let t=de.store({}),r=(0,u.createApi)(t,{register(e,t){return{...e,[t.name]:{name:t.name,predicate:t.predicate}}}}),i=(0,u.createEvent)();(0,u.sample)({clock:i,source:t,filter:(e,{name:t})=>e[t]!==void 0,fn:(e,{name:t})=>`Predicate '${t}' already registered. Registering again will override the previous registration.`}).watch(e=>n.t(`warn`,e)),(0,u.sample)({clock:i,fn:({name:e,predicate:t})=>Object.freeze({name:e,predicate:t}),target:r.register});let a=t.map(e=>Object.values(e));function o(e){return t.map(t=>t[e]?.predicate,{skipVoid:!1})}function s(t){let n=(0,u.createStore)(()=>void 0,{skipVoid:!1}),r=(0,u.attach)({source:{predicate:o(t),snapshot:e.stateSnapshotStore},effect:({predicate:e,snapshot:t})=>{if(e)return(...n)=>e({...t,args:n})}});return(0,u.sample)({source:{responses:e.responses.listStore,fields:e.fields.listStore},target:r}),(0,u.sample)({clock:r.doneData,filter:e=>e!==void 0,target:n}),r(),n}return{register:i,getByName:o,listStore:a,getEvokablePredicate:s}});function pe(e){return(0,d.invoke)(fe,e)}var me=(e,t,n)=>{n.register({name:e,predicate:t})},V=(0,u.createDomain)(`feature`),he=(0,d.createFactory)(({client:e})=>{let t=V.store({}),r=V.store([]),i=(0,u.createApi)(t,{register(e,t){return{...e,[t.id]:t.feature}}}),a=(0,u.createEvent)();(0,u.sample)({clock:a,source:t,filter:(e,{id:t})=>e[t]!==void 0,fn:(e,{id:t})=>`Feature '${t}' already registered. Registering again will override the previous registration.`}).watch(e=>n.t(`warn`,e)),(0,u.sample)({clock:a,fn:({id:e,feature:t})=>Object.freeze({id:e,feature:{id:e,feature:{...t,id:e}}}),target:i.register});let s=(0,u.createEffect)(async({id:e,key:t,storage:n=`local`})=>{let r=o.t(`feature:${e}:${t}`,`global`),i=(n===`session`?o.r:o.n).get(r).boolean();return i===null?null:{id:e,key:t,bucket:i,storage:n}}),c=(0,u.createEffect)(e=>{if(!e)return null;let t=o.t(`feature:${e.id}:${e.key}`,`global`);(e.storage===`session`?o.r:o.n).set(t,e.bucket)}),l=new Map,d=(0,u.attach)({source:{allFeaturesStore:t,resolvedFeaturesStore:r},effect:async({allFeaturesStore:e,resolvedFeaturesStore:t},{id:n,decide:r,key:i})=>{let a=t.find(e=>e.id===n&&e.key===i);if(a)return a;let o=e[n];if(!o)throw Error(`Feature with id '${n}' not found`);let s=l.get(`${n}:${i}`);if(s!==void 0){let e=await s;return{id:o.id,bucket:e,key:i,storage:o.feature.storage}}let c=r();l.set(`${n}:${i}`,c);let u=await c;return{id:o.id,bucket:u,key:i,storage:o.feature.storage}}});(0,u.sample)({clock:i.register,fn:e=>{let{id:t,feature:n}=e;return{id:t,key:n.feature.key,storage:n.feature.storage}},target:s}),(0,u.sample)({source:t,clock:d.doneData,fn:(e,t)=>{let{id:n,bucket:r,storage:i}=t,a=e[n]?.feature.key;return a?{key:a,id:n,bucket:r,storage:i}:null},target:c});let f=(0,u.combine)({allFeaturesStore:t,resolvedFeaturesStore:r}).map(({allFeaturesStore:e,resolvedFeaturesStore:t})=>Object.values(e).map(e=>{let n=t.find(t=>t.id===e.id&&t.key===e.feature.key);return n?{id:e.id,name:e.feature.name,key:e.feature.key,enabled:e.feature.enabled,weight:e.feature.weight,getBucket:()=>({id:e.id,bucket:n.bucket}),isResolved:!0}:{id:e.id,name:e.feature.name,key:e.feature.key,enabled:e.feature.enabled,weight:e.feature.weight,getBucket:async()=>await d(e.feature),isResolved:!1}}));(0,u.sample)({clock:d.doneData,source:{resolvedFeatures:r},filter:({resolvedFeatures:e},{id:t,key:n})=>!e.some(e=>e.id===t&&e.key===n),fn:(e,t)=>t,target:e.eventBus.prepend(e=>({type:`feature_decide`,feature:e}))}),(0,u.sample)({clock:[s.doneData,d.doneData],source:r,fn:(e,t)=>!t||e.some(e=>e.id===t.id&&e.key===t.key)?e:[...e,t],target:r});function p(e){return f.map(t=>t.find(t=>t.id===e))}function m(e){return t.map(t=>t[e],{skipVoid:!1})}function h(e){let t=(0,u.createStore)(async()=>void 0,{skipVoid:!1}),n=(0,u.attach)({source:p(e),effect:async e=>{if(e)return async()=>(await e.getBucket()).bucket}});return(0,u.sample)({source:r,filter:t=>t.some(t=>t.id===e),target:n}),(0,u.sample)({clock:n.doneData,filter:e=>e!==void 0,target:t}),n(),t}return{register:a,getById:p,getByName:m,listStore:f,getEvokableFeature:h}});function ge(e){return(0,d.invoke)(he,e)}var _e=(e,t,n)=>{n.register({id:e,feature:t})},H=(0,u.createDomain)(`history`);function U(e,t){return{id:c.t(`history-entry-${Date.now()}-${Math.random()}}`),node:t,at:Date.now(),experienceId:e}}var ve=(0,d.createFactory)(()=>{let e=H.store({entries:[]}),t=H.event(),n=H.event(),r=H.event(),i=H.event();e.on(t,(e,t)=>({entries:[...e.entries,U(t.experienceId,t.node)]})),e.on(n,(e,t)=>({entries:[...e.entries.slice(0,-1),U(t.experienceId,t.node)]})),e.on(i,(e,t)=>t);function o(e,t){let n={lastStepIndex:-1,secondLastStepIndex:-1};for(let r=e.length-1;r>=0;r--){let i=e[r],o=i?.node;if(!(!o||!a.u(o))&&!(t&&i.experienceId!==t))if(n.lastStepIndex===-1)n.lastStepIndex=r;else{n.secondLastStepIndex=r;break}}return n}return e.on(r,(e,t)=>{let{secondLastStepIndex:n}=o(e.entries,t.experienceId),r=n===-1?e.entries:e.entries.slice(0,n+1);return{...e,entries:r}}),{push:t,replace:n,back:r,restore:i,entriesStore:e.map(e=>e.entries)}});function ye(){return(0,d.invoke)(ve)}var be=0,xe=e=>{let t=(0,u.createStore)([]);return t.on(e,(e,t)=>[...e,{id:be++,at:new Date,payload:t}]),t},Se=(0,u.createDomain)(`field`),Ce=(0,d.createFactory)(()=>{let e=Se.store({}),t=(0,u.createApi)(e,{register(e,t){return{...e,[t.field.id]:t.field}},updateByKey(e,t){let n=Object.values(e).find(e=>e.key===t.fieldKey);return n?{...e,[n.id]:Object.assign({},n,t.updates)}:e}});function n(e){t.register({field:e})}let r={};e.watch(e=>{r=e});function i(e,n){let i=Object.values(r).find(t=>t.key===e)?.key;i&&t.updateByKey({fieldKey:i,updates:n})}let a=e.map(e=>Object.values(e));function o(t){return e.map(e=>e[t]??null,{skipVoid:!1})}function s(t){return e.map(e=>Object.values(e).find(e=>e.key===t)??null,{skipVoid:!1})}function c(t){return e.map(e=>Object.values(e).find(e=>e.name===t)??null,{skipVoid:!1})}return{register:n,update:i,getById:o,getByKey:s,listStore:a,getByName:c}});function we(){return(0,d.invoke)(Ce)}var Te=(0,u.createDomain)(`step`),Ee=(0,d.createFactory)(()=>{let e=Te.store({}),t=(0,u.createApi)(e,{register(e,t){return{...e,[t.step.id]:t.step}}});function n(e){t.register({step:e})}let r=e.map(e=>Object.values(e));function i(t){return e.map(e=>e[t]??null,{skipVoid:!1})}function a(t){return e.map(e=>Object.values(e).find(e=>e.key===t)??null,{skipVoid:!1})}return{register:n,getById:i,getByKey:a,listStore:r,indexStore:e}});function De(){return(0,d.invoke)(Ee)}function Oe(e,t){t.register(e)}var ke=(0,u.createDomain)(`content`),Ae=(0,d.createFactory)(()=>{let e=ke.store({}),t=(0,u.createApi)(e,{register(e,t){return{...e,[t.content.id]:t.content}},patch(e,t){let n=e[t.id];if(!n)return e;let r=t.apply(n.data);return r===n.data?e:{...e,[t.id]:{...n,data:r}}}});function n(e){t.register({content:e})}function r(e,n){t.patch({id:e,apply:n})}let i=e.map(e=>Object.values(e));function a(t){return e.map(e=>e[t]??null,{skipVoid:!1})}return{register:n,patch:r,getById:a,listStore:i,indexStore:e}});function je(){return(0,d.invoke)(Ae)}function Me(e,t){t.register(e)}var Ne=(0,u.createDomain)(`action`),Pe=(0,d.createFactory)(({client:e})=>{let t=Ne.store({}),r=(0,u.createApi)(t,{register(e,t){return{...e,[t.key]:{key:t.key,action:t.action}}}}),i=(0,u.createEvent)();(0,u.sample)({clock:i,source:t,filter:(e,{key:t})=>e[t]!==void 0,fn:(e,{key:t})=>`Action '${t}' already registered. Registering again will override the previous registration.`}).watch(e=>n.t(`warn`,e)),(0,u.sample)({clock:i,fn:({key:e,action:t})=>Object.freeze({key:e,action:t}),target:r.register});let a=t.map(e=>Object.values(e));function o(e){return t.map(t=>t[e]?.action,{skipVoid:!1})}function s(t,n){let r=(0,u.createStore)(()=>void 0,{skipVoid:!1}),i=n?{experience:n.experience}:null,a=(0,u.attach)({source:{action:o(t),snapshot:e.stateSnapshotStore},effect:({action:e,snapshot:t})=>{if(e)return(...n)=>e({...t,args:n},i)}});return(0,u.sample)({source:{responses:e.responses.listStore,fields:e.fields.listStore},target:a}),(0,u.sample)({clock:a.doneData,filter:e=>e!==void 0,target:r}),a(),r}return{register:i,getByKey:o,listStore:a,getEvokableAction:s}});function Fe(e){return(0,d.invoke)(Pe,e)}var Ie=(e,t,n)=>{n.register({key:e,action:t})};function W(e,t,n,r){return{fieldKey:e.key,userMessage:n,systemMessage:r,value:t}}function G(e){return e===null||e===``||Array.isArray(e)&&!e.length}function Le(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||e===null}function K(e){try{return JSON.stringify(e),!0}catch{return!1}}function Re(e,t){return t.find(t=>t.key===e)??null}function ze(e,t){return e.multiple&&(typeof t==`string`||typeof t==`number`||typeof t==`boolean`)?[t]:t}function Be(e,t){if(e.type!==`object`||G(t))return null;if(e.multiple){if(!Array.isArray(t))return W(e,t,`This field expects multiple values`,`Field expects an array of objects.`);for(let n of t){if(typeof n!=`object`||!n)return W(e,t,`This field expects object values`,`Field expects an array of objects, but received non-object value.`);if(!K(n))return W(e,t,`This field contains non-serializable data`,`Field value contains non-JSON-serializable data (functions, circular references, etc.).`)}return null}return Array.isArray(t)?W(e,t,`This field expects a single value`,`Field expects a single object, not an array.`):typeof t!=`object`||!t?W(e,t,`This field expects an object value`,`Field expects an object value.`):K(t)?null:W(e,t,`This field contains non-serializable data`,`Field value contains non-JSON-serializable data (functions, circular references, etc.).`)}function Ve(e,t){if(G(t)||!Array.isArray(e.options)||e.options.length===0)return null;let n=Array.isArray(t)?t:[t];if(e.type===`object`){let r=new Set(e.options.map(e=>JSON.stringify(e.value)));return n.every(e=>r.has(JSON.stringify(e)))?null:W(e,t,`This field expects a valid option`,`Field expects a valid option from the defined choices.`)}let r=e.options.map(e=>e.value);return n.every(e=>!Le(e)||e===null?!1:r.includes(e))?null:W(e,t,`This field expects a valid option`,`Field expects a valid option. Valid options are: ${r.join(`, `)}`)}async function He(t,n,r,i){if(n.validation&&!e.t(n.validation)&&!G(r)){let e=i?{$input:r,responses:i}:{$input:r},a=await t(n.validation,e);if(typeof a==`string`)return W(n,r,a,`Field validation resulted in an error: ${a}.`);if(a===!1)return W(n,r,`This field is invalid`,`Field validation resulted in an unspecified error.`)}return n.required&&G(r)?W(n,r,`This field is required`,`Field is required.`):!n.multiple&&Array.isArray(r)&&r.length>1?W(n,r,`This field expects a single response`,`Field expects a single response.`):null}var Ue=(0,u.createDomain)(`response`),We=(0,d.createFactory)(({client:e})=>{let n=Ue.store({}),r=(0,u.createEvent)(),i=(0,u.createEvent)(),a=(0,u.createApi)(n,{register(e,t){return{...e,[t.fieldKey]:t.response}},registerBatch(e,t){return{...e,...t}},clear(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))},clearAll(){return{}}});function o(e,t){if(typeof e==`string`){if(t===void 0)throw Error(`Response is required when registering a single field`);a.register({fieldKey:e,response:t})}else a.registerBatch(e)}let s=(n,r)=>t.t(e,n,r),c=(0,u.attach)({source:{allFields:e.fields.listStore,existingResponses:n},effect:async({allFields:e,existingResponses:t},n)=>{let r=[],i={},a={...t,...n},o=Object.entries(n),c=await Promise.allSettled(o.map(async([t,n])=>{let o=Re(t,e);if(!o){r.push({fieldKey:t,userMessage:`Field '${t}' not found`,systemMessage:`No field with key '${t}' exists. Available field keys are: ${e.map(e=>e.key).join(`,`)}.`,value:n});return}let c=ze(o,n),l=await He(s,o,c,a);if(l){r.push(l);return}let u=Be(o,c);if(u){r.push(u);return}let d=Ve(o,c);if(d){r.push(d);return}i[o.key]=n}));for(let[e,t]of c.entries()){if(t.status!==`rejected`)continue;let n=o[e];if(!n)continue;let[i,a]=n,s=t.reason instanceof Error?t.reason.message:String(t.reason);r.push({fieldKey:i,userMessage:`An unexpected error occurred validating this field`,systemMessage:`Validation threw for field '${i}': ${s}`,value:a})}return{responsesToCommit:i,validationErrors:r}}});async function l(e){return c(e)}let d=(0,u.attach)({source:n,effect:async(e,t)=>{let{responsesToCommit:n,validationErrors:r}=await c(t);return r.length?{errors:r}:(a.registerBatch(n),{errors:[]})}});async function f(e){return d(e)}let p=n.map(e=>e),m=n.map(e=>Object.entries(e).map(([e,t])=>({fieldKey:e,value:t})));function h(e){return(0,u.combine)({f:e,s:n},({f:e,s:t})=>{let n=e?t[e.key]??null:null;return n===null?e?.defaultValue!==void 0&&e.defaultValue!==null?e.defaultValue:null:n})}function g(t){return h(e.fields.getById(t))}function _(t){return h(e.fields.getByKey(t))}function v(t){return h(e.fields.getByName(t))}return(0,u.sample)({clock:r,target:a.clearAll}),(0,u.sample)({clock:i,target:a.clear}),{register:o,clearAll:r,clear:i,commit:f,getResponsesToCommit:l,listStore:m,getAllStore:p,getByFieldId:g,getByFieldKey:_,getByFieldName:v}});function Ge(e){return(0,d.invoke)(We,e)}var Ke=(0,u.createDomain)(`condition`),qe=(0,d.createFactory)(()=>{let e=Ke.store({}),t=(0,u.createApi)(e,{register(e,t){return{...e,[t.condition.id]:t.condition}}});function n(e){t.register({condition:e})}let r=e.map(e=>Object.values(e));function i(t){return e.map(e=>e[t]??null,{skipVoid:!1})}function a(t){return e.map(e=>Object.values(e).find(e=>e.key===t)??null,{skipVoid:!1})}return{register:n,getById:i,getByKey:a,listStore:r,indexStore:e}});function Je(){return(0,d.invoke)(qe)}function Ye(){if(r.i()){let e=[document.currentScript,document.getElementById(`picked_script`),document.getElementById(`picked`),document.getElementById(`cvly`),document.getElementById(`cvly-x`)];for(let t of e)if(t?.dataset.api)return t.dataset.api}return`https://api.picked.app`}function q(){if(!r.f())return{};let e=new URLSearchParams(window.location.search),t={},n=new Set;for(let[t]of e.entries())t.startsWith(`picked-`)&&n.add(t);for(let r of n){let n=r.replace(`picked-`,``);t[n]=e.getAll(r)}let i=o.t(`s`);if(n.size>0)o.r.set(i,t);else{let e=o.r.get(i);if(e)return e.json()||{}}return t}var J=o.t(`session`,`global`);function Xe(){return r.r()?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).substring(2,15)}-${Math.random().toString(36).substring(2,15)}-${Math.random().toString(36).substring(2,15)}`}function Ze(){if(!r.s())return null;let e=o.n.get(J);if(!e.isSet())return null;try{return e.json()}catch{return null}}var Qe=(0,d.createFactory)(()=>{let e=Ze(),t={id:e?.id??Xe()};e?.isUser!==void 0&&(t.isUser=e.isUser),e?.identifiers&&Object.keys(e.identifiers).length>0&&(t.identifiers=e.identifiers);let n=(0,u.createStore)(t),i=(0,u.createApi)(n,{setIsUser:(e,t)=>({...e,isUser:t}),setIdentifier:(e,{key:t,value:n})=>({...e,identifiers:{...e.identifiers??{},[t]:n}}),removeIdentifier:(e,t)=>{let n=e.identifiers;if(!n||!(t in n))return e;let r={};for(let[e,i]of Object.entries(n))e!==t&&(r[e]=i);let i={id:e.id};return e.isUser!==void 0&&(i.isUser=e.isUser),Object.keys(r).length>0&&(i.identifiers=r),i}});return(0,u.sample)({source:n,target:(0,u.attach)({source:n,effect:e=>{if(r.s())try{o.n.get(J).set(e)}catch{}}})}),{store:n,setIsUser:i.setIsUser,setIdentifier:i.setIdentifier,removeIdentifier:i.removeIdentifier}});function $e(){return(0,d.invoke)(Qe,void 0)}function Y(){if(r.f())return globalThis.window.pickedConfig}function et(){if(r.f())return Y()?.projectId}function tt(){if(!r.i())return;let e=document.getElementById(`picked_script`)||document.querySelector(`script#picked`)||document.getElementById(`cvly`);if(e)return e.dataset.projectid||e.getAttribute(`project-id`)||void 0}function nt(e){if(e.projectId)return e.projectId;let t=et();if(t)return t;let n=tt();if(n)return n;throw Error(`projectId is required. You can provide it via one of:
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../object-CIkt7Fkr.cjs"),t=require("../rules-logic-CGZIYgAI.cjs"),n=require("../logger-CSTvAyyB.cjs"),r=require("../supports-DBzjGaWD.cjs"),i=require("../dom-CDrHc_j9.cjs"),a=require("../experience-instance-DurC3pE-.cjs"),o=require("../storage-DUw9UJ2h.cjs"),s=require("../api-B9koex39.cjs"),c=require("../id-Js-62re-.cjs"),l=require("../inert-script-report-ijRHPtcY.cjs");let u=require("effector"),d=require("@withease/factories");var f=(0,u.createDomain)(`experience`),p=(0,d.createFactory)(({client:e,experience:n})=>{let r=f.store(n),o=(0,u.createApi)(r,{merge(e,t){return{...e,...t.experience}}}),s=r.map(e=>({name:e.name,decisionLogic:e.condition,targetSelectors:e.targets,initializeOpenLogic:e.initializeOpen})),c=(0,u.combine)(r,e.components.listStore,(e,t)=>(e.componentName?t.find(t=>t.name===e.componentName):void 0)||t.find(t=>t.name===`experience:${e.id}`)||t.find(e=>e.name===`experience`),{skipVoid:!1}),l=(0,u.combine)(r,e.steps.indexStore,e.conditions.indexStore,(e,t,n)=>{let r=e.nodes.filter(a.u).map(e=>t[e.stepId]).filter(e=>e!==void 0),i=e.nodes.filter(a.l).map(e=>n[e.conditionId]).filter(e=>e!==void 0);return{steps:r,nodes:e.nodes,edges:e.edges,conditions:i}}),d=n.actions??[],p,m=(0,u.attach)({source:s,effect:(t,r)=>{let a=i.i(t.targetSelectors,n.id);a.forEach(({elements:e})=>e.forEach(e=>i.s(e,n.id))),i.t(a,n.id,n.key).forEach(t=>{r?e.experienceInstances.spawn(p,t,r):e.experienceInstances.spawn(p,t)})}}),h=(0,u.attach)({source:(0,u.combine)({preconditionPassed:e.preconditionPassedStore,isUser:e.session.store.map(e=>e.isUser,{skipVoid:!1}),config:s}),effect:async({preconditionPassed:r,isUser:a,config:o})=>{if(!r||!a)return!1;let{decisionLogic:s,targetSelectors:c}=o;return c.length===0||i.i(c,n.id).length<1?!1:s===void 0?!0:t.n(s)?await t.t(e,s)===!0:!0}}),g=(0,u.createEffect)(async()=>{if(!e.contentLoader)return!0;try{await e.contentLoader({id:n.id,key:n.key})}catch{`${n.id}`}return!0}),_=(0,u.createEvent)(),v=(0,u.createEvent)(),y=f.createStore(void 0,{skipVoid:!1}).on(_,(e,t)=>t).on(v,(e,t)=>t);return(0,u.sample)({clock:_,target:h}),(0,u.sample)({clock:h.doneData,source:y,filter:(e,t)=>t,fn:e=>e,target:m}),(0,u.sample)({clock:h.doneData,filter:Boolean,target:g}),(0,u.sample)({clock:v,source:y,fn:e=>e,target:m}),(0,u.sample)({clock:v,target:g}),p={id:n.id,key:n.key,name:n.name,configStore:s,treeStore:l,componentStore:c,actions:d,merge:o.merge,initialiseFx:m,shouldInitialiseFx:h,initialiseRequested:_,initialiseDirectly:v,prepareExperienceContentFx:g},p});function m(e){return(0,d.invoke)(p,e)}var h=(0,d.createFactory)(({client:e})=>{let t=f.store({}),n=(0,u.createApi)(t,{register(e,t){return{...e,[t.id]:t}}}),r=(0,u.createEvent)(),i=(0,u.createEffect)(t=>{n.register(m({client:e,experience:t}))});(0,u.sample)({clock:r,source:t,filter:(e,t)=>e[t.id]!==void 0,fn:(e,t)=>({existing:e[t.id],experience:t})}).watch(({existing:e,experience:t})=>{e?.merge({experience:t,strategy:`override`})}),(0,u.sample)({clock:r,source:t,filter:(e,t)=>e[t.id]===void 0,fn:(e,t)=>t,target:i});let a=t.map(e=>Object.values(e));function o(e){return t.map(t=>t[e],{skipVoid:!1})}function s(e){return t.map(t=>Object.values(t).find(t=>t.key===e)??t[e],{skipVoid:!1})}let c=(0,u.attach)({source:t,effect:(e,t)=>{let n=`key`in t?Object.values(e).find(e=>e.key===t.key):e[t.id];if(!n){`key`in t?`${t.key}`:`${t.id}`;return}let{options:r}=t;r?.bypassCondition?n.initialiseDirectly(r):n.initialiseRequested(r)}});return{register:r,get:o,getById:o,getByKey:s,launch:c,open:(0,u.attach)({source:{experiences:t,instances:e.experienceInstances.listStore},effect:async({experiences:e,instances:t},n)=>{let r=`key`in n?Object.values(e).find(e=>e.key===n.key):e[n.id],i=t.filter(e=>e.experienceId===r?.id);if(i.length>0){for(let e of i)e.open();return}await c(`key`in n?{key:n.key,options:{...n.options,initialiseOpen:!0}}:{id:n.id,options:{...n.options,initialiseOpen:!0}})}}),listStore:a,initialiseExperiencesFx:(0,u.attach)({source:a,effect:e=>{for(let t of e)t.initialiseRequested(void 0)}})}});function g(e){return(0,d.invoke)(h,e)}var _=async e=>{await e.experiences.initialiseExperiencesFx()};function v(e){return(0,u.createEffect)(async()=>{await e()})}var y=(e,t,n)=>{let r=t.name,i=t.setup(e);if(i){let e=n[r]??{};n[r]=Object.freeze({...e,...i})}},b=(0,u.createDomain)(`component`),x=(0,d.createFactory)(({client:e,component:t,name:n})=>({name:n,component:t,frameworkStore:e.frameworks.getByName(t.frameworkName)}));function S(e){return(0,d.invoke)(x,e)}var C=(0,d.createFactory)(({client:e})=>{let t=b.store({}),r=(0,u.createApi)(t,{register(e,t){return{...e,[t.name]:t}}}),i=(0,u.createEvent)();(0,u.sample)({clock:i,source:t,filter:(e,{name:t})=>e[t]!==void 0,fn:(e,{name:t})=>`Component '${t}' already registered. Registering again will override the previous registration.`}).watch(e=>n.t(`warn`,e)),(0,u.sample)({clock:i,fn:({name:t,component:n})=>S({client:e,name:t,component:n}),target:r.register});let a=t.map(e=>Object.values(e));function o(e){return t.map(t=>t[e],{skipVoid:!1})}return{register:i,getByName:o,listStore:a}});function w(e){return(0,d.invoke)(C,e)}var T=(e,t,n)=>{n.register({name:e,component:t})},E=(0,u.createDomain)(`framework`),D=(0,d.createFactory)(e=>{let t=E.store({}),r=(0,u.createApi)(t,{register(e,t){return{...e,[t.name]:t.framework}}}),i=(0,u.createEvent)();(0,u.sample)({clock:i,source:t,filter:(e,{name:t})=>e[t]!==void 0,fn:(e,{name:t})=>`Framework '${t}' already registered. Registering again will override the previous registration.`}).watch(e=>n.t(`warn`,e)),(0,u.sample)({clock:i,target:r.register});let a=t.map(e=>Object.values(e));function o(e){return t.map(t=>t[e],{skipVoid:!1})}return{register:i,getByName:o,listStore:a}});function O(e){return(0,d.invoke)(D,e)}var k=(e,t)=>{t.register({name:e.name,framework:e})},A=(0,d.createFactory)(({client:e})=>{let t=`window`in globalThis,n={location:t?globalThis.location:void 0,document:t?globalThis.document:void 0,sessionStorage:t?globalThis.sessionStorage:void 0,localStorage:t?globalThis.localStorage:void 0};return(0,u.combine)(e.responses.listStore,e.fields.listStore,(t,r)=>Object.freeze({client:e,responses:t,fields:r,...n}))});function ee(e){return(0,d.invoke)(A,e)}function te(e){return typeof e==`number`&&!isNaN(e)}function j(e){return typeof e==`string`}function M(e){return Array.isArray(e)}function N(e){return e instanceof Promise}function P(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.keys(e).length===1}function F(e){if(te(e))return e;let t=parseFloat(`${e}`);return isNaN(t)?0:t}function I(e){return`${e}`}var ne={"==":(e,t)=>e==t,"===":(e,t)=>e===t,"!=":(e,t)=>e!=t,"!==":(e,t)=>e!==t,">":(e,t)=>F(e)>F(t),">=":(e,t)=>F(e)>=F(t),"<":(e,t,n)=>{let r=F(e),i=F(t);if(n===void 0)return r<i;let a=F(n);return r<i&&i<a},"<=":(e,t,n)=>{let r=F(e),i=F(t);if(n===void 0)return r<=i;let a=F(n);return r<=i&&i<=a},"!!":async e=>await R(e),"!":async e=>!await R(e),"%":(e,t)=>F(e)%F(t),log:e=>(console.log(e),e),in:(e,t)=>t?j(t)?t.indexOf(I(e))!==-1:M(t)?t.includes(e):!1:!1,cat:(...e)=>e.map(I).join(``),substr:(e,t,n)=>{let r=I(e),i=F(t);if(n===void 0)return r.substr(i);let a=F(n);if(a<0){let e=r.substr(i);return e.substr(0,e.length+a)}return r.substr(i,a)},"+":(...e)=>e.reduce((e,t)=>F(e)+F(t),0),"*":(...e)=>e.reduce((e,t)=>F(e)*F(t),1),"-":(e,t)=>{let n=F(e);return t===void 0?-n:n-F(t)},"/":(e,t)=>F(e)/F(t),min:(...e)=>Math.min(...e.map(F)),max:(...e)=>Math.max(...e.map(F)),merge:(...e)=>e.reduce((e,t)=>M(t)?e.concat(t):e.concat([t]),[]),var(e,t){let n=arguments.length>1?t:null;if(e===``||e===`.`||e==null)return this;if(typeof e==`number`&&Array.isArray(this))return e>=0&&e<this.length?this[e]:n;let r=I(e);if(r===``||r===`.`)return this;let i=r.split(`.`),a=this;for(let e of i){if(a==null)return n;if(Array.isArray(a)){let t=parseInt(e,10);a=isNaN(t)?a[e]:a[t]}else a=a[e]}return a===void 0?n:a},async missing(...e){let t=M(e[0])?e[0]:e,n=[];for(let e of t){let t=await L({var:e},this);(t===null||t===``)&&n.push(`${e}`)}return n},async missing_some(e,t){let n=await L({missing:t},this);if(!M(n)||!M(t))return[];let r=n.filter(j);return t.filter(j).length-r.length>=F(e)?[]:r},invoke(...e){let[t,...n]=e;return typeof t==`function`?Reflect.apply(t,null,n):null},startsWith:(e,t)=>j(e)&&j(t)&&e.startsWith(t),endsWith:(e,t)=>j(e)&&j(t)&&e.endsWith(t),regexp_matches(e,t){let n=e,r=``;if(M(e)){let[t,i]=e;n=t,r=i}return!j(n)||!j(r)?!1:new RegExp(n,r).test(I(t))},throw(e){throw Error(I(e))}};async function L(e,t){if(!e)return e;if(N(e))return L(await e,t);if(M(e))return Promise.all(e.map(e=>L(e,t)));if(!P(e))return e;let n=re(e),r=n?e[n]??[]:[];switch(M(r)||(r=[r]),n){case`if`:case`?:`:for(let e=0;e<r.length-1;e+=2)if(await R(await L(r[e],t)))return L(r[e+1],t);return r.length%2==1?L(r[r.length-1],t):null;case`and`:{let e=null;for(let n of r)if(e=await L(n,t),!await R(e))return e;return e}case`or`:{let e=null;for(let n of r)if(e=await L(n,t),await R(e))return e;return e}case`map`:{let e=await L(r[0],t);return M(e)?await Promise.all(e.map(e=>L(r[1],e))):[]}case`filter`:{let e=await L(r[0],t);return M(e)?(await Promise.all(e.map(async e=>({item:e,shouldInclude:await R(await L(r[1],e))})))).filter(({shouldInclude:e})=>e).map(({item:e})=>e):[]}case`reduce`:{let e=await L(r[0],t);if(!M(e))return r.length>2?await L(r[2],t):null;let n=r[1],i=r.length>2?await L(r[2],t):null;for(let t of e)i=await L(n,{current:t,accumulator:i});return i}case`all`:{let e=await L(r[0],t);if(!M(e)||e.length===0)return!1;for(let t of e)if(!await R(await L(r[1],t)))return!1;return!0}case`some`:{let e=await L(r[0],t);if(!M(e))return!1;for(let t of e)if(await R(await L(r[1],t)))return!0;return!1}case`none`:{let e=await L(r[0],t);if(!M(e))return!0;for(let t of e)if(await R(await L(r[1],t)))return!1;return!0}case`catch`:try{return await L(r[0],t)}catch(e){return P(e)?await L(e,t):r[1]?await L(r[1],e):e instanceof Error?e.message:e}}let i=await Promise.all(r.map(e=>L(e,t))),a=n?ne[n]:void 0;if(!a)throw Error(`Unrecognized operation ${n}`);return a.apply(t,i)}async function R(e){return N(e)?R(await e):!(Array.isArray(e)&&e.length===0)&&!!e}function re(e){return Object.keys(e)[0]}function z(e,t,n){return new Proxy(Object.create(null),{get(r,i){if(typeof i!=`string`)return;let a=e.find(e=>e.key===i);if(a!==void 0)return async()=>n.has(i)?!1:await L(a.logic,{...t,conditions:z(e,t,new Set(n).add(i))})===!0}})}var ie=(0,d.createFactory)(({client:e})=>(0,u.attach)({source:{stateSnapshot:e.stateSnapshotStore,predicates:e.predicates.listStore,actions:e.actions.listStore,features:e.features.listStore,responses:e.responses.getAllStore,conditions:e.conditions.listStore},effect:async({stateSnapshot:e,predicates:t,actions:n,features:r,responses:i,conditions:a},{rule:o,context:s})=>{let c=t.reduce((t,n)=>(t[n.name]=async(...t)=>await n.predicate({...e,args:t}),t),{}),l=n.reduce((t,n)=>(t[n.key]=async(...t)=>await n.action({...e,args:t},null)??void 0,t),{}),u=r.reduce((e,t)=>(e[t.id]=async()=>{let{bucket:e}=await t.getBucket();return e},e),{}),d={responses:i,location:typeof e.location==`object`?{hash:e.location.hash,host:e.location.host,hostname:e.location.hostname,href:e.location.href,origin:e.location.origin,pathname:e.location.pathname,port:e.location.port,protocol:e.location.protocol,search:e.location.search}:void 0,predicates:c,actions:l,features:u,...s};return await L(o,{...d,conditions:z(a,d,new Set)})}}));function ae(e){return(0,d.invoke)(ie,e)}var oe=6e3,se=o.t(`last_ping`,`global`),ce=async e=>{try{let t=Date.now(),n=o.n.get(se),r=0;if(n.isSet()&&(r=n.json()??0),r&&t-r<oe)return!0;let i={projectId:e.projectId,path:window.location.pathname},a={},c=document.getElementById(`picked_script`)?.dataset.verceltoken;c&&(a[`x-vercel-protection-bypass`]=c);let l=(await s.n(e.apiUrl,`ping`,i,a)).ok;return l&&n.set(t),l}catch{return!1}},B=(0,u.createDomain)(`lifecycle`),le=(0,d.createFactory)(({client:e})=>{let n=B.store(!1),a=(0,u.createStore)(void 0,{skipVoid:!1,domain:B}),o=(0,u.createStore)(void 0,{skipVoid:!1,domain:B}),s=B.store(`idle`),c=B.store([]),l=(0,u.createStore)(void 0,{skipVoid:!1,domain:B}),d=(0,u.createStore)(void 0,{skipVoid:!1,domain:B}),f=(0,u.createEvent)(),p=(0,u.createEvent)(),m=(0,u.createEvent)(),h=(0,u.createEvent)(),g=(0,u.createEvent)(),v=(0,u.createEvent)();c.on(h,(e,t)=>[...e,t]),l.on(g,(e,t)=>t),d.on(v,(e,t)=>t),n.on(p,()=>!0);let y=(0,u.createEffect)(()=>{ce(e)}),b=(0,u.createEffect)(async()=>{await i.r()}),x=(0,u.createEffect)(async()=>{await _(e)}),S=(0,u.attach)({effect:x}),C=(0,u.attach)({source:c,effect:async e=>{for(let t of e)await t()}}),w=(0,u.attach)({source:l,effect:async n=>n===void 0?!0:typeof n==`boolean`?n:await t.t(e,n)===!0}),T=(0,u.attach)({source:d,effect:async n=>n===void 0?!0:typeof n==`boolean`?n:await t.t(e,n)===!0}),E=(0,u.sample)({clock:f,source:s,filter:e=>e===`idle`&&r.i(),fn:()=>void 0});(0,u.sample)({clock:E,fn:()=>`starting`,target:s}),(0,u.sample)({clock:E,target:y}),(0,u.sample)({clock:E,target:C}),(0,u.sample)({clock:E,target:b}),(0,u.sample)({clock:C.done,target:w}),(0,u.sample)({clock:w.doneData,target:a}),(0,u.sample)({clock:T.doneData,target:o}),(0,u.sample)({clock:w.doneData,filter:e=>e,target:T}),(0,u.sample)({clock:T.doneData,target:e.session.setIsUser}),(0,u.sample)({clock:T.doneData,fn:e=>({type:`user_decide`,value:e}),target:e.eventBus}),(0,u.sample)({clock:w.doneData,filter:e=>!e,fn:()=>void 0,target:m}),(0,u.sample)({clock:T.doneData,fn:()=>void 0,target:m}),(0,u.sample)({clock:m,fn:()=>({type:`initialize`}),target:e.eventBus});let D=(0,u.createStore)(!1).on(b.done,()=>!0),O=(0,u.createStore)(!1).on(m,()=>!0),k=(0,u.createStore)(!1).on(S.done,()=>!0),A=(0,u.combine)(a,o,(e,t)=>e===!0&&t===!0);return(0,u.sample)({clock:m,source:A,filter:e=>e,fn:()=>void 0,target:x}),(0,u.sample)({clock:(0,u.combine)(D,O,A,(e,t,n)=>e&&t&&n),filter:e=>e,fn:()=>void 0,target:S}),(0,u.sample)({clock:(0,u.combine)(D,O,A,k,(e,t,n,r)=>e&&t&&(!n||r)),filter:e=>e,fn:()=>void 0,target:p}),(0,u.sample)({clock:p,fn:()=>`ready`,target:s}),(0,u.sample)({clock:p,fn:()=>({type:`ready`}),target:e.eventBus}),(0,u.sample)({clock:p,source:e.session.store,fn:({id:e,isUser:t,identifiers:n})=>({type:`session`,id:e,isUser:t,identifiers:n}),target:e.eventBus}),(0,u.sample)({clock:[C.fail,w.fail,T.fail,x.fail,S.fail,b.fail],fn:()=>`failed`,target:s}),{start:f,readyStore:n,preconditionPassedStore:a,conditionPassedStore:o,lifecycleStageStore:s,registerPluginStartHook:h,setPrecondition:g,setCondition:v}});function ue(e){return(0,d.invoke)(le,e)}var de=(0,u.createDomain)(`predicate`),fe=(0,d.createFactory)(({client:e})=>{let t=de.store({}),r=(0,u.createApi)(t,{register(e,t){return{...e,[t.name]:{name:t.name,predicate:t.predicate}}}}),i=(0,u.createEvent)();(0,u.sample)({clock:i,source:t,filter:(e,{name:t})=>e[t]!==void 0,fn:(e,{name:t})=>`Predicate '${t}' already registered. Registering again will override the previous registration.`}).watch(e=>n.t(`warn`,e)),(0,u.sample)({clock:i,fn:({name:e,predicate:t})=>Object.freeze({name:e,predicate:t}),target:r.register});let a=t.map(e=>Object.values(e));function o(e){return t.map(t=>t[e]?.predicate,{skipVoid:!1})}function s(t){let n=(0,u.createStore)(()=>void 0,{skipVoid:!1}),r=(0,u.attach)({source:{predicate:o(t),snapshot:e.stateSnapshotStore},effect:({predicate:e,snapshot:t})=>{if(e)return(...n)=>e({...t,args:n})}});return(0,u.sample)({source:{responses:e.responses.listStore,fields:e.fields.listStore},target:r}),(0,u.sample)({clock:r.doneData,filter:e=>e!==void 0,target:n}),r(),n}return{register:i,getByName:o,listStore:a,getEvokablePredicate:s}});function pe(e){return(0,d.invoke)(fe,e)}var me=(e,t,n)=>{n.register({name:e,predicate:t})},V=(0,u.createDomain)(`feature`),he=(0,d.createFactory)(({client:e})=>{let t=V.store({}),r=V.store([]),i=(0,u.createApi)(t,{register(e,t){return{...e,[t.id]:t.feature}}}),a=(0,u.createEvent)();(0,u.sample)({clock:a,source:t,filter:(e,{id:t})=>e[t]!==void 0,fn:(e,{id:t})=>`Feature '${t}' already registered. Registering again will override the previous registration.`}).watch(e=>n.t(`warn`,e)),(0,u.sample)({clock:a,fn:({id:e,feature:t})=>Object.freeze({id:e,feature:{id:e,feature:{...t,id:e}}}),target:i.register});let s=(0,u.createEffect)(async({id:e,key:t,storage:n=`local`})=>{let r=o.t(`feature:${e}:${t}`,`global`),i=(n===`session`?o.r:o.n).get(r).boolean();return i===null?null:{id:e,key:t,bucket:i,storage:n}}),c=(0,u.createEffect)(e=>{if(!e)return null;let t=o.t(`feature:${e.id}:${e.key}`,`global`);(e.storage===`session`?o.r:o.n).set(t,e.bucket)}),l=new Map,d=(0,u.attach)({source:{allFeaturesStore:t,resolvedFeaturesStore:r},effect:async({allFeaturesStore:e,resolvedFeaturesStore:t},{id:n,decide:r,key:i})=>{let a=t.find(e=>e.id===n&&e.key===i);if(a)return a;let o=e[n];if(!o)throw Error(`Feature with id '${n}' not found`);let s=l.get(`${n}:${i}`);if(s!==void 0){let e=await s;return{id:o.id,bucket:e,key:i,storage:o.feature.storage}}let c=r();l.set(`${n}:${i}`,c);let u=await c;return{id:o.id,bucket:u,key:i,storage:o.feature.storage}}});(0,u.sample)({clock:i.register,fn:e=>{let{id:t,feature:n}=e;return{id:t,key:n.feature.key,storage:n.feature.storage}},target:s}),(0,u.sample)({source:t,clock:d.doneData,fn:(e,t)=>{let{id:n,bucket:r,storage:i}=t,a=e[n]?.feature.key;return a?{key:a,id:n,bucket:r,storage:i}:null},target:c});let f=(0,u.combine)({allFeaturesStore:t,resolvedFeaturesStore:r}).map(({allFeaturesStore:e,resolvedFeaturesStore:t})=>Object.values(e).map(e=>{let n=t.find(t=>t.id===e.id&&t.key===e.feature.key);return n?{id:e.id,name:e.feature.name,key:e.feature.key,enabled:e.feature.enabled,weight:e.feature.weight,getBucket:()=>({id:e.id,bucket:n.bucket}),isResolved:!0}:{id:e.id,name:e.feature.name,key:e.feature.key,enabled:e.feature.enabled,weight:e.feature.weight,getBucket:async()=>await d(e.feature),isResolved:!1}}));(0,u.sample)({clock:d.doneData,source:{resolvedFeatures:r},filter:({resolvedFeatures:e},{id:t,key:n})=>!e.some(e=>e.id===t&&e.key===n),fn:(e,t)=>t,target:e.eventBus.prepend(e=>({type:`feature_decide`,feature:e}))}),(0,u.sample)({clock:[s.doneData,d.doneData],source:r,fn:(e,t)=>!t||e.some(e=>e.id===t.id&&e.key===t.key)?e:[...e,t],target:r});function p(e){return f.map(t=>t.find(t=>t.id===e))}function m(e){return t.map(t=>t[e],{skipVoid:!1})}function h(e){let t=(0,u.createStore)(async()=>void 0,{skipVoid:!1}),n=(0,u.attach)({source:p(e),effect:async e=>{if(e)return async()=>(await e.getBucket()).bucket}});return(0,u.sample)({source:r,filter:t=>t.some(t=>t.id===e),target:n}),(0,u.sample)({clock:n.doneData,filter:e=>e!==void 0,target:t}),n(),t}return{register:a,getById:p,getByName:m,listStore:f,getEvokableFeature:h}});function ge(e){return(0,d.invoke)(he,e)}var _e=(e,t,n)=>{n.register({id:e,feature:t})},H=(0,u.createDomain)(`history`);function U(e,t){return{id:c.t(`history-entry-${Date.now()}-${Math.random()}}`),node:t,at:Date.now(),experienceId:e}}var ve=(0,d.createFactory)(()=>{let e=H.store({entries:[]}),t=H.event(),n=H.event(),r=H.event(),i=H.event();e.on(t,(e,t)=>({entries:[...e.entries,U(t.experienceId,t.node)]})),e.on(n,(e,t)=>({entries:[...e.entries.slice(0,-1),U(t.experienceId,t.node)]})),e.on(i,(e,t)=>t);function o(e,t){let n={lastStepIndex:-1,secondLastStepIndex:-1};for(let r=e.length-1;r>=0;r--){let i=e[r],o=i?.node;if(!(!o||!a.u(o))&&!(t&&i.experienceId!==t))if(n.lastStepIndex===-1)n.lastStepIndex=r;else{n.secondLastStepIndex=r;break}}return n}return e.on(r,(e,t)=>{let{secondLastStepIndex:n}=o(e.entries,t.experienceId),r=n===-1?e.entries:e.entries.slice(0,n+1);return{...e,entries:r}}),{push:t,replace:n,back:r,restore:i,entriesStore:e.map(e=>e.entries)}});function ye(){return(0,d.invoke)(ve)}var be=0,xe=e=>{let t=(0,u.createStore)([]);return t.on(e,(e,t)=>[...e,{id:be++,at:new Date,payload:t}]),t},Se=(0,u.createDomain)(`field`),Ce=(0,d.createFactory)(()=>{let e=Se.store({}),t=(0,u.createApi)(e,{register(e,t){return{...e,[t.field.id]:t.field}},updateByKey(e,t){let n=Object.values(e).find(e=>e.key===t.fieldKey);return n?{...e,[n.id]:Object.assign({},n,t.updates)}:e}});function n(e){t.register({field:e})}let r={};e.watch(e=>{r=e});function i(e,n){let i=Object.values(r).find(t=>t.key===e)?.key;i&&t.updateByKey({fieldKey:i,updates:n})}let a=e.map(e=>Object.values(e));function o(t){return e.map(e=>e[t]??null,{skipVoid:!1})}function s(t){return e.map(e=>Object.values(e).find(e=>e.key===t)??null,{skipVoid:!1})}function c(t){return e.map(e=>Object.values(e).find(e=>e.name===t)??null,{skipVoid:!1})}return{register:n,update:i,getById:o,getByKey:s,listStore:a,getByName:c}});function we(){return(0,d.invoke)(Ce)}var Te=(0,u.createDomain)(`step`),Ee=(0,d.createFactory)(()=>{let e=Te.store({}),t=(0,u.createApi)(e,{register(e,t){return{...e,[t.step.id]:t.step}}});function n(e){t.register({step:e})}let r=e.map(e=>Object.values(e));function i(t){return e.map(e=>e[t]??null,{skipVoid:!1})}function a(t){return e.map(e=>Object.values(e).find(e=>e.key===t)??null,{skipVoid:!1})}return{register:n,getById:i,getByKey:a,listStore:r,indexStore:e}});function De(){return(0,d.invoke)(Ee)}function Oe(e,t){t.register(e)}var ke=(0,u.createDomain)(`content`),Ae=(0,d.createFactory)(()=>{let e=ke.store({}),t=(0,u.createApi)(e,{register(e,t){return{...e,[t.content.id]:t.content}},patch(e,t){let n=e[t.id];if(!n)return e;let r=t.apply(n.data);return r===n.data?e:{...e,[t.id]:{...n,data:r}}}});function n(e){t.register({content:e})}function r(e,n){t.patch({id:e,apply:n})}let i=e.map(e=>Object.values(e));function a(t){return e.map(e=>e[t]??null,{skipVoid:!1})}return{register:n,patch:r,getById:a,listStore:i,indexStore:e}});function je(){return(0,d.invoke)(Ae)}function Me(e,t){t.register(e)}var Ne=(0,u.createDomain)(`action`),Pe=(0,d.createFactory)(({client:e})=>{let t=Ne.store({}),r=(0,u.createApi)(t,{register(e,t){return{...e,[t.key]:{key:t.key,action:t.action}}}}),i=(0,u.createEvent)();(0,u.sample)({clock:i,source:t,filter:(e,{key:t})=>e[t]!==void 0,fn:(e,{key:t})=>`Action '${t}' already registered. Registering again will override the previous registration.`}).watch(e=>n.t(`warn`,e)),(0,u.sample)({clock:i,fn:({key:e,action:t})=>Object.freeze({key:e,action:t}),target:r.register});let a=t.map(e=>Object.values(e));function o(e){return t.map(t=>t[e]?.action,{skipVoid:!1})}function s(t,n){let r=(0,u.createStore)(()=>void 0,{skipVoid:!1}),i=n?{experience:n.experience}:null,a=(0,u.attach)({source:{action:o(t),snapshot:e.stateSnapshotStore},effect:({action:e,snapshot:t})=>{if(e)return(...n)=>e({...t,args:n},i)}});return(0,u.sample)({source:{responses:e.responses.listStore,fields:e.fields.listStore},target:a}),(0,u.sample)({clock:a.doneData,filter:e=>e!==void 0,target:r}),a(),r}return{register:i,getByKey:o,listStore:a,getEvokableAction:s}});function Fe(e){return(0,d.invoke)(Pe,e)}var Ie=(e,t,n)=>{n.register({key:e,action:t})};function W(e,t,n,r){return{fieldKey:e.key,userMessage:n,systemMessage:r,value:t}}function G(e){return e===null||e===``||Array.isArray(e)&&!e.length}function Le(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||e===null}function K(e){try{return JSON.stringify(e),!0}catch{return!1}}function Re(e,t){return t.find(t=>t.key===e)??null}function ze(e,t){return e.multiple&&(typeof t==`string`||typeof t==`number`||typeof t==`boolean`)?[t]:t}function Be(e,t){if(e.type!==`object`||G(t))return null;if(e.multiple){if(!Array.isArray(t))return W(e,t,`This field expects multiple values`,`Field expects an array of objects.`);for(let n of t){if(typeof n!=`object`||!n)return W(e,t,`This field expects object values`,`Field expects an array of objects, but received non-object value.`);if(!K(n))return W(e,t,`This field contains non-serializable data`,`Field value contains non-JSON-serializable data (functions, circular references, etc.).`)}return null}return Array.isArray(t)?W(e,t,`This field expects a single value`,`Field expects a single object, not an array.`):typeof t!=`object`||!t?W(e,t,`This field expects an object value`,`Field expects an object value.`):K(t)?null:W(e,t,`This field contains non-serializable data`,`Field value contains non-JSON-serializable data (functions, circular references, etc.).`)}function Ve(e,t){if(G(t)||!Array.isArray(e.options)||e.options.length===0)return null;let n=Array.isArray(t)?t:[t];if(e.type===`object`){let r=new Set(e.options.map(e=>JSON.stringify(e.value)));return n.every(e=>r.has(JSON.stringify(e)))?null:W(e,t,`This field expects a valid option`,`Field expects a valid option from the defined choices.`)}let r=e.options.map(e=>e.value);return n.every(e=>!Le(e)||e===null?!1:r.includes(e))?null:W(e,t,`This field expects a valid option`,`Field expects a valid option. Valid options are: ${r.join(`, `)}`)}async function He(t,n,r,i){if(n.validation&&!e.t(n.validation)&&!G(r)){let e=i?{$input:r,responses:i}:{$input:r},a=await t(n.validation,e);if(typeof a==`string`)return W(n,r,a,`Field validation resulted in an error: ${a}.`);if(a===!1)return W(n,r,`This field is invalid`,`Field validation resulted in an unspecified error.`)}return n.required&&G(r)?W(n,r,`This field is required`,`Field is required.`):!n.multiple&&Array.isArray(r)&&r.length>1?W(n,r,`This field expects a single response`,`Field expects a single response.`):null}var Ue=(0,u.createDomain)(`response`),We=(0,d.createFactory)(({client:e})=>{let n=Ue.store({}),r=(0,u.createEvent)(),i=(0,u.createEvent)(),a=(0,u.createApi)(n,{register(e,t){return{...e,[t.fieldKey]:t.response}},registerBatch(e,t){return{...e,...t}},clear(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))},clearAll(){return{}}});function o(e,t){if(typeof e==`string`){if(t===void 0)throw Error(`Response is required when registering a single field`);a.register({fieldKey:e,response:t})}else a.registerBatch(e)}let s=(n,r)=>t.t(e,n,r),c=(0,u.attach)({source:{allFields:e.fields.listStore,existingResponses:n},effect:async({allFields:e,existingResponses:t},n)=>{let r=[],i={},a={...t,...n},o=Object.entries(n),c=await Promise.allSettled(o.map(async([t,n])=>{let o=Re(t,e);if(!o){r.push({fieldKey:t,userMessage:`Field '${t}' not found`,systemMessage:`No field with key '${t}' exists. Available field keys are: ${e.map(e=>e.key).join(`,`)}.`,value:n});return}let c=ze(o,n),l=await He(s,o,c,a);if(l){r.push(l);return}let u=Be(o,c);if(u){r.push(u);return}let d=Ve(o,c);if(d){r.push(d);return}i[o.key]=n}));for(let[e,t]of c.entries()){if(t.status!==`rejected`)continue;let n=o[e];if(!n)continue;let[i,a]=n,s=t.reason instanceof Error?t.reason.message:String(t.reason);r.push({fieldKey:i,userMessage:`An unexpected error occurred validating this field`,systemMessage:`Validation threw for field '${i}': ${s}`,value:a})}return{responsesToCommit:i,validationErrors:r}}});async function l(e){return c(e)}let d=(0,u.attach)({source:n,effect:async(e,t)=>{let{responsesToCommit:n,validationErrors:r}=await c(t);return r.length?{errors:r}:(a.registerBatch(n),{errors:[]})}});async function f(e){return d(e)}let p=n.map(e=>e),m=n.map(e=>Object.entries(e).map(([e,t])=>({fieldKey:e,value:t})));function h(e){return(0,u.combine)({f:e,s:n},({f:e,s:t})=>{let n=e?t[e.key]??null:null;return n===null?e?.defaultValue!==void 0&&e.defaultValue!==null?e.defaultValue:null:n})}function g(t){return h(e.fields.getById(t))}function _(t){return h(e.fields.getByKey(t))}function v(t){return h(e.fields.getByName(t))}return(0,u.sample)({clock:r,target:a.clearAll}),(0,u.sample)({clock:i,target:a.clear}),{register:o,clearAll:r,clear:i,commit:f,getResponsesToCommit:l,listStore:m,getAllStore:p,getByFieldId:g,getByFieldKey:_,getByFieldName:v}});function Ge(e){return(0,d.invoke)(We,e)}var Ke=(0,u.createDomain)(`condition`),qe=(0,d.createFactory)(()=>{let e=Ke.store({}),t=(0,u.createApi)(e,{register(e,t){return{...e,[t.condition.id]:t.condition}}});function n(e){t.register({condition:e})}let r=e.map(e=>Object.values(e));function i(t){return e.map(e=>e[t]??null,{skipVoid:!1})}function a(t){return e.map(e=>Object.values(e).find(e=>e.key===t)??null,{skipVoid:!1})}return{register:n,getById:i,getByKey:a,listStore:r,indexStore:e}});function Je(){return(0,d.invoke)(qe)}function Ye(){if(r.i()){let e=[document.currentScript,document.getElementById(`picked_script`),document.getElementById(`picked`),document.getElementById(`cvly`),document.getElementById(`cvly-x`)];for(let t of e)if(t?.dataset.api)return t.dataset.api}return`https://api.picked.app`}function q(){if(!r.f())return{};let e=new URLSearchParams(window.location.search),t={},n=new Set;for(let[t]of e.entries())t.startsWith(`picked-`)&&n.add(t);for(let r of n){let n=r.replace(`picked-`,``);t[n]=e.getAll(r)}let i=o.t(`s`);if(n.size>0)o.r.set(i,t);else{let e=o.r.get(i);if(e)return e.json()||{}}return t}var J=o.t(`session`,`global`);function Xe(){return r.r()?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).substring(2,15)}-${Math.random().toString(36).substring(2,15)}-${Math.random().toString(36).substring(2,15)}`}function Ze(){if(!r.s())return null;let e=o.n.get(J);if(!e.isSet())return null;try{return e.json()}catch{return null}}var Qe=(0,d.createFactory)(()=>{let e=Ze(),t={id:e?.id??Xe()};e?.isUser!==void 0&&(t.isUser=e.isUser),e?.identifiers&&Object.keys(e.identifiers).length>0&&(t.identifiers=e.identifiers);let n=(0,u.createStore)(t),i=(0,u.createApi)(n,{setIsUser:(e,t)=>({...e,isUser:t}),setIdentifier:(e,{key:t,value:n})=>({...e,identifiers:{...e.identifiers??{},[t]:n}}),removeIdentifier:(e,t)=>{let n=e.identifiers;if(!n||!(t in n))return e;let r={};for(let[e,i]of Object.entries(n))e!==t&&(r[e]=i);let i={id:e.id};return e.isUser!==void 0&&(i.isUser=e.isUser),Object.keys(r).length>0&&(i.identifiers=r),i}});return(0,u.sample)({source:n,target:(0,u.attach)({source:n,effect:e=>{if(r.s())try{o.n.get(J).set(e)}catch{}}})}),{store:n,setIsUser:i.setIsUser,setIdentifier:i.setIdentifier,removeIdentifier:i.removeIdentifier}});function $e(){return(0,d.invoke)(Qe,void 0)}function Y(){if(r.f())return globalThis.window.pickedConfig}function et(){if(r.f())return Y()?.projectId}function tt(){if(!r.i())return;let e=document.getElementById(`picked_script`)||document.querySelector(`script#picked`)||document.getElementById(`cvly`);if(e)return e.dataset.projectid||e.getAttribute(`project-id`)||void 0}function nt(e){if(e.projectId)return e.projectId;let t=et();if(t)return t;let n=tt();if(n)return n;throw Error(`projectId is required. You can provide it via one of:
2
2
  (1) createClient({ projectId }) options;
3
3
  (2) window.pickedConfig = { projectId };
4
- (3) a <script> tag with id 'picked_script', 'picked', or 'cvly' that includes a data-projectid (or project-id) attribute.`)}function X(e){return e==null||e===``||Number.isNaN(e)}var rt={default:(e,t)=>X(e)?String(t??``):String(e),append:(e,t)=>t&&!X(e)?`${e} ${t}`:e,prepend:(e,t)=>t&&!X(e)?`${t} ${e}`:e,upper:e=>typeof e==`string`?e.toUpperCase():e,lower:e=>typeof e==`string`?e.toLowerCase():e,capitalize:e=>typeof e==`string`?e.charAt(0).toUpperCase()+e.slice(1):e,list:e=>{if(!e||typeof e!=`object`)return e;let t=new Intl.ListFormat(`en`,{style:`long`,type:`conjunction`});if(Array.isArray(e))return t.format(e.map(String));if(e instanceof Map){let n=Array.from(e.entries()).map(([e,t])=>`${e}: ${t}`);return t.format(n)}return e instanceof Set?t.format(Array.from(e).map(String)):e}};function it(e){return typeof e==`object`&&!!e}function at(e,t){let n=t;for(let t of e.split(`.`))if(it(n)&&t in n)n=n[t];else return;return typeof n==`function`?n():n}function ot(e,t){let n=e.split(`|`).map(e=>e.trim()),r=at(n.shift()??``,t);for(let e of n){let[t,...n]=e.split(`:`),i=t?.trim()??``,a=n.join(`:`).trim().replaceAll(/(?:^['"]|['"]$)/g,``),o=rt[i];o&&(r=o(r,a))}return X(r)?``:typeof r==`object`?JSON.stringify(r):String(r)}function st(e,t){let n=``,r=0;for(;r<e.length;)if(e[r]===`{`&&e[r+1]===`{`){r+=2;let i=``;for(;r<e.length;){if(e[r]===`}`&&e[r+1]===`}`){r+=2;break}i+=e[r++]}n+=ot(i.trim(),t)}else n+=e[r++];return n}var Z=`preview-token`;function Q(){return!r.f()||!r.t()?!1:!!q()[Z]?.[0]}var $=class{static logger=n.t;options;dataSource=null;contentLoader;previewEmbedderOrigins=null;plugins={};eventBus=(0,u.createEvent)();events;projectId;apiUrl;dashboardUrl;documentationSiteUrl;session=$e();searchParams=q();history=ye();components=w({client:this});experienceInstances=a.n({client:this});experiences=g({client:this});frameworks=O({client:this});predicates=pe({client:this});features=ge({client:this});conditions=Je();fields=we();responses=Ge({client:this});steps=De();contents=je();actions=Fe({client:this});conditionResults=a.r();stateSnapshotStore=ee({client:this});evaluateRuleLogicFx=ae({client:this});start;readyStore;preconditionPassedStore;conditionPassedStore;lifecycleStageStore;lifecycle=ue({client:this});renderStringFx=(0,u.attach)({source:this.responses.listStore,effect:(e,{template:t,context:n})=>{let r={};for(let t of e)r[t.fieldKey]=t.value;return st(t,{...n,responses:r})}});constructor(e){this.events=xe(this.eventBus),this.projectId=nt(e),this.options=Object.freeze(e),this.apiUrl=e.apiUrl||Ye(),this.dashboardUrl=e.dashboardUrl??`https://dashboard.picked.app`,this.documentationSiteUrl=e.documentationSiteUrl??`https://docs.picked.app`,this.start=this.lifecycle.start,this.readyStore=this.lifecycle.readyStore,this.preconditionPassedStore=this.lifecycle.preconditionPassedStore,this.conditionPassedStore=this.lifecycle.conditionPassedStore,this.lifecycleStageStore=this.lifecycle.lifecycleStageStore,this.setupPlugins(),this.setupFeatures(),this.setupPredicates(),this.setupActions(),this.setupComponents(),this.lifecycle.setPrecondition(e.precondition),this.lifecycle.setCondition(e.condition),this.eventBus({type:`load`,version:s.r()}),this.maybeStartPreviewChannel()}maybeStartPreviewChannel(){Q()&&Promise.resolve().then(()=>require("../preview-channel-Cx0e6fye.cjs")).then(e=>e.initPreviewChannel(this)).catch(()=>void 0)}registerFramework=e=>{k(e,this.frameworks)};registerComponent=(e,t)=>{T(e,t,this.components)};registerPlugin=e=>{y(this,e,this.plugins);let t=this.plugins[e.name];t?.onStart&&this.lifecycle.registerPluginStartHook(t.onStart)};registerFeature=(e,t)=>{_e(e,t,this.features)};registerPredicate=(e,t)=>{me(e,t,this.predicates)};registerCondition=e=>{this.conditions.register(e)};registerField=e=>{this.fields.register(e)};registerStep=e=>{Oe(e,this.steps)};registerContent=e=>{Me(e,this.contents)};patchContent=(e,t)=>{this.contents.patch(e,t)};registerAction=(e,t)=>{Ie(e,t,this.actions)};registerExperience=e=>{e.component&&T(`experience:${e.id}`,e.component,this.components),this.experiences.register(e)};launchExperienceById=async(e,t)=>{this.experiences.launch({id:e,options:t})};launchExperienceByKey=async(e,t)=>{this.experiences.launch({key:e,options:t})};openExperienceById=async e=>{this.experiences.open({id:e})};openExperienceByKey=async e=>{this.experiences.open({key:e})};setupPlugins(){this.options.plugins?.forEach(e=>{if(Array.isArray(e)){e.forEach(e=>{this.registerPlugin(e)});return}let t=typeof e==`function`?e():e;if(Array.isArray(t)){t.forEach(e=>this.registerPlugin(e));return}this.registerPlugin(t)})}setupFeatures(){let e=this.options.features;e&&Object.entries(e).forEach(([e,t])=>{let n=typeof t==`function`?t():t;this.registerFeature(e,n)}),this.searchParams.feature&&this.searchParams.feature.forEach(e=>{try{let[t,n]=e.split(`:`);if(!t||!n)return;let r=n;r===`true`&&(r=!0),r===`false`&&(r=!1),this.registerFeature(t,{key:`${r}`,name:t,decide:()=>r,storage:`session`})}catch{}})}setupPredicates(){let e=this.options.predicates;e&&Object.entries(e).forEach(([e,t])=>{if(typeof t!=`function`){`${e}`;return}this.registerPredicate(e,t)})}setupActions(){let e=this.options.actions;e&&Object.entries(e).forEach(([e,t])=>{if(typeof t!=`function`){`${e}`;return}this.registerAction(e,t)})}setupComponents(){let e=this.options.components;e&&Object.entries(e).forEach(([e,t])=>{this.registerComponent(e,t)})}getPluginConfig=e=>this.plugins[e]??{}},ct=`application/picked-javascript`,lt=`application/picked-module`,ut=`data-picked-hydrated`;async function dt(e){if(!(`document`in globalThis))return;let t=`application/picked-module`,n=`data-picked-hydrated`;function r(e,t){let r=document.createElement(`script`);for(let t of Array.from(e.attributes))t.name!==`type`&&r.setAttribute(t.name,t.value);t&&r.setAttribute(`type`,t),r.setAttribute(n,``),e.src?r.async=!1:r.textContent=e.textContent;let i=e.src?new Promise(e=>{r.addEventListener(`load`,()=>e(),{once:!0}),r.addEventListener(`error`,()=>e(),{once:!0})}):null;return e.src?e.replaceWith(r):(globalThis.__pickedEmbedScriptRoot=e.getRootNode(),e.replaceWith(r),globalThis.__pickedEmbedScriptRoot=null),i}let i=Array.from(e.querySelectorAll(`script[type="application/picked-javascript"]:not([${n}]), script[type="${t}"]:not([${n}])`)).filter(e=>e instanceof HTMLScriptElement);for(let e of i){if(!e.isConnected)continue;let n=r(e,e.getAttribute(`type`)===t?`module`:null);n&&await n}}function ft(){return`<script>(${dt.toString()})(document)<\/script>`}function pt(e){return typeof e==`object`&&!!e&&`id`in e&&typeof e.id==`string`&&`content`in e&&(typeof e.content==`string`||e.content===null)}function mt(e){return{$$type:`lazy-component`,load:e}}function ht(e){return typeof e==`object`&&!!e&&`$$type`in e&&e.$$type===`lazy-component`}var gt=e=>{let t=new $(e);return r.m(t),t};exports.PICKED_HYDRATED_ATTR=ut,exports.PICKED_MODULE_SCRIPT_TYPE=lt,exports.PICKED_SCRIPT_TYPE=ct,exports.PREVIEW_TOKEN_PARAM=Z,exports.Picked=$,exports.buildRehydrateBootstrap=ft,exports.createClient=gt,exports.createPluginEffect=v,exports.createStorageKey=o.t,exports.evaluateRuleLogic=t.t,exports.getPickedConfig=Y,exports.isHtmlAssetValue=pt,exports.isInsideIframe=r.t,exports.isLazyLoader=ht,exports.isPickedRoot=i.a,exports.isPreviewSession=Q,exports.lazyComponent=mt,exports.localStore=o.n,exports.onInertScriptSubtrees=l.t,exports.rehydrateScripts=dt,exports.reportInertScriptSubtrees=l.n,exports.resetInertScriptReport=l.r,exports.sessionStore=o.r,exports.subscribe=o.i,exports.supportsCookies=r.n,exports.supportsCryptoRandomUUID=r.r,exports.supportsDocument=r.i,exports.supportsHistory=r.a,exports.supportsIntersectionObserver=r.o,exports.supportsLocalStorage=r.s,exports.supportsLocation=r.c,exports.supportsSessionStorage=r.l,exports.supportsShadowRoot=r.u,exports.supportsWebComponents=r.d,exports.supportsWindow=r.f;
4
+ (3) a <script> tag with id 'picked_script', 'picked', or 'cvly' that includes a data-projectid (or project-id) attribute.`)}function X(e){return e==null||e===``||Number.isNaN(e)}var rt={default:(e,t)=>X(e)?String(t??``):String(e),append:(e,t)=>t&&!X(e)?`${e} ${t}`:e,prepend:(e,t)=>t&&!X(e)?`${t} ${e}`:e,upper:e=>typeof e==`string`?e.toUpperCase():e,lower:e=>typeof e==`string`?e.toLowerCase():e,capitalize:e=>typeof e==`string`?e.charAt(0).toUpperCase()+e.slice(1):e,list:e=>{if(!e||typeof e!=`object`)return e;let t=new Intl.ListFormat(`en`,{style:`long`,type:`conjunction`});if(Array.isArray(e))return t.format(e.map(String));if(e instanceof Map){let n=Array.from(e.entries()).map(([e,t])=>`${e}: ${t}`);return t.format(n)}return e instanceof Set?t.format(Array.from(e).map(String)):e}};function it(e){return typeof e==`object`&&!!e}function at(e,t){let n=t;for(let t of e.split(`.`))if(it(n)&&t in n)n=n[t];else return;return typeof n==`function`?n():n}function ot(e,t){let n=e.split(`|`).map(e=>e.trim()),r=at(n.shift()??``,t);for(let e of n){let[t,...n]=e.split(`:`),i=t?.trim()??``,a=n.join(`:`).trim().replaceAll(/(?:^['"]|['"]$)/g,``),o=rt[i];o&&(r=o(r,a))}return X(r)?``:typeof r==`object`?JSON.stringify(r):String(r)}function st(e,t){let n=``,r=0;for(;r<e.length;)if(e[r]===`{`&&e[r+1]===`{`){r+=2;let i=``;for(;r<e.length;){if(e[r]===`}`&&e[r+1]===`}`){r+=2;break}i+=e[r++]}n+=ot(i.trim(),t)}else n+=e[r++];return n}var Z=`preview-token`;function Q(){return!r.f()||!r.t()?!1:!!q()[Z]?.[0]}var $=class{static logger=n.t;options;dataSource=null;contentLoader;previewEmbedderOrigins=null;plugins={};eventBus=(0,u.createEvent)();events;projectId;apiUrl;dashboardUrl;documentationSiteUrl;session=$e();searchParams=q();history=ye();components=w({client:this});experienceInstances=a.n({client:this});experiences=g({client:this});frameworks=O({client:this});predicates=pe({client:this});features=ge({client:this});conditions=Je();fields=we();responses=Ge({client:this});steps=De();contents=je();actions=Fe({client:this});conditionResults=a.r();stateSnapshotStore=ee({client:this});evaluateRuleLogicFx=ae({client:this});start;readyStore;preconditionPassedStore;conditionPassedStore;lifecycleStageStore;lifecycle=ue({client:this});renderStringFx=(0,u.attach)({source:this.responses.listStore,effect:(e,{template:t,context:n})=>{let r={};for(let t of e)r[t.fieldKey]=t.value;return st(t,{...n,responses:r})}});constructor(e){this.events=xe(this.eventBus),this.projectId=nt(e),this.options=Object.freeze(e),this.apiUrl=e.apiUrl||Ye(),this.dashboardUrl=e.dashboardUrl??`https://dashboard.picked.app`,this.documentationSiteUrl=e.documentationSiteUrl??`https://docs.picked.app`,this.start=this.lifecycle.start,this.readyStore=this.lifecycle.readyStore,this.preconditionPassedStore=this.lifecycle.preconditionPassedStore,this.conditionPassedStore=this.lifecycle.conditionPassedStore,this.lifecycleStageStore=this.lifecycle.lifecycleStageStore,this.setupPlugins(),this.setupFeatures(),this.setupPredicates(),this.setupActions(),this.setupComponents(),this.lifecycle.setPrecondition(e.precondition),this.lifecycle.setCondition(e.condition),this.eventBus({type:`load`,version:s.r()}),this.maybeStartPreviewChannel()}maybeStartPreviewChannel(){Q()&&Promise.resolve().then(()=>require("../preview-channel-Cx0e6fye.cjs")).then(e=>e.initPreviewChannel(this)).catch(()=>void 0)}registerFramework=e=>{k(e,this.frameworks)};registerComponent=(e,t)=>{T(e,t,this.components)};registerPlugin=e=>{y(this,e,this.plugins);let t=this.plugins[e.name];t?.onStart&&this.lifecycle.registerPluginStartHook(t.onStart)};registerFeature=(e,t)=>{_e(e,t,this.features)};registerPredicate=(e,t)=>{me(e,t,this.predicates)};registerCondition=e=>{this.conditions.register(e)};registerField=e=>{this.fields.register(e)};registerStep=e=>{Oe(e,this.steps)};registerContent=e=>{Me(e,this.contents)};patchContent=(e,t)=>{this.contents.patch(e,t)};registerAction=(e,t)=>{Ie(e,t,this.actions)};registerExperience=e=>{e.component&&T(`experience:${e.id}`,e.component,this.components),this.experiences.register(e)};launchExperienceById=async(e,t)=>{this.experiences.launch({id:e,options:t})};launchExperienceByKey=async(e,t)=>{this.experiences.launch({key:e,options:t})};openExperienceById=async e=>{this.experiences.open({id:e})};openExperienceByKey=async e=>{this.experiences.open({key:e})};setupPlugins(){this.options.plugins?.forEach(e=>{if(Array.isArray(e)){e.forEach(e=>{this.registerPlugin(e)});return}let t=typeof e==`function`?e():e;if(Array.isArray(t)){t.forEach(e=>this.registerPlugin(e));return}this.registerPlugin(t)})}setupFeatures(){let e=this.options.features;e&&Object.entries(e).forEach(([e,t])=>{let n=typeof t==`function`?t():t;this.registerFeature(e,n)}),this.searchParams.feature&&this.searchParams.feature.forEach(e=>{try{let[t,n]=e.split(`:`);if(!t||!n)return;let r=n;r===`true`&&(r=!0),r===`false`&&(r=!1),this.registerFeature(t,{key:`${r}`,name:t,decide:()=>r,storage:`session`})}catch{}})}setupPredicates(){let e=this.options.predicates;e&&Object.entries(e).forEach(([e,t])=>{if(typeof t!=`function`){`${e}`;return}this.registerPredicate(e,t)})}setupActions(){let e=this.options.actions;e&&Object.entries(e).forEach(([e,t])=>{if(typeof t!=`function`){`${e}`;return}this.registerAction(e,t)})}setupComponents(){let e=this.options.components;e&&Object.entries(e).forEach(([e,t])=>{this.registerComponent(e,t)})}getPluginConfig=e=>this.plugins[e]??{}},ct=`application/picked-javascript`,lt=`application/picked-module`,ut=`data-picked-hydrated`;async function dt(e){if(!(`document`in globalThis))return;let t=`application/picked-module`,n=`data-picked-hydrated`;function r(e){try{Function(e.textContent)}catch(t){return t instanceof SyntaxError?(console.error(`[picked] Skipped a rehydrated inline script that failed to parse.`,t),e.setAttribute(n,``),!0):!1}return!1}function i(e,t){let r=document.createElement(`script`);for(let t of Array.from(e.attributes))t.name!==`type`&&r.setAttribute(t.name,t.value);t&&r.setAttribute(`type`,t),r.setAttribute(n,``),e.src?r.async=!1:r.textContent=e.textContent;let i=e.src?new Promise(e=>{r.addEventListener(`load`,()=>e(),{once:!0}),r.addEventListener(`error`,()=>e(),{once:!0})}):null;return e.src?e.replaceWith(r):(globalThis.__pickedEmbedScriptRoot=e.getRootNode(),e.replaceWith(r),globalThis.__pickedEmbedScriptRoot=null),i}let a=Array.from(e.querySelectorAll(`script[type="application/picked-javascript"]:not([${n}]), script[type="${t}"]:not([${n}])`)).filter(e=>e instanceof HTMLScriptElement);for(let e of a){if(!e.isConnected)continue;let n=e.getAttribute(`type`)===t?`module`:null;if(!e.src&&n===null&&r(e))continue;let a=i(e,n);a&&await a}}function ft(){return`<script>(${dt.toString()})(document)<\/script>`}function pt(e){return typeof e==`object`&&!!e&&`id`in e&&typeof e.id==`string`&&`content`in e&&(typeof e.content==`string`||e.content===null)}function mt(e){return{$$type:`lazy-component`,load:e}}function ht(e){return typeof e==`object`&&!!e&&`$$type`in e&&e.$$type===`lazy-component`}var gt=e=>{let t=new $(e);return r.m(t),t};exports.PICKED_HYDRATED_ATTR=ut,exports.PICKED_MODULE_SCRIPT_TYPE=lt,exports.PICKED_SCRIPT_TYPE=ct,exports.PREVIEW_TOKEN_PARAM=Z,exports.Picked=$,exports.buildRehydrateBootstrap=ft,exports.createClient=gt,exports.createPluginEffect=v,exports.createStorageKey=o.t,exports.evaluateRuleLogic=t.t,exports.getPickedConfig=Y,exports.isHtmlAssetValue=pt,exports.isInsideIframe=r.t,exports.isLazyLoader=ht,exports.isPickedRoot=i.a,exports.isPreviewSession=Q,exports.lazyComponent=mt,exports.localStore=o.n,exports.onInertScriptSubtrees=l.t,exports.rehydrateScripts=dt,exports.reportInertScriptSubtrees=l.n,exports.resetInertScriptReport=l.r,exports.sessionStore=o.r,exports.subscribe=o.i,exports.supportsCookies=r.n,exports.supportsCryptoRandomUUID=r.r,exports.supportsDocument=r.i,exports.supportsHistory=r.a,exports.supportsIntersectionObserver=r.o,exports.supportsLocalStorage=r.s,exports.supportsLocation=r.c,exports.supportsSessionStorage=r.l,exports.supportsShadowRoot=r.u,exports.supportsWebComponents=r.d,exports.supportsWindow=r.f;
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../../../api-BQRx-Qnj.cjs"),t=require("../../../plugin-BUE_ulSi.cjs");exports.createClientHeaders=e.i,exports.dynamicExperiencesPlugin=t.t,exports.fetchExperienceContent=t.n,exports.fetchProject=t.r;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../../../api-B9koex39.cjs"),t=require("../../../plugin-YbSSGrM7.cjs");exports.createClientHeaders=e.i,exports.dynamicExperiencesPlugin=t.t,exports.fetchExperienceContent=t.n,exports.fetchProject=t.r;
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../../experience-instance-DurC3pE-.cjs"),t=require("../../plugin-BUE_ulSi.cjs");let n=require("effector");var r=1e4;function i(e){if(e?.location!==void 0)return{location:e.location}}function a(t,n){return t.nodes.filter(e.u).some(e=>n.get(e.stepId)===!0)}async function o(n,o){let{projectConfig:s}=o,c=n.session.store.getState().id;n.conditionResults.reset(),t.i(n,s,{isPreview:!1,sessionId:c});let l=i(o.attributes),u=o.timeoutMs??r,d=new Map(s.steps.map(e=>[e.id,e.layoutContentId!==void 0&&e.layoutContentId!==null])),f=[];for(let t of s.experiences)await e.o(n,{condition:t.condition},{context:l})&&f.push(t);let p=new Map;for(let e of f){if(!a(e,d))continue;let r=o.getContent?await o.getContent({id:e.id,key:e.key},{previewToken:o.previewToken}):await t.n(n.apiUrl,n.projectId,e.id,{previewToken:o.previewToken,signal:AbortSignal.timeout(u)});if(r)for(let e of r.content)p.set(e.id,e)}return{versionId:s.versionId,projectConfig:s,content:Array.from(p.values()),conditionResults:n.conditionResults.store.getState()}}function s(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:t=>e(t),reject:e=>t(e)}}function c(t,r){let{promise:i,resolve:a}=s(),o=(0,n.createEvent)(),c=(0,n.createEvent)(),l=(0,n.createEvent)(),u=(0,n.createEvent)(),d=(0,n.createEvent)(),f=t.experiences.listStore.map(n=>n.map(n=>e.t({client:t,experience:n}))),p=(0,n.createStore)({currentExperienceIndex:0,renderedExperiences:[],isComplete:!1}),m=(0,n.createEffect)(async e=>{let r=(0,n.attach)({source:e.experience.componentStore,effect:async(n,r)=>{let i=e.availableRenderers[r];return n&&i?.isValidComponent(n.component)?{rendered:await i.render(n.component,t,e.experience),rendererIndex:r}:null}}),i=e.startRendererIndex??0;for(let t=i;t<e.availableRenderers.length;t++){let e=await r(t);if(e)return e}return null}),h=(0,n.createEffect)(async({experience:e,availableRenderers:t,startRendererIndex:n=0})=>e?m({experience:e,availableRenderers:t,startRendererIndex:n}):null);return p.on(l,(e,t)=>({...e,renderedExperiences:[...e.renderedExperiences,t],currentExperienceIndex:e.currentExperienceIndex+1})).on(d,e=>({...e,currentExperienceIndex:e.currentExperienceIndex+1})).on(u,e=>({...e,isComplete:!0})).reset(o),(0,n.sample)({clock:o,target:c}),(0,n.sample)({clock:c,source:{experiences:f,state:p},filter:({experiences:e,state:t})=>t.currentExperienceIndex<e.length&&!t.isComplete,fn:({experiences:e,state:t})=>({experience:e[t.currentExperienceIndex],availableRenderers:r,startRendererIndex:0}),target:h}),(0,n.sample)({clock:h.doneData,filter:e=>e!==null,fn:e=>e.rendered.body,target:l}),(0,n.sample)({clock:l,target:c}),(0,n.sample)({clock:h.doneData,filter:e=>e===null,target:d}),(0,n.sample)({clock:d,target:c}),(0,n.sample)({clock:[c,d,l],source:{experiences:f,state:p},filter:({experiences:e,state:t})=>t.currentExperienceIndex>=e.length,target:u}),(0,n.sample)({clock:u,target:(0,n.attach)({source:p,effect:e=>{e.isComplete&&a(e.renderedExperiences)}})}),o(),i}exports.createExperienceInstance=e.t,exports.evaluateConditionMemo=e.i,exports.hashRule=e.a,exports.isExperienceActive=e.o,exports.registerProjectConfig=t.i,exports.render=c,exports.ruleReferencesAction=e.s,exports.ruleReferencesActionDeep=e.c,exports.serialize=o;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../../experience-instance-DurC3pE-.cjs"),t=require("../../plugin-YbSSGrM7.cjs");let n=require("effector");var r=1e4;function i(e){if(e?.location!==void 0)return{location:e.location}}function a(t,n){return t.nodes.filter(e.u).some(e=>n.get(e.stepId)===!0)}async function o(n,o){let{projectConfig:s}=o,c=n.session.store.getState().id;n.conditionResults.reset(),t.i(n,s,{isPreview:!1,sessionId:c});let l=i(o.attributes),u=o.timeoutMs??r,d=new Map(s.steps.map(e=>[e.id,e.layoutContentId!==void 0&&e.layoutContentId!==null])),f=[];for(let t of s.experiences)await e.o(n,{condition:t.condition},{context:l})&&f.push(t);let p=new Map;for(let e of f){if(!a(e,d))continue;let r=o.getContent?await o.getContent({id:e.id,key:e.key},{previewToken:o.previewToken}):await t.n(n.apiUrl,n.projectId,e.id,{previewToken:o.previewToken,signal:AbortSignal.timeout(u)});if(r)for(let e of r.content)p.set(e.id,e)}return{versionId:s.versionId,projectConfig:s,content:Array.from(p.values()),conditionResults:n.conditionResults.store.getState()}}function s(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:t=>e(t),reject:e=>t(e)}}function c(t,r){let{promise:i,resolve:a}=s(),o=(0,n.createEvent)(),c=(0,n.createEvent)(),l=(0,n.createEvent)(),u=(0,n.createEvent)(),d=(0,n.createEvent)(),f=t.experiences.listStore.map(n=>n.map(n=>e.t({client:t,experience:n}))),p=(0,n.createStore)({currentExperienceIndex:0,renderedExperiences:[],isComplete:!1}),m=(0,n.createEffect)(async e=>{let r=(0,n.attach)({source:e.experience.componentStore,effect:async(n,r)=>{let i=e.availableRenderers[r];return n&&i?.isValidComponent(n.component)?{rendered:await i.render(n.component,t,e.experience),rendererIndex:r}:null}}),i=e.startRendererIndex??0;for(let t=i;t<e.availableRenderers.length;t++){let e=await r(t);if(e)return e}return null}),h=(0,n.createEffect)(async({experience:e,availableRenderers:t,startRendererIndex:n=0})=>e?m({experience:e,availableRenderers:t,startRendererIndex:n}):null);return p.on(l,(e,t)=>({...e,renderedExperiences:[...e.renderedExperiences,t],currentExperienceIndex:e.currentExperienceIndex+1})).on(d,e=>({...e,currentExperienceIndex:e.currentExperienceIndex+1})).on(u,e=>({...e,isComplete:!0})).reset(o),(0,n.sample)({clock:o,target:c}),(0,n.sample)({clock:c,source:{experiences:f,state:p},filter:({experiences:e,state:t})=>t.currentExperienceIndex<e.length&&!t.isComplete,fn:({experiences:e,state:t})=>({experience:e[t.currentExperienceIndex],availableRenderers:r,startRendererIndex:0}),target:h}),(0,n.sample)({clock:h.doneData,filter:e=>e!==null,fn:e=>e.rendered.body,target:l}),(0,n.sample)({clock:l,target:c}),(0,n.sample)({clock:h.doneData,filter:e=>e===null,target:d}),(0,n.sample)({clock:d,target:c}),(0,n.sample)({clock:[c,d,l],source:{experiences:f,state:p},filter:({experiences:e,state:t})=>t.currentExperienceIndex>=e.length,target:u}),(0,n.sample)({clock:u,target:(0,n.attach)({source:p,effect:e=>{e.isComplete&&a(e.renderedExperiences)}})}),o(),i}exports.createExperienceInstance=e.t,exports.evaluateConditionMemo=e.i,exports.hashRule=e.a,exports.isExperienceActive=e.o,exports.registerProjectConfig=t.i,exports.render=c,exports.ruleReferencesAction=e.s,exports.ruleReferencesActionDeep=e.c,exports.serialize=o;
@@ -39,7 +39,7 @@ The condition builder lets you create rules using AND/OR groups. Each rule compa
39
39
 
40
40
  **Actions** — references to actions that have been triggered during the flow.
41
41
 
42
- **Features** — the state of feature flags in your project. Branch based on which variant a visitor is assigned to.
42
+ **Feature flags** — the state of feature flags in your project. Branch on whether a visitor is allocated to a flag.
43
43
 
44
44
  **Location** — properties of the visitor's current page URL, including pathname, search parameters, hostname, and hash. For example, show different content based on which page the visitor is on.
45
45
 
@@ -4,55 +4,71 @@ layout: docs
4
4
 
5
5
  import { Screenshot } from '../../components/Screenshot'
6
6
 
7
- # Features
7
+ # Feature flags
8
8
 
9
- Features let you run A/B tests and feature flags. Control which visitors see which variant of your site without deploying code changes.
9
+ Feature flags let you run A/B tests and roll changes out gradually. Control which visitors see a change to your site, without deploying code.
10
10
 
11
11
  <Screenshot
12
12
  route="/{orgSlug}/{projectId}/workspaces/{workspaceId}/features"
13
- alt="The features list for a workspace on the Picked dashboard"
13
+ alt="The feature flags list for a workspace on the Picked dashboard"
14
14
  />
15
15
 
16
- ## Create a feature
16
+ ## Create a feature flag
17
17
 
18
18
  1. Open your project.
19
- 2. Click **Features** in the sidebar.
20
- 3. Click **New Feature**.
19
+ 2. Click **Feature flags** in the sidebar.
20
+ 3. Click **New feature flag**.
21
21
  4. Enter a name.
22
- 5. Click **Create**.
22
+ 5. Click **Create feature flag**.
23
23
 
24
24
  ## Keys
25
25
 
26
- Each feature has a unique key. Use this key in your application to check which variant a visitor is assigned to. The key is set when you create the feature and cannot be changed later.
26
+ Each feature flag has a unique key. Use this key in your application to check whether a visitor is allocated to the flag. The key is set when you create the flag and cannot be changed later.
27
27
 
28
- ## Configure variants
28
+ ## Configure allocation
29
29
 
30
- Each feature has one or more variants. Visitors are assigned to a variant based on the rules you define.
30
+ Set allocation from the feature flag detail page:
31
31
 
32
- Configure variant allocation, targeting rules, and rollout percentages from the feature detail page.
32
+ | Control | What it does |
33
+ | --- | --- |
34
+ | **Enabled** | Whether visitors are allocated to the flag. A disabled flag allocates nobody. |
35
+ | **Weight** | The percentage of visitors allocated to the flag, from 0 to 100. |
36
+ | **Description** | An internal note describing what the flag tests. |
33
37
 
34
- ## How visitors are bucketed
38
+ A feature flag has one weight, and resolves to one of two outcomes per visitor: allocated, or not. A weight of 30 allocates 30% of visitors and leaves the other 70% unallocated. A weight of 0 allocates nobody; a weight of 100 allocates everybody.
35
39
 
36
- Visitors are assigned to variants using weight-based probabilistic rollout. Each variant has a weight from 0 to 100, representing the percentage of traffic it receives.
40
+ ## How visitors are allocated
37
41
 
38
- For example, with two variants weighted 50/50, roughly half of visitors see each variant. A variant weighted at 0 receives no traffic.
42
+ Allocation is deterministic. Each visitor is assigned a stable value derived from their visitor ID, which is compared against the flag's weight — if the value falls below the weight, the visitor is allocated.
39
43
 
40
- Bucketing is deterministic — the same visitor sees the same variant on repeat visits, unless the feature version changes.
44
+ The same visitor always gets the same result, on every visit, as long as the weight and version stay the same.
41
45
 
42
- ## Feature versions
46
+ :::warning
47
+ Allocation is shared across feature flags, not calculated independently for each one.
43
48
 
44
- Each feature has a version number (starting at 1). Incrementing the version resets all visitor assignments, so every visitor is re-evaluated as if they were seeing the feature for the first time.
49
+ Every flag compares against the same per-visitor value, so allocations are nested rather than independent. A flag at weight 50 always includes everyone allocated to a flag at weight 30. Two flags both at weight 50 allocate **exactly the same visitors** — not two independent halves.
50
+
51
+ If you are running concurrent tests and need genuinely independent groups, this is not supported today. Define the flag in SDK code with your own allocation logic instead.
52
+ :::
53
+
54
+ ## Feature flag versions
55
+
56
+ Each feature flag has a version number, starting at 1. The version forms part of the key the SDK uses to cache allocation decisions in the visitor's browser. Incrementing it discards those cached decisions, so every visitor is evaluated again on their next page load.
45
57
 
46
58
  ### What happens when you increment the version
47
59
 
48
- - **All visitors are re-allocated.** Every visitor currently allocated to this feature will be re-evaluated against the new version. A visitor who was in the control group may end up in a variant, and vice versa.
49
- - **Cached decisions are invalidated.** The SDK caches allocation decisions in browser storage using a key that includes the version. When the version changes, the old cache entry no longer matches, forcing a fresh evaluation on the next page load.
50
- - **This is irreversible.** You cannot decrement a version. Once incremented, the previous allocation assignments are lost.
60
+ - **Cached decisions are invalidated.** The SDK caches decisions under a key that includes the version, so the old entry no longer matches and the flag is treated as undecided.
61
+ - **Visitors are re-evaluated against the current weight.** Allocation is deterministic, so re-evaluating the same visitor against an unchanged weight produces the same result.
62
+ - **This is irreversible.** You cannot decrement a version.
63
+
64
+ :::note
65
+ Incrementing the version does not reshuffle visitors. It clears cached decisions and runs allocation again — with an unchanged weight, everyone lands where they were. Change the weight if you want visitors to move.
66
+ :::
51
67
 
52
68
  ### When to increment
53
69
 
54
- Increment the version when you have changed the weight or allocation and want all visitors — including those already allocated — to be re-evaluated from scratch.
70
+ Increment the version after changing the weight, when you want visitors who are already allocated to be re-evaluated against the new weight rather than keeping their cached decision.
55
71
 
56
72
  ### When not to increment
57
73
 
58
- If you only want changes to affect new visitors (those who haven't been allocated yet), update the weight without incrementing the version. Existing visitors will keep their current assignment.
74
+ If you want a weight change to affect only visitors who have not been allocated yet, change the weight without incrementing the version. Existing visitors keep their current allocation.
@@ -35,7 +35,7 @@ When building rules, you can reference these data sources:
35
35
 
36
36
  **Actions** — references to actions that have been triggered during the flow.
37
37
 
38
- **Features** — the state of feature flags in your project. Use this to branch based on which variant a visitor is assigned to.
38
+ **Feature flags** — the state of feature flags in your project. Use this to branch on whether a visitor is allocated to a flag.
39
39
 
40
40
  **Location** — properties of the visitor's current page URL, including pathname, search parameters, hostname, and hash.
41
41
 
package/dist/docs/mcp.md CHANGED
@@ -79,13 +79,13 @@ Add to `.cursor/mcp.json` in your project root:
79
79
  | `get_condition` / `list_conditions` | Read conditions |
80
80
  | `get_action` / `list_actions` | Read actions |
81
81
 
82
- ### Features
82
+ ### Feature flags
83
83
 
84
84
  | Tool | Description |
85
85
  | ---------------- | -------------------------------------------------- |
86
- | `create_feature` | Create a feature |
87
- | `get_feature` | Get feature details |
88
- | `list_features` | List features |
86
+ | `create_feature` | Create a feature flag |
87
+ | `get_feature` | Get feature flag details |
88
+ | `list_features` | List feature flags |
89
89
  | `update_feature` | Update name, description, enabled state, or weight |
90
90
 
91
91
  ### Analytics
@@ -6,7 +6,7 @@ import { Screenshot } from '../../components/Screenshot'
6
6
 
7
7
  # Reports
8
8
 
9
- Reports show analytics data for your project. Track how visitors interact with your experiences and features.
9
+ Reports show analytics data for your project. Track how visitors interact with your experiences and feature flags.
10
10
 
11
11
  <Screenshot
12
12
  route="/{orgSlug}/{projectId}/reports"
@@ -0,0 +1,129 @@
1
+ ---
2
+ layout: docs
3
+ ---
4
+
5
+ # Allocation and exposure
6
+
7
+ Reading a feature flag's bucket is what allocates a visitor to it. This page covers when that happens, how to observe it, and how to make sure a visitor is allocated before you report on it.
8
+
9
+ ## Registering a flag is not deciding it
10
+
11
+ The SDK loads every flag in your project at startup, but it does not allocate visitors then. A flag stays undecided until something reads its bucket. The first read runs the `decide` function, stores the result, and reports the decision.
12
+
13
+ That means you choose when a visitor is committed to a flag, simply by choosing when you read it.
14
+
15
+ ## Reading a bucket records an exposure
16
+
17
+ Because the first read is the decision, reading a bucket is the moment the visitor enters the test. Read every flag at startup and every visitor counts as exposed to every test, including ones they never reached.
18
+
19
+ :::warning
20
+ Avoid looping over every flag at startup to read its bucket. It commits every visitor to every test immediately and removes your ability to defer a decision until the data it depends on has arrived.
21
+ :::
22
+
23
+ Read a flag at the point the decision matters — after the cart loads, after the quote returns, after you know who the visitor is.
24
+
25
+ ## Inspecting flags without deciding them
26
+
27
+ `client.features.listStore` holds every registered flag. Each entry reports whether it has been decided yet, so you can inspect flags without committing anyone:
28
+
29
+ ```ts
30
+ for (const flag of client.features.listStore.getState()) {
31
+ console.log(flag.id, flag.isResolved)
32
+ }
33
+ ```
34
+
35
+ `getBucket()` behaves differently depending on that state:
36
+
37
+ - **Resolved** — returns `{ id, bucket }` synchronously. Reading it changes nothing.
38
+ - **Not resolved** — returns a promise. Awaiting it runs `decide` and commits the visitor.
39
+
40
+ `await` works for both, so you can treat them uniformly when you do intend to decide.
41
+
42
+ ## When `feature_decide` fires
43
+
44
+ A `feature_decide` event is emitted the first time a flag is decided for a visitor — and only then.
45
+
46
+ :::warning
47
+ On later page loads the decision is restored from browser storage, and **no event is emitted**. A returning visitor produces no `feature_decide` events at all, even though they are still allocated.
48
+
49
+ An integration built only on `feature_decide` will therefore report nothing for returning visitors.
50
+ :::
51
+
52
+ Use the right source for the question you are asking:
53
+
54
+ | Question | Use |
55
+ | --- | --- |
56
+ | What is this visitor allocated to right now? | `client.features.listStore` |
57
+ | Was a new decision just made? | `feature_decide` on `client.eventBus` |
58
+ | What decisions happened before I subscribed? | `client.events` |
59
+
60
+ ## Observing decisions
61
+
62
+ `listStore` updates whenever a flag resolves, whether it was restored from storage or decided just now. Watching it gives you the current picture at all times:
63
+
64
+ ```ts
65
+ const buckets = new Map<string, string | boolean>()
66
+
67
+ client.features.listStore.watch((flags) => {
68
+ for (const flag of flags) {
69
+ if (!flag.isResolved) continue
70
+ buckets.set(flag.id, flag.getBucket().bucket)
71
+ }
72
+ })
73
+ ```
74
+
75
+ Use `feature_decide` when you need to know a decision was *made*, rather than what the current value is — for example to send your own exposure event:
76
+
77
+ ```ts
78
+ client.eventBus.watch((event) => {
79
+ if (event.type !== 'feature_decide') return
80
+ analytics.track('Experiment exposure', {
81
+ flag: event.feature.id,
82
+ bucket: event.feature.bucket,
83
+ })
84
+ })
85
+ ```
86
+
87
+ If you subscribe after startup, earlier events are still available. `client.events` holds every event fired since the client initialised:
88
+
89
+ ```ts
90
+ const earlier = client.events
91
+ .getState()
92
+ .filter((entry) => entry.payload.type === 'feature_decide')
93
+ ```
94
+
95
+ ## Deciding before you report
96
+
97
+ To guarantee a flag is decided before a downstream event fires, await it first:
98
+
99
+ ```ts
100
+ const flag = client.features.getById('quote-experiment').getState()
101
+
102
+ if (flag) {
103
+ const { bucket } = await flag.getBucket()
104
+ trackViewQuote({ experiment: bucket })
105
+ }
106
+ ```
107
+
108
+ Awaiting `getBucket()` resolves the flag if it has not been decided, and returns the stored value if it has. Either way the bucket is known before the next line runs.
109
+
110
+ ## What Picked already reports
111
+
112
+ Before building your own tracking, note what the SDK sends already.
113
+
114
+ Every Picked analytics event carries a `feature_list` context describing the flags this visitor has resolved:
115
+
116
+ | Field | Description |
117
+ | --- | --- |
118
+ | `ab_feature` | Flag ID |
119
+ | `ab_name` | Flag name |
120
+ | `ab_key` | Version key, such as `v3` |
121
+ | `ab_bucket` | The resolved bucket |
122
+
123
+ Only resolved flags appear, so the context reflects what the visitor was actually exposed to at the time the event fired.
124
+
125
+ If the [Sentry plugin](https://www.npmjs.com/package/@picked/sentry) is installed, each decision also tags the Sentry scope as `picked.feature.<flag-id>` with the bucket as the value, so errors can be filtered by variant.
126
+
127
+ ## Preview mode
128
+
129
+ In [preview mode](/workspaces#preview) decisions are stored in session storage rather than local storage. They do not persist beyond the tab, and a preview visitor may be allocated differently from a production visitor. Treat preview allocations as disposable.
@@ -2,13 +2,31 @@
2
2
  layout: docs
3
3
  ---
4
4
 
5
- # Features
5
+ # Feature flags
6
6
 
7
- Define feature flags with a `decide` function that resolves to a bucket value, access results through framework hooks, and invalidate cached decisions by bumping the version.
7
+ Feature flags let you run A/B tests and roll changes out gradually. Manage them from the dashboard, or define them in SDK code when you need your own decision logic.
8
8
 
9
- ## Defining features
9
+ ## Where feature flags come from
10
10
 
11
- Define features when creating the Picked client by passing a `features` object. Each feature requires a unique identifier, a versioning key, a human-readable name, and a `decide` function:
11
+ Most flags are managed from the dashboard. The [dynamic experiences plugin](/sdk/plugins/dynamic-experiences) fetches your project configuration at runtime and registers every flag automatically — you do not declare them in code.
12
+
13
+ For a dashboard-managed flag, the SDK generates the definition:
14
+
15
+ | Field | Value |
16
+ | --- | --- |
17
+ | `id` | The flag's dashboard key |
18
+ | `key` | `v{version}` — for example `v3` |
19
+ | `name` | The flag's dashboard name |
20
+ | `enabled` | The dashboard **Enabled** toggle |
21
+ | `weight` | The dashboard **Weight**, 0–100 |
22
+ | `storage` | `local`, or `session` in [preview mode](/sdk/feature-allocation#preview-mode) |
23
+ | `decide` | Generated — allocates by comparing the visitor's stable value against `weight` |
24
+
25
+ The generated `decide` derives from the visitor ID and the weight alone, so a dashboard-managed flag cannot base its decision on your application's data. Define the flag in SDK code when you need that.
26
+
27
+ ## Defining flags in SDK code
28
+
29
+ Define flags when creating the Picked client by passing a `features` object. Use this when a decision depends on data only your application has. Each flag requires a unique identifier, a versioning key, a human-readable name, and a `decide` function:
12
30
 
13
31
  ```ts
14
32
  import { createClient } from '@picked/client'
@@ -38,7 +56,7 @@ const client = createClient({
38
56
  })
39
57
  ```
40
58
 
41
- Features can also be defined as factory functions for lazy initialization:
59
+ Feature flags can also be defined as factory functions for lazy initialization:
42
60
 
43
61
  ```ts
44
62
  features: {
@@ -50,19 +68,21 @@ features: {
50
68
  }
51
69
  ```
52
70
 
53
- ## How features work
71
+ ## How feature flags work
72
+
73
+ When a feature flag is registered, the SDK follows this execution order:
54
74
 
55
- When a feature is registered, the SDK follows this execution order:
75
+ 1. **Registration** — flags are registered with the client at startup. Registering does not allocate anyone.
76
+ 2. **Cache check** — the SDK looks in browser storage for a decision from a previous visit, keyed by the flag `id` and `key`. If one exists the flag starts out already resolved, which is why a returning visitor is allocated before anything reads the flag.
77
+ 3. **Lazy evaluation** — with no cached decision, `decide` runs the first time something reads the bucket.
78
+ 4. **Storage** — the resolved bucket is written to browser storage.
79
+ 5. **Event emission** — a `feature_decide` event fires, but only for a decision made during this page view. A decision restored in step 2 emits nothing.
56
80
 
57
- 1. **Registration**: Features are registered to the Picked client during initialization
58
- 2. **Cache Check**: The SDK checks browser storage (localStorage or sessionStorage) for a previously resolved value using the feature `id` and `key`
59
- 3. **Lazy Evaluation**: If no cached value exists, the `decide` function will be called the first time the feature is accessed
60
- 4. **Storage**: Once resolved, the bucket value is persisted to browser storage for consistency across page loads
61
- 5. **Event Emission**: A `feature_decide` event is fired on the event bus when a feature is resolved for the first time
81
+ See [Allocation and exposure](/sdk/feature-allocation) for what this means when tracking exposures.
62
82
 
63
83
  ## URL-based overrides
64
84
 
65
- You can override feature decisions via URL search parameters for testing purposes:
85
+ You can override feature flag decisions via URL search parameters for testing purposes:
66
86
 
67
87
  ```
68
88
  https://example.com?picked-feature=my-feature:true
@@ -76,11 +96,11 @@ https://example.com?picked-feature=my-feature:true&picked-feature=homepage-varia
76
96
 
77
97
  The format is `?picked-feature=<feature-id>:<bucket-value>`.
78
98
 
79
- This is useful for QA testing specific feature variants without modifying code. The override is persisted in session storage and will be cleared when the browser tab is closed.
99
+ This is useful for QA testing specific bucket values without modifying code. The override is persisted in session storage and will be cleared when the browser tab is closed.
80
100
 
81
- ## Accessing features
101
+ ## Accessing feature flags
82
102
 
83
- Once features are defined, you can access their resolved bucket values in your application code. The SDK provides framework-specific hooks and a framework-agnostic event bus for subscribing to feature decisions.
103
+ Once feature flags are defined, you can read their resolved bucket values in your application code. The SDK provides framework hooks and a framework-agnostic event bus.
84
104
 
85
105
  :::code-group
86
106
 
@@ -91,49 +111,67 @@ const client = createClient({
91
111
  /* Create client options here */
92
112
  })
93
113
 
94
- client.eventBus.subscribe('feature_decide', ({ feature }) => {
95
- if (feature.id === 'my-feature') {
96
- console.log(feature) // { id: 'my-feature', bucket: 'control' }
114
+ client.eventBus.watch((event) => {
115
+ if (event.type === 'feature_decide' && event.feature.id === 'my-feature') {
116
+ console.log(event.feature) // { id: 'my-feature', key: 'v1', bucket: 'control' }
97
117
  }
98
118
  })
99
119
  ```
100
120
 
101
- ```ts [Svelte]
121
+ ```svelte [Svelte]
102
122
  <script lang="ts">
103
- import { getFeature } from '@picked/svelte/hooks'
104
- // Returns an Effector store containing the feature resolver
105
- const myFeature = getFeature('my-feature')
123
+ import { getFeatureResult } from '@picked/svelte/hooks'
124
+
125
+ // A store holding { id, bucket }, or undefined until the flag resolves
126
+ const result = getFeatureResult('my-feature')
106
127
  </script>
107
- <!-- $myFeature is a reactive Effector store (see Effector docs for details) -->
108
- {#if $myFeature()}
109
- <p>My feature is enabled</p>
110
- {:else}
111
- <p>My feature is disabled</p>
128
+
129
+ {#if $result?.bucket === 'control'}
130
+ <p>Control</p>
131
+ {:else if $result?.bucket === 'variant-a'}
132
+ <p>Variant A</p>
112
133
  {/if}
113
134
  ```
114
135
 
115
- ```ts [React]
116
- import { useFeature } from '@picked/react/hooks'
136
+ ```tsx [React]
137
+ import { useFeatureResult } from '@picked/react/hooks'
117
138
 
118
139
  function MyComponent() {
119
- // Returns the resolved bucket value for 'my-feature'
120
- const myFeature = useFeature('my-feature')
140
+ // { id, bucket }, or undefined until the flag resolves
141
+ const result = useFeatureResult('my-feature')
121
142
 
122
143
  return (
123
144
  <div>
124
- {myFeature === 'control' && <p>Control variant</p>}
125
- {myFeature === 'variant-a' && <p>Variant A</p>}
145
+ {result?.bucket === 'control' && <p>Control</p>}
146
+ {result?.bucket === 'variant-a' && <p>Variant A</p>}
126
147
  </div>
127
148
  )
128
149
  }
129
-
130
150
  ```
131
151
 
132
152
  :::
133
153
 
134
- ## Using features in experience conditions
154
+ ### Choosing an accessor
155
+
156
+ Accessors differ in what they return, and in whether reading one resolves the flag. Resolving is what commits a visitor to a bucket and reports the decision — see [Allocation and exposure](/sdk/feature-allocation).
157
+
158
+ | API | Returns | Resolves the flag? |
159
+ | --- | --- | --- |
160
+ | `useFeature` / `getFeature` | `() => Promise<bucket>` | Only when you call the returned function |
161
+ | `useFeatureResult` / `getFeatureResult` | `{ id, bucket }`, `undefined` until resolved | Yes, as soon as the component renders |
162
+ | `useFeatureEnabled` / `getFeatureEnabled` | `boolean \| undefined` — the dashboard **Enabled** flag | No |
163
+ | `client.features.listStore` | Every registered flag, each with an `isResolved` flag | No |
164
+ | `client.features.getById(id)` | A store holding a single flag | No |
165
+
166
+ :::warning
167
+ `useFeatureResult` and `getFeatureResult` resolve the flag as soon as the component renders, committing the visitor to a bucket at that moment.
168
+
169
+ If the decision should wait for data you do not have yet — a cart, a quote, a signed-in profile — use `useFeature` or `getFeature` and call the function they return once that data arrives.
170
+ :::
171
+
172
+ ## Using feature flags in experience conditions
135
173
 
136
- Features can be used with experience conditions via JSON logic:
174
+ Feature flags can be used with experience conditions via JSON logic:
137
175
 
138
176
  ```ts
139
177
  const myExperience = createExperience({
@@ -144,7 +182,7 @@ const myExperience = createExperience({
144
182
  '==': [
145
183
  {
146
184
  invoke: {
147
- var: 'features.summer-sale', // Reference feature by ID
185
+ var: 'features.summer-sale', // Reference the flag by ID
148
186
  },
149
187
  },
150
188
  true, // Check if bucket equals true
@@ -155,14 +193,21 @@ const myExperience = createExperience({
155
193
  })
156
194
  ```
157
195
 
158
- ## Listening to feature decisions
196
+ The ID in `features.<id>` is the flag's **Key** from the dashboard — the same value shown on the flag detail page.
197
+
198
+ Evaluating a condition reads the bucket, so a flag referenced by an experience condition is allocated at the moment that condition runs.
199
+
200
+ ## Listening to feature flag decisions
159
201
 
160
- Subscribe to the `feature_decide` event to track when features are resolved:
202
+ Subscribe to the `feature_decide` event to track when flags are resolved:
161
203
 
162
204
  ```ts
163
- client.eventBus.subscribe('feature_decide', ({ feature }) => {
164
- console.log(`Feature "${feature.id}" resolved to bucket:`, feature.bucket)
165
- // Example output: Feature "summer-sale" resolved to bucket: true
205
+ client.eventBus.watch((event) => {
206
+ if (event.type !== 'feature_decide') return
207
+
208
+ const { feature } = event
209
+ console.log(`Flag "${feature.id}" resolved to bucket:`, feature.bucket)
210
+ // Example output: Flag "summer-sale" resolved to bucket: true
166
211
 
167
212
  // Send to analytics
168
213
  analytics.track('Feature Decision', {
@@ -174,25 +219,33 @@ client.eventBus.subscribe('feature_decide', ({ feature }) => {
174
219
 
175
220
  ## Versioning and cache invalidation
176
221
 
177
- Feature decisions are cached in browser storage (localStorage or sessionStorage) using a key derived from the feature ID and version. This ensures visitors see a consistent experience across page loads.
222
+ Feature flag decisions are cached in browser storage (localStorage, or sessionStorage in preview) under a key derived from the flag ID and version, so a visitor keeps the same decision across page loads.
223
+
224
+ :::warning
225
+ Bucket values that are strings, such as `'variant-a'`, are not yet restored correctly from storage — the visitor is treated as unallocated on their next page load. Boolean bucket values, which includes every flag managed from the dashboard, are unaffected. Tracked in PICK-1574.
226
+ :::
178
227
 
179
228
  ### How versioning works
180
229
 
181
- When you create a feature in the dashboard, it starts at version 1. The SDK uses the version to build the cache key — for example, a feature at version 3 uses the key `v3`. This version is also included in the allocation hash, so it directly affects which variant a visitor is assigned to.
230
+ When you create a feature flag in the dashboard, it starts at version 1. The SDK uses the version to build the cache key — for example, a flag at version 3 caches under `v3`.
231
+
232
+ The version affects **caching only**. It is not part of the allocation calculation, which for dashboard-managed flags derives from the visitor ID and the flag's weight.
182
233
 
183
234
  ### What happens when the version is incremented
184
235
 
185
- When you increment a feature's version in the dashboard:
236
+ When you increment a flag's version in the dashboard:
186
237
 
187
- 1. **Cache keys change.** The old cache entry (e.g., `v3`) no longer matches the new key (`v4`), so the SDK treats the feature as undecided.
188
- 2. **All visitors are re-allocated.** The allocation hash includes the version, so every visitor gets a new hash value and may be assigned to a different variant.
189
- 3. **The `decide` function runs again.** On the next page load, the SDK calls `decide()` fresh and caches the new result.
238
+ 1. **Cache keys change.** The old cache entry (e.g., `v3`) no longer matches the new key (`v4`), so the SDK treats the flag as undecided.
239
+ 2. **The `decide` function runs again.** On the next page load, the SDK calls `decide()` fresh and caches the new result.
240
+ 3. **Visitors are re-evaluated, not reshuffled.** For dashboard-managed flags allocation is deterministic, so re-evaluating the same visitor against an unchanged weight produces the same bucket.
190
241
 
191
- > **Warning:** Incrementing the version re-allocates all visitors, not just new ones. This is irreversible. Only increment when you intentionally want to reset all assignments — for example, after changing traffic allocation weights.
242
+ :::note
243
+ Incrementing the version clears cached decisions and runs allocation again. It does not randomise visitors — with an unchanged weight, everyone lands where they were. Increment it after changing a weight, so visitors who already hold a cached decision are re-evaluated against the new one.
244
+ :::
192
245
 
193
246
  ### SDK `key` vs dashboard version
194
247
 
195
- If you define features statically in the SDK (not loaded from the dashboard), use the `key` field for manual versioning:
248
+ If you define feature flags statically in the SDK (not loaded from the dashboard), use the `key` field for manual versioning:
196
249
 
197
250
  ```ts
198
251
  features: {
@@ -203,10 +256,11 @@ features: {
203
256
  }
204
257
  ```
205
258
 
206
- For features managed through the dashboard, versioning is handled automatically — the dashboard appends the version number to the cache key used by the SDK.
259
+ For flags managed through the dashboard, versioning is handled automatically — the dashboard appends the version number to the cache key used by the SDK.
207
260
 
208
261
  ## Best practices
209
262
 
210
263
  - **Use `session` storage for temporary tests**: Set `storage: 'session'` for short-lived experiments that shouldn't persist across browser sessions
211
- - **Keep `decide` functions fast**: The function blocks experience rendering, so avoid heavy computations or slow network calls
212
- - **Return consistent types**: Don't mix boolean and string returns for the same feature - pick one type and stick with it
264
+ - **Keep `decide` functions fast**: Anything awaiting the flag — an experience condition, a component reading the result — waits for `decide` to finish, so avoid slow network calls inside it
265
+ - **Allocate when the decision matters**: Defer reading a flag until the data it depends on has arrived, rather than reading every flag at startup. See [Allocation and exposure](/sdk/feature-allocation)
266
+ - **Return consistent types**: Don't mix boolean and string returns for the same flag - pick one type and stick with it
@@ -80,4 +80,10 @@ const picked = createClient({
80
80
  })
81
81
  ```
82
82
 
83
+ :::warning
84
+ A precondition or condition that references a flag reads its bucket, which allocates the visitor at that moment. Preconditions run at startup, so a flag referenced there is allocated for every visitor before anything else happens — including visitors who never reach the experience it gates.
85
+
86
+ See [Allocation and exposure](/sdk/feature-allocation) before referencing a flag in a precondition.
87
+ :::
88
+
83
89
  See [conditions](./conditions.md) for more detail
@@ -4,7 +4,7 @@ layout: docs
4
4
 
5
5
  # Dynamic Experiences Plugin
6
6
 
7
- A plugin that fetches your project configuration from the Picked API at runtime, letting you manage experiences, features, steps, fields, and conditions entirely from the [dashboard](/experiences).
7
+ A plugin that fetches your project configuration from the Picked API at runtime, letting you manage experiences, feature flags, steps, fields, and conditions entirely from the [dashboard](/experiences).
8
8
 
9
9
  ## Setup Plugin
10
10
 
@@ -32,27 +32,27 @@ Unlike [createExperiencePlugin](./create-experience.md), you do not define exper
32
32
 
33
33
  When the client starts, the plugin resolves your project configuration using a three-tier strategy:
34
34
 
35
- 1. **Preview mode** — When you [enter preview mode from the dashboard](/workspaces#preview), the plugin fetches fresh config from the API. Feature decisions use session storage so they are not persisted beyond the current tab.
35
+ 1. **Preview mode** — When you [enter preview mode from the dashboard](/workspaces#preview), the plugin fetches fresh config from the API. Feature flag decisions use session storage so they are not persisted beyond the current tab.
36
36
 
37
37
  2. **Build-time config** — If `projectConfig` was passed as a plugin option, or the [Vite Plugin](/vite-plugin) injected config at build time, the plugin uses that config with no network request.
38
38
 
39
39
  3. **Runtime fetch** — Otherwise, the plugin fetches config from the API when the client starts.
40
40
 
41
- Once resolved, the plugin registers all features, conditions, fields, steps, and experiences with the client. Experiences then initialize according to their [conditions](/sdk/conditions) and [target selectors](/sdk/experiences).
41
+ Once resolved, the plugin registers all feature flags, conditions, fields, steps, and experiences with the client. Experiences then initialize according to their [conditions](/sdk/conditions) and [target selectors](/sdk/experiences).
42
42
 
43
43
  :::note
44
44
  The [Vite Plugin](/vite-plugin) eliminates the runtime API request in production by embedding your project config at build time. This is the recommended setup for Vite-based applications.
45
45
  :::
46
46
 
47
- ## Feature Allocation
47
+ ## Feature flag allocation
48
48
 
49
- Each [feature](/sdk/features) in your project has an `enabled` state and a `weight` (0–100) that controls the percentage of traffic allocated to it. The plugin uses a deterministic hash of the user's session ID to produce a stable allocation value. A user whose value falls below the feature weight is allocated to that feature — the same user always gets the same result.
49
+ Each [feature flag](/sdk/features) in your project has an `enabled` state and a `weight` (0–100) that controls the percentage of traffic allocated to it. The plugin uses a deterministic hash of the user's session ID to produce a stable allocation value. A user whose value falls below the flag's weight is allocated to that flag — the same user always gets the same result.
50
50
 
51
- Feature decisions are cached in `localStorage` by default, or `sessionStorage` when in [preview mode](#preview-mode).
51
+ Feature flag decisions are cached in `localStorage` by default, or `sessionStorage` when in [preview mode](#preview-mode).
52
52
 
53
53
  ## Preview Mode
54
54
 
55
55
  When you [enter preview mode from the dashboard](/workspaces#preview), the SDK receives a preview token and activates preview mode:
56
56
 
57
57
  - The plugin fetches fresh config from the API using the token, bypassing any build-time or cached config
58
- - Feature decisions use session storage, so closing the tab resets them
58
+ - Feature flag decisions use session storage, so closing the tab resets them
@@ -4,7 +4,7 @@ layout: docs
4
4
 
5
5
  # Vite Plugin
6
6
 
7
- `@picked/vite-plugin-picked` integrates Picked into your Vite project. It fetches your project configuration at build time and injects it via Vite's `define`, eliminating the runtime API request. During development it also serves a launcher page for previewing experiences with feature overrides.
7
+ `@picked/vite-plugin-picked` integrates Picked into your Vite project. It fetches your project configuration at build time and injects it via Vite's `define`, eliminating the runtime API request. During development it also serves a launcher page for previewing experiences with feature flag overrides.
8
8
 
9
9
  ## Installation
10
10
 
@@ -57,9 +57,9 @@ When a preview token is present at runtime, the SDK ignores the build-time confi
57
57
 
58
58
  During development, the plugin serves an HTML page at `/` that lets you:
59
59
 
60
- - See all features in your project with their current status
61
- - Toggle features on/off for local testing
62
- - Preview experiences with specific feature overrides
60
+ - See all feature flags in your project with their current status
61
+ - Toggle feature flags on/off for local testing
62
+ - Preview experiences with specific feature flag overrides
63
63
 
64
64
  After the dev server starts, the launcher URL appears alongside Vite's native output:
65
65
 
@@ -16,7 +16,7 @@ A workspace is a version of your project's configuration. Use workspaces to stag
16
16
 
17
17
  ## How workspaces work
18
18
 
19
- Each project has a workspace that holds your experiences, features, and entity configurations. When you make changes in the dashboard — editing a flow, updating a feature, or modifying an entity — those changes exist in the workspace until you publish.
19
+ Each project has a workspace that holds your experiences, feature flags, and entity configurations. When you make changes in the dashboard — editing a flow, updating a feature flag, or modifying an entity — those changes exist in the workspace until you publish.
20
20
 
21
21
  A workspace is in one of three states:
22
22
 
@@ -30,7 +30,7 @@ Preview your workspace to see how changes look before publishing.
30
30
 
31
31
  1. Click **Preview** in the workspace toolbar.
32
32
  2. Enter the URL of your site.
33
- 3. Optionally override individual features — set each to **Default**, **On**, or **Off**.
33
+ 3. Optionally override individual feature flags — set each to **Default**, **On**, or **Off**.
34
34
  4. Click **Open Preview**.
35
35
 
36
36
  Your site opens in a new tab with the unpublished workspace applied. Preview uses query parameters to pass the workspace state to the SDK, so visitors on your live site are unaffected.
@@ -59,7 +59,7 @@ The publish modal shows a side-by-side change preview comparing the current work
59
59
  renderHeight={579}
60
60
  />
61
61
 
62
- The preview groups changes by entity type — experiences, features, steps, fields, actions, and conditions. Each row shows whether the entity was **added**, **removed**, or **modified**. For modifications, expand the row to see which properties changed.
62
+ The preview groups changes by entity type — experiences, feature flags, steps, fields, actions, and conditions. Each row shows whether the entity was **added**, **removed**, or **modified**. For modifications, expand the row to see which properties changed.
63
63
 
64
64
  When the change preview includes breaking changes — for example, removing a field that other steps still reference — a banner highlights the breaking entries above the diff so you can reconsider before publishing.
65
65
 
@@ -67,7 +67,7 @@ The first publish of a workspace has no previous snapshot to compare against, so
67
67
 
68
68
  ## Unpublished changes
69
69
 
70
- The workspace tracks whether any changes have been made since the last publish. If you create or update an experience, feature, or entity after the last publish, the toolbar shows a warning badge indicating unpublished changes.
70
+ The workspace tracks whether any changes have been made since the last publish. If you create or update an experience, feature flag, or entity after the last publish, the toolbar shows a warning badge indicating unpublished changes.
71
71
 
72
72
  ## Workspace settings
73
73
 
package/dist/esm/index.js CHANGED
@@ -5,7 +5,7 @@ import { a as i, c as a, d as o, f as s, i as c, l, m as u, n as d, o as f, r as
5
5
  import { a as _, i as v, r as ee, s as y, t as b } from "../dom-BwmTHeT7.js";
6
6
  import { l as x, n as S, r as C, u as w } from "../experience-instance-DOJShRk5.js";
7
7
  import { i as T, n as E, r as D, t as O } from "../storage-1MW3-_As.js";
8
- import { n as te, r as ne } from "../api-CrJ2Nedc.js";
8
+ import { n as te, r as ne } from "../api-DQ1DqG_F.js";
9
9
  import { t as re } from "../id-Bo4RBeOs.js";
10
10
  import { n as ie, r as ae, t as oe } from "../inert-script-report-B_bMPRzp.js";
11
11
  import { attach as k, combine as A, createApi as j, createDomain as M, createEffect as N, createEvent as P, createStore as F, sample as I } from "effector";
@@ -1826,7 +1826,15 @@ var Ht = class {
1826
1826
  async function $(e) {
1827
1827
  if (!("document" in globalThis)) return;
1828
1828
  let t = "application/picked-module", n = "data-picked-hydrated";
1829
- function r(e, t) {
1829
+ function r(e) {
1830
+ try {
1831
+ Function(e.textContent);
1832
+ } catch (t) {
1833
+ return t instanceof SyntaxError ? (console.error("[picked] Skipped a rehydrated inline script that failed to parse.", t), e.setAttribute(n, ""), !0) : !1;
1834
+ }
1835
+ return !1;
1836
+ }
1837
+ function i(e, t) {
1830
1838
  let r = document.createElement("script");
1831
1839
  for (let t of Array.from(e.attributes)) t.name !== "type" && r.setAttribute(t.name, t.value);
1832
1840
  t && r.setAttribute("type", t), r.setAttribute(n, ""), e.src ? r.async = !1 : r.textContent = e.textContent;
@@ -1835,11 +1843,13 @@ async function $(e) {
1835
1843
  }) : null;
1836
1844
  return e.src ? e.replaceWith(r) : (globalThis.__pickedEmbedScriptRoot = e.getRootNode(), e.replaceWith(r), globalThis.__pickedEmbedScriptRoot = null), i;
1837
1845
  }
1838
- let i = Array.from(e.querySelectorAll(`script[type="application/picked-javascript"]:not([${n}]), script[type="${t}"]:not([${n}])`)).filter((e) => e instanceof HTMLScriptElement);
1839
- for (let e of i) {
1846
+ let a = Array.from(e.querySelectorAll(`script[type="application/picked-javascript"]:not([${n}]), script[type="${t}"]:not([${n}])`)).filter((e) => e instanceof HTMLScriptElement);
1847
+ for (let e of a) {
1840
1848
  if (!e.isConnected) continue;
1841
- let n = r(e, e.getAttribute("type") === t ? "module" : null);
1842
- n && await n;
1849
+ let n = e.getAttribute("type") === t ? "module" : null;
1850
+ if (!e.src && n === null && r(e)) continue;
1851
+ let a = i(e, n);
1852
+ a && await a;
1843
1853
  }
1844
1854
  }
1845
1855
  function Kt() {
@@ -1,3 +1,3 @@
1
- import { i as e } from "../../../api-CrJ2Nedc.js";
2
- import { n as t, r as n, t as r } from "../../../plugin-mLEsguQ4.js";
1
+ import { i as e } from "../../../api-DQ1DqG_F.js";
2
+ import { n as t, r as n, t as r } from "../../../plugin-EPx6sE_l.js";
3
3
  export { e as createClientHeaders, r as dynamicExperiencesPlugin, t as fetchExperienceContent, n as fetchProject };
@@ -1,5 +1,5 @@
1
1
  import { a as e, c as t, i as n, o as r, s as i, t as a, u as o } from "../../experience-instance-DOJShRk5.js";
2
- import { i as s, n as c } from "../../plugin-mLEsguQ4.js";
2
+ import { i as s, n as c } from "../../plugin-EPx6sE_l.js";
3
3
  import { attach as l, createEffect as u, createEvent as d, createStore as f, sample as p } from "effector";
4
4
  //#region src/server/serialize.ts
5
5
  var m = 1e4;
@@ -1,5 +1,5 @@
1
1
  import "./logger-DMN6TxJJ.js";
2
- import { t as e } from "./api-CrJ2Nedc.js";
2
+ import { t as e } from "./api-DQ1DqG_F.js";
3
3
  import { attach as t } from "effector";
4
4
  //#region src/plugins/dynamic-experiences/hash.ts
5
5
  function n(e) {
@@ -1 +1 @@
1
- require("./logger-CSTvAyyB.cjs");const e=require("./api-BQRx-Qnj.cjs");let t=require("effector");function n(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return t>>>0}function r(e){return n(e)%100}function i(e,t){return t<=0?!1:t>=100?!0:e<t}function a(e){return typeof e==`object`&&!!e&&`features`in e&&Array.isArray(e.features)}function o(e,t){if(Array.isArray(t.conditions))for(let n of t.conditions)e.registerCondition(n)}function s(e,t){e.registerExperience({id:t.id,key:t.key,name:t.name,targets:t.targets,nodes:t.nodes,edges:t.edges,condition:t.condition,initializeOpen:t.initializeOpen,componentName:t.componentName})}function c(e,t){if(Array.isArray(t.fields))for(let n of t.fields)e.registerField(n)}function l(e,t){if(!Array.isArray(t.steps))return;let n=new Map(t.fields.map(e=>[e.id,e.key]));for(let r of t.steps){let t=[];for(let e of r.fieldIds??[]){let i=n.get(e);if(i===void 0){`${r.key}${e}`;continue}t.push(i)}let i=r.layoutContentId?e.contents.getById(r.layoutContentId):null;e.registerStep({id:r.id,key:r.key,name:r.name,fieldKeys:t,layoutName:r.layoutName,...r.layoutContentId!==void 0&&{layoutContentId:r.layoutContentId,layoutContentStore:i}})}}function u(e,t){if(Array.isArray(t.experiences))for(let n of t.experiences)s(e,n)}function d(e,t,n){m(e,t,n.isPreview,n.sessionId),o(e,t),c(e,t),l(e,t),u(e,t)}function f(e){let t=e.searchParams[`preview-token`];if(t&&t.length>0)return t[0]}function p(e){let t=new Set,n=e.searchParams.feature;if(!n)return t;for(let e of n){let n=e.indexOf(`:`);n>0&&t.add(e.substring(0,n))}return t}function m(e,t,n,i){let a=p(e),o=r(i);for(let r of t.features)a.has(r.id)||h(e,r,n,o)}function h(e,t,n,r){e.registerFeature(t.id,{key:`v${t.version}`,name:t.name,enabled:t.enabled,weight:t.weight,storage:n?`session`:`local`,decide:()=>t.enabled?i(r,t.weight):!1})}function g(e){try{let t=new URL(e).hostname;return t===`localhost`||t===`127.0.0.1`||t===`::1`}catch{return!1}}function _(e){if(typeof e!=`object`||!e||!(`cause`in e))return!1;let{cause:t}=e;return typeof t!=`object`||!t||!(`code`in t)?!1:t.code===`ECONNREFUSED`}async function v(t,n,r){let i=r?.previewToken?`projects/${n}?preview_token=${encodeURIComponent(r.previewToken)}`:`projects/${n}`,o;try{o=await e.t(t,i,r?.headers)}catch(e){return g(t)&&_(e),null}if(!o.ok)return`${o.status.toString()}`,null;let s;try{s=await o.json()}catch{return null}return a(s)?s:null}function y(e){return typeof e!=`object`||!e||!(`experienceId`in e)||!(`content`in e)?!1:Array.isArray(e.content)}async function b(t,n,r,i){let a=i?.previewToken?`projects/${n}/experiences/${r}/content?preview_token=${encodeURIComponent(i.previewToken)}`:`projects/${n}/experiences/${r}/content`,o;try{o=await e.t(t,a,i?.headers,i?.signal)}catch(e){return g(t)&&_(e)||`${r}`,null}if(!o.ok)return`${r}${o.status.toString()}`,null;let s;try{s=await o.json()}catch{return`${r}`,null}return y(s)?s:(`${r}`,null)}function x(e,t){for(let n of t.content)e.registerContent({id:n.id,contentModelKey:n.contentModelKey,data:n.data})}function S(e){if(typeof e!=`object`||!e||!(`projectConfig`in e)||!(`experienceContent`in e)||!(`manifestMetadata`in e))return!1;let{experienceContent:t}=e;return typeof t==`function`}async function C(){try{let e=await import(`virtual:picked/data`);return S(e)?e:null}catch{return null}}function w(e,t,n){return r=>b(e,t,r.id,n?{previewToken:n}:void 0)}function T(e,t){return n=>e(n,t?{previewToken:t}:void 0)}function E(e){return(t,n)=>e.experienceContent(t,n)}function D(e,t){let n=new Map;return(r,i)=>{let a=n.get(r.id);if(a)return a;let o=(async()=>{try{let n=await t(r,i);return n&&x(e,n),n}finally{n.delete(r.id)}})();return n.set(r.id,o),o}}function O(e,t){let n=new Set(t&&Array.isArray(t.experiences)?t.experiences.map(e=>e.id):[]);return(t,r)=>n.has(t.id)?e(t,r):Promise.resolve(null)}async function k(e){let{client:t,apiUrl:n,options:r}=e,i=f(t),a=!!i,o=r?.projectConfig??null,s=r?.getContent?T(r.getContent,i):null,c=null;if(i)return o??=await v(n,t.projectId,{previewToken:i}),s??=w(n,t.projectId,i),{config:o,contentLoader:s,dataSource:c,isPreview:a};if(o&&s)return{config:o,contentLoader:s,dataSource:c,isPreview:a};let l=await C();return l?(o??=l.projectConfig,s??=E(l),c=l.manifestMetadata,{config:o,contentLoader:s,dataSource:c,isPreview:a}):(o??=await v(n,t.projectId),s??=w(n,t.projectId),{config:o,contentLoader:s,dataSource:c,isPreview:a})}function A(e){return{name:`dynamic-experiences`,setup:n=>{let r=e?.apiUrl??n.apiUrl;return{onStart:(0,t.attach)({source:n.session.store.map(e=>e.id),effect:async t=>{let{config:i,contentLoader:a,dataSource:o,isPreview:s}=await k({client:n,apiUrl:r,options:e});a&&(n.contentLoader=D(n,O(a,i))),n.dataSource=o,i&&(n.previewEmbedderOrigins=i.previewEmbedderOrigins??null,d(n,i,{isPreview:s,sessionId:t}))}})}}}}Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return A}});
1
+ require("./logger-CSTvAyyB.cjs");const e=require("./api-B9koex39.cjs");let t=require("effector");function n(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return t>>>0}function r(e){return n(e)%100}function i(e,t){return t<=0?!1:t>=100?!0:e<t}function a(e){return typeof e==`object`&&!!e&&`features`in e&&Array.isArray(e.features)}function o(e,t){if(Array.isArray(t.conditions))for(let n of t.conditions)e.registerCondition(n)}function s(e,t){e.registerExperience({id:t.id,key:t.key,name:t.name,targets:t.targets,nodes:t.nodes,edges:t.edges,condition:t.condition,initializeOpen:t.initializeOpen,componentName:t.componentName})}function c(e,t){if(Array.isArray(t.fields))for(let n of t.fields)e.registerField(n)}function l(e,t){if(!Array.isArray(t.steps))return;let n=new Map(t.fields.map(e=>[e.id,e.key]));for(let r of t.steps){let t=[];for(let e of r.fieldIds??[]){let i=n.get(e);if(i===void 0){`${r.key}${e}`;continue}t.push(i)}let i=r.layoutContentId?e.contents.getById(r.layoutContentId):null;e.registerStep({id:r.id,key:r.key,name:r.name,fieldKeys:t,layoutName:r.layoutName,...r.layoutContentId!==void 0&&{layoutContentId:r.layoutContentId,layoutContentStore:i}})}}function u(e,t){if(Array.isArray(t.experiences))for(let n of t.experiences)s(e,n)}function d(e,t,n){m(e,t,n.isPreview,n.sessionId),o(e,t),c(e,t),l(e,t),u(e,t)}function f(e){let t=e.searchParams[`preview-token`];if(t&&t.length>0)return t[0]}function p(e){let t=new Set,n=e.searchParams.feature;if(!n)return t;for(let e of n){let n=e.indexOf(`:`);n>0&&t.add(e.substring(0,n))}return t}function m(e,t,n,i){let a=p(e),o=r(i);for(let r of t.features)a.has(r.id)||h(e,r,n,o)}function h(e,t,n,r){e.registerFeature(t.id,{key:`v${t.version}`,name:t.name,enabled:t.enabled,weight:t.weight,storage:n?`session`:`local`,decide:()=>t.enabled?i(r,t.weight):!1})}function g(e){try{let t=new URL(e).hostname;return t===`localhost`||t===`127.0.0.1`||t===`::1`}catch{return!1}}function _(e){if(typeof e!=`object`||!e||!(`cause`in e))return!1;let{cause:t}=e;return typeof t!=`object`||!t||!(`code`in t)?!1:t.code===`ECONNREFUSED`}async function v(t,n,r){let i=r?.previewToken?`projects/${n}?preview_token=${encodeURIComponent(r.previewToken)}`:`projects/${n}`,o;try{o=await e.t(t,i,r?.headers)}catch(e){return g(t)&&_(e),null}if(!o.ok)return`${o.status.toString()}`,null;let s;try{s=await o.json()}catch{return null}return a(s)?s:null}function y(e){return typeof e!=`object`||!e||!(`experienceId`in e)||!(`content`in e)?!1:Array.isArray(e.content)}async function b(t,n,r,i){let a=i?.previewToken?`projects/${n}/experiences/${r}/content?preview_token=${encodeURIComponent(i.previewToken)}`:`projects/${n}/experiences/${r}/content`,o;try{o=await e.t(t,a,i?.headers,i?.signal)}catch(e){return g(t)&&_(e)||`${r}`,null}if(!o.ok)return`${r}${o.status.toString()}`,null;let s;try{s=await o.json()}catch{return`${r}`,null}return y(s)?s:(`${r}`,null)}function x(e,t){for(let n of t.content)e.registerContent({id:n.id,contentModelKey:n.contentModelKey,data:n.data})}function S(e){if(typeof e!=`object`||!e||!(`projectConfig`in e)||!(`experienceContent`in e)||!(`manifestMetadata`in e))return!1;let{experienceContent:t}=e;return typeof t==`function`}async function C(){try{let e=await import(`virtual:picked/data`);return S(e)?e:null}catch{return null}}function w(e,t,n){return r=>b(e,t,r.id,n?{previewToken:n}:void 0)}function T(e,t){return n=>e(n,t?{previewToken:t}:void 0)}function E(e){return(t,n)=>e.experienceContent(t,n)}function D(e,t){let n=new Map;return(r,i)=>{let a=n.get(r.id);if(a)return a;let o=(async()=>{try{let n=await t(r,i);return n&&x(e,n),n}finally{n.delete(r.id)}})();return n.set(r.id,o),o}}function O(e,t){let n=new Set(t&&Array.isArray(t.experiences)?t.experiences.map(e=>e.id):[]);return(t,r)=>n.has(t.id)?e(t,r):Promise.resolve(null)}async function k(e){let{client:t,apiUrl:n,options:r}=e,i=f(t),a=!!i,o=r?.projectConfig??null,s=r?.getContent?T(r.getContent,i):null,c=null;if(i)return o??=await v(n,t.projectId,{previewToken:i}),s??=w(n,t.projectId,i),{config:o,contentLoader:s,dataSource:c,isPreview:a};if(o&&s)return{config:o,contentLoader:s,dataSource:c,isPreview:a};let l=await C();return l?(o??=l.projectConfig,s??=E(l),c=l.manifestMetadata,{config:o,contentLoader:s,dataSource:c,isPreview:a}):(o??=await v(n,t.projectId),s??=w(n,t.projectId),{config:o,contentLoader:s,dataSource:c,isPreview:a})}function A(e){return{name:`dynamic-experiences`,setup:n=>{let r=e?.apiUrl??n.apiUrl;return{onStart:(0,t.attach)({source:n.session.store.map(e=>e.id),effect:async t=>{let{config:i,contentLoader:a,dataSource:o,isPreview:s}=await k({client:n,apiUrl:r,options:e});a&&(n.contentLoader=D(n,O(a,i))),n.dataSource=o,i&&(n.previewEmbedderOrigins=i.previewEmbedderOrigins??null,d(n,i,{isPreview:s,sessionId:t}))}})}}}}Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return A}});
@@ -22,6 +22,12 @@ declare global {
22
22
  * inside a shadow tree, each inline script's own root is published on `globalThis.__pickedEmbedScriptRoot`
23
23
  * while it runs, so shadow-scoped page scripts read `window.__pickedEmbedScriptRoot` to find their own root.
24
24
  *
25
+ * Classic inline scripts are pre-parsed with the `Function` constructor and skipped only when that
26
+ * throws a `SyntaxError`, so a body that would blank the experience on insertion is logged and left
27
+ * inert. Any other failure says nothing about the body — a CSP omitting `'unsafe-eval'` throws an
28
+ * `EvalError` and Trusted Types throws a `TypeError` however well the body parses — so the script is
29
+ * injected unchanged and the page keeps working under those policies.
30
+ *
25
31
  * This function intentionally references only globals and its own parameter, never the exported
26
32
  * `PICKED_*` constants above, so {@link buildRehydrateBootstrap} can serialise it with `.toString()` for
27
33
  * injection into a sandboxed iframe, where module imports are unavailable.
@@ -1 +1 @@
1
- {"version":3,"file":"rehydrate-scripts.d.ts","sourceRoot":"","sources":["../../../src/utils/rehydrate-scripts.ts"],"names":[],"mappings":"AAAA,mFAAmF;AAEnF,mGAAmG;AACnG,eAAO,MAAM,kBAAkB,kCAAkC,CAAA;AACjE,2GAA2G;AAC3G,eAAO,MAAM,yBAAyB,8BAA8B,CAAA;AACpE,sEAAsE;AACtE,eAAO,MAAM,oBAAoB,yBAAyB,CAAA;AAE1D,OAAO,CAAC,MAAM,CAAC;IACb;;;;OAIG;IACH,IAAI,uBAAuB,EAAE,IAAI,GAAG,IAAI,GAAG,SAAS,CAAA;CACrD;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAsB,gBAAgB,CAAC,IAAI,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,CAsEtE;AAED;;;;;;;GAOG;AACH,wBAAgB,uBAAuB,IAAI,MAAM,CAEhD"}
1
+ {"version":3,"file":"rehydrate-scripts.d.ts","sourceRoot":"","sources":["../../../src/utils/rehydrate-scripts.ts"],"names":[],"mappings":"AAAA,mFAAmF;AAEnF,mGAAmG;AACnG,eAAO,MAAM,kBAAkB,kCAAkC,CAAA;AACjE,2GAA2G;AAC3G,eAAO,MAAM,yBAAyB,8BAA8B,CAAA;AACpE,sEAAsE;AACtE,eAAO,MAAM,oBAAoB,yBAAyB,CAAA;AAE1D,OAAO,CAAC,MAAM,CAAC;IACb;;;;OAIG;IACH,IAAI,uBAAuB,EAAE,IAAI,GAAG,IAAI,GAAG,SAAS,CAAA;CACrD;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAsB,gBAAgB,CAAC,IAAI,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,CAoGtE;AAED;;;;;;;GAOG;AACH,wBAAgB,uBAAuB,IAAI,MAAM,CAEhD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@picked/client",
3
- "version": "0.0.70-next.3",
3
+ "version": "0.0.70-next.5",
4
4
  "dependencies": {
5
5
  "@withease/factories": "^1.0.5"
6
6
  },