@storyblok/js 4.4.0 → 4.4.2

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.
@@ -4,4 +4,4 @@
4
4
  * description: SDK to integrate Storyblok into your project using JavaScript.
5
5
  * author: undefined
6
6
  */
7
- (function(R,g){typeof exports=="object"&&typeof module<"u"?g(exports):typeof define=="function"&&define.amd?define(["exports"],g):(R=typeof globalThis<"u"?globalThis:R||self,g(R.storyblok={}))})(this,function(R){"use strict";var Pe=Object.defineProperty;var Ie=(R,g,w)=>g in R?Pe(R,g,{enumerable:!0,configurable:!0,writable:!0,value:w}):R[g]=w;var v=(R,g,w)=>Ie(R,typeof g!="symbol"?g+"":g,w);let g=function(e){return e.DOCUMENT="doc",e.HEADING="heading",e.PARAGRAPH="paragraph",e.QUOTE="blockquote",e.OL_LIST="ordered_list",e.UL_LIST="bullet_list",e.LIST_ITEM="list_item",e.CODE_BLOCK="code_block",e.HR="horizontal_rule",e.BR="hard_break",e.IMAGE="image",e.EMOJI="emoji",e.COMPONENT="blok",e.TABLE="table",e.TABLE_ROW="tableRow",e.TABLE_CELL="tableCell",e.TABLE_HEADER="tableHeader",e}({}),w=function(e){return e.BOLD="bold",e.STRONG="strong",e.STRIKE="strike",e.UNDERLINE="underline",e.ITALIC="italic",e.CODE="code",e.LINK="link",e.ANCHOR="anchor",e.STYLED="styled",e.SUPERSCRIPT="superscript",e.SUBSCRIPT="subscript",e.TEXT_STYLE="textStyle",e.HIGHLIGHT="highlight",e}({}),B=function(e){return e.TEXT="text",e}({}),P=function(e){return e.URL="url",e.STORY="story",e.ASSET="asset",e.EMAIL="email",e}({});const Z=["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"],ee=(e={})=>{const{custom:t,...s}=e,r={...s,...t};return Object.keys(r).map(i=>`${i}="${r[i]}"`).join(" ")},te=(e={})=>Object.keys(e).map(t=>`${t}: ${e[t]}`).join("; ");function re(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}const L=e=>Object.fromEntries(Object.entries(e).filter(([t,s])=>s!==void 0));function se(e,t){if(!t)return{src:e,attrs:{}};let s=0,r=0;const i={},n=[];function c(u,a,y,m,A){typeof u!="number"||u<=a||u>=y?console.warn(`[StoryblokRichText] - ${m.charAt(0).toUpperCase()+m.slice(1)} value must be a number between ${a} and ${y} (inclusive)`):A.push(`${m}(${u})`)}if(typeof t=="object"){if(t.width!==void 0&&(typeof t.width=="number"&&t.width>=0?(i.width=t.width,s=t.width):console.warn("[StoryblokRichText] - Width value must be a number greater than or equal to 0")),t.height!==void 0&&(typeof t.height=="number"&&t.height>=0?(i.height=t.height,r=t.height):console.warn("[StoryblokRichText] - Height value must be a number greater than or equal to 0")),t.height===0&&t.width===0&&(delete i.width,delete i.height,console.warn("[StoryblokRichText] - Width and height values cannot both be 0")),t.loading&&["lazy","eager"].includes(t.loading)&&(i.loading=t.loading),t.class&&(i.class=t.class),t.filters){const{filters:u}=t||{},{blur:a,brightness:y,fill:m,format:A,grayscale:H,quality:S,rotate:O}=u||{};a&&c(a,0,100,"blur",n),S&&c(S,0,100,"quality",n),y&&c(y,0,100,"brightness",n),m&&n.push(`fill(${m})`),H&&n.push("grayscale()"),O&&[0,90,180,270].includes(t.filters.rotate||0)&&n.push(`rotate(${O})`),A&&["webp","png","jpeg"].includes(A)&&n.push(`format(${A})`)}t.srcset&&(i.srcset=t.srcset.map(u=>{if(typeof u=="number")return`${e}/m/${u}x0/${n.length>0?`filters:${n.join(":")}`:""} ${u}w`;if(Array.isArray(u)&&u.length===2){const[a,y]=u;return`${e}/m/${a}x${y}/${n.length>0?`filters:${n.join(":")}`:""} ${a}w`}else{console.warn("[StoryblokRichText] - srcset entry must be a number or a tuple of two numbers");return}}).join(", ")),t.sizes&&(i.sizes=t.sizes.join(", "))}let l=`${e}/m/`;return(s>0||r>0)&&(l=`${l}${s}x${r}/`),n.length>0&&(l=`${l}filters:${n.join(":")}`),{src:l,attrs:i}}function z(e,t={},s){const r=ee(t),i=r?`${e} ${r}`:e,n=Array.isArray(s)?s.join(""):s||"";if(e){if(Z.includes(e))return`<${i}>`}else return n;return`<${i}>${n}</${e}>`}function F(e={}){const t=new Map,{renderFn:s=z,textFn:r=re,resolvers:i={},optimizeImages:n=!1,keyedResolvers:c=!1}=e,l=s!==z,u=(o={})=>{const{textAlign:h,class:d,id:f,style:b,...k}=o,p=[];return b&&p.push(b.endsWith(";")?b:`${b};`),h&&p.push(`text-align: ${h};`),L({...k,class:d,id:f,...p.length>0?{style:p.join(" ")}:{}})},a=o=>(h,d)=>{const f=u(h.attrs);return d.render(o,f,h.children||null)},y=(o,h)=>{const{src:d,alt:f,title:b,srcset:k,sizes:p}=o.attrs||{};let E=d,_={};if(n){const{src:Oe,attrs:Ce}=se(d,n);E=Oe,_=Ce}const C={src:E,alt:f,title:b,srcset:k,sizes:p,..._};return h.render("img",L(C))},m=(o,h)=>{const{level:d,...f}=o.attrs||{},b=u(f);return h.render(`h${d}`,b,o.children)},A=(o,h)=>{var f,b,k,p;const d=h.render("img",{src:(f=o.attrs)==null?void 0:f.fallbackImage,alt:(b=o.attrs)==null?void 0:b.alt,style:"width: 1.25em; height: 1.25em; vertical-align: text-top",draggable:"false",loading:"lazy"});return h.render("span",{"data-type":"emoji","data-name":(k=o.attrs)==null?void 0:k.name,"data-emoji":(p=o.attrs)==null?void 0:p.emoji},d)},H=(o,h)=>h.render("pre",o.attrs||{},h.render("code",{},o.children||"")),S=(o,h=!1)=>({text:d,attrs:f},b)=>{const{class:k,id:p,...E}=f||{},_=h?{class:k,id:p,style:te(E)||void 0}:f||{};return b.render(o,L(_),d)},O=o=>U(o),we=o=>{const{marks:h,...d}=o;if("text"in o){if(h)return h.reduce((b,k)=>O({...k,text:b}),O({...d,children:d.children}));const f=o.attrs||{};if(c){const b=t.get("txt")||0;t.set("txt",b+1),f.key=`txt-${b}`}return r(d.text,f)}return""},W=(o,h)=>{const{linktype:d,href:f,anchor:b,...k}=o.attrs||{};let p="";switch(d){case P.ASSET:case P.URL:p=f;break;case P.EMAIL:p=`mailto:${f}`;break;case P.STORY:p=f,b&&(p=`${p}#${b}`);break;default:p=f;break}const E={...k};return p&&(E.href=p),h.render("a",E,o.text)},_e=(o,h)=>{var d,f;return console.warn("[StoryblokRichtText] - BLOK resolver is not available for vanilla usage"),h.render("span",{blok:(d=o==null?void 0:o.attrs)==null?void 0:d.body[0],id:(f=o.attrs)==null?void 0:f.id,style:"display: none"})},Se=(o,h)=>{const d=u(o.attrs),f=o.children||null;return h.render("table",d,h.render("tbody",{},f))},Ae=(o,h)=>{const d=u(o.attrs);return h.render("tr",d,o.children)},Ee=(o,h)=>{const{colspan:d,rowspan:f,colwidth:b,backgroundColor:k,textAlign:p,...E}=o.attrs||{},_=[];b&&_.push(`width: ${b}px;`),k&&_.push(`background-color: ${k};`),p&&_.push(`text-align: ${p};`);const C={...E,...d>1?{colspan:d}:{},...f>1?{rowspan:f}:{},..._.length>0?{style:_.join(" ")}:{}};return h.render("td",L(C),o.children)},Te=(o,h)=>{const{colspan:d,rowspan:f,colwidth:b,backgroundColor:k,textAlign:p,...E}=o.attrs||{},_=[];b&&_.push(`width: ${b}px;`),k&&_.push(`background-color: ${k};`),p&&_.push(`text-align: ${p};`);const C={...E,...d>1?{colspan:d}:{},...f>1?{rowspan:f}:{},..._.length>0?{style:_.join(" ")}:{}};return h.render("th",L(C),o.children)},X=new Map([[g.DOCUMENT,a("")],[g.HEADING,m],[g.PARAGRAPH,a("p")],[g.UL_LIST,a("ul")],[g.OL_LIST,a("ol")],[g.LIST_ITEM,a("li")],[g.IMAGE,y],[g.EMOJI,A],[g.CODE_BLOCK,H],[g.HR,a("hr")],[g.BR,a("br")],[g.QUOTE,a("blockquote")],[g.COMPONENT,_e],[B.TEXT,we],[w.LINK,W],[w.ANCHOR,W],[w.STYLED,S("span",!0)],[w.BOLD,S("strong")],[w.TEXT_STYLE,S("span",!0)],[w.ITALIC,S("em")],[w.UNDERLINE,S("u")],[w.STRIKE,S("s")],[w.CODE,S("code")],[w.SUPERSCRIPT,S("sup")],[w.SUBSCRIPT,S("sub")],[w.HIGHLIGHT,S("mark")],[g.TABLE,Se],[g.TABLE_ROW,Ae],[g.TABLE_CELL,Ee],[g.TABLE_HEADER,Te]]),Q=new Map([...X,...Object.entries(i).map(([o,h])=>[o,h])]),Le=()=>({render:(d,f={},b)=>{if(c&&d){const k=t.get(d)||0;t.set(d,k+1),f.key=`${d}-${k}`}return s(d,f,b)},originalResolvers:X,mergedResolvers:Q});function N(o){const h=Q.get(o.type);if(!h)return console.error("<Storyblok>",`No resolver found for node type ${o.type}`),"";const d=Le();if(o.type==="text")return h(o,d);const f=o.content?o.content.map(U):void 0;return h({...o,children:f},d)}function U(o){return o.type==="doc"?l?o.content.map(N):o.content.map(N).join(""):Array.isArray(o)?o.map(N):N(o)}return{render:U}}let G=!1;const q=[],M=e=>new Promise((t,s)=>{if(typeof window>"u"){s(new Error("Cannot load Storyblok bridge: window is undefined (server-side environment)"));return}if(window.storyblokRegisterEvent=i=>{if(!window.location.search.includes("_storyblok")){console.warn("You are not in Draft Mode or in the Visual Editor.");return}G?i():q.push(i)},document.getElementById("storyblok-javascript-bridge")){t(void 0);return}const r=document.createElement("script");r.async=!0,r.src=e,r.id="storyblok-javascript-bridge",r.onerror=i=>s(i),r.onload=i=>{q.forEach(n=>n()),G=!0,t(i)},document.getElementsByTagName("head")[0].appendChild(r)});var ie=class extends Error{constructor(e){super(e),this.name="AbortError"}};function ne(e,t,s){if(!Number.isFinite(t))throw new TypeError("Expected `limit` to be a finite number");if(!Number.isFinite(s))throw new TypeError("Expected `interval` to be a finite number");const r=[];let i=[],n=0,c=!1;const l=async()=>{n++;const a=r.shift();if(a)try{const m=await e(...a.args);a.resolve(m)}catch(m){a.reject(m)}const y=setTimeout(()=>{n--,r.length>0&&l(),i=i.filter(m=>m!==y)},s);i.includes(y)||i.push(y)},u=(...a)=>c?Promise.reject(new Error("Throttled function is already aborted and not accepting new promises")):new Promise((y,m)=>{r.push({resolve:y,reject:m,args:a}),n<t&&l()});return u.abort=()=>{c=!0,i.forEach(clearTimeout),i=[],r.forEach(a=>a.reject(()=>new ie("Throttle function aborted"))),r.length=0},u}var oe=ne;const V=(e="")=>e.includes("/cdn/"),le=(e,t=25,s=1)=>({...e,per_page:t,page:s}),ae=e=>new Promise(t=>setTimeout(t,e)),ce=(e=0,t)=>Array.from({length:e},t),ue=(e=0,t=e)=>{const s=Math.abs(t-e)||0,r=e<t?1:-1;return ce(s,(i,n)=>n*r+e)},he=async(e,t)=>Promise.all(e.map(t)),de=(e=[],t)=>e.map(t).reduce((s,r)=>[...s,...r],[]),$=(e,t,s)=>{const r=[];for(const i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;const n=e[i];if(n==null)continue;const c=s?"":encodeURIComponent(i);let l;typeof n=="object"?l=$(n,t?t+encodeURIComponent(`[${c}]`):c,Array.isArray(n)):l=`${t?t+encodeURIComponent(`[${c}]`):c}=${encodeURIComponent(n)}`,r.push(l)}return r.join("&")},D=e=>{const t={eu:"api.storyblok.com",us:"api-us.storyblok.com",cn:"app.storyblokchina.cn",ap:"api-ap.storyblok.com",ca:"api-ca.storyblok.com"};return t[e]??t.eu};var fe=class{constructor(e){v(this,"baseURL");v(this,"timeout");v(this,"headers");v(this,"responseInterceptor");v(this,"fetch");v(this,"ejectInterceptor");v(this,"url");v(this,"parameters");v(this,"fetchOptions");this.baseURL=e.baseURL,this.headers=e.headers||new Headers,this.timeout=e!=null&&e.timeout?e.timeout*1e3:0,this.responseInterceptor=e.responseInterceptor,this.fetch=(...t)=>e.fetch?e.fetch(...t):fetch(...t),this.ejectInterceptor=!1,this.url="",this.parameters={},this.fetchOptions={}}get(e,t){return this.url=e,this.parameters=t,this._methodHandler("get")}post(e,t){return this.url=e,this.parameters=t,this._methodHandler("post")}put(e,t){return this.url=e,this.parameters=t,this._methodHandler("put")}delete(e,t){return this.url=e,this.parameters=t??{},this._methodHandler("delete")}async _responseHandler(e){const t=[],s={data:{},headers:{},status:0,statusText:""};e.status!==204&&await e.json().then(r=>{s.data=r});for(const r of e.headers.entries())t[r[0]]=r[1];return s.headers={...t},s.status=e.status,s.statusText=e.statusText,s}async _methodHandler(e){let t=`${this.baseURL}${this.url}`,s=null;e==="get"?t=`${this.baseURL}${this.url}?${$(this.parameters)}`:s=JSON.stringify(this.parameters);const r=new URL(t),i=new AbortController,{signal:n}=i;let c;this.timeout&&(c=setTimeout(()=>i.abort(),this.timeout));try{const l=await this.fetch(`${r}`,{method:e,headers:this.headers,body:s,signal:n,...this.fetchOptions});this.timeout&&clearTimeout(c);const u=await this._responseHandler(l);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(u)):this._statusHandler(u)}catch(l){return{message:l}}}setFetchOptions(e={}){Object.keys(e).length>0&&"method"in e&&delete e.method,this.fetchOptions={...e}}eject(){this.ejectInterceptor=!0}_normalizeErrorMessage(e){if(Array.isArray(e))return e[0]||"Unknown error";if(e&&typeof e=="object"){if(e.error)return e.error;for(const t in e){if(Array.isArray(e[t]))return`${t}: ${e[t][0]}`;if(typeof e[t]=="string")return`${t}: ${e[t]}`}if(e.slug)return e.slug}return"Unknown error"}_statusHandler(e){const t=/20[0-6]/g;return new Promise((s,r)=>{if(t.test(`${e.status}`))return s(e);const i={message:this._normalizeErrorMessage(e.data),status:e.status,response:e};r(i)})}},ye=fe;const J="SB-Agent",x={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"7.0.0"},ge={PUBLISHED:"published"};let I={};const T={};var be=class{constructor(e,t){v(this,"client");v(this,"maxRetries");v(this,"retriesDelay");v(this,"throttle");v(this,"accessToken");v(this,"cache");v(this,"resolveCounter");v(this,"relations");v(this,"links");v(this,"version");v(this,"richTextResolver");v(this,"resolveNestedRelations");v(this,"stringifiedStoriesCache");v(this,"inlineAssets");let s=e.endpoint||t;if(!s){const n=e.https===!1?"http":"https";e.oauthToken?s=`${n}://${D(e.region)}/v1`:s=`${n}://${D(e.region)}/v2`}const r=new Headers;r.set("Content-Type","application/json"),r.set("Accept","application/json"),e.headers&&(e.headers.constructor.name==="Headers"?e.headers.entries().toArray():Object.entries(e.headers)).forEach(([c,l])=>{r.set(c,l)}),r.has(J)||(r.set(J,x.defaultAgentName),r.set(x.defaultAgentVersion,x.packageVersion));let i=5;e.oauthToken&&(r.set("Authorization",e.oauthToken),i=3),e.rateLimit&&(i=e.rateLimit),this.maxRetries=e.maxRetries||10,this.retriesDelay=300,this.throttle=oe(this.throttledRequest.bind(this),i,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.stringifiedStoriesCache={},this.version=e.version||ge.PUBLISHED,this.inlineAssets=e.inlineAssets||!1,this.client=new ye({baseURL:s,timeout:e.timeout||0,headers:r,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}parseParams(e){return e.token||(e.token=this.getToken()),e.cv||(e.cv=T[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),typeof e.resolve_relations<"u"&&(e.resolve_level=2),e}factoryParamOptions(e,t){return V(e)?this.parseParams(t):t}makeRequest(e,t,s,r,i){const n=this.factoryParamOptions(e,le(t,s,r));return this.cacheResponse(e,n,void 0,i)}get(e,t={},s){t||(t={});const r=`/${e}`;V(r)&&(t.version=t.version||this.version);const i=this.factoryParamOptions(r,t);return this.cacheResponse(r,i,void 0,s)}async getAll(e,t={},s,r){const i=(t==null?void 0:t.per_page)||25,n=`/${e}`.replace(/\/$/,""),c=s??n.substring(n.lastIndexOf("/")+1);t.version=t.version||this.version;const l=1,u=await this.makeRequest(n,t,i,l,r),a=u.total?Math.ceil(u.total/(u.perPage||i)):1,y=await he(ue(l,a),m=>this.makeRequest(n,t,i,m+1,r));return de([u,...y],m=>Object.values(m.data[c]))}post(e,t={},s){const r=`/${e}`;return this.throttle("post",r,t,s)}put(e,t={},s){const r=`/${e}`;return this.throttle("put",r,t,s)}delete(e,t={},s){t||(t={});const r=`/${e}`;return this.throttle("delete",r,t,s)}getStories(e={},t){return this._addResolveLevel(e),this.get("cdn/stories",e,t)}getStory(e,t={},s){return this._addResolveLevel(t),this.get(`cdn/stories/${e}`,t,s)}getToken(){return this.accessToken}ejectInterceptor(){this.client.eject()}_addResolveLevel(e){typeof e.resolve_relations<"u"&&(e.resolve_level=2)}_cleanCopy(e){return JSON.parse(JSON.stringify(e))}_insertLinks(e,t,s){const r=e[t];r&&r.fieldtype==="multilink"&&r.linktype==="story"&&typeof r.id=="string"&&this.links[s][r.id]?r.story=this._cleanCopy(this.links[s][r.id]):r&&r.linktype==="story"&&typeof r.uuid=="string"&&this.links[s][r.uuid]&&(r.story=this._cleanCopy(this.links[s][r.uuid]))}getStoryReference(e,t){return this.relations[e][t]?JSON.parse(this.stringifiedStoriesCache[t]||JSON.stringify(this.relations[e][t])):t}_resolveField(e,t,s){const r=e[t];typeof r=="string"?e[t]=this.getStoryReference(s,r):Array.isArray(r)&&(e[t]=r.map(i=>this.getStoryReference(s,i)).filter(Boolean))}_insertRelations(e,t,s,r){if(Array.isArray(s)?s.find(c=>c.endsWith(`.${t}`)):s.endsWith(`.${t}`)){this._resolveField(e,t,r);return}const n=e.component?`${e.component}.${t}`:t;(Array.isArray(s)?s.includes(n):s===n)&&this._resolveField(e,t,r)}iterateTree(e,t,s){const r=(i,n="")=>{if(!(!i||i._stopResolving)){if(Array.isArray(i))i.forEach((c,l)=>r(c,`${n}[${l}]`));else if(typeof i=="object")for(const c in i){const l=n?`${n}.${c}`:c;(i.component&&i._uid||i.type==="link")&&(this._insertRelations(i,c,t,s),this._insertLinks(i,c,s)),r(i[c],l)}}};r(e.content)}async resolveLinks(e,t,s){let r=[];if(e.link_uuids){const i=e.link_uuids.length,n=[],c=50;for(let l=0;l<i;l+=c){const u=Math.min(i,l+c);n.push(e.link_uuids.slice(l,u))}for(let l=0;l<n.length;l++)(await this.getStories({per_page:c,language:t.language,version:t.version,starts_with:t.starts_with,by_uuids:n[l].join(",")})).data.stories.forEach(a=>{r.push(a)})}else r=e.links;r.forEach(i=>{this.links[s][i.uuid]={...i,_stopResolving:!0}})}async resolveRelations(e,t,s){let r=[];if(e.rel_uuids){const i=e.rel_uuids.length,n=[],c=50;for(let l=0;l<i;l+=c){const u=Math.min(i,l+c);n.push(e.rel_uuids.slice(l,u))}for(let l=0;l<n.length;l++)(await this.getStories({per_page:c,language:t.language,version:t.version,starts_with:t.starts_with,by_uuids:n[l].join(","),excluding_fields:t.excluding_fields})).data.stories.forEach(a=>{r.push(a)});r.length>0&&(e.rels=r,delete e.rel_uuids)}else r=e.rels;r&&r.length>0&&r.forEach(i=>{this.relations[s][i.uuid]={...i,_stopResolving:!0}})}async resolveStories(e,t,s){var i,n;let r=[];if(this.links[s]={},this.relations[s]={},typeof t.resolve_relations<"u"&&t.resolve_relations.length>0&&(typeof t.resolve_relations=="string"&&(r=t.resolve_relations.split(",")),await this.resolveRelations(e,t,s)),t.resolve_links&&["1","story","url","link"].includes(t.resolve_links)&&((i=e.links)!=null&&i.length||(n=e.link_uuids)!=null&&n.length)&&await this.resolveLinks(e,t,s),this.resolveNestedRelations)for(const c in this.relations[s])this.iterateTree(this.relations[s][c],r,s);e.story?this.iterateTree(e.story,r,s):e.stories.forEach(c=>{this.iterateTree(c,r,s)}),this.stringifiedStoriesCache={},delete this.links[s],delete this.relations[s]}async cacheResponse(e,t,s,r){const i=$({url:e,params:t}),n=this.cacheProvider();if(t.version==="published"&&e!=="/cdn/spaces/me"){const c=await n.get(i);if(c)return Promise.resolve(c)}return new Promise(async(c,l)=>{var u;try{const a=await this.throttle("get",e,t,r);if(a.status!==200)return l(a);let y={data:a.data,headers:a.headers};if((u=a.headers)!=null&&u["per-page"]&&(y=Object.assign({},y,{perPage:a.headers["per-page"]?Number.parseInt(a.headers["per-page"]):0,total:a.headers["per-page"]?Number.parseInt(a.headers.total):0})),y.data.story||y.data.stories){const A=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(y.data,t,`${A}`),y=await this.processInlineAssets(y)}t.version==="published"&&e!=="/cdn/spaces/me"&&await n.set(i,y);const m=this.cache.clear==="onpreview"&&t.version==="draft"||this.cache.clear==="auto";return t.token&&y.data.cv&&(m&&T[t.token]&&T[t.token]!==y.data.cv&&await this.flushCache(),T[t.token]=y.data.cv),c(y)}catch(a){if(a.response&&a.status===429&&(s=typeof s>"u"?0:s+1,s<this.maxRetries))return console.log(`Hit rate limit. Retrying in ${this.retriesDelay/1e3} seconds.`),await ae(this.retriesDelay),this.cacheResponse(e,t,s).then(c).catch(l);l(a)}})}throttledRequest(e,t,s,r){return this.client.setFetchOptions(r),this.client[e](t,s)}cacheVersions(){return T}cacheVersion(){return T[this.accessToken]}setCacheVersion(e){this.accessToken&&(T[this.accessToken]=e)}clearCacheVersion(){this.accessToken&&(T[this.accessToken]=0)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(I[e])},getAll(){return Promise.resolve(I)},set(e,t){return I[e]=t,Promise.resolve(void 0)},flush(){return I={},Promise.resolve(void 0)}};case"custom":if(this.cache.custom)return this.cache.custom;default:return{get(){return Promise.resolve()},getAll(){return Promise.resolve(void 0)},set(){return Promise.resolve(void 0)},flush(){return Promise.resolve(void 0)}}}}async flushCache(){return await this.cacheProvider().flush(),this.clearCacheVersion(),this}async processInlineAssets(e){if(!this.inlineAssets)return e;const t=s=>{if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(i=>t(i));let r={...s};r.fieldtype==="asset"&&Array.isArray(e.data.assets)&&(r={...e.data.assets.find(i=>i.id===r.id),...r});for(const i in r)typeof r[i]=="object"&&(r[i]=t(r[i]));return r};return e.data.story&&(e.data.story.content=t(e.data.story.content)),e.data.stories&&(e.data.stories=e.data.stories.map(s=>(s.content=t(s.content),s))),e}},K=be;const pe=(e={})=>{const{apiOptions:t}=e;if(!t||!t.accessToken){console.error("You need to provide an access token to interact with Storyblok API. Read https://www.storyblok.com/docs/api/content-delivery#topics/authentication");return}return{storyblokApi:new K(t)}},me=e=>{if(typeof e!="object"||typeof e._editable>"u")return{};try{const t=JSON.parse(e._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return t?{"data-blok-c":JSON.stringify(t),"data-blok-uid":`${t.id}-${t.uid}`}:{}}catch{return{}}};let j="https://app.storyblok.com/f/storyblok-v2-latest.js";const Y=(e,t,s={})=>{var l;const i=!(typeof window>"u")&&typeof window.storyblokRegisterEvent<"u",n=new URL((l=window.location)==null?void 0:l.href).searchParams.get("_storyblok"),c=n!==null&&+n===e;if(!(!i||!c)){if(!e){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(s).on(["input","published","change"],a=>{var y;a&&(a.action==="input"&&((y=a.story)==null?void 0:y.id)===e?t(a.story):(a.action==="change"||a.action==="published")&&a.storyId===e&&window.location.reload())})})}},ve=(e={})=>{var y,m;const{bridge:t,accessToken:s,use:r=[],apiOptions:i={},bridgeUrl:n}=e;i.accessToken=i.accessToken||s;const c={bridge:t,apiOptions:i};let l={};r.forEach(A=>{l={...l,...A(c)}}),n&&(j=n);const a=!(typeof window>"u")&&((m=(y=window.location)==null?void 0:y.search)==null?void 0:m.includes("_storyblok_tk"));return t!==!1&&a&&M(j),l};function Re(e,t){return F(t).render(e)}const ke=()=>M(j);R.BlockTypes=g,R.MarkTypes=w,R.StoryblokClient=K,R.TextTypes=B,R.apiPlugin=pe,R.loadStoryblokBridge=ke,R.registerStoryblokBridge=Y,R.renderRichText=Re,R.richTextResolver=F,R.storyblokEditable=me,R.storyblokInit=ve,R.useStoryblokBridge=Y,Object.defineProperty(R,Symbol.toStringTag,{value:"Module"})});
7
+ (function(v,b){typeof exports=="object"&&typeof module<"u"?b(exports):typeof define=="function"&&define.amd?define(["exports"],b):(v=typeof globalThis<"u"?globalThis:v||self,b(v.storyblok={}))})(this,function(v){"use strict";var Be=Object.defineProperty;var De=(v,b,E)=>b in v?Be(v,b,{enumerable:!0,configurable:!0,writable:!0,value:E}):v[b]=E;var R=(v,b,E)=>De(v,typeof b!="symbol"?b+"":b,E);let b=function(e){return e.DOCUMENT="doc",e.HEADING="heading",e.PARAGRAPH="paragraph",e.QUOTE="blockquote",e.OL_LIST="ordered_list",e.UL_LIST="bullet_list",e.LIST_ITEM="list_item",e.CODE_BLOCK="code_block",e.HR="horizontal_rule",e.BR="hard_break",e.IMAGE="image",e.EMOJI="emoji",e.COMPONENT="blok",e.TABLE="table",e.TABLE_ROW="tableRow",e.TABLE_CELL="tableCell",e.TABLE_HEADER="tableHeader",e}({}),E=function(e){return e.BOLD="bold",e.STRONG="strong",e.STRIKE="strike",e.UNDERLINE="underline",e.ITALIC="italic",e.CODE="code",e.LINK="link",e.ANCHOR="anchor",e.STYLED="styled",e.SUPERSCRIPT="superscript",e.SUBSCRIPT="subscript",e.TEXT_STYLE="textStyle",e.HIGHLIGHT="highlight",e}({}),D=function(e){return e.TEXT="text",e}({}),N=function(e){return e.URL="url",e.STORY="story",e.ASSET="asset",e.EMAIL="email",e}({});const ne=["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"],oe=(e={})=>{const{custom:t,...s}=e,r={...s,...t};return Object.keys(r).map(i=>`${i}="${r[i]}"`).join(" ")},ae=(e={})=>Object.keys(e).map(t=>`${t}: ${e[t]}`).join("; ");function le(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}const T=e=>Object.fromEntries(Object.entries(e).filter(([t,s])=>s!==void 0));function ce(e,t){if(!t)return{src:e,attrs:{}};let s=0,r=0;const i={},n=[];function l(u,c,f,y,S){typeof u!="number"||u<=c||u>=f?console.warn(`[StoryblokRichText] - ${y.charAt(0).toUpperCase()+y.slice(1)} value must be a number between ${c} and ${f} (inclusive)`):S.push(`${y}(${u})`)}if(typeof t=="object"){if(t.width!==void 0&&(typeof t.width=="number"&&t.width>=0?(i.width=t.width,s=t.width):console.warn("[StoryblokRichText] - Width value must be a number greater than or equal to 0")),t.height!==void 0&&(typeof t.height=="number"&&t.height>=0?(i.height=t.height,r=t.height):console.warn("[StoryblokRichText] - Height value must be a number greater than or equal to 0")),t.height===0&&t.width===0&&(delete i.width,delete i.height,console.warn("[StoryblokRichText] - Width and height values cannot both be 0")),t.loading&&["lazy","eager"].includes(t.loading)&&(i.loading=t.loading),t.class&&(i.class=t.class),t.filters){const{filters:u}=t||{},{blur:c,brightness:f,fill:y,format:S,grayscale:O,quality:A,rotate:I}=u||{};c&&l(c,0,100,"blur",n),A&&l(A,0,100,"quality",n),f&&l(f,0,100,"brightness",n),y&&n.push(`fill(${y})`),O&&n.push("grayscale()"),I&&[0,90,180,270].includes(t.filters.rotate||0)&&n.push(`rotate(${I})`),S&&["webp","png","jpeg"].includes(S)&&n.push(`format(${S})`)}t.srcset&&(i.srcset=t.srcset.map(u=>{if(typeof u=="number")return`${e}/m/${u}x0/${n.length>0?`filters:${n.join(":")}`:""} ${u}w`;if(Array.isArray(u)&&u.length===2){const[c,f]=u;return`${e}/m/${c}x${f}/${n.length>0?`filters:${n.join(":")}`:""} ${c}w`}else{console.warn("[StoryblokRichText] - srcset entry must be a number or a tuple of two numbers");return}}).join(", ")),t.sizes&&(i.sizes=t.sizes.join(", "))}let a=`${e}/m/`;return(s>0||r>0)&&(a=`${a}${s}x${r}/`),n.length>0&&(a=`${a}filters:${n.join(":")}`),{src:a,attrs:i}}function z(e,t={},s){const r=oe(t),i=r?`${e} ${r}`:e,n=Array.isArray(s)?s.join(""):s||"";if(e){if(ne.includes(e))return`<${i}>`}else return n;return`<${i}>${n}</${e}>`}function V(e={}){const t=new Map,{renderFn:s=z,textFn:r=le,resolvers:i={},optimizeImages:n=!1,keyedResolvers:l=!1}=e,a=s!==z,u=(o={})=>{const{textAlign:h,class:d,id:g,style:m,..._}=o,p=[];return m&&p.push(m.endsWith(";")?m:`${m};`),h&&p.push(`text-align: ${h};`),T({..._,class:d,id:g,...p.length>0?{style:p.join(" ")}:{}})},c=o=>(h,d)=>{const g=u(h.attrs);return d.render(o,g,h.children||null)},f=(o,h)=>{const{src:d,alt:g,title:m,srcset:_,sizes:p}=o.attrs||{};let w=d,k={};if(n){const{src:qe,attrs:Fe}=ce(d,n);w=qe,k=Fe}const P={src:w,alt:g,title:m,srcset:_,sizes:p,...k};return h.render("img",T(P))},y=(o,h)=>{const{level:d,...g}=o.attrs||{},m=u(g);return h.render(`h${d}`,m,o.children)},S=(o,h)=>{var g,m,_,p;const d=h.render("img",{src:(g=o.attrs)==null?void 0:g.fallbackImage,alt:(m=o.attrs)==null?void 0:m.alt,style:"width: 1.25em; height: 1.25em; vertical-align: text-top",draggable:"false",loading:"lazy"});return h.render("span",{"data-type":"emoji","data-name":(_=o.attrs)==null?void 0:_.name,"data-emoji":(p=o.attrs)==null?void 0:p.emoji},d)},O=(o,h)=>h.render("pre",o.attrs||{},h.render("code",{},o.children||"")),A=(o,h=!1)=>({text:d,attrs:g},m)=>{const{class:_,id:p,...w}=g||{},k=h?{class:_,id:p,style:ae(w)||void 0}:g||{};return m.render(o,T(k),d)},I=o=>B(o),xe=o=>{const{marks:h,...d}=o;if("text"in o){if(h)return h.reduce((m,_)=>I({..._,text:m}),I({...d,children:d.children}));const g=o.attrs||{};if(l){const m=t.get("txt")||0;t.set("txt",m+1),g.key=`txt-${m}`}return r(d.text,g)}return""},re=(o,h)=>{const{linktype:d,href:g,anchor:m,..._}=o.attrs||{};let p="";switch(d){case N.ASSET:case N.URL:p=g;break;case N.EMAIL:p=`mailto:${g}`;break;case N.STORY:p=g,m&&(p=`${p}#${m}`);break;default:p=g;break}const w={..._};return p&&(w.href=p),h.render("a",w,o.text)},He=(o,h)=>{var d,g;return console.warn("[StoryblokRichtText] - BLOK resolver is not available for vanilla usage"),h.render("span",{blok:(d=o==null?void 0:o.attrs)==null?void 0:d.body[0],id:(g=o.attrs)==null?void 0:g.id,style:"display: none"})},Me=(o,h)=>{const d=u(o.attrs),g=o.children||null;return h.render("table",d,h.render("tbody",{},g))},Ue=(o,h)=>{const d=u(o.attrs);return h.render("tr",d,o.children)},$e=(o,h)=>{const{colspan:d,rowspan:g,colwidth:m,backgroundColor:_,textAlign:p,...w}=o.attrs||{},k=[];m&&k.push(`width: ${m}px;`),_&&k.push(`background-color: ${_};`),p&&k.push(`text-align: ${p};`);const P={...w,...d>1?{colspan:d}:{},...g>1?{rowspan:g}:{},...k.length>0?{style:k.join(" ")}:{}};return h.render("td",T(P),o.children)},je=(o,h)=>{const{colspan:d,rowspan:g,colwidth:m,backgroundColor:_,textAlign:p,...w}=o.attrs||{},k=[];m&&k.push(`width: ${m}px;`),_&&k.push(`background-color: ${_};`),p&&k.push(`text-align: ${p};`);const P={...w,...d>1?{colspan:d}:{},...g>1?{rowspan:g}:{},...k.length>0?{style:k.join(" ")}:{}};return h.render("th",T(P),o.children)},se=new Map([[b.DOCUMENT,c("")],[b.HEADING,y],[b.PARAGRAPH,c("p")],[b.UL_LIST,c("ul")],[b.OL_LIST,c("ol")],[b.LIST_ITEM,c("li")],[b.IMAGE,f],[b.EMOJI,S],[b.CODE_BLOCK,O],[b.HR,c("hr")],[b.BR,c("br")],[b.QUOTE,c("blockquote")],[b.COMPONENT,He],[D.TEXT,xe],[E.LINK,re],[E.ANCHOR,re],[E.STYLED,A("span",!0)],[E.BOLD,A("strong")],[E.TEXT_STYLE,A("span",!0)],[E.ITALIC,A("em")],[E.UNDERLINE,A("u")],[E.STRIKE,A("s")],[E.CODE,A("code")],[E.SUPERSCRIPT,A("sup")],[E.SUBSCRIPT,A("sub")],[E.HIGHLIGHT,A("mark")],[b.TABLE,Me],[b.TABLE_ROW,Ue],[b.TABLE_CELL,$e],[b.TABLE_HEADER,je]]),ie=new Map([...se,...Object.entries(i).map(([o,h])=>[o,h])]),Ge=()=>({render:(d,g={},m)=>{if(l&&d){const _=t.get(d)||0;t.set(d,_+1),g.key=`${d}-${_}`}return s(d,g,m)},originalResolvers:se,mergedResolvers:ie});function M(o){const h=ie.get(o.type);if(!h)return console.error("<Storyblok>",`No resolver found for node type ${o.type}`),"";const d=Ge();if(o.type==="text")return h(o,d);const g=o.content?o.content.map(B):void 0;return h({...o,children:g},d)}function B(o){return o.type==="doc"?a?o.content.map(M):o.content.map(M).join(""):Array.isArray(o)?o.map(M):M(o)}return{render:B}}let Y=!1;const J=[],K=e=>new Promise((t,s)=>{if(typeof window>"u"){s(new Error("Cannot load Storyblok bridge: window is undefined (server-side environment)"));return}if(window.storyblokRegisterEvent=i=>{if(!window.location.search.includes("_storyblok")){console.warn("You are not in Draft Mode or in the Visual Editor.");return}Y?i():J.push(i)},document.getElementById("storyblok-javascript-bridge")){t(void 0);return}const r=document.createElement("script");r.async=!0,r.src=e,r.id="storyblok-javascript-bridge",r.onerror=i=>s(i),r.onload=i=>{J.forEach(n=>n()),Y=!0,t(i)},document.getElementsByTagName("head")[0].appendChild(r)}),W=(e="")=>e.includes("/cdn/"),ue=(e,t=25,s=1)=>({...e,per_page:t,page:s}),he=e=>new Promise(t=>setTimeout(t,e)),de=(e=0,t)=>Array.from({length:e},t),fe=(e=0,t=e)=>{const s=Math.abs(t-e)||0,r=e<t?1:-1;return de(s,(i,n)=>n*r+e)},ge=async(e,t)=>Promise.all(e.map(t)),ye=(e=[],t)=>e.map(t).reduce((s,r)=>[...s,...r],[]),U=(e,t,s)=>{const r=[];for(const i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;const n=e[i];if(n==null)continue;const l=s?"":encodeURIComponent(i);let a;typeof n=="object"?a=U(n,t?t+encodeURIComponent(`[${l}]`):l,Array.isArray(n)):a=`${t?t+encodeURIComponent(`[${l}]`):l}=${encodeURIComponent(n)}`,r.push(a)}return r.join("&")},Q=e=>{const t={eu:"api.storyblok.com",us:"api-us.storyblok.com",cn:"app.storyblokchina.cn",ap:"api-ap.storyblok.com",ca:"api-ca.storyblok.com"};return t[e]??t.eu};var be=class{constructor(e){R(this,"baseURL");R(this,"timeout");R(this,"headers");R(this,"responseInterceptor");R(this,"fetch");R(this,"ejectInterceptor");R(this,"url");R(this,"parameters");R(this,"fetchOptions");this.baseURL=e.baseURL,this.headers=e.headers||new Headers,this.timeout=e!=null&&e.timeout?e.timeout*1e3:0,this.responseInterceptor=e.responseInterceptor,this.fetch=(...t)=>e.fetch?e.fetch(...t):fetch(...t),this.ejectInterceptor=!1,this.url="",this.parameters={},this.fetchOptions={}}get(e,t){return this.url=e,this.parameters=t,this._methodHandler("get")}post(e,t){return this.url=e,this.parameters=t,this._methodHandler("post")}put(e,t){return this.url=e,this.parameters=t,this._methodHandler("put")}delete(e,t){return this.url=e,this.parameters=t??{},this._methodHandler("delete")}async _responseHandler(e){const t=[],s={data:{},headers:{},status:0,statusText:""};e.status!==204&&await e.json().then(r=>{s.data=r});for(const r of e.headers.entries())t[r[0]]=r[1];return s.headers={...t},s.status=e.status,s.statusText=e.statusText,s}async _methodHandler(e){let t=`${this.baseURL}${this.url}`,s=null;e==="get"?t=`${this.baseURL}${this.url}?${U(this.parameters)}`:s=JSON.stringify(this.parameters);const r=new URL(t),i=new AbortController,{signal:n}=i;let l=null;this.timeout&&(l=setTimeout(()=>i.abort(),this.timeout));try{const a=await this.fetch(`${r}`,{method:e,headers:this.headers,body:s,signal:n,...this.fetchOptions});this.timeout&&l&&clearTimeout(l);const u=await this._responseHandler(a);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(u)):this._statusHandler(u)}catch(a){return{message:a}}}setFetchOptions(e={}){Object.keys(e).length>0&&"method"in e&&delete e.method,this.fetchOptions={...e}}eject(){this.ejectInterceptor=!0}_normalizeErrorMessage(e){if(Array.isArray(e))return e[0]||"Unknown error";if(e&&typeof e=="object"){if(e.error)return e.error;for(const t in e){if(Array.isArray(e[t]))return`${t}: ${e[t][0]}`;if(typeof e[t]=="string")return`${t}: ${e[t]}`}if(e.slug)return e.slug}return"Unknown error"}_statusHandler(e){const t=/20[0-6]/g;return new Promise((s,r)=>{if(t.test(`${e.status}`))return s(e);const i={message:this._normalizeErrorMessage(e.data),status:e.status,response:e};r(i)})}},me=be;const X="SB-Agent",$={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"7.0.0"},Z={DRAFT:"draft",PUBLISHED:"published"},Re=25,j={SMALL:25,MEDIUM:50,LARGE:75},C={SINGLE_OR_SMALL:50,MEDIUM:15,LARGE:10,VERY_LARGE:6},G=1e3,q=3;function pe(e){return e.version===Z.DRAFT}function ve(e,t){const s=e.includes("/cdn/stories/"),r=e.split("/").length>3&&!e.endsWith("/cdn/stories"),i="find_by"in t;return s&&r||i}function _e(e){return e<=j.SMALL?C.SINGLE_OR_SMALL:e<=j.MEDIUM?C.MEDIUM:e<=j.LARGE?C.LARGE:C.VERY_LARGE}function x(e,t,s={},r){if(s.userRateLimit!==void 0)return Math.min(s.userRateLimit,G);if(s.serverHeadersRateLimit!==void 0)return Math.min(s.serverHeadersRateLimit,G);if(t&&!pe(t))return G;if(r!==void 0)return r;if(ve(e,t))return C.SINGLE_OR_SMALL;const i=t.per_page||Re;return _e(i)}function Ee(e){if(!e)return null;const t=e["x-ratelimit"]||e["X-RateLimit"],s=e["x-ratelimit-policy"]||e["X-RateLimit-Policy"];if(!t&&!s)return null;const r={};if(t){const i=t.match(/r=(\d+)/);i&&(r.remaining=Number.parseInt(i[1],10))}if(s){const i=s.match(/q=(\d+)/);i&&(r.max=Number.parseInt(i[1],10))}return Object.keys(r).length>0?r:null}function ke(e,t=!1){return{userRateLimit:e,serverHeadersRateLimit:void 0,isManagementApi:t}}var Ae=class extends Error{constructor(e){super(e),this.name="AbortError"}};function Se(e,t,s){if(!Number.isFinite(t))throw new TypeError("Expected `limit` to be a finite number");if(!Number.isFinite(s))throw new TypeError("Expected `interval` to be a finite number");const r=[];let i=[],n=0,l=!1;const a=async()=>{n++;const c=r.shift();if(c)try{const y=await e(...c.args);c.resolve(y)}catch(y){c.reject(y)}const f=setTimeout(()=>{n--,r.length>0&&a(),i=i.filter(y=>y!==f)},s);i.includes(f)||i.push(f)},u=(...c)=>l?Promise.reject(new Error("Throttled function is already aborted and not accepting new promises")):new Promise((f,y)=>{r.push({resolve:f,reject:y,args:c}),n<t&&a()});return u.abort=()=>{l=!0,i.forEach(clearTimeout),i=[],r.forEach(c=>c.reject(()=>new Ae("Throttle function aborted"))),r.length=0},u}var we=Se,Le=class{constructor(e,t=1e3){R(this,"queues");R(this,"interval");R(this,"throttledRequestFn");this.queues=new Map,this.interval=t,this.throttledRequestFn=e}getQueue(e){let t=this.queues.get(e);return t||(t=we(this.throttledRequestFn,e,this.interval),this.queues.set(e,t)),t}execute(e,...t){return this.getQueue(e)(...t)}abortAll(){this.queues.forEach(e=>{var t;(t=e.abort)==null||t.call(e)}),this.queues.clear()}getQueueCount(){return this.queues.size}};let H={};const L={};var Te=class{constructor(e,t){R(this,"client");R(this,"maxRetries");R(this,"retriesDelay");R(this,"throttleManager");R(this,"accessToken");R(this,"cache");R(this,"resolveCounter");R(this,"relations");R(this,"links");R(this,"version");R(this,"rateLimitConfig");R(this,"richTextResolver");R(this,"resolveNestedRelations");R(this,"stringifiedStoriesCache");R(this,"inlineAssets");let s=e.endpoint||t;if(!s){const i=e.https===!1?"http":"https";e.oauthToken?s=`${i}://${Q(e.region)}/v1`:s=`${i}://${Q(e.region)}/v2`}const r=new Headers;r.set("Content-Type","application/json"),r.set("Accept","application/json"),e.headers&&(e.headers.constructor.name==="Headers"?e.headers.entries().toArray():Object.entries(e.headers)).forEach(([n,l])=>{r.set(n,l)}),r.has(X)||(r.set(X,$.defaultAgentName),r.set($.defaultAgentVersion,$.packageVersion)),e.oauthToken&&r.set("Authorization",e.oauthToken),this.rateLimitConfig=ke(e.rateLimit,!!e.oauthToken),this.maxRetries=e.maxRetries||10,this.retriesDelay=300,this.throttleManager=new Le(this.throttledRequest.bind(this),1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.stringifiedStoriesCache={},this.version=e.version||Z.PUBLISHED,this.inlineAssets=e.inlineAssets||!1,this.client=new me({baseURL:s,timeout:e.timeout||0,headers:r,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}parseParams(e){return e.token||(e.token=this.getToken()),e.cv||(e.cv=L[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),typeof e.resolve_relations<"u"&&(e.resolve_level=2),e}factoryParamOptions(e,t){return W(e)?this.parseParams(t):t}makeRequest(e,t,s,r,i){const n=this.factoryParamOptions(e,ue(t,s,r));return this.cacheResponse(e,n,void 0,i)}get(e,t={},s){t||(t={});const r=`/${e}`;W(r)&&(t.version=t.version||this.version);const i=this.factoryParamOptions(r,t);return this.cacheResponse(r,i,void 0,s)}async getAll(e,t={},s,r){const i=(t==null?void 0:t.per_page)||25,n=`/${e}`.replace(/\/$/,""),l=s??n.substring(n.lastIndexOf("/")+1);t.version=t.version||this.version;const a=1,u=await this.makeRequest(n,t,i,a,r),c=u.total?Math.ceil(u.total/(u.perPage||i)):1,f=await ge(fe(a,c),y=>this.makeRequest(n,t,i,y+1,r));return ye([u,...f],y=>Object.values(y.data[l]))}post(e,t={},s){const r=`/${e}`,i=x(void 0,void 0,this.rateLimitConfig,q);return this.throttleManager.execute(i,"post",r,t,s)}put(e,t={},s){const r=`/${e}`,i=x(void 0,void 0,this.rateLimitConfig,q);return this.throttleManager.execute(i,"put",r,t,s)}delete(e,t={},s){t||(t={});const r=`/${e}`,i=x(void 0,void 0,this.rateLimitConfig,q);return this.throttleManager.execute(i,"delete",r,t,s)}getStories(e={},t){return this._addResolveLevel(e),this.get("cdn/stories",e,t)}getStory(e,t={},s){return this._addResolveLevel(t),this.get(`cdn/stories/${e}`,t,s)}getToken(){return this.accessToken}ejectInterceptor(){this.client.eject()}_addResolveLevel(e){typeof e.resolve_relations<"u"&&(e.resolve_level=2)}_cleanCopy(e){return JSON.parse(JSON.stringify(e))}_insertLinks(e,t,s){const r=e[t];r&&r.fieldtype==="multilink"&&r.linktype==="story"&&typeof r.id=="string"&&this.links[s][r.id]?r.story=this._cleanCopy(this.links[s][r.id]):r&&r.linktype==="story"&&typeof r.uuid=="string"&&this.links[s][r.uuid]&&(r.story=this._cleanCopy(this.links[s][r.uuid]))}getStoryReference(e,t){return this.relations[e][t]?JSON.parse(this.stringifiedStoriesCache[t]||JSON.stringify(this.relations[e][t])):t}_resolveField(e,t,s){const r=e[t];typeof r=="string"?e[t]=this.getStoryReference(s,r):Array.isArray(r)&&(e[t]=r.map(i=>this.getStoryReference(s,i)).filter(Boolean))}_insertRelations(e,t,s,r){if(Array.isArray(s)?s.find(l=>l.endsWith(`.${t}`)):s.endsWith(`.${t}`)){this._resolveField(e,t,r);return}const n=e.component?`${e.component}.${t}`:t;(Array.isArray(s)?s.includes(n):s===n)&&this._resolveField(e,t,r)}iterateTree(e,t,s){const r=(i,n="")=>{if(!(!i||i._stopResolving)){if(Array.isArray(i))i.forEach((l,a)=>r(l,`${n}[${a}]`));else if(typeof i=="object")for(const l in i){const a=n?`${n}.${l}`:l;(i.component&&i._uid||i.type==="link")&&(this._insertRelations(i,l,t,s),this._insertLinks(i,l,s)),r(i[l],a)}}};r(e.content)}async resolveLinks(e,t,s){let r=[];if(e.link_uuids){const i=e.link_uuids.length,n=[],l=50;for(let a=0;a<i;a+=l){const u=Math.min(i,a+l);n.push(e.link_uuids.slice(a,u))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,starts_with:t.starts_with,by_uuids:n[a].join(",")})).data.stories.forEach(c=>{r.push(c)})}else r=e.links;r.forEach(i=>{this.links[s][i.uuid]={...i,_stopResolving:!0}})}async resolveRelations(e,t,s){let r=[];if(e.rel_uuids){const i=e.rel_uuids.length,n=[],l=50;for(let a=0;a<i;a+=l){const u=Math.min(i,a+l);n.push(e.rel_uuids.slice(a,u))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,starts_with:t.starts_with,by_uuids:n[a].join(","),excluding_fields:t.excluding_fields})).data.stories.forEach(c=>{r.push(c)});r.length>0&&(e.rels=r,delete e.rel_uuids)}else r=e.rels;r&&r.length>0&&r.forEach(i=>{this.relations[s][i.uuid]={...i,_stopResolving:!0}})}async resolveStories(e,t,s){var i,n;let r=[];if(this.links[s]={},this.relations[s]={},typeof t.resolve_relations<"u"&&t.resolve_relations.length>0&&(typeof t.resolve_relations=="string"&&(r=t.resolve_relations.split(",")),await this.resolveRelations(e,t,s)),t.resolve_links&&["1","story","url","link"].includes(t.resolve_links)&&((i=e.links)!=null&&i.length||(n=e.link_uuids)!=null&&n.length)&&await this.resolveLinks(e,t,s),this.resolveNestedRelations)for(const l in this.relations[s])this.iterateTree(this.relations[s][l],r,s);e.story?this.iterateTree(e.story,r,s):e.stories.forEach(l=>{this.iterateTree(l,r,s)}),this.stringifiedStoriesCache={},delete this.links[s],delete this.relations[s]}async cacheResponse(e,t,s,r){const i=U({url:e,params:t}),n=this.cacheProvider();if(t.version==="published"&&e!=="/cdn/spaces/me"){const a=await n.get(i);if(a)return Promise.resolve(a)}const l=x(e,t,this.rateLimitConfig);return new Promise(async(a,u)=>{var c;try{const f=await this.throttleManager.execute(l,"get",e,t,r);if(f.status!==200)return u(f);let y={data:f.data,headers:f.headers};const S=Ee(f.headers);if((S==null?void 0:S.max)!==void 0&&(this.rateLimitConfig.serverHeadersRateLimit=S.max),(c=f.headers)!=null&&c["per-page"]&&(y=Object.assign({},y,{perPage:f.headers["per-page"]?Number.parseInt(f.headers["per-page"]):0,total:f.headers["per-page"]?Number.parseInt(f.headers.total):0})),y.data.story||y.data.stories){const A=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(y.data,t,`${A}`),y=await this.processInlineAssets(y)}t.version==="published"&&e!=="/cdn/spaces/me"&&await n.set(i,y);const O=this.cache.clear==="onpreview"&&t.version==="draft"||this.cache.clear==="auto";return t.token&&y.data.cv&&(O&&L[t.token]&&L[t.token]!==y.data.cv&&await this.flushCache(),L[t.token]=y.data.cv),a(y)}catch(f){if(f.response&&f.status===429&&(s=typeof s>"u"?0:s+1,s<this.maxRetries))return console.log(`Hit rate limit. Retrying in ${this.retriesDelay/1e3} seconds.`),await he(this.retriesDelay),this.cacheResponse(e,t,s).then(a).catch(u);u(f)}})}throttledRequest(e,t,s,r){return this.client.setFetchOptions(r),this.client[e](t,s)}cacheVersions(){return L}cacheVersion(){return L[this.accessToken]}setCacheVersion(e){this.accessToken&&(L[this.accessToken]=e)}clearCacheVersion(){this.accessToken&&(L[this.accessToken]=0)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(H[e])},getAll(){return Promise.resolve(H)},set(e,t){return H[e]=t,Promise.resolve(void 0)},flush(){return H={},Promise.resolve(void 0)}};case"custom":if(this.cache.custom)return this.cache.custom;default:return{get(){return Promise.resolve()},getAll(){return Promise.resolve(void 0)},set(){return Promise.resolve(void 0)},flush(){return Promise.resolve(void 0)}}}}async flushCache(){return await this.cacheProvider().flush(),this.clearCacheVersion(),this}async processInlineAssets(e){if(!this.inlineAssets)return e;const t=s=>{if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(i=>t(i));let r={...s};r.fieldtype==="asset"&&Array.isArray(e.data.assets)&&(r={...e.data.assets.find(i=>i.id===r.id),...r});for(const i in r)typeof r[i]=="object"&&(r[i]=t(r[i]));return r};return e.data.story&&(e.data.story.content=t(e.data.story.content)),e.data.stories&&(e.data.stories=e.data.stories.map(s=>(s.content=t(s.content),s))),e}},ee=Te;const Ce=(e={})=>{const{apiOptions:t}=e;if(!t||!t.accessToken){console.error("You need to provide an access token to interact with Storyblok API. Read https://www.storyblok.com/docs/api/content-delivery#topics/authentication");return}return{storyblokApi:new ee(t)}},Oe=e=>{if(typeof e!="object"||typeof e._editable>"u")return{};try{const t=JSON.parse(e._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return t?{"data-blok-c":JSON.stringify(t),"data-blok-uid":`${t.id}-${t.uid}`}:{}}catch{return{}}};let F="https://app.storyblok.com/f/storyblok-v2-latest.js";const te=(e,t,s={})=>{var a;const i=!(typeof window>"u")&&typeof window.storyblokRegisterEvent<"u",n=new URL((a=window.location)==null?void 0:a.href).searchParams.get("_storyblok"),l=n!==null&&+n===e;if(!(!i||!l)){if(!e){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(s).on(["input","published","change"],c=>{var f;c&&(c.action==="input"&&((f=c.story)==null?void 0:f.id)===e?t(c.story):(c.action==="change"||c.action==="published")&&c.storyId===e&&window.location.reload())})})}},Ie=(e={})=>{var f,y;const{bridge:t,accessToken:s,use:r=[],apiOptions:i={},bridgeUrl:n}=e;i.accessToken=i.accessToken||s;const l={bridge:t,apiOptions:i};let a={};r.forEach(S=>{a={...a,...S(l)}}),n&&(F=n);const c=!(typeof window>"u")&&((y=(f=window.location)==null?void 0:f.search)==null?void 0:y.includes("_storyblok_tk"));return t!==!1&&c&&K(F),a};function Pe(e,t){return V(t).render(e)}const Ne=()=>K(F);v.BlockTypes=b,v.MarkTypes=E,v.StoryblokClient=ee,v.TextTypes=D,v.apiPlugin=Ce,v.loadStoryblokBridge=Ne,v.registerStoryblokBridge=te,v.renderRichText=Pe,v.richTextResolver=V,v.storyblokEditable=Oe,v.storyblokInit=Ie,v.useStoryblokBridge=te,Object.defineProperty(v,Symbol.toStringTag,{value:"Module"})});