@storyblok/js 3.1.0 → 3.1.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,4 +1,4 @@
1
- (function(y,E){typeof exports=="object"&&typeof module<"u"?E(exports):typeof define=="function"&&define.amd?define(["exports"],E):(y=typeof globalThis<"u"?globalThis:y||self,E(y.storyblok={}))})(this,function(y){"use strict";let E=!1;const U=[],H=i=>new Promise((e,t)=>{if(typeof window>"u"||(window.storyblokRegisterEvent=r=>{if(window.location===window.parent.location){console.warn("You are not in Draft Mode or in the Visual Editor.");return}E?r():U.push(r)},document.getElementById("storyblok-javascript-bridge")))return;const s=document.createElement("script");s.async=!0,s.src=i,s.id="storyblok-javascript-bridge",s.onerror=r=>t(r),s.onload=r=>{U.forEach(n=>n()),E=!0,e(r)},document.getElementsByTagName("head")[0].appendChild(s)});var F=Object.defineProperty,K=(i,e,t)=>e in i?F(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,p=(i,e,t)=>K(i,typeof e!="symbol"?e+"":e,t);function B(i){return!(i!==i||i===1/0||i===-1/0)}function Y(i,e,t){if(!B(e))throw new TypeError("Expected `limit` to be a finite number");if(!B(t))throw new TypeError("Expected `interval` to be a finite number");const s=[];let r=[],n=0;const o=function(){n++;const a=setTimeout(function(){n--,s.length>0&&o(),r=r.filter(function(d){return d!==a})},t);r.indexOf(a)<0&&r.push(a);const h=s.shift();h.resolve(i.apply(h.self,h.args))},l=function(...a){const h=this;return new Promise(function(d,u){s.push({resolve:d,reject:u,args:a,self:h}),n<e&&o()})};return l.abort=function(){r.forEach(clearTimeout),r=[],s.forEach(function(a){a.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),s.length=0},l}class O{constructor(){p(this,"isCDNUrl",(e="")=>e.indexOf("/cdn/")>-1),p(this,"getOptionsPage",(e,t=25,s=1)=>({...e,per_page:t,page:s})),p(this,"delay",e=>new Promise(t=>setTimeout(t,e))),p(this,"arrayFrom",(e=0,t)=>[...Array(e)].map(t)),p(this,"range",(e=0,t=e)=>{const s=Math.abs(t-e)||0,r=e<t?1:-1;return this.arrayFrom(s,(n,o)=>o*r+e)}),p(this,"asyncMap",async(e,t)=>Promise.all(e.map(t))),p(this,"flatMap",(e=[],t)=>e.map(t).reduce((s,r)=>[...s,...r],[])),p(this,"escapeHTML",function(e){const t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},s=/[&<>"']/g,r=RegExp(s.source);return e&&r.test(e)?e.replace(s,n=>t[n]):e})}stringify(e,t,s){const r=[];for(const n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;const o=e[n],l=s?"":encodeURIComponent(n);let a;typeof o=="object"?a=this.stringify(o,t?t+encodeURIComponent("["+l+"]"):l,Array.isArray(o)):a=(t?t+encodeURIComponent("["+l+"]"):l)+"="+encodeURIComponent(o),r.push(a)}return r.join("&")}getRegionURL(e){const t="api.storyblok.com",s="api-us.storyblok.com",r="app.storyblokchina.cn",n="api-ap.storyblok.com",o="api-ca.storyblok.com";switch(e){case"us":return s;case"cn":return r;case"ap":return n;case"ca":return o;default:return t}}}const X=function(i,e){const t={};for(const s in i){const r=i[s];e.indexOf(s)>-1&&r!==null&&(t[s]=r)}return t},W=i=>i==="email",Q=()=>({singleTag:"hr"}),Z=()=>({tag:"blockquote"}),ee=()=>({tag:"ul"}),te=i=>({tag:["pre",{tag:"code",attrs:i.attrs}]}),se=()=>({singleTag:"br"}),re=i=>({tag:`h${i.attrs.level}`}),ie=i=>({singleTag:[{tag:"img",attrs:X(i.attrs,["src","alt","title"])}]}),ne=()=>({tag:"li"}),oe=()=>({tag:"ol"}),ae=()=>({tag:"p"}),le=i=>({tag:[{tag:"span",attrs:{"data-type":"emoji","data-name":i.attrs.name,emoji:i.attrs.emoji}}]}),ce=()=>({tag:"b"}),he=()=>({tag:"s"}),ue=()=>({tag:"u"}),de=()=>({tag:"strong"}),pe=()=>({tag:"code"}),ge=()=>({tag:"i"}),fe=i=>{if(!i.attrs)return{tag:""};const e=new O().escapeHTML,t={...i.attrs},{linktype:s="url"}=i.attrs;if(delete t.linktype,t.href&&(t.href=e(i.attrs.href||"")),W(s)&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),t.custom){for(const r in t.custom)t[r]=t.custom[r];delete t.custom}return{tag:[{tag:"a",attrs:t}]}},me=i=>({tag:[{tag:"span",attrs:i.attrs}]}),ye=()=>({tag:"sub"}),be=()=>({tag:"sup"}),ke=i=>({tag:[{tag:"span",attrs:i.attrs}]}),ve=i=>{var e;return(e=i.attrs)!=null&&e.color?{tag:[{tag:"span",attrs:{style:`background-color:${i.attrs.color};`}}]}:{tag:""}},$e=i=>{var e;return(e=i.attrs)!=null&&e.color?{tag:[{tag:"span",attrs:{style:`color:${i.attrs.color}`}}]}:{tag:""}},D={nodes:{horizontal_rule:Q,blockquote:Z,bullet_list:ee,code_block:te,hard_break:se,heading:re,image:ie,list_item:ne,ordered_list:oe,paragraph:ae,emoji:le},marks:{bold:ce,strike:he,underline:ue,strong:de,code:pe,italic:ge,link:fe,styled:me,subscript:ye,superscript:be,anchor:ke,highlight:ve,textStyle:$e}},Te=function(i){const e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},t=/[&<>"']/g,s=RegExp(t.source);return i&&s.test(i)?i.replace(t,r=>e[r]):i};class Re{constructor(e){p(this,"marks"),p(this,"nodes"),e||(e=D),this.marks=e.marks||[],this.nodes=e.nodes||[]}addNode(e,t){this.nodes[e]=t}addMark(e,t){this.marks[e]=t}render(e,t={optimizeImages:!1}){if(console.warn("Warning ⚠️: The RichTextResolver class is deprecated and will be removed in the next major release. Please use the `@storyblok/richtext` package instead. https://github.com/storyblok/richtext/"),e&&e.content&&Array.isArray(e.content)){let s="";return e.content.forEach(r=>{s+=this.renderNode(r)}),t.optimizeImages?this.optimizeImages(s,t.optimizeImages):s}return console.warn(`The render method must receive an Object with a "content" field.
1
+ (function(y,E){typeof exports=="object"&&typeof module<"u"?E(exports):typeof define=="function"&&define.amd?define(["exports"],E):(y=typeof globalThis<"u"?globalThis:y||self,E(y.storyblok={}))})(this,function(y){"use strict";let E=!1;const H=[],U=i=>new Promise((e,t)=>{if(typeof window>"u"||(window.storyblokRegisterEvent=r=>{if(window.location===window.parent.location){console.warn("You are not in Draft Mode or in the Visual Editor.");return}E?r():H.push(r)},document.getElementById("storyblok-javascript-bridge")))return;const s=document.createElement("script");s.async=!0,s.src=i,s.id="storyblok-javascript-bridge",s.onerror=r=>t(r),s.onload=r=>{H.forEach(n=>n()),E=!0,e(r)},document.getElementsByTagName("head")[0].appendChild(s)});var F=Object.defineProperty,K=(i,e,t)=>e in i?F(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,p=(i,e,t)=>K(i,typeof e!="symbol"?e+"":e,t);function B(i){return!(i!==i||i===1/0||i===-1/0)}function Y(i,e,t){if(!B(e))throw new TypeError("Expected `limit` to be a finite number");if(!B(t))throw new TypeError("Expected `interval` to be a finite number");const s=[];let r=[],n=0;const o=function(){n++;const a=setTimeout(function(){n--,s.length>0&&o(),r=r.filter(function(d){return d!==a})},t);r.indexOf(a)<0&&r.push(a);const h=s.shift();h.resolve(i.apply(h.self,h.args))},l=function(...a){const h=this;return new Promise(function(d,u){s.push({resolve:d,reject:u,args:a,self:h}),n<e&&o()})};return l.abort=function(){r.forEach(clearTimeout),r=[],s.forEach(function(a){a.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),s.length=0},l}class O{constructor(){p(this,"isCDNUrl",(e="")=>e.indexOf("/cdn/")>-1),p(this,"getOptionsPage",(e,t=25,s=1)=>({...e,per_page:t,page:s})),p(this,"delay",e=>new Promise(t=>setTimeout(t,e))),p(this,"arrayFrom",(e=0,t)=>[...Array(e)].map(t)),p(this,"range",(e=0,t=e)=>{const s=Math.abs(t-e)||0,r=e<t?1:-1;return this.arrayFrom(s,(n,o)=>o*r+e)}),p(this,"asyncMap",async(e,t)=>Promise.all(e.map(t))),p(this,"flatMap",(e=[],t)=>e.map(t).reduce((s,r)=>[...s,...r],[])),p(this,"escapeHTML",function(e){const t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},s=/[&<>"']/g,r=RegExp(s.source);return e&&r.test(e)?e.replace(s,n=>t[n]):e})}stringify(e,t,s){const r=[];for(const n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;const o=e[n],l=s?"":encodeURIComponent(n);let a;typeof o=="object"?a=this.stringify(o,t?t+encodeURIComponent("["+l+"]"):l,Array.isArray(o)):a=(t?t+encodeURIComponent("["+l+"]"):l)+"="+encodeURIComponent(o),r.push(a)}return r.join("&")}getRegionURL(e){const t="api.storyblok.com",s="api-us.storyblok.com",r="app.storyblokchina.cn",n="api-ap.storyblok.com",o="api-ca.storyblok.com";switch(e){case"us":return s;case"cn":return r;case"ap":return n;case"ca":return o;default:return t}}}const X=function(i,e){const t={};for(const s in i){const r=i[s];e.indexOf(s)>-1&&r!==null&&(t[s]=r)}return t},W=i=>i==="email",Q=()=>({singleTag:"hr"}),Z=()=>({tag:"blockquote"}),ee=()=>({tag:"ul"}),te=i=>({tag:["pre",{tag:"code",attrs:i.attrs}]}),se=()=>({singleTag:"br"}),re=i=>({tag:`h${i.attrs.level}`}),ie=i=>({singleTag:[{tag:"img",attrs:X(i.attrs,["src","alt","title"])}]}),ne=()=>({tag:"li"}),oe=()=>({tag:"ol"}),ae=()=>({tag:"p"}),le=i=>({tag:[{tag:"span",attrs:{"data-type":"emoji","data-name":i.attrs.name,emoji:i.attrs.emoji}}]}),ce=()=>({tag:"b"}),he=()=>({tag:"s"}),ue=()=>({tag:"u"}),de=()=>({tag:"strong"}),pe=()=>({tag:"code"}),ge=()=>({tag:"i"}),fe=i=>{if(!i.attrs)return{tag:""};const e=new O().escapeHTML,t={...i.attrs},{linktype:s="url"}=i.attrs;if(delete t.linktype,t.href&&(t.href=e(i.attrs.href||"")),W(s)&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),t.custom){for(const r in t.custom)t[r]=t.custom[r];delete t.custom}return{tag:[{tag:"a",attrs:t}]}},me=i=>({tag:[{tag:"span",attrs:i.attrs}]}),ye=()=>({tag:"sub"}),be=()=>({tag:"sup"}),ke=i=>({tag:[{tag:"span",attrs:i.attrs}]}),ve=i=>{var e;return(e=i.attrs)!=null&&e.color?{tag:[{tag:"span",attrs:{style:`background-color:${i.attrs.color};`}}]}:{tag:""}},$e=i=>{var e;return(e=i.attrs)!=null&&e.color?{tag:[{tag:"span",attrs:{style:`color:${i.attrs.color}`}}]}:{tag:""}},D={nodes:{horizontal_rule:Q,blockquote:Z,bullet_list:ee,code_block:te,hard_break:se,heading:re,image:ie,list_item:ne,ordered_list:oe,paragraph:ae,emoji:le},marks:{bold:ce,strike:he,underline:ue,strong:de,code:pe,italic:ge,link:fe,styled:me,subscript:ye,superscript:be,anchor:ke,highlight:ve,textStyle:$e}},Te=function(i){const e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},t=/[&<>"']/g,s=RegExp(t.source);return i&&s.test(i)?i.replace(t,r=>e[r]):i};class Re{constructor(e){p(this,"marks"),p(this,"nodes"),e||(e=D),this.marks=e.marks||[],this.nodes=e.nodes||[]}addNode(e,t){this.nodes[e]=t}addMark(e,t){this.marks[e]=t}render(e,t={optimizeImages:!1}){if(console.warn("Warning ⚠️: The RichTextResolver class is deprecated and will be removed in the next major release. Please use the `@storyblok/richtext` package instead. https://github.com/storyblok/richtext/"),e&&e.content&&Array.isArray(e.content)){let s="";return e.content.forEach(r=>{s+=this.renderNode(r)}),t.optimizeImages?this.optimizeImages(s,t.optimizeImages):s}return console.warn(`The render method must receive an Object with a "content" field.
2
2
  The "content" field must be an array of nodes as the type ISbRichtext.
3
3
  ISbRichtext:
4
4
  content?: ISbRichtext[]
@@ -21,4 +21,4 @@
21
21
  }
22
22
  ],
23
23
  type: 'doc'
24
- }`),""}optimizeImages(e,t){let s=0,r=0,n="",o="";typeof t!="boolean"&&(typeof t.width=="number"&&t.width>0&&(n+=`width="${t.width}" `,s=t.width),typeof t.height=="number"&&t.height>0&&(n+=`height="${t.height}" `,r=t.height),(t.loading==="lazy"||t.loading==="eager")&&(n+=`loading="${t.loading}" `),typeof t.class=="string"&&t.class.length>0&&(n+=`class="${t.class}" `),t.filters&&(typeof t.filters.blur=="number"&&t.filters.blur>=0&&t.filters.blur<=100&&(o+=`:blur(${t.filters.blur})`),typeof t.filters.brightness=="number"&&t.filters.brightness>=-100&&t.filters.brightness<=100&&(o+=`:brightness(${t.filters.brightness})`),t.filters.fill&&(t.filters.fill.match(/[0-9A-Fa-f]{6}/g)||t.filters.fill==="transparent")&&(o+=`:fill(${t.filters.fill})`),t.filters.format&&["webp","png","jpeg"].includes(t.filters.format)&&(o+=`:format(${t.filters.format})`),typeof t.filters.grayscale=="boolean"&&t.filters.grayscale&&(o+=":grayscale()"),typeof t.filters.quality=="number"&&t.filters.quality>=0&&t.filters.quality<=100&&(o+=`:quality(${t.filters.quality})`),t.filters.rotate&&[90,180,270].includes(t.filters.rotate)&&(o+=`:rotate(${t.filters.rotate})`),o.length>0&&(o="/filters"+o))),n.length>0&&(e=e.replace(/<img/g,`<img ${n.trim()}`));const l=s>0||r>0||o.length>0?`${s}x${r}${o}`:"";return e=e.replace(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g,`a.storyblok.com/f/$1/$2.$3/m/${l}`),typeof t!="boolean"&&(t.sizes||t.srcset)&&(e=e.replace(/<img.*?src=["|'](.*?)["|']/g,a=>{var h,d;const u=a.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);if(u&&u.length>0){const m={srcset:(h=t.srcset)==null?void 0:h.map(b=>{if(typeof b=="number")return`//${u}/m/${b}x0${o} ${b}w`;if(typeof b=="object"&&b.length===2){let S=0,L=0;return typeof b[0]=="number"&&(S=b[0]),typeof b[1]=="number"&&(L=b[1]),`//${u}/m/${S}x${L}${o} ${S}w`}}).join(", "),sizes:(d=t.sizes)==null?void 0:d.map(b=>b).join(", ")};let $="";return m.srcset&&($+=`srcset="${m.srcset}" `),m.sizes&&($+=`sizes="${m.sizes}" `),a.replace(/<img/g,`<img ${$.trim()}`)}return a})),e}renderNode(e){const t=[];e.marks&&e.marks.forEach(r=>{const n=this.getMatchingMark(r);n&&n.tag!==""&&t.push(this.renderOpeningTag(n.tag))});const s=this.getMatchingNode(e);return s&&s.tag&&t.push(this.renderOpeningTag(s.tag)),e.content?e.content.forEach(r=>{t.push(this.renderNode(r))}):e.text?t.push(Te(e.text)):s&&s.singleTag?t.push(this.renderTag(s.singleTag," /")):s&&s.html?t.push(s.html):e.type==="emoji"&&t.push(this.renderEmoji(e)),s&&s.tag&&t.push(this.renderClosingTag(s.tag)),e.marks&&e.marks.slice(0).reverse().forEach(r=>{const n=this.getMatchingMark(r);n&&n.tag!==""&&t.push(this.renderClosingTag(n.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(s=>{if(s.constructor===String)return`<${s}${t}>`;{let r=`<${s.tag}`;if(s.attrs){for(const n in s.attrs)if(Object.prototype.hasOwnProperty.call(s.attrs,n)){const o=s.attrs[n];o!==null&&(r+=` ${n}="${o}"`)}}return`${r}${t}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(t=>t.constructor===String?`</${t}>`:`</${t.tag}>`).join("")}getMatchingNode(e){const t=this.nodes[e.type];if(typeof t=="function")return t(e)}getMatchingMark(e){const t=this.marks[e.type];if(typeof t=="function")return t(e)}renderEmoji(e){if(e.attrs.emoji)return e.attrs.emoji;const t=[{tag:"img",attrs:{src:e.attrs.fallbackImage,draggable:"false",loading:"lazy",align:"absmiddle"}}];return this.renderTag(t," /")}}const I=Re;class we{constructor(e){p(this,"baseURL"),p(this,"timeout"),p(this,"headers"),p(this,"responseInterceptor"),p(this,"fetch"),p(this,"ejectInterceptor"),p(this,"url"),p(this,"parameters"),p(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;if(e==="get"){const a=new O;t=`${this.baseURL}${this.url}?${a.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const r=new URL(t),n=new AbortController,{signal:o}=n;let l;this.timeout&&(l=setTimeout(()=>n.abort(),this.timeout));try{const a=await this.fetch(`${r}`,{method:e,headers:this.headers,body:s,signal:o,...this.fetchOptions});this.timeout&&clearTimeout(l);const h=await this._responseHandler(a);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(h)):this._statusHandler(h)}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}_statusHandler(e){const t=/20[0-6]/g;return new Promise((s,r)=>{if(t.test(`${e.status}`))return s(e);const n={message:e.statusText,status:e.status,response:Array.isArray(e.data)?e.data[0]:e.data.error||e.data.slug};r(n)})}}const Se=we,z="SB-Agent",A={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"6.0.0"};let x={};const _={};class _e{constructor(e,t){p(this,"client"),p(this,"maxRetries"),p(this,"retriesDelay"),p(this,"throttle"),p(this,"accessToken"),p(this,"cache"),p(this,"helpers"),p(this,"resolveCounter"),p(this,"relations"),p(this,"links"),p(this,"richTextResolver"),p(this,"resolveNestedRelations"),p(this,"stringifiedStoriesCache");let s=e.endpoint||t;if(!s){const o=new O().getRegionURL,l=e.https===!1?"http":"https";e.oauthToken?s=`${l}://${o(e.region)}/v1`:s=`${l}://${o(e.region)}/v2`}const r=new Headers;r.set("Content-Type","application/json"),r.set("Accept","application/json"),e.headers&&e.headers.entries().toArray().forEach(([o,l])=>{r.set(o,l)}),r.has(z)||(r.set(z,A.defaultAgentName),r.set(A.defaultAgentVersion,A.packageVersion));let n=5;e.oauthToken&&(r.set("Authorization",e.oauthToken),n=3),e.rateLimit&&(n=e.rateLimit),e.richTextSchema?this.richTextResolver=new I(e.richTextSchema):this.richTextResolver=new I,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||10,this.retriesDelay=300,this.throttle=Y(this.throttledRequest,n,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new O,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.stringifiedStoriesCache={},this.client=new Se({baseURL:s,timeout:e.timeout||0,headers:r,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let s="";return t.attrs.body&&t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})}parseParams(e){return e.token||(e.token=this.getToken()),e.cv||(e.cv=_[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 this.helpers.isCDNUrl(e)?this.parseParams(t):t}makeRequest(e,t,s,r,n){const o=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,s,r));return this.cacheResponse(e,o,void 0,n)}get(e,t,s){t||(t={});const r=`/${e}`,n=this.factoryParamOptions(r,t);return this.cacheResponse(r,n,void 0,s)}async getAll(e,t,s,r){const n=(t==null?void 0:t.per_page)||25,o=`/${e}`,l=o.split("/"),a=s||l[l.length-1],h=1,d=await this.makeRequest(o,t,n,h,r),u=d.total?Math.ceil(d.total/n):1,m=await this.helpers.asyncMap(this.helpers.range(h,u),$=>this.makeRequest(o,t,n,$+1,r));return this.helpers.flatMap([d,...m],$=>Object.values($.data[a]))}post(e,t,s){const r=`/${e}`;return Promise.resolve(this.throttle("post",r,t,s))}put(e,t,s){const r=`/${e}`;return Promise.resolve(this.throttle("put",r,t,s))}delete(e,t,s){const r=`/${e}`;return Promise.resolve(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]?(this.stringifiedStoriesCache[t]||(this.stringifiedStoriesCache[t]=JSON.stringify(this.relations[e][t])),JSON.parse(this.stringifiedStoriesCache[t])):t}_insertRelations(e,t,s,r){s.indexOf(`${e.component}.${t}`)>-1&&(typeof e[t]=="string"?e[t]=this.getStoryReference(r,e[t]):Array.isArray(e[t])&&(e[t]=e[t].map(n=>this.getStoryReference(r,n)).filter(Boolean)))}iterateTree(e,t,s){const r=n=>{if(n!=null){if(n.constructor===Array)for(let o=0;o<n.length;o++)r(n[o]);else if(n.constructor===Object){if(n._stopResolving)return;for(const o in n)(n.component&&n._uid||n.type==="link")&&(this._insertRelations(n,o,t,s),this._insertLinks(n,o,s)),r(n[o])}}};r(e.content)}async resolveLinks(e,t,s){let r=[];if(e.link_uuids){const n=e.link_uuids.length,o=[],l=50;for(let a=0;a<n;a+=l){const h=Math.min(n,a+l);o.push(e.link_uuids.slice(a,h))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:o[a].join(",")})).data.stories.forEach(h=>{r.push(h)})}else r=e.links;r.forEach(n=>{this.links[s][n.uuid]={...n,_stopResolving:!0}})}async resolveRelations(e,t,s){let r=[];if(e.rel_uuids){const n=e.rel_uuids.length,o=[],l=50;for(let a=0;a<n;a+=l){const h=Math.min(n,a+l);o.push(e.rel_uuids.slice(a,h))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:o[a].join(","),excluding_fields:t.excluding_fields})).data.stories.forEach(h=>{r.push(h)})}else r=e.rels;r&&r.length>0&&r.forEach(n=>{this.relations[s][n.uuid]={...n,_stopResolving:!0}})}async resolveStories(e,t,s){var r,n;let o=[];if(this.links[s]={},this.relations[s]={},typeof t.resolve_relations<"u"&&t.resolve_relations.length>0&&(typeof t.resolve_relations=="string"&&(o=t.resolve_relations.split(",")),await this.resolveRelations(e,t,s)),t.resolve_links&&["1","story","url","link"].indexOf(t.resolve_links)>-1&&((r=e.links)!=null&&r.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],o,s);e.story?this.iterateTree(e.story,o,s):e.stories.forEach(l=>{this.iterateTree(l,o,s)}),this.stringifiedStoriesCache={},delete this.links[s],delete this.relations[s]}async cacheResponse(e,t,s,r){const n=this.helpers.stringify({url:e,params:t}),o=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&await this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const l=await o.get(n);if(l)return Promise.resolve(l)}return new Promise(async(l,a)=>{var h;try{const d=await this.throttle("get",e,t,r);if(d.status!==200)return a(d);let u={data:d.data,headers:d.headers};if((h=d.headers)!=null&&h["per-page"]&&(u=Object.assign({},u,{perPage:d.headers["per-page"]?parseInt(d.headers["per-page"]):0,total:d.headers["per-page"]?parseInt(d.headers.total):0})),u.data.story||u.data.stories){const m=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(u.data,t,`${m}`)}return t.version==="published"&&e!="/cdn/spaces/me"&&await o.set(n,u),u.data.cv&&t.token&&(t.version==="draft"&&_[t.token]!=u.data.cv&&await this.flushCache(),_[t.token]=t.cv?t.cv:u.data.cv),l(u)}catch(d){if(d.response&&d.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 this.helpers.delay(this.retriesDelay),this.cacheResponse(e,t,s).then(l).catch(a);a(d)}})}throttledRequest(e,t,s,r){return this.client.setFetchOptions(r),this.client[e](t,s)}cacheVersions(){return _}cacheVersion(){return _[this.accessToken]}setCacheVersion(e){this.accessToken&&(_[this.accessToken]=e)}clearCacheVersion(){this.accessToken&&(_[this.accessToken]=0)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(x[e])},getAll(){return Promise.resolve(x)},set(e,t){return x[e]=t,Promise.resolve(void 0)},flush(){return x={},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}}const Ee=(i={})=>{const{apiOptions:e}=i;if(!e.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 _e(e)}},Ie=i=>{if(typeof i!="object"||typeof i._editable>"u")return{};try{const e=JSON.parse(i._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return e?{"data-blok-c":JSON.stringify(e),"data-blok-uid":e.id+"-"+e.uid}:{}}catch{return{}}};var k=(i=>(i.DOCUMENT="doc",i.HEADING="heading",i.PARAGRAPH="paragraph",i.QUOTE="blockquote",i.OL_LIST="ordered_list",i.UL_LIST="bullet_list",i.LIST_ITEM="list_item",i.CODE_BLOCK="code_block",i.HR="horizontal_rule",i.BR="hard_break",i.IMAGE="image",i.EMOJI="emoji",i.COMPONENT="blok",i))(k||{}),v=(i=>(i.BOLD="bold",i.STRONG="strong",i.STRIKE="strike",i.UNDERLINE="underline",i.ITALIC="italic",i.CODE="code",i.LINK="link",i.ANCHOR="anchor",i.STYLED="styled",i.SUPERSCRIPT="superscript",i.SUBSCRIPT="subscript",i.TEXT_STYLE="textStyle",i.HIGHLIGHT="highlight",i))(v||{}),C=(i=>(i.TEXT="text",i))(C||{}),j=(i=>(i.URL="url",i.STORY="story",i.ASSET="asset",i.EMAIL="email",i))(j||{});function je(i,e){if(!e)return{src:i,attrs:{}};let t=0,s=0;const r={},n=[];function o(a,h,d,u,m){typeof a!="number"||a<=h||a>=d?console.warn(`[StoryblokRichText] - ${u.charAt(0).toUpperCase()+u.slice(1)} value must be a number between ${h} and ${d} (inclusive)`):m.push(`${u}(${a})`)}if(typeof e=="object"){if(typeof e.width=="number"&&e.width>0?(r.width=e.width,t=e.width):console.warn("[StoryblokRichText] - Width value must be a number greater than 0"),e.height&&typeof e.height=="number"&&e.height>0?(r.height=e.height,s=e.height):console.warn("[StoryblokRichText] - Height value must be a number greater than 0"),e.loading&&["lazy","eager"].includes(e.loading)&&(r.loading=e.loading),e.class&&(r.class=e.class),e.filters){const{filters:a}=e||{},{blur:h,brightness:d,fill:u,format:m,grayscale:$,quality:b,rotate:S}=a||{};h&&o(h,0,100,"blur",n),b&&o(b,0,100,"quality",n),d&&o(d,0,100,"brightness",n),u&&n.push(`fill(${u})`),$&&n.push("grayscale()"),S&&[0,90,180,270].includes(e.filters.rotate||0)&&n.push(`rotate(${S})`),m&&["webp","png","jpeg"].includes(m)&&n.push(`format(${m})`)}e.srcset&&(r.srcset=e.srcset.map(a=>{if(typeof a=="number")return`${i}/m/${a}x0/${n.length>0?"filters:"+n.join(":"):""} ${a}w`;if(Array.isArray(a)&&a.length===2){const[h,d]=a;return`${i}/m/${h}x${d}/${n.length>0?"filters:"+n.join(":"):""} ${h}w`}}).join(", ")),e.sizes&&(r.sizes=e.sizes.join(", "))}let l=`${i}/m/`;return t>0&&s>0&&(l=`${l}${t}x${s}/`),n.length>0&&(l=`${l}filters:${n.join(":")}`),{src:l,attrs:r}}const Oe=(i={})=>Object.keys(i).map(e=>`${e}="${i[e]}"`).join(" "),xe=(i={})=>Object.keys(i).map(e=>`${e}: ${i[e]}`).join("; ");function Le(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function Ae(i,e={},t){const s=Oe(e);return`<${s?`${i} ${s}`:i}>${Array.isArray(t)?t.join(""):t||""}</${i}>`}function Ce(i={}){let e=0;const{renderFn:t=Ae,textFn:s=Le,resolvers:r={},optimizeImages:n=!1}=i,o=c=>g=>t(c,{...g.attrs,key:`${c}-${e}`},g.children||null),l=c=>{const{src:g,alt:f,...T}=c.attrs||{};let R=g,w={};if(n){const{src:He,attrs:Be}=je(g,n);R=He,w=Be}const Ue={src:R,alt:f||"",key:`img-${e}`,...T,...w};return t("img",Ue,"")},a=c=>{const{level:g,...f}=c.attrs||{};return t(`h${g}`,{...f,key:`h${g}-${e}`},c.children)},h=c=>{var g,f,T,R;return t("span",{"data-type":"emoji","data-name":(g=c.attrs)==null?void 0:g.name,emoji:(f=c.attrs)==null?void 0:f.emoji,key:`emoji-${e}`},t("img",{src:(T=c.attrs)==null?void 0:T.fallbackImage,alt:(R=c.attrs)==null?void 0:R.alt,style:"width: 1.25em; height: 1.25em; vertical-align: text-top",draggable:"false",loading:"lazy"},""))},d=c=>t("pre",{...c.attrs,key:`code-${e}`},t("code",{key:`code-${e}`},c.children||"")),u=(c,g=!1)=>({text:f,attrs:T})=>t(c,g?{style:xe(T),key:`${c}-${e}`}:{...T,key:`${c}-${e}`},f),m=c=>M(c),$=c=>{const{marks:g,...f}=c;return"text"in c?g?g.reduce((T,R)=>m({...R,text:T}),m({...f,children:f.children})):s(f.text):""},b=c=>{const{linktype:g,href:f,anchor:T,...R}=c.attrs||{};let w="";switch(g){case j.ASSET:case j.URL:w=f;break;case j.EMAIL:w=`mailto:${f}`;break;case j.STORY:w=f;break}return T&&(w=`${w}#${T}`),t("a",{...R,href:w,key:`a-${e}`},c.text)},S=c=>{var g,f;return console.warn("[StoryblokRichtText] - BLOK resolver is not available for vanilla usage"),t("span",{blok:(g=c==null?void 0:c.attrs)==null?void 0:g.body[0],id:(f=c.attrs)==null?void 0:f.id,key:`component-${e}`,style:"display: none"},"")},L=new Map([[k.DOCUMENT,o("div")],[k.HEADING,a],[k.PARAGRAPH,o("p")],[k.UL_LIST,o("ul")],[k.OL_LIST,o("ol")],[k.LIST_ITEM,o("li")],[k.IMAGE,l],[k.EMOJI,h],[k.CODE_BLOCK,d],[k.HR,o("hr")],[k.BR,o("br")],[k.QUOTE,o("blockquote")],[k.COMPONENT,S],[C.TEXT,$],[v.LINK,b],[v.ANCHOR,b],[v.STYLED,u("span",!0)],[v.BOLD,u("strong")],[v.TEXT_STYLE,u("span",!0)],[v.ITALIC,u("em")],[v.UNDERLINE,u("u")],[v.STRIKE,u("s")],[v.CODE,u("code")],[v.SUPERSCRIPT,u("sup")],[v.SUBSCRIPT,u("sub")],[v.HIGHLIGHT,u("mark")],...Object.entries(r).map(([c,g])=>[c,g])]);function J(c){e+=1;const g=L.get(c.type);if(!g)return console.error("<Storyblok>",`No resolver found for node type ${c.type}`),"";if(c.type==="text")return g(c);const f=c.content?c.content.map(M):void 0;return g({...c,children:f})}function M(c){return Array.isArray(c)?c.map(J):J(c)}return{render:M}}let P,N="https://app.storyblok.com/f/storyblok-v2-latest.js";const q=(i,e,t={})=>{var l;const r=!(typeof window>"u")&&typeof window.storyblokRegisterEvent<"u",o=+new URL((l=window.location)==null?void 0:l.href).searchParams.get("_storyblok")===i;if(!(!r||!o)){if(!i){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(t).on(["input","published","change"],h=>{h.action==="input"&&h.story.id===i?e(h.story):(h.action==="change"||h.action==="published")&&h.storyId===i&&window.location.reload()})})}},Pe=(i={})=>{var u,m;const{bridge:e,accessToken:t,use:s=[],apiOptions:r={},richText:n={},bridgeUrl:o}=i;r.accessToken=r.accessToken||t;const l={bridge:e,apiOptions:r};let a={};s.forEach($=>{a={...a,...$(l)}}),o&&(N=o);const d=!(typeof window>"u")&&((m=(u=window.location)==null?void 0:u.search)==null?void 0:m.includes("_storyblok_tk"));return e!==!1&&d&&H(N),P=new I(n.schema),n.resolver&&G(P,n.resolver),a},G=(i,e)=>{i.addNode("blok",t=>{let s="";return t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})},V=i=>!i||!(i!=null&&i.content.some(e=>e.content||e.type==="blok"||e.type==="horizontal_rule")),Ne=(i,e,t)=>{let s=t||P;if(!s){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return V(i)?"":(e&&(s=new I(e.schema),e.resolver&&G(s,e.resolver)),s.render(i))},Me=()=>H(N);y.BlockTypes=k,y.MarkTypes=v,y.RichTextResolver=I,y.RichTextSchema=D,y.TextTypes=C,y.apiPlugin=Ee,y.isRichTextEmpty=V,y.loadStoryblokBridge=Me,y.registerStoryblokBridge=q,y.renderRichText=Ne,y.richTextResolver=Ce,y.storyblokEditable=Ie,y.storyblokInit=Pe,y.useStoryblokBridge=q,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"})});
24
+ }`),""}optimizeImages(e,t){let s=0,r=0,n="",o="";typeof t!="boolean"&&(typeof t.width=="number"&&t.width>0&&(n+=`width="${t.width}" `,s=t.width),typeof t.height=="number"&&t.height>0&&(n+=`height="${t.height}" `,r=t.height),(t.loading==="lazy"||t.loading==="eager")&&(n+=`loading="${t.loading}" `),typeof t.class=="string"&&t.class.length>0&&(n+=`class="${t.class}" `),t.filters&&(typeof t.filters.blur=="number"&&t.filters.blur>=0&&t.filters.blur<=100&&(o+=`:blur(${t.filters.blur})`),typeof t.filters.brightness=="number"&&t.filters.brightness>=-100&&t.filters.brightness<=100&&(o+=`:brightness(${t.filters.brightness})`),t.filters.fill&&(t.filters.fill.match(/[0-9A-Fa-f]{6}/g)||t.filters.fill==="transparent")&&(o+=`:fill(${t.filters.fill})`),t.filters.format&&["webp","png","jpeg"].includes(t.filters.format)&&(o+=`:format(${t.filters.format})`),typeof t.filters.grayscale=="boolean"&&t.filters.grayscale&&(o+=":grayscale()"),typeof t.filters.quality=="number"&&t.filters.quality>=0&&t.filters.quality<=100&&(o+=`:quality(${t.filters.quality})`),t.filters.rotate&&[90,180,270].includes(t.filters.rotate)&&(o+=`:rotate(${t.filters.rotate})`),o.length>0&&(o="/filters"+o))),n.length>0&&(e=e.replace(/<img/g,`<img ${n.trim()}`));const l=s>0||r>0||o.length>0?`${s}x${r}${o}`:"";return e=e.replace(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g,`a.storyblok.com/f/$1/$2.$3/m/${l}`),typeof t!="boolean"&&(t.sizes||t.srcset)&&(e=e.replace(/<img.*?src=["|'](.*?)["|']/g,a=>{var h,d;const u=a.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);if(u&&u.length>0){const m={srcset:(h=t.srcset)==null?void 0:h.map(b=>{if(typeof b=="number")return`//${u}/m/${b}x0${o} ${b}w`;if(typeof b=="object"&&b.length===2){let S=0,L=0;return typeof b[0]=="number"&&(S=b[0]),typeof b[1]=="number"&&(L=b[1]),`//${u}/m/${S}x${L}${o} ${S}w`}}).join(", "),sizes:(d=t.sizes)==null?void 0:d.map(b=>b).join(", ")};let $="";return m.srcset&&($+=`srcset="${m.srcset}" `),m.sizes&&($+=`sizes="${m.sizes}" `),a.replace(/<img/g,`<img ${$.trim()}`)}return a})),e}renderNode(e){const t=[];e.marks&&e.marks.forEach(r=>{const n=this.getMatchingMark(r);n&&n.tag!==""&&t.push(this.renderOpeningTag(n.tag))});const s=this.getMatchingNode(e);return s&&s.tag&&t.push(this.renderOpeningTag(s.tag)),e.content?e.content.forEach(r=>{t.push(this.renderNode(r))}):e.text?t.push(Te(e.text)):s&&s.singleTag?t.push(this.renderTag(s.singleTag," /")):s&&s.html?t.push(s.html):e.type==="emoji"&&t.push(this.renderEmoji(e)),s&&s.tag&&t.push(this.renderClosingTag(s.tag)),e.marks&&e.marks.slice(0).reverse().forEach(r=>{const n=this.getMatchingMark(r);n&&n.tag!==""&&t.push(this.renderClosingTag(n.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(s=>{if(s.constructor===String)return`<${s}${t}>`;{let r=`<${s.tag}`;if(s.attrs){for(const n in s.attrs)if(Object.prototype.hasOwnProperty.call(s.attrs,n)){const o=s.attrs[n];o!==null&&(r+=` ${n}="${o}"`)}}return`${r}${t}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(t=>t.constructor===String?`</${t}>`:`</${t.tag}>`).join("")}getMatchingNode(e){const t=this.nodes[e.type];if(typeof t=="function")return t(e)}getMatchingMark(e){const t=this.marks[e.type];if(typeof t=="function")return t(e)}renderEmoji(e){if(e.attrs.emoji)return e.attrs.emoji;const t=[{tag:"img",attrs:{src:e.attrs.fallbackImage,draggable:"false",loading:"lazy",align:"absmiddle"}}];return this.renderTag(t," /")}}const I=Re;class we{constructor(e){p(this,"baseURL"),p(this,"timeout"),p(this,"headers"),p(this,"responseInterceptor"),p(this,"fetch"),p(this,"ejectInterceptor"),p(this,"url"),p(this,"parameters"),p(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;if(e==="get"){const a=new O;t=`${this.baseURL}${this.url}?${a.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const r=new URL(t),n=new AbortController,{signal:o}=n;let l;this.timeout&&(l=setTimeout(()=>n.abort(),this.timeout));try{const a=await this.fetch(`${r}`,{method:e,headers:this.headers,body:s,signal:o,...this.fetchOptions});this.timeout&&clearTimeout(l);const h=await this._responseHandler(a);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(h)):this._statusHandler(h)}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}_statusHandler(e){const t=/20[0-6]/g;return new Promise((s,r)=>{if(t.test(`${e.status}`))return s(e);const n={message:e.statusText,status:e.status,response:Array.isArray(e.data)?e.data[0]:e.data.error||e.data.slug};r(n)})}}const Se=we,z="SB-Agent",A={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"6.0.0"};let x={};const _={};class _e{constructor(e,t){p(this,"client"),p(this,"maxRetries"),p(this,"retriesDelay"),p(this,"throttle"),p(this,"accessToken"),p(this,"cache"),p(this,"helpers"),p(this,"resolveCounter"),p(this,"relations"),p(this,"links"),p(this,"richTextResolver"),p(this,"resolveNestedRelations"),p(this,"stringifiedStoriesCache");let s=e.endpoint||t;if(!s){const o=new O().getRegionURL,l=e.https===!1?"http":"https";e.oauthToken?s=`${l}://${o(e.region)}/v1`:s=`${l}://${o(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(([o,l])=>{r.set(o,l)}),r.has(z)||(r.set(z,A.defaultAgentName),r.set(A.defaultAgentVersion,A.packageVersion));let n=5;e.oauthToken&&(r.set("Authorization",e.oauthToken),n=3),e.rateLimit&&(n=e.rateLimit),e.richTextSchema?this.richTextResolver=new I(e.richTextSchema):this.richTextResolver=new I,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||10,this.retriesDelay=300,this.throttle=Y(this.throttledRequest,n,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new O,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.stringifiedStoriesCache={},this.client=new Se({baseURL:s,timeout:e.timeout||0,headers:r,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let s="";return t.attrs.body&&t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})}parseParams(e){return e.token||(e.token=this.getToken()),e.cv||(e.cv=_[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 this.helpers.isCDNUrl(e)?this.parseParams(t):t}makeRequest(e,t,s,r,n){const o=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,s,r));return this.cacheResponse(e,o,void 0,n)}get(e,t,s){t||(t={});const r=`/${e}`,n=this.factoryParamOptions(r,t);return this.cacheResponse(r,n,void 0,s)}async getAll(e,t,s,r){const n=(t==null?void 0:t.per_page)||25,o=`/${e}`,l=o.split("/"),a=s||l[l.length-1],h=1,d=await this.makeRequest(o,t,n,h,r),u=d.total?Math.ceil(d.total/n):1,m=await this.helpers.asyncMap(this.helpers.range(h,u),$=>this.makeRequest(o,t,n,$+1,r));return this.helpers.flatMap([d,...m],$=>Object.values($.data[a]))}post(e,t,s){const r=`/${e}`;return Promise.resolve(this.throttle("post",r,t,s))}put(e,t,s){const r=`/${e}`;return Promise.resolve(this.throttle("put",r,t,s))}delete(e,t,s){const r=`/${e}`;return Promise.resolve(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]?(this.stringifiedStoriesCache[t]||(this.stringifiedStoriesCache[t]=JSON.stringify(this.relations[e][t])),JSON.parse(this.stringifiedStoriesCache[t])):t}_insertRelations(e,t,s,r){s.indexOf(`${e.component}.${t}`)>-1&&(typeof e[t]=="string"?e[t]=this.getStoryReference(r,e[t]):Array.isArray(e[t])&&(e[t]=e[t].map(n=>this.getStoryReference(r,n)).filter(Boolean)))}iterateTree(e,t,s){const r=n=>{if(n!=null){if(n.constructor===Array)for(let o=0;o<n.length;o++)r(n[o]);else if(n.constructor===Object){if(n._stopResolving)return;for(const o in n)(n.component&&n._uid||n.type==="link")&&(this._insertRelations(n,o,t,s),this._insertLinks(n,o,s)),r(n[o])}}};r(e.content)}async resolveLinks(e,t,s){let r=[];if(e.link_uuids){const n=e.link_uuids.length,o=[],l=50;for(let a=0;a<n;a+=l){const h=Math.min(n,a+l);o.push(e.link_uuids.slice(a,h))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:o[a].join(",")})).data.stories.forEach(h=>{r.push(h)})}else r=e.links;r.forEach(n=>{this.links[s][n.uuid]={...n,_stopResolving:!0}})}async resolveRelations(e,t,s){let r=[];if(e.rel_uuids){const n=e.rel_uuids.length,o=[],l=50;for(let a=0;a<n;a+=l){const h=Math.min(n,a+l);o.push(e.rel_uuids.slice(a,h))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:o[a].join(","),excluding_fields:t.excluding_fields})).data.stories.forEach(h=>{r.push(h)})}else r=e.rels;r&&r.length>0&&r.forEach(n=>{this.relations[s][n.uuid]={...n,_stopResolving:!0}})}async resolveStories(e,t,s){var r,n;let o=[];if(this.links[s]={},this.relations[s]={},typeof t.resolve_relations<"u"&&t.resolve_relations.length>0&&(typeof t.resolve_relations=="string"&&(o=t.resolve_relations.split(",")),await this.resolveRelations(e,t,s)),t.resolve_links&&["1","story","url","link"].indexOf(t.resolve_links)>-1&&((r=e.links)!=null&&r.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],o,s);e.story?this.iterateTree(e.story,o,s):e.stories.forEach(l=>{this.iterateTree(l,o,s)}),this.stringifiedStoriesCache={},delete this.links[s],delete this.relations[s]}async cacheResponse(e,t,s,r){const n=this.helpers.stringify({url:e,params:t}),o=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&await this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const l=await o.get(n);if(l)return Promise.resolve(l)}return new Promise(async(l,a)=>{var h;try{const d=await this.throttle("get",e,t,r);if(d.status!==200)return a(d);let u={data:d.data,headers:d.headers};if((h=d.headers)!=null&&h["per-page"]&&(u=Object.assign({},u,{perPage:d.headers["per-page"]?parseInt(d.headers["per-page"]):0,total:d.headers["per-page"]?parseInt(d.headers.total):0})),u.data.story||u.data.stories){const m=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(u.data,t,`${m}`)}return t.version==="published"&&e!="/cdn/spaces/me"&&await o.set(n,u),u.data.cv&&t.token&&(t.version==="draft"&&_[t.token]!=u.data.cv&&await this.flushCache(),_[t.token]=t.cv?t.cv:u.data.cv),l(u)}catch(d){if(d.response&&d.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 this.helpers.delay(this.retriesDelay),this.cacheResponse(e,t,s).then(l).catch(a);a(d)}})}throttledRequest(e,t,s,r){return this.client.setFetchOptions(r),this.client[e](t,s)}cacheVersions(){return _}cacheVersion(){return _[this.accessToken]}setCacheVersion(e){this.accessToken&&(_[this.accessToken]=e)}clearCacheVersion(){this.accessToken&&(_[this.accessToken]=0)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(x[e])},getAll(){return Promise.resolve(x)},set(e,t){return x[e]=t,Promise.resolve(void 0)},flush(){return x={},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}}const Ee=(i={})=>{const{apiOptions:e}=i;if(!e.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 _e(e)}},Ie=i=>{if(typeof i!="object"||typeof i._editable>"u")return{};try{const e=JSON.parse(i._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return e?{"data-blok-c":JSON.stringify(e),"data-blok-uid":e.id+"-"+e.uid}:{}}catch{return{}}};var k=(i=>(i.DOCUMENT="doc",i.HEADING="heading",i.PARAGRAPH="paragraph",i.QUOTE="blockquote",i.OL_LIST="ordered_list",i.UL_LIST="bullet_list",i.LIST_ITEM="list_item",i.CODE_BLOCK="code_block",i.HR="horizontal_rule",i.BR="hard_break",i.IMAGE="image",i.EMOJI="emoji",i.COMPONENT="blok",i))(k||{}),v=(i=>(i.BOLD="bold",i.STRONG="strong",i.STRIKE="strike",i.UNDERLINE="underline",i.ITALIC="italic",i.CODE="code",i.LINK="link",i.ANCHOR="anchor",i.STYLED="styled",i.SUPERSCRIPT="superscript",i.SUBSCRIPT="subscript",i.TEXT_STYLE="textStyle",i.HIGHLIGHT="highlight",i))(v||{}),C=(i=>(i.TEXT="text",i))(C||{}),j=(i=>(i.URL="url",i.STORY="story",i.ASSET="asset",i.EMAIL="email",i))(j||{});function je(i,e){if(!e)return{src:i,attrs:{}};let t=0,s=0;const r={},n=[];function o(a,h,d,u,m){typeof a!="number"||a<=h||a>=d?console.warn(`[StoryblokRichText] - ${u.charAt(0).toUpperCase()+u.slice(1)} value must be a number between ${h} and ${d} (inclusive)`):m.push(`${u}(${a})`)}if(typeof e=="object"){if(typeof e.width=="number"&&e.width>0?(r.width=e.width,t=e.width):console.warn("[StoryblokRichText] - Width value must be a number greater than 0"),e.height&&typeof e.height=="number"&&e.height>0?(r.height=e.height,s=e.height):console.warn("[StoryblokRichText] - Height value must be a number greater than 0"),e.loading&&["lazy","eager"].includes(e.loading)&&(r.loading=e.loading),e.class&&(r.class=e.class),e.filters){const{filters:a}=e||{},{blur:h,brightness:d,fill:u,format:m,grayscale:$,quality:b,rotate:S}=a||{};h&&o(h,0,100,"blur",n),b&&o(b,0,100,"quality",n),d&&o(d,0,100,"brightness",n),u&&n.push(`fill(${u})`),$&&n.push("grayscale()"),S&&[0,90,180,270].includes(e.filters.rotate||0)&&n.push(`rotate(${S})`),m&&["webp","png","jpeg"].includes(m)&&n.push(`format(${m})`)}e.srcset&&(r.srcset=e.srcset.map(a=>{if(typeof a=="number")return`${i}/m/${a}x0/${n.length>0?"filters:"+n.join(":"):""} ${a}w`;if(Array.isArray(a)&&a.length===2){const[h,d]=a;return`${i}/m/${h}x${d}/${n.length>0?"filters:"+n.join(":"):""} ${h}w`}}).join(", ")),e.sizes&&(r.sizes=e.sizes.join(", "))}let l=`${i}/m/`;return t>0&&s>0&&(l=`${l}${t}x${s}/`),n.length>0&&(l=`${l}filters:${n.join(":")}`),{src:l,attrs:r}}const Oe=(i={})=>Object.keys(i).map(e=>`${e}="${i[e]}"`).join(" "),xe=(i={})=>Object.keys(i).map(e=>`${e}: ${i[e]}`).join("; ");function Le(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function Ae(i,e={},t){const s=Oe(e);return`<${s?`${i} ${s}`:i}>${Array.isArray(t)?t.join(""):t||""}</${i}>`}function Ce(i={}){let e=0;const{renderFn:t=Ae,textFn:s=Le,resolvers:r={},optimizeImages:n=!1}=i,o=c=>g=>t(c,{...g.attrs,key:`${c}-${e}`},g.children||null),l=c=>{const{src:g,alt:f,...T}=c.attrs||{};let R=g,w={};if(n){const{src:Ue,attrs:Be}=je(g,n);R=Ue,w=Be}const He={src:R,alt:f||"",key:`img-${e}`,...T,...w};return t("img",He,"")},a=c=>{const{level:g,...f}=c.attrs||{};return t(`h${g}`,{...f,key:`h${g}-${e}`},c.children)},h=c=>{var g,f,T,R;return t("span",{"data-type":"emoji","data-name":(g=c.attrs)==null?void 0:g.name,emoji:(f=c.attrs)==null?void 0:f.emoji,key:`emoji-${e}`},t("img",{src:(T=c.attrs)==null?void 0:T.fallbackImage,alt:(R=c.attrs)==null?void 0:R.alt,style:"width: 1.25em; height: 1.25em; vertical-align: text-top",draggable:"false",loading:"lazy"},""))},d=c=>t("pre",{...c.attrs,key:`code-${e}`},t("code",{key:`code-${e}`},c.children||"")),u=(c,g=!1)=>({text:f,attrs:T})=>t(c,g?{style:xe(T),key:`${c}-${e}`}:{...T,key:`${c}-${e}`},f),m=c=>M(c),$=c=>{const{marks:g,...f}=c;return"text"in c?g?g.reduce((T,R)=>m({...R,text:T}),m({...f,children:f.children})):s(f.text):""},b=c=>{const{linktype:g,href:f,anchor:T,...R}=c.attrs||{};let w="";switch(g){case j.ASSET:case j.URL:w=f;break;case j.EMAIL:w=`mailto:${f}`;break;case j.STORY:w=f;break}return T&&(w=`${w}#${T}`),t("a",{...R,href:w,key:`a-${e}`},c.text)},S=c=>{var g,f;return console.warn("[StoryblokRichtText] - BLOK resolver is not available for vanilla usage"),t("span",{blok:(g=c==null?void 0:c.attrs)==null?void 0:g.body[0],id:(f=c.attrs)==null?void 0:f.id,key:`component-${e}`,style:"display: none"},"")},L=new Map([[k.DOCUMENT,o("div")],[k.HEADING,a],[k.PARAGRAPH,o("p")],[k.UL_LIST,o("ul")],[k.OL_LIST,o("ol")],[k.LIST_ITEM,o("li")],[k.IMAGE,l],[k.EMOJI,h],[k.CODE_BLOCK,d],[k.HR,o("hr")],[k.BR,o("br")],[k.QUOTE,o("blockquote")],[k.COMPONENT,S],[C.TEXT,$],[v.LINK,b],[v.ANCHOR,b],[v.STYLED,u("span",!0)],[v.BOLD,u("strong")],[v.TEXT_STYLE,u("span",!0)],[v.ITALIC,u("em")],[v.UNDERLINE,u("u")],[v.STRIKE,u("s")],[v.CODE,u("code")],[v.SUPERSCRIPT,u("sup")],[v.SUBSCRIPT,u("sub")],[v.HIGHLIGHT,u("mark")],...Object.entries(r).map(([c,g])=>[c,g])]);function J(c){e+=1;const g=L.get(c.type);if(!g)return console.error("<Storyblok>",`No resolver found for node type ${c.type}`),"";if(c.type==="text")return g(c);const f=c.content?c.content.map(M):void 0;return g({...c,children:f})}function M(c){return Array.isArray(c)?c.map(J):J(c)}return{render:M}}let P,N="https://app.storyblok.com/f/storyblok-v2-latest.js";const q=(i,e,t={})=>{var l;const r=!(typeof window>"u")&&typeof window.storyblokRegisterEvent<"u",o=+new URL((l=window.location)==null?void 0:l.href).searchParams.get("_storyblok")===i;if(!(!r||!o)){if(!i){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(t).on(["input","published","change"],h=>{h.action==="input"&&h.story.id===i?e(h.story):(h.action==="change"||h.action==="published")&&h.storyId===i&&window.location.reload()})})}},Pe=(i={})=>{var u,m;const{bridge:e,accessToken:t,use:s=[],apiOptions:r={},richText:n={},bridgeUrl:o}=i;r.accessToken=r.accessToken||t;const l={bridge:e,apiOptions:r};let a={};s.forEach($=>{a={...a,...$(l)}}),o&&(N=o);const d=!(typeof window>"u")&&((m=(u=window.location)==null?void 0:u.search)==null?void 0:m.includes("_storyblok_tk"));return e!==!1&&d&&U(N),P=new I(n.schema),n.resolver&&G(P,n.resolver),a},G=(i,e)=>{i.addNode("blok",t=>{let s="";return t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})},V=i=>!i||!(i!=null&&i.content.some(e=>e.content||e.type==="blok"||e.type==="horizontal_rule")),Ne=(i,e,t)=>{let s=t||P;if(!s){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return V(i)?"":(e&&(s=new I(e.schema),e.resolver&&G(s,e.resolver)),s.render(i))},Me=()=>U(N);y.BlockTypes=k,y.MarkTypes=v,y.RichTextResolver=I,y.RichTextSchema=D,y.TextTypes=C,y.apiPlugin=Ee,y.isRichTextEmpty=V,y.loadStoryblokBridge=Me,y.registerStoryblokBridge=q,y.renderRichText=Ne,y.richTextResolver=Ce,y.storyblokEditable=Ie,y.storyblokInit=Pe,y.useStoryblokBridge=q,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"})});
@@ -13,13 +13,13 @@ const M = [], D = (i) => new Promise((e, t) => {
13
13
  }, document.getElementsByTagName("head")[0].appendChild(s);
14
14
  });
15
15
  var J = Object.defineProperty, F = (i, e, t) => e in i ? J(i, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : i[e] = t, p = (i, e, t) => F(i, typeof e != "symbol" ? e + "" : e, t);
16
- function U(i) {
16
+ function H(i) {
17
17
  return !(i !== i || i === 1 / 0 || i === -1 / 0);
18
18
  }
19
19
  function K(i, e, t) {
20
- if (!U(e))
20
+ if (!H(e))
21
21
  throw new TypeError("Expected `limit` to be a finite number");
22
- if (!U(t))
22
+ if (!H(t))
23
23
  throw new TypeError("Expected `interval` to be a finite number");
24
24
  const s = [];
25
25
  let r = [], n = 0;
@@ -508,7 +508,7 @@ class we {
508
508
  });
509
509
  }
510
510
  }
511
- const Se = we, H = "SB-Agent", L = {
511
+ const Se = we, U = "SB-Agent", L = {
512
512
  defaultAgentName: "SB-JS-CLIENT",
513
513
  defaultAgentVersion: "SB-Agent-Version",
514
514
  packageVersion: "6.0.0"
@@ -529,9 +529,9 @@ class _e {
529
529
  e.oauthToken ? s = `${l}://${o(e.region)}/v1` : s = `${l}://${o(e.region)}/v2`;
530
530
  }
531
531
  const r = new Headers();
532
- r.set("Content-Type", "application/json"), r.set("Accept", "application/json"), e.headers && e.headers.entries().toArray().forEach(([o, l]) => {
532
+ 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(([o, l]) => {
533
533
  r.set(o, l);
534
- }), r.has(H) || (r.set(H, L.defaultAgentName), r.set(
534
+ }), r.has(U) || (r.set(U, L.defaultAgentName), r.set(
535
535
  L.defaultAgentVersion,
536
536
  L.packageVersion
537
537
  ));
@@ -1053,7 +1053,7 @@ const Ne = (i, e, t = {}) => {
1053
1053
  html: s
1054
1054
  };
1055
1055
  });
1056
- }, Le = (i) => !i || !(i != null && i.content.some((e) => e.content || e.type === "blok" || e.type === "horizontal_rule")), Ue = (i, e, t) => {
1056
+ }, Le = (i) => !i || !(i != null && i.content.some((e) => e.content || e.type === "blok" || e.type === "horizontal_rule")), He = (i, e, t) => {
1057
1057
  let s = t || A;
1058
1058
  if (!s) {
1059
1059
  console.error(
@@ -1062,7 +1062,7 @@ const Ne = (i, e, t = {}) => {
1062
1062
  return;
1063
1063
  }
1064
1064
  return Le(i) ? "" : (e && (s = new j(e.schema), e.resolver && B(s, e.resolver)), s.render(i));
1065
- }, He = () => D(C);
1065
+ }, Ue = () => D(C);
1066
1066
  export {
1067
1067
  b as BlockTypes,
1068
1068
  v as MarkTypes,
@@ -1071,9 +1071,9 @@ export {
1071
1071
  z as TextTypes,
1072
1072
  Ae as apiPlugin,
1073
1073
  Le as isRichTextEmpty,
1074
- He as loadStoryblokBridge,
1074
+ Ue as loadStoryblokBridge,
1075
1075
  Ne as registerStoryblokBridge,
1076
- Ue as renderRichText,
1076
+ He as renderRichText,
1077
1077
  Pe as richTextResolver,
1078
1078
  Ce as storyblokEditable,
1079
1079
  Me as storyblokInit,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storyblok/js",
3
- "version": "3.1.0",
3
+ "version": "3.1.1",
4
4
  "description": "SDK to integrate Storyblok into your project using JavaScript.",
5
5
  "main": "./dist/storyblok-js.js",
6
6
  "module": "./dist/storyblok-js.mjs",
@@ -29,7 +29,7 @@
29
29
  },
30
30
  "dependencies": {
31
31
  "@storyblok/richtext": "^2.0.0",
32
- "storyblok-js-client": "^6.9.0"
32
+ "storyblok-js-client": "^6.9.1"
33
33
  },
34
34
  "devDependencies": {
35
35
  "@tsconfig/recommended": "^1.0.7",