@storyblok/js 4.3.0 → 4.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 Q=["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"],Z=(e={})=>Object.keys(e).map(t=>`${t}="${e[t]}"`).join(" "),ee=(e={})=>Object.keys(e).map(t=>`${t}: ${e[t]}`).join("; ");function te(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 re(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(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 0"),t.height&&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 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 F(e,t={},s){const r=Z(t),i=r?`${e} ${r}`:e,n=Array.isArray(s)?s.join(""):s||"";if(e){if(Q.includes(e))return`<${i}>`}else return n;return`<${i}>${n}</${e}>`}function z(e={}){const t=new Map,{renderFn:s=F,textFn:r=te,resolvers:i={},optimizeImages:n=!1,keyedResolvers:c=!1}=e,l=s!==F,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}=re(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:ee(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""},Y=(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)},W=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,Y],[w.ANCHOR,Y],[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]]),X=new Map([...W,...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:W,mergedResolvers:X});function N(o){const h=X.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 M=[],q=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():M.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=>{M.forEach(n=>n()),G=!0,t(i)},document.getElementsByTagName("head")[0].appendChild(r)});var se=class extends Error{constructor(e){super(e),this.name="AbortError"}};function ie(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 se("Throttle function aborted"))),r.length=0},u}var ne=ie;const V=(e="")=>e.includes("/cdn/"),oe=(e,t=25,s=1)=>({...e,per_page:t,page:s}),le=e=>new Promise(t=>setTimeout(t,e)),ae=(e=0,t)=>Array.from({length:e},t),ce=(e=0,t=e)=>{const s=Math.abs(t-e)||0,r=e<t?1:-1;return ae(s,(i,n)=>n*r+e)},ue=async(e,t)=>Promise.all(e.map(t)),he=(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 de=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)})}},fe=de;const J="SB-Agent",x={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"7.0.0"},ye={PUBLISHED:"published"};let I={};const T={};var ge=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=ne(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||ye.PUBLISHED,this.inlineAssets=e.inlineAssets||!1,this.client=new fe({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,oe(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 ue(ce(l,a),m=>this.makeRequest(n,t,i,m+1,r));return he([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 le(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={...r,...e.data.assets.find(i=>i.id===r.id)});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}},be=ge;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 be(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 K=(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&&q(j),l};function Re(e,t){return z(t).render(e)}const ke=()=>q(j);R.BlockTypes=g,R.MarkTypes=w,R.TextTypes=B,R.apiPlugin=pe,R.loadStoryblokBridge=ke,R.registerStoryblokBridge=K,R.renderRichText=Re,R.richTextResolver=z,R.storyblokEditable=me,R.storyblokInit=ve,R.useStoryblokBridge=K,Object.defineProperty(R,Symbol.toStringTag,{value:"Module"})});
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 Q=["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"],Z=(e={})=>Object.keys(e).map(t=>`${t}="${e[t]}"`).join(" "),ee=(e={})=>Object.keys(e).map(t=>`${t}: ${e[t]}`).join("; ");function te(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 re(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 F(e,t={},s){const r=Z(t),i=r?`${e} ${r}`:e,n=Array.isArray(s)?s.join(""):s||"";if(e){if(Q.includes(e))return`<${i}>`}else return n;return`<${i}>${n}</${e}>`}function z(e={}){const t=new Map,{renderFn:s=F,textFn:r=te,resolvers:i={},optimizeImages:n=!1,keyedResolvers:c=!1}=e,l=s!==F,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}=re(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:ee(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""},Y=(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)},W=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,Y],[w.ANCHOR,Y],[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]]),X=new Map([...W,...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:W,mergedResolvers:X});function N(o){const h=X.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 se=class extends Error{constructor(e){super(e),this.name="AbortError"}};function ie(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 se("Throttle function aborted"))),r.length=0},u}var ne=ie;const V=(e="")=>e.includes("/cdn/"),oe=(e,t=25,s=1)=>({...e,per_page:t,page:s}),le=e=>new Promise(t=>setTimeout(t,e)),ae=(e=0,t)=>Array.from({length:e},t),ce=(e=0,t=e)=>{const s=Math.abs(t-e)||0,r=e<t?1:-1;return ae(s,(i,n)=>n*r+e)},ue=async(e,t)=>Promise.all(e.map(t)),he=(e=[],t)=>e.map(t).reduce((s,r)=>[...s,...r],[]),x=(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=x(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 de=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}?${x(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)})}},fe=de;const J="SB-Agent",$={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"7.0.0"},ye={PUBLISHED:"published"};let I={};const T={};var ge=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,$.defaultAgentName),r.set($.defaultAgentVersion,$.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=ne(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||ye.PUBLISHED,this.inlineAssets=e.inlineAssets||!1,this.client=new fe({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,oe(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 ue(ce(l,a),m=>this.makeRequest(n,t,i,m+1,r));return he([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=x({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 le(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}},be=ge;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 be(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 K=(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 z(t).render(e)}const ke=()=>M(j);R.BlockTypes=g,R.MarkTypes=w,R.TextTypes=B,R.apiPlugin=pe,R.loadStoryblokBridge=ke,R.registerStoryblokBridge=K,R.renderRichText=Re,R.richTextResolver=z,R.storyblokEditable=me,R.storyblokInit=ve,R.useStoryblokBridge=K,Object.defineProperty(R,Symbol.toStringTag,{value:"Module"})});
@@ -47,9 +47,9 @@ function ue(e, t) {
47
47
  typeof u != "number" || u <= a || u >= g ? console.warn(`[StoryblokRichText] - ${p.charAt(0).toUpperCase() + p.slice(1)} value must be a number between ${a} and ${g} (inclusive)`) : S.push(`${p}(${u})`);
48
48
  }
49
49
  if (typeof t == "object") {
50
- if (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 0"), t.height && 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 0"), t.loading && ["lazy", "eager"].includes(t.loading) && (i.loading = t.loading), t.class && (i.class = t.class), t.filters) {
51
- const { filters: u } = t || {}, { blur: a, brightness: g, fill: p, format: S, grayscale: x, quality: w, rotate: T } = u || {};
52
- a && c(a, 0, 100, "blur", n), w && c(w, 0, 100, "quality", n), g && c(g, 0, 100, "brightness", n), p && n.push(`fill(${p})`), x && n.push("grayscale()"), T && [
50
+ 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) {
51
+ const { filters: u } = t || {}, { blur: a, brightness: g, fill: p, format: S, grayscale: I, quality: k, rotate: T } = u || {};
52
+ a && c(a, 0, 100, "blur", n), k && c(k, 0, 100, "quality", n), g && c(g, 0, 100, "brightness", n), p && n.push(`fill(${p})`), I && n.push("grayscale()"), T && [
53
53
  0,
54
54
  90,
55
55
  180,
@@ -72,7 +72,7 @@ function ue(e, t) {
72
72
  }).join(", ")), t.sizes && (i.sizes = t.sizes.join(", "));
73
73
  }
74
74
  let l = `${e}/m/`;
75
- return s > 0 && r > 0 && (l = `${l}${s}x${r}/`), n.length > 0 && (l = `${l}filters:${n.join(":")}`), {
75
+ return (s > 0 || r > 0) && (l = `${l}${s}x${r}/`), n.length > 0 && (l = `${l}filters:${n.join(":")}`), {
76
76
  src: l,
77
77
  attrs: i
78
78
  };
@@ -98,10 +98,10 @@ function he(e = {}) {
98
98
  return d.render(o, f, h.children || null);
99
99
  }, g = (o, h) => {
100
100
  const { src: d, alt: f, title: y, srcset: v, sizes: b } = o.attrs || {};
101
- let A = d, k = {};
101
+ let A = d, w = {};
102
102
  if (n) {
103
103
  const { src: te, attrs: re } = ue(d, n);
104
- A = te, k = re;
104
+ A = te, w = re;
105
105
  }
106
106
  const L = {
107
107
  src: A,
@@ -109,7 +109,7 @@ function he(e = {}) {
109
109
  title: y,
110
110
  srcset: v,
111
111
  sizes: b,
112
- ...k
112
+ ...w
113
113
  };
114
114
  return h.render("img", O(L));
115
115
  }, p = (o, h) => {
@@ -129,13 +129,13 @@ function he(e = {}) {
129
129
  "data-name": (v = o.attrs) == null ? void 0 : v.name,
130
130
  "data-emoji": (b = o.attrs) == null ? void 0 : b.emoji
131
131
  }, d);
132
- }, x = (o, h) => h.render("pre", o.attrs || {}, h.render("code", {}, o.children || "")), w = (o, h = !1) => ({ text: d, attrs: f }, y) => {
133
- const { class: v, id: b, ...A } = f || {}, k = h ? {
132
+ }, I = (o, h) => h.render("pre", o.attrs || {}, h.render("code", {}, o.children || "")), k = (o, h = !1) => ({ text: d, attrs: f }, y) => {
133
+ const { class: v, id: b, ...A } = f || {}, w = h ? {
134
134
  class: v,
135
135
  id: b,
136
136
  style: ae(A) || void 0
137
137
  } : f || {};
138
- return y.render(o, O(k), d);
138
+ return y.render(o, O(w), d);
139
139
  }, T = (o) => N(o), K = (o) => {
140
140
  const { marks: h, ...d } = o;
141
141
  if ("text" in o) {
@@ -188,23 +188,23 @@ function he(e = {}) {
188
188
  const d = u(o.attrs);
189
189
  return h.render("tr", d, o.children);
190
190
  }, Q = (o, h) => {
191
- const { colspan: d, rowspan: f, colwidth: y, backgroundColor: v, textAlign: b, ...A } = o.attrs || {}, k = [];
192
- y && k.push(`width: ${y}px;`), v && k.push(`background-color: ${v};`), b && k.push(`text-align: ${b};`);
191
+ const { colspan: d, rowspan: f, colwidth: y, backgroundColor: v, textAlign: b, ...A } = o.attrs || {}, w = [];
192
+ y && w.push(`width: ${y}px;`), v && w.push(`background-color: ${v};`), b && w.push(`text-align: ${b};`);
193
193
  const L = {
194
194
  ...A,
195
195
  ...d > 1 ? { colspan: d } : {},
196
196
  ...f > 1 ? { rowspan: f } : {},
197
- ...k.length > 0 ? { style: k.join(" ") } : {}
197
+ ...w.length > 0 ? { style: w.join(" ") } : {}
198
198
  };
199
199
  return h.render("td", O(L), o.children);
200
200
  }, Z = (o, h) => {
201
- const { colspan: d, rowspan: f, colwidth: y, backgroundColor: v, textAlign: b, ...A } = o.attrs || {}, k = [];
202
- y && k.push(`width: ${y}px;`), v && k.push(`background-color: ${v};`), b && k.push(`text-align: ${b};`);
201
+ const { colspan: d, rowspan: f, colwidth: y, backgroundColor: v, textAlign: b, ...A } = o.attrs || {}, w = [];
202
+ y && w.push(`width: ${y}px;`), v && w.push(`background-color: ${v};`), b && w.push(`text-align: ${b};`);
203
203
  const L = {
204
204
  ...A,
205
205
  ...d > 1 ? { colspan: d } : {},
206
206
  ...f > 1 ? { rowspan: f } : {},
207
- ...k.length > 0 ? { style: k.join(" ") } : {}
207
+ ...w.length > 0 ? { style: w.join(" ") } : {}
208
208
  };
209
209
  return h.render("th", O(L), o.children);
210
210
  }, B = /* @__PURE__ */ new Map([
@@ -216,7 +216,7 @@ function he(e = {}) {
216
216
  [R.LIST_ITEM, a("li")],
217
217
  [R.IMAGE, g],
218
218
  [R.EMOJI, S],
219
- [R.CODE_BLOCK, x],
219
+ [R.CODE_BLOCK, I],
220
220
  [R.HR, a("hr")],
221
221
  [R.BR, a("br")],
222
222
  [R.QUOTE, a("blockquote")],
@@ -224,16 +224,16 @@ function he(e = {}) {
224
224
  [ne.TEXT, K],
225
225
  [_.LINK, U],
226
226
  [_.ANCHOR, U],
227
- [_.STYLED, w("span", !0)],
228
- [_.BOLD, w("strong")],
229
- [_.TEXT_STYLE, w("span", !0)],
230
- [_.ITALIC, w("em")],
231
- [_.UNDERLINE, w("u")],
232
- [_.STRIKE, w("s")],
233
- [_.CODE, w("code")],
234
- [_.SUPERSCRIPT, w("sup")],
235
- [_.SUBSCRIPT, w("sub")],
236
- [_.HIGHLIGHT, w("mark")],
227
+ [_.STYLED, k("span", !0)],
228
+ [_.BOLD, k("strong")],
229
+ [_.TEXT_STYLE, k("span", !0)],
230
+ [_.ITALIC, k("em")],
231
+ [_.UNDERLINE, k("u")],
232
+ [_.STRIKE, k("s")],
233
+ [_.CODE, k("code")],
234
+ [_.SUPERSCRIPT, k("sup")],
235
+ [_.SUBSCRIPT, k("sub")],
236
+ [_.HIGHLIGHT, k("mark")],
237
237
  [R.TABLE, W],
238
238
  [R.TABLE_ROW, X],
239
239
  [R.TABLE_CELL, Q],
@@ -350,7 +350,7 @@ const V = (e = "") => e.includes("/cdn/"), ye = (e, t = 25, s = 1) => ({
350
350
  };
351
351
  return t[e] ?? t.eu;
352
352
  };
353
- var ke = class {
353
+ var we = class {
354
354
  constructor(e) {
355
355
  m(this, "baseURL");
356
356
  m(this, "timeout");
@@ -450,7 +450,7 @@ var ke = class {
450
450
  r(i);
451
451
  });
452
452
  }
453
- }, we = ke;
453
+ }, ke = we;
454
454
  const M = "SB-Agent", $ = {
455
455
  defaultAgentName: "SB-JS-CLIENT",
456
456
  defaultAgentVersion: "SB-Agent-Version",
@@ -458,7 +458,7 @@ const M = "SB-Agent", $ = {
458
458
  }, _e = {
459
459
  PUBLISHED: "published"
460
460
  };
461
- let I = {};
461
+ let x = {};
462
462
  const E = {};
463
463
  var Se = class {
464
464
  /**
@@ -495,7 +495,7 @@ var Se = class {
495
495
  r.set(c, l);
496
496
  }), r.has(M) || (r.set(M, $.defaultAgentName), r.set($.defaultAgentVersion, $.packageVersion));
497
497
  let i = 5;
498
- e.oauthToken && (r.set("Authorization", e.oauthToken), i = 3), e.rateLimit && (i = e.rateLimit), this.maxRetries = e.maxRetries || 10, this.retriesDelay = 300, this.throttle = ge(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 || _e.PUBLISHED, this.inlineAssets = e.inlineAssets || !1, this.client = new we({
498
+ e.oauthToken && (r.set("Authorization", e.oauthToken), i = 3), e.rateLimit && (i = e.rateLimit), this.maxRetries = e.maxRetries || 10, this.retriesDelay = 300, this.throttle = ge(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 || _e.PUBLISHED, this.inlineAssets = e.inlineAssets || !1, this.client = new ke({
499
499
  baseURL: s,
500
500
  timeout: e.timeout || 0,
501
501
  headers: r,
@@ -758,16 +758,16 @@ var Se = class {
758
758
  case "memory":
759
759
  return {
760
760
  get(e) {
761
- return Promise.resolve(I[e]);
761
+ return Promise.resolve(x[e]);
762
762
  },
763
763
  getAll() {
764
- return Promise.resolve(I);
764
+ return Promise.resolve(x);
765
765
  },
766
766
  set(e, t) {
767
- return I[e] = t, Promise.resolve(void 0);
767
+ return x[e] = t, Promise.resolve(void 0);
768
768
  },
769
769
  flush() {
770
- return I = {}, Promise.resolve(void 0);
770
+ return x = {}, Promise.resolve(void 0);
771
771
  }
772
772
  };
773
773
  case "custom":
@@ -799,8 +799,8 @@ var Se = class {
799
799
  if (Array.isArray(s)) return s.map((i) => t(i));
800
800
  let r = { ...s };
801
801
  r.fieldtype === "asset" && Array.isArray(e.data.assets) && (r = {
802
- ...r,
803
- ...e.data.assets.find((i) => i.id === r.id)
802
+ ...e.data.assets.find((i) => i.id === r.id),
803
+ ...r
804
804
  });
805
805
  for (const i in r) typeof r[i] == "object" && (r[i] = t(r[i]));
806
806
  return r;
@@ -871,13 +871,13 @@ const Oe = (e, t, s = {}) => {
871
871
  function Pe(e, t) {
872
872
  return he(t).render(e);
873
873
  }
874
- const Ie = () => J(H);
874
+ const xe = () => J(H);
875
875
  export {
876
876
  R as BlockTypes,
877
877
  _ as MarkTypes,
878
878
  ne as TextTypes,
879
879
  Te as apiPlugin,
880
- Ie as loadStoryblokBridge,
880
+ xe as loadStoryblokBridge,
881
881
  Oe as registerStoryblokBridge,
882
882
  Pe as renderRichText,
883
883
  he as richTextResolver,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@storyblok/js",
3
3
  "type": "module",
4
- "version": "4.3.0",
4
+ "version": "4.3.1",
5
5
  "private": false,
6
6
  "description": "SDK to integrate Storyblok into your project using JavaScript.",
7
7
  "license": "MIT",
@@ -28,8 +28,8 @@
28
28
  "dist"
29
29
  ],
30
30
  "dependencies": {
31
- "@storyblok/richtext": "3.8.0",
32
- "storyblok-js-client": "7.1.4"
31
+ "@storyblok/richtext": "3.8.1",
32
+ "storyblok-js-client": "7.1.5"
33
33
  },
34
34
  "devDependencies": {
35
35
  "@tsconfig/recommended": "^1.0.8",