@storyblok/js 2.2.11 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- (function(d,m){typeof exports=="object"&&typeof module<"u"?m(exports):typeof define=="function"&&define.amd?define(["exports"],m):(d=typeof globalThis<"u"?globalThis:d||self,m(d.storyblok={}))})(this,function(d){"use strict";let m=!1;const _=[],j=i=>new Promise((t,e)=>{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}m?r():_.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=>e(r),s.onload=r=>{_.forEach(o=>o()),m=!0,t(r)},document.getElementsByTagName("head")[0].appendChild(s)});var N=Object.defineProperty,L=(i,t,e)=>t in i?N(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,h=(i,t,e)=>(L(i,typeof t!="symbol"?t+"":t,e),e);function S(i){return!(i!==i||i===1/0||i===-1/0)}function M(i,t,e){if(!S(t))throw new TypeError("Expected `limit` to be a finite number");if(!S(e))throw new TypeError("Expected `interval` to be a finite number");const s=[];let r=[],o=0;const n=function(){o++;const a=setTimeout(function(){o--,s.length>0&&n(),r=r.filter(function(u){return u!==a})},e);r.indexOf(a)<0&&r.push(a);const l=s.shift();l.resolve(i.apply(l.self,l.args))},c=function(...a){const l=this;return new Promise(function(u,p){s.push({resolve:u,reject:p,args:a,self:l}),o<t&&n()})};return c.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},c}class k{constructor(){h(this,"isCDNUrl",(t="")=>t.indexOf("/cdn/")>-1),h(this,"getOptionsPage",(t,e=25,s=1)=>({...t,per_page:e,page:s})),h(this,"delay",t=>new Promise(e=>setTimeout(e,t))),h(this,"arrayFrom",(t=0,e)=>[...Array(t)].map(e)),h(this,"range",(t=0,e=t)=>{const s=Math.abs(e-t)||0,r=t<e?1:-1;return this.arrayFrom(s,(o,n)=>n*r+t)}),h(this,"asyncMap",async(t,e)=>Promise.all(t.map(e))),h(this,"flatMap",(t=[],e)=>t.map(e).reduce((s,r)=>[...s,...r],[])),h(this,"escapeHTML",function(t){const e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},s=/[&<>"']/g,r=RegExp(s.source);return t&&r.test(t)?t.replace(s,o=>e[o]):t})}stringify(t,e,s){const r=[];for(const o in t){if(!Object.prototype.hasOwnProperty.call(t,o))continue;const n=t[o],c=s?"":encodeURIComponent(o);let a;typeof n=="object"?a=this.stringify(n,e?e+encodeURIComponent("["+c+"]"):c,Array.isArray(n)):a=(e?e+encodeURIComponent("["+c+"]"):c)+"="+encodeURIComponent(n),r.push(a)}return r.join("&")}getRegionURL(t){const e="api.storyblok.com",s="api-us.storyblok.com",r="app.storyblokchina.cn";switch(t){case"us":return s;case"cn":return r;default:return e}}}const z=function(i,t){const e={};for(const s in i){const r=i[s];t.indexOf(s)>-1&&r!==null&&(e[s]=r)}return e},H=i=>i==="email",U=()=>({singleTag:"hr"}),B=()=>({tag:"blockquote"}),q=()=>({tag:"ul"}),V=i=>({tag:["pre",{tag:"code",attrs:i.attrs}]}),J=()=>({singleTag:"br"}),D=i=>({tag:`h${i.attrs.level}`}),F=i=>({singleTag:[{tag:"img",attrs:z(i.attrs,["src","alt","title"])}]}),Y=()=>({tag:"li"}),K=()=>({tag:"ol"}),W=()=>({tag:"p"}),G=i=>({tag:[{tag:"span",attrs:{"data-type":"emoji","data-name":i.attrs.name,emoji:i.attrs.emoji}}]}),Q=()=>({tag:"b"}),X=()=>({tag:"strike"}),Z=()=>({tag:"u"}),tt=()=>({tag:"strong"}),et=()=>({tag:"code"}),st=()=>({tag:"i"}),rt=i=>{const t=new k().escapeHTML,e={...i.attrs},{linktype:s="url"}=i.attrs;if(e.href&&(e.href=t(i.attrs.href||"")),H(s)&&(e.href=`mailto:${e.href}`),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),e.custom){for(const r in e.custom)e[r]=e.custom[r];delete e.custom}return{tag:[{tag:"a",attrs:e}]}},ot=i=>({tag:[{tag:"span",attrs:i.attrs}]}),it=()=>({tag:"sub"}),nt=()=>({tag:"sup"}),at=i=>({tag:[{tag:"span",attrs:i.attrs}]}),lt=i=>{var t;return(t=i.attrs)!=null&&t.color?{tag:[{tag:"span",attrs:{style:`background-color:${i.attrs.color};`}}]}:{tag:""}},ct=i=>{var t;return(t=i.attrs)!=null&&t.color?{tag:[{tag:"span",attrs:{style:`color:${i.attrs.color}`}}]}:{tag:""}},E={nodes:{horizontal_rule:U,blockquote:B,bullet_list:q,code_block:V,hard_break:J,heading:D,image:F,list_item:Y,ordered_list:K,paragraph:W,emoji:G},marks:{bold:Q,strike:X,underline:Z,strong:tt,code:et,italic:st,link:rt,styled:ot,subscript:it,superscript:nt,anchor:at,highlight:lt,textStyle:ct}},ht=function(i){const t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},e=/[&<>"']/g,s=RegExp(e.source);return i&&s.test(i)?i.replace(e,r=>t[r]):i};class b{constructor(t){h(this,"marks"),h(this,"nodes"),t||(t=E),this.marks=t.marks||[],this.nodes=t.nodes||[]}addNode(t,e){this.nodes[t]=e}addMark(t,e){this.marks[t]=e}render(t,e={optimizeImages:!1}){if(t&&t.content&&Array.isArray(t.content)){let s="";return t.content.forEach(r=>{s+=this.renderNode(r)}),e.optimizeImages?this.optimizeImages(s,e.optimizeImages):s}return console.warn(`The render method must receive an Object with a "content" field.
1
+ (function(d,m){typeof exports=="object"&&typeof module<"u"?m(exports):typeof define=="function"&&define.amd?define(["exports"],m):(d=typeof globalThis<"u"?globalThis:d||self,m(d.storyblok={}))})(this,function(d){"use strict";let m=!1;const j=[],S=i=>new Promise((t,e)=>{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}m?r():j.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=>e(r),s.onload=r=>{j.forEach(o=>o()),m=!0,t(r)},document.getElementsByTagName("head")[0].appendChild(s)});var N=Object.defineProperty,L=(i,t,e)=>t in i?N(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,h=(i,t,e)=>(L(i,typeof t!="symbol"?t+"":t,e),e);function E(i){return!(i!==i||i===1/0||i===-1/0)}function M(i,t,e){if(!E(t))throw new TypeError("Expected `limit` to be a finite number");if(!E(e))throw new TypeError("Expected `interval` to be a finite number");const s=[];let r=[],o=0;const n=function(){o++;const a=setTimeout(function(){o--,s.length>0&&n(),r=r.filter(function(u){return u!==a})},e);r.indexOf(a)<0&&r.push(a);const l=s.shift();l.resolve(i.apply(l.self,l.args))},c=function(...a){const l=this;return new Promise(function(u,p){s.push({resolve:u,reject:p,args:a,self:l}),o<t&&n()})};return c.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},c}class v{constructor(){h(this,"isCDNUrl",(t="")=>t.indexOf("/cdn/")>-1),h(this,"getOptionsPage",(t,e=25,s=1)=>({...t,per_page:e,page:s})),h(this,"delay",t=>new Promise(e=>setTimeout(e,t))),h(this,"arrayFrom",(t=0,e)=>[...Array(t)].map(e)),h(this,"range",(t=0,e=t)=>{const s=Math.abs(e-t)||0,r=t<e?1:-1;return this.arrayFrom(s,(o,n)=>n*r+t)}),h(this,"asyncMap",async(t,e)=>Promise.all(t.map(e))),h(this,"flatMap",(t=[],e)=>t.map(e).reduce((s,r)=>[...s,...r],[])),h(this,"escapeHTML",function(t){const e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},s=/[&<>"']/g,r=RegExp(s.source);return t&&r.test(t)?t.replace(s,o=>e[o]):t})}stringify(t,e,s){const r=[];for(const o in t){if(!Object.prototype.hasOwnProperty.call(t,o))continue;const n=t[o],c=s?"":encodeURIComponent(o);let a;typeof n=="object"?a=this.stringify(n,e?e+encodeURIComponent("["+c+"]"):c,Array.isArray(n)):a=(e?e+encodeURIComponent("["+c+"]"):c)+"="+encodeURIComponent(n),r.push(a)}return r.join("&")}getRegionURL(t){const e="api.storyblok.com",s="api-us.storyblok.com",r="app.storyblokchina.cn";switch(t){case"us":return s;case"cn":return r;default:return e}}}const z=function(i,t){const e={};for(const s in i){const r=i[s];t.indexOf(s)>-1&&r!==null&&(e[s]=r)}return e},U=i=>i==="email",H=()=>({singleTag:"hr"}),B=()=>({tag:"blockquote"}),q=()=>({tag:"ul"}),V=i=>({tag:["pre",{tag:"code",attrs:i.attrs}]}),J=()=>({singleTag:"br"}),D=i=>({tag:`h${i.attrs.level}`}),F=i=>({singleTag:[{tag:"img",attrs:z(i.attrs,["src","alt","title"])}]}),Y=()=>({tag:"li"}),K=()=>({tag:"ol"}),W=()=>({tag:"p"}),G=i=>({tag:[{tag:"span",attrs:{"data-type":"emoji","data-name":i.attrs.name,emoji:i.attrs.emoji}}]}),Q=()=>({tag:"b"}),X=()=>({tag:"strike"}),Z=()=>({tag:"u"}),tt=()=>({tag:"strong"}),et=()=>({tag:"code"}),st=()=>({tag:"i"}),rt=i=>{const t=new v().escapeHTML,e={...i.attrs},{linktype:s="url"}=i.attrs;if(e.href&&(e.href=t(i.attrs.href||"")),U(s)&&(e.href=`mailto:${e.href}`),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),e.custom){for(const r in e.custom)e[r]=e.custom[r];delete e.custom}return{tag:[{tag:"a",attrs:e}]}},ot=i=>({tag:[{tag:"span",attrs:i.attrs}]}),it=()=>({tag:"sub"}),nt=()=>({tag:"sup"}),at=i=>({tag:[{tag:"span",attrs:i.attrs}]}),lt=i=>{var t;return(t=i.attrs)!=null&&t.color?{tag:[{tag:"span",attrs:{style:`background-color:${i.attrs.color};`}}]}:{tag:""}},ct=i=>{var t;return(t=i.attrs)!=null&&t.color?{tag:[{tag:"span",attrs:{style:`color:${i.attrs.color}`}}]}:{tag:""}},x={nodes:{horizontal_rule:H,blockquote:B,bullet_list:q,code_block:V,hard_break:J,heading:D,image:F,list_item:Y,ordered_list:K,paragraph:W,emoji:G},marks:{bold:Q,strike:X,underline:Z,strong:tt,code:et,italic:st,link:rt,styled:ot,subscript:it,superscript:nt,anchor:at,highlight:lt,textStyle:ct}},ht=function(i){const t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},e=/[&<>"']/g,s=RegExp(e.source);return i&&s.test(i)?i.replace(e,r=>t[r]):i};class b{constructor(t){h(this,"marks"),h(this,"nodes"),t||(t=x),this.marks=t.marks||[],this.nodes=t.nodes||[]}addNode(t,e){this.nodes[t]=e}addMark(t,e){this.marks[t]=e}render(t,e={optimizeImages:!1}){if(t&&t.content&&Array.isArray(t.content)){let s="";return t.content.forEach(r=>{s+=this.renderNode(r)}),e.optimizeImages?this.optimizeImages(s,e.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(t,e){let s=0,r=0,o="",n="";typeof e!="boolean"&&(typeof e.width=="number"&&e.width>0&&(o+=`width="${e.width}" `,s=e.width),typeof e.height=="number"&&e.height>0&&(o+=`height="${e.height}" `,r=e.height),(e.loading==="lazy"||e.loading==="eager")&&(o+=`loading="${e.loading}" `),typeof e.class=="string"&&e.class.length>0&&(o+=`class="${e.class}" `),e.filters&&(typeof e.filters.blur=="number"&&e.filters.blur>=0&&e.filters.blur<=100&&(n+=`:blur(${e.filters.blur})`),typeof e.filters.brightness=="number"&&e.filters.brightness>=-100&&e.filters.brightness<=100&&(n+=`:brightness(${e.filters.brightness})`),e.filters.fill&&(e.filters.fill.match(/[0-9A-Fa-f]{6}/g)||e.filters.fill==="transparent")&&(n+=`:fill(${e.filters.fill})`),e.filters.format&&["webp","png","jpeg"].includes(e.filters.format)&&(n+=`:format(${e.filters.format})`),typeof e.filters.grayscale=="boolean"&&e.filters.grayscale&&(n+=":grayscale()"),typeof e.filters.quality=="number"&&e.filters.quality>=0&&e.filters.quality<=100&&(n+=`:quality(${e.filters.quality})`),e.filters.rotate&&[90,180,270].includes(e.filters.rotate)&&(n+=`:rotate(${e.filters.rotate})`),n.length>0&&(n="/filters"+n))),o.length>0&&(t=t.replace(/<img/g,`<img ${o.trim()}`));const c=s>0||r>0||n.length>0?`${s}x${r}${n}`:"";return t=t.replace(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g,`a.storyblok.com/f/$1/$2.$3/m/${c}`),typeof e!="boolean"&&(e.sizes||e.srcset)&&(t=t.replace(/<img.*?src=["|'](.*?)["|']/g,a=>{var l,u;const p=a.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);if(p&&p.length>0){const f={srcset:(l=e.srcset)==null?void 0:l.map(g=>{if(typeof g=="number")return`//${p}/m/${g}x0${n} ${g}w`;if(typeof g=="object"&&g.length===2){let $=0,A=0;return typeof g[0]=="number"&&($=g[0]),typeof g[1]=="number"&&(A=g[1]),`//${p}/m/${$}x${A}${n} ${$}w`}}).join(", "),sizes:(u=e.sizes)==null?void 0:u.map(g=>g).join(", ")};let R="";return f.srcset&&(R+=`srcset="${f.srcset}" `),f.sizes&&(R+=`sizes="${f.sizes}" `),a.replace(/<img/g,`<img ${R.trim()}`)}return a})),t}renderNode(t){const e=[];t.marks&&t.marks.forEach(r=>{const o=this.getMatchingMark(r);o&&o.tag!==""&&e.push(this.renderOpeningTag(o.tag))});const s=this.getMatchingNode(t);return s&&s.tag&&e.push(this.renderOpeningTag(s.tag)),t.content?t.content.forEach(r=>{e.push(this.renderNode(r))}):t.text?e.push(ht(t.text)):s&&s.singleTag?e.push(this.renderTag(s.singleTag," /")):s&&s.html?e.push(s.html):t.type==="emoji"&&e.push(this.renderEmoji(t)),s&&s.tag&&e.push(this.renderClosingTag(s.tag)),t.marks&&t.marks.slice(0).reverse().forEach(r=>{const o=this.getMatchingMark(r);o&&o.tag!==""&&e.push(this.renderClosingTag(o.tag))}),e.join("")}renderTag(t,e){return t.constructor===String?`<${t}${e}>`:t.map(s=>{if(s.constructor===String)return`<${s}${e}>`;{let r=`<${s.tag}`;if(s.attrs)for(const o in s.attrs){const n=s.attrs[o];n!==null&&(r+=` ${o}="${n}"`)}return`${r}${e}>`}}).join("")}renderOpeningTag(t){return this.renderTag(t,"")}renderClosingTag(t){return t.constructor===String?`</${t}>`:t.slice(0).reverse().map(e=>e.constructor===String?`</${e}>`:`</${e.tag}>`).join("")}getMatchingNode(t){const e=this.nodes[t.type];if(typeof e=="function")return e(t)}getMatchingMark(t){const e=this.marks[t.type];if(typeof e=="function")return e(t)}renderEmoji(t){if(t.attrs.emoji)return t.attrs.emoji;const e=[{tag:"img",attrs:{src:t.attrs.fallbackImage,draggable:"false",loading:"lazy",align:"absmiddle"}}];return this.renderTag(e," /")}}class ut{constructor(t){h(this,"baseURL"),h(this,"timeout"),h(this,"headers"),h(this,"responseInterceptor"),h(this,"fetch"),h(this,"ejectInterceptor"),h(this,"url"),h(this,"parameters"),this.baseURL=t.baseURL,this.headers=t.headers||new Headers,this.timeout=t!=null&&t.timeout?t.timeout*1e3:0,this.responseInterceptor=t.responseInterceptor,this.fetch=(...e)=>t.fetch?t.fetch(...e):fetch(...e),this.ejectInterceptor=!1,this.url="",this.parameters={}}get(t,e){return this.url=t,this.parameters=e,this._methodHandler("get")}post(t,e){return this.url=t,this.parameters=e,this._methodHandler("post")}put(t,e){return this.url=t,this.parameters=e,this._methodHandler("put")}delete(t,e){return this.url=t,this.parameters=e,this._methodHandler("delete")}async _responseHandler(t){const e=[],s={data:{},headers:{},status:0,statusText:""};t.status!==204&&await t.json().then(r=>{s.data=r});for(const r of t.headers.entries())e[r[0]]=r[1];return s.headers={...e},s.status=t.status,s.statusText=t.statusText,s}async _methodHandler(t){let e=`${this.baseURL}${this.url}`,s=null;if(t==="get"){const a=new k;e=`${this.baseURL}${this.url}?${a.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const r=new URL(e),o=new AbortController,{signal:n}=o;let c;this.timeout&&(c=setTimeout(()=>o.abort(),this.timeout));try{const a=await this.fetch(`${r}`,{method:t,headers:this.headers,body:s,signal:n});this.timeout&&clearTimeout(c);const l=await this._responseHandler(a);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(l)):this._statusHandler(l)}catch(a){return{message:a}}}eject(){this.ejectInterceptor=!0}_statusHandler(t){const e=/20[0-6]/g;return new Promise(s=>{if(e.test(`${t.status}`))return s(t);const r={message:t.statusText,status:t.status,response:Array.isArray(t.data)?t.data[0]:t.data.error||t.data.slug};throw new Error(JSON.stringify(r))})}}const x="SB-Agent",w={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"5.14.2"};let v={};const y={};class dt{constructor(t,e){h(this,"client"),h(this,"maxRetries"),h(this,"throttle"),h(this,"accessToken"),h(this,"cache"),h(this,"helpers"),h(this,"resolveCounter"),h(this,"relations"),h(this,"links"),h(this,"richTextResolver"),h(this,"resolveNestedRelations");let s=t.endpoint||e;if(!s){const n=new k().getRegionURL,c=t.https===!1?"http":"https";t.oauthToken?s=`${c}://${n(t.region)}/v1`:s=`${c}://${n(t.region)}/v2`}const r=new Headers;if(r.set("Content-Type","application/json"),r.set("Accept","application/json"),t.headers)for(const n in t.headers)r.set(n,t.headers[n]);r.has(x)||(r.set(x,w.defaultAgentName),r.set(w.defaultAgentVersion,w.packageVersion));let o=5;t.oauthToken&&(r.set("Authorization",t.oauthToken),o=3),t.rateLimit&&(o=t.rateLimit),t.richTextSchema?this.richTextResolver=new b(t.richTextSchema):this.richTextResolver=new b,t.componentResolver&&this.setComponentResolver(t.componentResolver),this.maxRetries=t.maxRetries||5,this.throttle=M(this.throttledRequest,o,1e3),this.accessToken=t.accessToken||"",this.relations={},this.links={},this.cache=t.cache||{clear:"manual"},this.helpers=new k,this.resolveCounter=0,this.resolveNestedRelations=t.resolveNestedRelations||!0,this.client=new ut({baseURL:s,timeout:t.timeout||0,headers:r,responseInterceptor:t.responseInterceptor,fetch:t.fetch})}setComponentResolver(t){this.richTextResolver.addNode("blok",e=>{let s="";return e.attrs.body&&e.attrs.body.forEach(r=>{s+=t(r.component,r)}),{html:s}})}parseParams(t){return t.version||(t.version="published"),t.token||(t.token=this.getToken()),t.cv||(t.cv=y[t.token]),Array.isArray(t.resolve_relations)&&(t.resolve_relations=t.resolve_relations.join(",")),t}factoryParamOptions(t,e){return this.helpers.isCDNUrl(t)?this.parseParams(e):e}makeRequest(t,e,s,r){const o=this.factoryParamOptions(t,this.helpers.getOptionsPage(e,s,r));return this.cacheResponse(t,o)}get(t,e){e||(e={});const s=`/${t}`,r=this.factoryParamOptions(s,e);return this.cacheResponse(s,r)}async getAll(t,e,s){const r=(e==null?void 0:e.per_page)||25,o=`/${t}`,n=o.split("/"),c=s||n[n.length-1],a=1,l=await this.makeRequest(o,e,r,a),u=l.total?Math.ceil(l.total/r):1,p=await this.helpers.asyncMap(this.helpers.range(a,u),f=>this.makeRequest(o,e,r,f+1));return this.helpers.flatMap([l,...p],f=>Object.values(f.data[c]))}post(t,e){const s=`/${t}`;return Promise.resolve(this.throttle("post",s,e))}put(t,e){const s=`/${t}`;return Promise.resolve(this.throttle("put",s,e))}delete(t,e){const s=`/${t}`;return Promise.resolve(this.throttle("delete",s,e))}getStories(t){return this.get("cdn/stories",t)}getStory(t,e){return this.get(`cdn/stories/${t}`,e)}getToken(){return this.accessToken}ejectInterceptor(){this.client.eject()}_cleanCopy(t){return JSON.parse(JSON.stringify(t))}_insertLinks(t,e,s){const r=t[e];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]))}_insertRelations(t,e,s,r){if(s.indexOf(`${t.component}.${e}`)>-1){if(typeof t[e]=="string")this.relations[r][t[e]]&&(t[e]=this._cleanCopy(this.relations[r][t[e]]));else if(t[e]&&t[e].constructor===Array){const o=[];t[e].forEach(n=>{this.relations[r][n]&&o.push(this._cleanCopy(this.relations[r][n]))}),t[e]=o}}}iterateTree(t,e,s){const r=o=>{if(o!=null){if(o.constructor===Array)for(let n=0;n<o.length;n++)r(o[n]);else if(o.constructor===Object){if(o._stopResolving)return;for(const n in o)(o.component&&o._uid||o.type==="link")&&(this._insertRelations(o,n,e,s),this._insertLinks(o,n,s)),r(o[n])}}};r(t.content)}async resolveLinks(t,e,s){let r=[];if(t.link_uuids){const o=t.link_uuids.length,n=[],c=50;for(let a=0;a<o;a+=c){const l=Math.min(o,a+c);n.push(t.link_uuids.slice(a,l))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:c,language:e.language,version:e.version,by_uuids:n[a].join(",")})).data.stories.forEach(l=>{r.push(l)})}else r=t.links;r.forEach(o=>{this.links[s][o.uuid]={...o,_stopResolving:!0}})}async resolveRelations(t,e,s){let r=[];if(t.rel_uuids){const o=t.rel_uuids.length,n=[],c=50;for(let a=0;a<o;a+=c){const l=Math.min(o,a+c);n.push(t.rel_uuids.slice(a,l))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:c,language:e.language,version:e.version,by_uuids:n[a].join(",")})).data.stories.forEach(l=>{r.push(l)})}else r=t.rels;r&&r.length>0&&r.forEach(o=>{this.relations[s][o.uuid]={...o,_stopResolving:!0}})}async resolveStories(t,e,s){var r,o;let n=[];if(this.links[s]={},this.relations[s]={},typeof e.resolve_relations<"u"&&e.resolve_relations.length>0&&(typeof e.resolve_relations=="string"&&(n=e.resolve_relations.split(",")),await this.resolveRelations(t,e,s)),e.resolve_links&&["1","story","url","link"].indexOf(e.resolve_links)>-1&&((r=t.links)!=null&&r.length||(o=t.link_uuids)!=null&&o.length)&&await this.resolveLinks(t,e,s),this.resolveNestedRelations)for(const c in this.relations[s])this.iterateTree(this.relations[s][c],n,s);t.story?this.iterateTree(t.story,n,s):t.stories.forEach(c=>{this.iterateTree(c,n,s)}),delete this.links[s],delete this.relations[s]}async cacheResponse(t,e,s){(typeof s>"u"||!s)&&(s=0);const r=this.helpers.stringify({url:t,params:e}),o=this.cacheProvider();if(this.cache.clear==="auto"&&e.version==="draft"&&await this.flushCache(),e.version==="published"&&t!="/cdn/spaces/me"){const n=await o.get(r);if(n)return Promise.resolve(n)}return new Promise(async(n,c)=>{var a;try{const l=await this.throttle("get",t,e);if(l.status!==200)return c(l);let u={data:l.data,headers:l.headers};if((a=l.headers)!=null&&a["per-page"]&&(u=Object.assign({},u,{perPage:l.headers["per-page"]?parseInt(l.headers["per-page"]):0,total:l.headers["per-page"]?parseInt(l.headers.total):0})),u.data.story||u.data.stories){const p=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(u.data,e,`${p}`)}return e.version==="published"&&t!="/cdn/spaces/me"&&await o.set(r,u),u.data.cv&&e.token&&(e.version=="draft"&&y[e.token]!=u.data.cv&&await this.flushCache(),y[e.token]=u.data.cv),n(u)}catch(l){if(l.response&&l.response.status===429&&(s=s?s+1:0,s<this.maxRetries))return console.log(`Hit rate limit. Retrying in ${s} seconds.`),await this.helpers.delay(1e3*s),this.cacheResponse(t,e,s).then(n).catch(c);c(l.message)}})}throttledRequest(t,e,s){return this.client[t](e,s)}cacheVersions(){return y}cacheVersion(){return y[this.accessToken]}setCacheVersion(t){this.accessToken&&(y[this.accessToken]=t)}cacheProvider(){switch(this.cache.type){case"memory":return{get(t){return Promise.resolve(v[t])},getAll(){return Promise.resolve(v)},set(t,e){return v[t]=e,Promise.resolve(void 0)},flush(){return v={},Promise.resolve(void 0)}};case"custom":if(this.cache.custom)return this.cache.custom;default:return{get(){return Promise.resolve(void 0)},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}}const pt=(i={})=>{const{apiOptions:t}=i;if(!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 dt(t)}},gt=i=>{if(typeof i!="object"||typeof i._editable>"u")return{};const t=JSON.parse(i._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(t),"data-blok-uid":t.id+"-"+t.uid}};let T;const I="https://app.storyblok.com/f/storyblok-v2-latest.js",P=(i,t,e={})=>{var c;const r=!(typeof window>"u")&&typeof window.storyblokRegisterEvent<"u",n=+new URL((c=window.location)==null?void 0:c.href).searchParams.get("_storyblok")===i;if(!(!r||!n)){if(!i){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(e).on(["input","published","change"],l=>{l.action==="input"&&l.story.id===i?t(l.story):(l.action==="change"||l.action==="published")&&l.storyId===i&&window.location.reload()})})}},ft=(i={})=>{var u,p;const{bridge:t,accessToken:e,use:s=[],apiOptions:r={},richText:o={}}=i;r.accessToken=r.accessToken||e;const n={bridge:t,apiOptions:r};let c={};s.forEach(f=>{c={...c,...f(n)}});const l=!(typeof window>"u")&&((p=(u=window.location)==null?void 0:u.search)==null?void 0:p.includes("_storyblok_tk"));return t!==!1&&l&&j(I),T=new b(o.schema),o.resolver&&C(T,o.resolver),c},C=(i,t)=>{i.addNode("blok",e=>{let s="";return e.attrs.body.forEach(r=>{s+=t(r.component,r)}),{html:s}})},O=i=>!i||!(i!=null&&i.content.some(t=>t.content||t.type==="blok"||t.type==="horizontal_rule")),mt=(i,t,e)=>{let s=e||T;if(!s){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return O(i)?"":(t&&(s=new b(t.schema),t.resolver&&C(s,t.resolver)),s.render(i))},yt=()=>j(I);d.RichTextResolver=b,d.RichTextSchema=E,d.apiPlugin=pt,d.isRichTextEmpty=O,d.loadStoryblokBridge=yt,d.registerStoryblokBridge=P,d.renderRichText=mt,d.storyblokEditable=gt,d.storyblokInit=ft,d.useStoryblokBridge=P,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"})});
24
+ }`),""}optimizeImages(t,e){let s=0,r=0,o="",n="";typeof e!="boolean"&&(typeof e.width=="number"&&e.width>0&&(o+=`width="${e.width}" `,s=e.width),typeof e.height=="number"&&e.height>0&&(o+=`height="${e.height}" `,r=e.height),(e.loading==="lazy"||e.loading==="eager")&&(o+=`loading="${e.loading}" `),typeof e.class=="string"&&e.class.length>0&&(o+=`class="${e.class}" `),e.filters&&(typeof e.filters.blur=="number"&&e.filters.blur>=0&&e.filters.blur<=100&&(n+=`:blur(${e.filters.blur})`),typeof e.filters.brightness=="number"&&e.filters.brightness>=-100&&e.filters.brightness<=100&&(n+=`:brightness(${e.filters.brightness})`),e.filters.fill&&(e.filters.fill.match(/[0-9A-Fa-f]{6}/g)||e.filters.fill==="transparent")&&(n+=`:fill(${e.filters.fill})`),e.filters.format&&["webp","png","jpeg"].includes(e.filters.format)&&(n+=`:format(${e.filters.format})`),typeof e.filters.grayscale=="boolean"&&e.filters.grayscale&&(n+=":grayscale()"),typeof e.filters.quality=="number"&&e.filters.quality>=0&&e.filters.quality<=100&&(n+=`:quality(${e.filters.quality})`),e.filters.rotate&&[90,180,270].includes(e.filters.rotate)&&(n+=`:rotate(${e.filters.rotate})`),n.length>0&&(n="/filters"+n))),o.length>0&&(t=t.replace(/<img/g,`<img ${o.trim()}`));const c=s>0||r>0||n.length>0?`${s}x${r}${n}`:"";return t=t.replace(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g,`a.storyblok.com/f/$1/$2.$3/m/${c}`),typeof e!="boolean"&&(e.sizes||e.srcset)&&(t=t.replace(/<img.*?src=["|'](.*?)["|']/g,a=>{var l,u;const p=a.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);if(p&&p.length>0){const g={srcset:(l=e.srcset)==null?void 0:l.map(f=>{if(typeof f=="number")return`//${p}/m/${f}x0${n} ${f}w`;if(typeof f=="object"&&f.length===2){let _=0,A=0;return typeof f[0]=="number"&&(_=f[0]),typeof f[1]=="number"&&(A=f[1]),`//${p}/m/${_}x${A}${n} ${_}w`}}).join(", "),sizes:(u=e.sizes)==null?void 0:u.map(f=>f).join(", ")};let k="";return g.srcset&&(k+=`srcset="${g.srcset}" `),g.sizes&&(k+=`sizes="${g.sizes}" `),a.replace(/<img/g,`<img ${k.trim()}`)}return a})),t}renderNode(t){const e=[];t.marks&&t.marks.forEach(r=>{const o=this.getMatchingMark(r);o&&o.tag!==""&&e.push(this.renderOpeningTag(o.tag))});const s=this.getMatchingNode(t);return s&&s.tag&&e.push(this.renderOpeningTag(s.tag)),t.content?t.content.forEach(r=>{e.push(this.renderNode(r))}):t.text?e.push(ht(t.text)):s&&s.singleTag?e.push(this.renderTag(s.singleTag," /")):s&&s.html?e.push(s.html):t.type==="emoji"&&e.push(this.renderEmoji(t)),s&&s.tag&&e.push(this.renderClosingTag(s.tag)),t.marks&&t.marks.slice(0).reverse().forEach(r=>{const o=this.getMatchingMark(r);o&&o.tag!==""&&e.push(this.renderClosingTag(o.tag))}),e.join("")}renderTag(t,e){return t.constructor===String?`<${t}${e}>`:t.map(s=>{if(s.constructor===String)return`<${s}${e}>`;{let r=`<${s.tag}`;if(s.attrs)for(const o in s.attrs){const n=s.attrs[o];n!==null&&(r+=` ${o}="${n}"`)}return`${r}${e}>`}}).join("")}renderOpeningTag(t){return this.renderTag(t,"")}renderClosingTag(t){return t.constructor===String?`</${t}>`:t.slice(0).reverse().map(e=>e.constructor===String?`</${e}>`:`</${e.tag}>`).join("")}getMatchingNode(t){const e=this.nodes[t.type];if(typeof e=="function")return e(t)}getMatchingMark(t){const e=this.marks[t.type];if(typeof e=="function")return e(t)}renderEmoji(t){if(t.attrs.emoji)return t.attrs.emoji;const e=[{tag:"img",attrs:{src:t.attrs.fallbackImage,draggable:"false",loading:"lazy",align:"absmiddle"}}];return this.renderTag(e," /")}}class ut{constructor(t){h(this,"baseURL"),h(this,"timeout"),h(this,"headers"),h(this,"responseInterceptor"),h(this,"fetch"),h(this,"ejectInterceptor"),h(this,"url"),h(this,"parameters"),this.baseURL=t.baseURL,this.headers=t.headers||new Headers,this.timeout=t!=null&&t.timeout?t.timeout*1e3:0,this.responseInterceptor=t.responseInterceptor,this.fetch=(...e)=>t.fetch?t.fetch(...e):fetch(...e),this.ejectInterceptor=!1,this.url="",this.parameters={}}get(t,e){return this.url=t,this.parameters=e,this._methodHandler("get")}post(t,e){return this.url=t,this.parameters=e,this._methodHandler("post")}put(t,e){return this.url=t,this.parameters=e,this._methodHandler("put")}delete(t,e){return this.url=t,this.parameters=e,this._methodHandler("delete")}async _responseHandler(t){const e=[],s={data:{},headers:{},status:0,statusText:""};t.status!==204&&await t.json().then(r=>{s.data=r});for(const r of t.headers.entries())e[r[0]]=r[1];return s.headers={...e},s.status=t.status,s.statusText=t.statusText,s}async _methodHandler(t){let e=`${this.baseURL}${this.url}`,s=null;if(t==="get"){const a=new v;e=`${this.baseURL}${this.url}?${a.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const r=new URL(e),o=new AbortController,{signal:n}=o;let c;this.timeout&&(c=setTimeout(()=>o.abort(),this.timeout));try{const a=await this.fetch(`${r}`,{method:t,headers:this.headers,body:s,signal:n});this.timeout&&clearTimeout(c);const l=await this._responseHandler(a);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(l)):this._statusHandler(l)}catch(a){return{message:a}}}eject(){this.ejectInterceptor=!0}_statusHandler(t){const e=/20[0-6]/g;return new Promise(s=>{if(e.test(`${t.status}`))return s(t);const r={message:t.statusText,status:t.status,response:Array.isArray(t.data)?t.data[0]:t.data.error||t.data.slug};throw new Error(JSON.stringify(r))})}}const I="SB-Agent",T={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"5.14.2"};let w={};const y={};class dt{constructor(t,e){h(this,"client"),h(this,"maxRetries"),h(this,"throttle"),h(this,"accessToken"),h(this,"cache"),h(this,"helpers"),h(this,"resolveCounter"),h(this,"relations"),h(this,"links"),h(this,"richTextResolver"),h(this,"resolveNestedRelations");let s=t.endpoint||e;if(!s){const n=new v().getRegionURL,c=t.https===!1?"http":"https";t.oauthToken?s=`${c}://${n(t.region)}/v1`:s=`${c}://${n(t.region)}/v2`}const r=new Headers;if(r.set("Content-Type","application/json"),r.set("Accept","application/json"),t.headers)for(const n in t.headers)r.set(n,t.headers[n]);r.has(I)||(r.set(I,T.defaultAgentName),r.set(T.defaultAgentVersion,T.packageVersion));let o=5;t.oauthToken&&(r.set("Authorization",t.oauthToken),o=3),t.rateLimit&&(o=t.rateLimit),t.richTextSchema?this.richTextResolver=new b(t.richTextSchema):this.richTextResolver=new b,t.componentResolver&&this.setComponentResolver(t.componentResolver),this.maxRetries=t.maxRetries||5,this.throttle=M(this.throttledRequest,o,1e3),this.accessToken=t.accessToken||"",this.relations={},this.links={},this.cache=t.cache||{clear:"manual"},this.helpers=new v,this.resolveCounter=0,this.resolveNestedRelations=t.resolveNestedRelations||!0,this.client=new ut({baseURL:s,timeout:t.timeout||0,headers:r,responseInterceptor:t.responseInterceptor,fetch:t.fetch})}setComponentResolver(t){this.richTextResolver.addNode("blok",e=>{let s="";return e.attrs.body&&e.attrs.body.forEach(r=>{s+=t(r.component,r)}),{html:s}})}parseParams(t){return t.version||(t.version="published"),t.token||(t.token=this.getToken()),t.cv||(t.cv=y[t.token]),Array.isArray(t.resolve_relations)&&(t.resolve_relations=t.resolve_relations.join(",")),t}factoryParamOptions(t,e){return this.helpers.isCDNUrl(t)?this.parseParams(e):e}makeRequest(t,e,s,r){const o=this.factoryParamOptions(t,this.helpers.getOptionsPage(e,s,r));return this.cacheResponse(t,o)}get(t,e){e||(e={});const s=`/${t}`,r=this.factoryParamOptions(s,e);return this.cacheResponse(s,r)}async getAll(t,e,s){const r=(e==null?void 0:e.per_page)||25,o=`/${t}`,n=o.split("/"),c=s||n[n.length-1],a=1,l=await this.makeRequest(o,e,r,a),u=l.total?Math.ceil(l.total/r):1,p=await this.helpers.asyncMap(this.helpers.range(a,u),g=>this.makeRequest(o,e,r,g+1));return this.helpers.flatMap([l,...p],g=>Object.values(g.data[c]))}post(t,e){const s=`/${t}`;return Promise.resolve(this.throttle("post",s,e))}put(t,e){const s=`/${t}`;return Promise.resolve(this.throttle("put",s,e))}delete(t,e){const s=`/${t}`;return Promise.resolve(this.throttle("delete",s,e))}getStories(t){return this.get("cdn/stories",t)}getStory(t,e){return this.get(`cdn/stories/${t}`,e)}getToken(){return this.accessToken}ejectInterceptor(){this.client.eject()}_cleanCopy(t){return JSON.parse(JSON.stringify(t))}_insertLinks(t,e,s){const r=t[e];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]))}_insertRelations(t,e,s,r){if(s.indexOf(`${t.component}.${e}`)>-1){if(typeof t[e]=="string")this.relations[r][t[e]]&&(t[e]=this._cleanCopy(this.relations[r][t[e]]));else if(t[e]&&t[e].constructor===Array){const o=[];t[e].forEach(n=>{this.relations[r][n]&&o.push(this._cleanCopy(this.relations[r][n]))}),t[e]=o}}}iterateTree(t,e,s){const r=o=>{if(o!=null){if(o.constructor===Array)for(let n=0;n<o.length;n++)r(o[n]);else if(o.constructor===Object){if(o._stopResolving)return;for(const n in o)(o.component&&o._uid||o.type==="link")&&(this._insertRelations(o,n,e,s),this._insertLinks(o,n,s)),r(o[n])}}};r(t.content)}async resolveLinks(t,e,s){let r=[];if(t.link_uuids){const o=t.link_uuids.length,n=[],c=50;for(let a=0;a<o;a+=c){const l=Math.min(o,a+c);n.push(t.link_uuids.slice(a,l))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:c,language:e.language,version:e.version,by_uuids:n[a].join(",")})).data.stories.forEach(l=>{r.push(l)})}else r=t.links;r.forEach(o=>{this.links[s][o.uuid]={...o,_stopResolving:!0}})}async resolveRelations(t,e,s){let r=[];if(t.rel_uuids){const o=t.rel_uuids.length,n=[],c=50;for(let a=0;a<o;a+=c){const l=Math.min(o,a+c);n.push(t.rel_uuids.slice(a,l))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:c,language:e.language,version:e.version,by_uuids:n[a].join(",")})).data.stories.forEach(l=>{r.push(l)})}else r=t.rels;r&&r.length>0&&r.forEach(o=>{this.relations[s][o.uuid]={...o,_stopResolving:!0}})}async resolveStories(t,e,s){var r,o;let n=[];if(this.links[s]={},this.relations[s]={},typeof e.resolve_relations<"u"&&e.resolve_relations.length>0&&(typeof e.resolve_relations=="string"&&(n=e.resolve_relations.split(",")),await this.resolveRelations(t,e,s)),e.resolve_links&&["1","story","url","link"].indexOf(e.resolve_links)>-1&&((r=t.links)!=null&&r.length||(o=t.link_uuids)!=null&&o.length)&&await this.resolveLinks(t,e,s),this.resolveNestedRelations)for(const c in this.relations[s])this.iterateTree(this.relations[s][c],n,s);t.story?this.iterateTree(t.story,n,s):t.stories.forEach(c=>{this.iterateTree(c,n,s)}),delete this.links[s],delete this.relations[s]}async cacheResponse(t,e,s){(typeof s>"u"||!s)&&(s=0);const r=this.helpers.stringify({url:t,params:e}),o=this.cacheProvider();if(this.cache.clear==="auto"&&e.version==="draft"&&await this.flushCache(),e.version==="published"&&t!="/cdn/spaces/me"){const n=await o.get(r);if(n)return Promise.resolve(n)}return new Promise(async(n,c)=>{var a;try{const l=await this.throttle("get",t,e);if(l.status!==200)return c(l);let u={data:l.data,headers:l.headers};if((a=l.headers)!=null&&a["per-page"]&&(u=Object.assign({},u,{perPage:l.headers["per-page"]?parseInt(l.headers["per-page"]):0,total:l.headers["per-page"]?parseInt(l.headers.total):0})),u.data.story||u.data.stories){const p=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(u.data,e,`${p}`)}return e.version==="published"&&t!="/cdn/spaces/me"&&await o.set(r,u),u.data.cv&&e.token&&(e.version=="draft"&&y[e.token]!=u.data.cv&&await this.flushCache(),y[e.token]=u.data.cv),n(u)}catch(l){if(l.response&&l.response.status===429&&(s=s?s+1:0,s<this.maxRetries))return console.log(`Hit rate limit. Retrying in ${s} seconds.`),await this.helpers.delay(1e3*s),this.cacheResponse(t,e,s).then(n).catch(c);c(l.message)}})}throttledRequest(t,e,s){return this.client[t](e,s)}cacheVersions(){return y}cacheVersion(){return y[this.accessToken]}setCacheVersion(t){this.accessToken&&(y[this.accessToken]=t)}cacheProvider(){switch(this.cache.type){case"memory":return{get(t){return Promise.resolve(w[t])},getAll(){return Promise.resolve(w)},set(t,e){return w[t]=e,Promise.resolve(void 0)},flush(){return w={},Promise.resolve(void 0)}};case"custom":if(this.cache.custom)return this.cache.custom;default:return{get(){return Promise.resolve(void 0)},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}}const pt=(i={})=>{const{apiOptions:t}=i;if(!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 dt(t)}},gt=i=>{if(typeof i!="object"||typeof i._editable>"u")return{};const t=JSON.parse(i._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return t?{"data-blok-c":JSON.stringify(t),"data-blok-uid":t.id+"-"+t.uid}:{}};let R,$="https://app.storyblok.com/f/storyblok-v2-latest.js";const P=(i,t,e={})=>{var c;const r=!(typeof window>"u")&&typeof window.storyblokRegisterEvent<"u",n=+new URL((c=window.location)==null?void 0:c.href).searchParams.get("_storyblok")===i;if(!(!r||!n)){if(!i){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(e).on(["input","published","change"],l=>{l.action==="input"&&l.story.id===i?t(l.story):(l.action==="change"||l.action==="published")&&l.storyId===i&&window.location.reload()})})}},ft=(i={})=>{var p,g;const{bridge:t,accessToken:e,use:s=[],apiOptions:r={},richText:o={},bridgeUrl:n}=i;r.accessToken=r.accessToken||e;const c={bridge:t,apiOptions:r};let a={};s.forEach(k=>{a={...a,...k(c)}}),n&&($=n);const u=!(typeof window>"u")&&((g=(p=window.location)==null?void 0:p.search)==null?void 0:g.includes("_storyblok_tk"));return t!==!1&&u&&S($),R=new b(o.schema),o.resolver&&C(R,o.resolver),a},C=(i,t)=>{i.addNode("blok",e=>{let s="";return e.attrs.body.forEach(r=>{s+=t(r.component,r)}),{html:s}})},O=i=>!i||!(i!=null&&i.content.some(t=>t.content||t.type==="blok"||t.type==="horizontal_rule")),mt=(i,t,e)=>{let s=e||R;if(!s){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return O(i)?"":(t&&(s=new b(t.schema),t.resolver&&C(s,t.resolver)),s.render(i))},yt=()=>S($);d.RichTextResolver=b,d.RichTextSchema=x,d.apiPlugin=pt,d.isRichTextEmpty=O,d.loadStoryblokBridge=yt,d.registerStoryblokBridge=P,d.renderRichText=mt,d.storyblokEditable=gt,d.storyblokInit=ft,d.useStoryblokBridge=P,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"})});
@@ -1,26 +1,26 @@
1
- let T = !1;
2
- const _ = [], S = (i) => new Promise((t, e) => {
1
+ let _ = !1;
2
+ const j = [], E = (i) => new Promise((t, e) => {
3
3
  if (typeof window > "u" || (window.storyblokRegisterEvent = (r) => {
4
4
  if (window.location === window.parent.location) {
5
5
  console.warn("You are not in Draft Mode or in the Visual Editor.");
6
6
  return;
7
7
  }
8
- T ? r() : _.push(r);
8
+ _ ? r() : j.push(r);
9
9
  }, document.getElementById("storyblok-javascript-bridge")))
10
10
  return;
11
11
  const s = document.createElement("script");
12
12
  s.async = !0, s.src = i, s.id = "storyblok-javascript-bridge", s.onerror = (r) => e(r), s.onload = (r) => {
13
- _.forEach((o) => o()), T = !0, t(r);
13
+ j.forEach((o) => o()), _ = !0, t(r);
14
14
  }, document.getElementsByTagName("head")[0].appendChild(s);
15
15
  });
16
16
  var P = Object.defineProperty, C = (i, t, e) => t in i ? P(i, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : i[t] = e, h = (i, t, e) => (C(i, typeof t != "symbol" ? t + "" : t, e), e);
17
- function j(i) {
17
+ function x(i) {
18
18
  return !(i !== i || i === 1 / 0 || i === -1 / 0);
19
19
  }
20
20
  function A(i, t, e) {
21
- if (!j(t))
21
+ if (!x(t))
22
22
  throw new TypeError("Expected `limit` to be a finite number");
23
- if (!j(e))
23
+ if (!x(e))
24
24
  throw new TypeError("Expected `interval` to be a finite number");
25
25
  const s = [];
26
26
  let r = [], o = 0;
@@ -53,7 +53,7 @@ function A(i, t, e) {
53
53
  }), s.length = 0;
54
54
  }, c;
55
55
  }
56
- class y {
56
+ class b {
57
57
  constructor() {
58
58
  h(this, "isCDNUrl", (t = "") => t.indexOf("/cdn/") > -1), h(this, "getOptionsPage", (t, e = 25, s = 1) => ({
59
59
  ...t,
@@ -125,7 +125,7 @@ const O = function(i, t) {
125
125
  tag: "blockquote"
126
126
  }), z = () => ({
127
127
  tag: "ul"
128
- }), H = (i) => ({
128
+ }), U = (i) => ({
129
129
  tag: [
130
130
  "pre",
131
131
  {
@@ -133,7 +133,7 @@ const O = function(i, t) {
133
133
  attrs: i.attrs
134
134
  }
135
135
  ]
136
- }), U = () => ({
136
+ }), H = () => ({
137
137
  singleTag: "br"
138
138
  }), q = (i) => ({
139
139
  tag: `h${i.attrs.level}`
@@ -174,7 +174,7 @@ const O = function(i, t) {
174
174
  }), X = () => ({
175
175
  tag: "i"
176
176
  }), Z = (i) => {
177
- const t = new y().escapeHTML, e = { ...i.attrs }, { linktype: s = "url" } = i.attrs;
177
+ const t = new b().escapeHTML, e = { ...i.attrs }, { linktype: s = "url" } = i.attrs;
178
178
  if (e.href && (e.href = t(i.attrs.href || "")), N(s) && (e.href = `mailto:${e.href}`), e.anchor && (e.href = `${e.href}#${e.anchor}`, delete e.anchor), e.custom) {
179
179
  for (const r in e.custom)
180
180
  e[r] = e.custom[r];
@@ -239,8 +239,8 @@ const O = function(i, t) {
239
239
  horizontal_rule: L,
240
240
  blockquote: M,
241
241
  bullet_list: z,
242
- code_block: H,
243
- hard_break: U,
242
+ code_block: U,
243
+ hard_break: H,
244
244
  heading: q,
245
245
  image: B,
246
246
  list_item: V,
@@ -273,7 +273,7 @@ const O = function(i, t) {
273
273
  }, e = /[&<>"']/g, s = RegExp(e.source);
274
274
  return i && s.test(i) ? i.replace(e, (r) => t[r]) : i;
275
275
  };
276
- class b {
276
+ class k {
277
277
  constructor(t) {
278
278
  h(this, "marks"), h(this, "nodes"), t || (t = nt), this.marks = t.marks || [], this.nodes = t.nodes || [];
279
279
  }
@@ -330,19 +330,19 @@ class b {
330
330
  /a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g
331
331
  );
332
332
  if (p && p.length > 0) {
333
- const g = {
334
- srcset: (l = e.srcset) == null ? void 0 : l.map((d) => {
335
- if (typeof d == "number")
336
- return `//${p}/m/${d}x0${n} ${d}w`;
337
- if (typeof d == "object" && d.length === 2) {
338
- let v = 0, R = 0;
339
- return typeof d[0] == "number" && (v = d[0]), typeof d[1] == "number" && (R = d[1]), `//${p}/m/${v}x${R}${n} ${v}w`;
333
+ const d = {
334
+ srcset: (l = e.srcset) == null ? void 0 : l.map((g) => {
335
+ if (typeof g == "number")
336
+ return `//${p}/m/${g}x0${n} ${g}w`;
337
+ if (typeof g == "object" && g.length === 2) {
338
+ let v = 0, T = 0;
339
+ return typeof g[0] == "number" && (v = g[0]), typeof g[1] == "number" && (T = g[1]), `//${p}/m/${v}x${T}${n} ${v}w`;
340
340
  }
341
341
  }).join(", "),
342
- sizes: (u = e.sizes) == null ? void 0 : u.map((d) => d).join(", ")
342
+ sizes: (u = e.sizes) == null ? void 0 : u.map((g) => g).join(", ")
343
343
  };
344
- let k = "";
345
- return g.srcset && (k += `srcset="${g.srcset}" `), g.sizes && (k += `sizes="${g.sizes}" `), a.replace(/<img/g, `<img ${k.trim()}`);
344
+ let m = "";
345
+ return d.srcset && (m += `srcset="${d.srcset}" `), d.sizes && (m += `sizes="${d.sizes}" `), a.replace(/<img/g, `<img ${m.trim()}`);
346
346
  }
347
347
  return a;
348
348
  })), t;
@@ -448,7 +448,7 @@ class lt {
448
448
  async _methodHandler(t) {
449
449
  let e = `${this.baseURL}${this.url}`, s = null;
450
450
  if (t === "get") {
451
- const a = new y();
451
+ const a = new b();
452
452
  e = `${this.baseURL}${this.url}?${a.stringify(
453
453
  this.parameters
454
454
  )}`;
@@ -490,12 +490,12 @@ class lt {
490
490
  });
491
491
  }
492
492
  }
493
- const x = "SB-Agent", w = {
493
+ const S = "SB-Agent", w = {
494
494
  defaultAgentName: "SB-JS-CLIENT",
495
495
  defaultAgentVersion: "SB-Agent-Version",
496
496
  packageVersion: "5.14.2"
497
497
  };
498
- let m = {};
498
+ let y = {};
499
499
  const f = {};
500
500
  class ct {
501
501
  /**
@@ -507,19 +507,19 @@ class ct {
507
507
  h(this, "client"), h(this, "maxRetries"), h(this, "throttle"), h(this, "accessToken"), h(this, "cache"), h(this, "helpers"), h(this, "resolveCounter"), h(this, "relations"), h(this, "links"), h(this, "richTextResolver"), h(this, "resolveNestedRelations");
508
508
  let s = t.endpoint || e;
509
509
  if (!s) {
510
- const n = new y().getRegionURL, c = t.https === !1 ? "http" : "https";
510
+ const n = new b().getRegionURL, c = t.https === !1 ? "http" : "https";
511
511
  t.oauthToken ? s = `${c}://${n(t.region)}/v1` : s = `${c}://${n(t.region)}/v2`;
512
512
  }
513
513
  const r = new Headers();
514
514
  if (r.set("Content-Type", "application/json"), r.set("Accept", "application/json"), t.headers)
515
515
  for (const n in t.headers)
516
516
  r.set(n, t.headers[n]);
517
- r.has(x) || (r.set(x, w.defaultAgentName), r.set(
517
+ r.has(S) || (r.set(S, w.defaultAgentName), r.set(
518
518
  w.defaultAgentVersion,
519
519
  w.packageVersion
520
520
  ));
521
521
  let o = 5;
522
- t.oauthToken && (r.set("Authorization", t.oauthToken), o = 3), t.rateLimit && (o = t.rateLimit), t.richTextSchema ? this.richTextResolver = new b(t.richTextSchema) : this.richTextResolver = new b(), t.componentResolver && this.setComponentResolver(t.componentResolver), this.maxRetries = t.maxRetries || 5, this.throttle = A(this.throttledRequest, o, 1e3), this.accessToken = t.accessToken || "", this.relations = {}, this.links = {}, this.cache = t.cache || { clear: "manual" }, this.helpers = new y(), this.resolveCounter = 0, this.resolveNestedRelations = t.resolveNestedRelations || !0, this.client = new lt({
522
+ t.oauthToken && (r.set("Authorization", t.oauthToken), o = 3), t.rateLimit && (o = t.rateLimit), t.richTextSchema ? this.richTextResolver = new k(t.richTextSchema) : this.richTextResolver = new k(), t.componentResolver && this.setComponentResolver(t.componentResolver), this.maxRetries = t.maxRetries || 5, this.throttle = A(this.throttledRequest, o, 1e3), this.accessToken = t.accessToken || "", this.relations = {}, this.links = {}, this.cache = t.cache || { clear: "manual" }, this.helpers = new b(), this.resolveCounter = 0, this.resolveNestedRelations = t.resolveNestedRelations || !0, this.client = new lt({
523
523
  baseURL: s,
524
524
  timeout: t.timeout || 0,
525
525
  headers: r,
@@ -558,11 +558,11 @@ class ct {
558
558
  async getAll(t, e, s) {
559
559
  const r = (e == null ? void 0 : e.per_page) || 25, o = `/${t}`, n = o.split("/"), c = s || n[n.length - 1], a = 1, l = await this.makeRequest(o, e, r, a), u = l.total ? Math.ceil(l.total / r) : 1, p = await this.helpers.asyncMap(
560
560
  this.helpers.range(a, u),
561
- (g) => this.makeRequest(o, e, r, g + 1)
561
+ (d) => this.makeRequest(o, e, r, d + 1)
562
562
  );
563
563
  return this.helpers.flatMap(
564
564
  [l, ...p],
565
- (g) => Object.values(g.data[c])
565
+ (d) => Object.values(d.data[c])
566
566
  );
567
567
  }
568
568
  post(t, e) {
@@ -750,16 +750,16 @@ class ct {
750
750
  case "memory":
751
751
  return {
752
752
  get(t) {
753
- return Promise.resolve(m[t]);
753
+ return Promise.resolve(y[t]);
754
754
  },
755
755
  getAll() {
756
- return Promise.resolve(m);
756
+ return Promise.resolve(y);
757
757
  },
758
758
  set(t, e) {
759
- return m[t] = e, Promise.resolve(void 0);
759
+ return y[t] = e, Promise.resolve(void 0);
760
760
  },
761
761
  flush() {
762
- return m = {}, Promise.resolve(void 0);
762
+ return y = {}, Promise.resolve(void 0);
763
763
  }
764
764
  };
765
765
  case "custom":
@@ -801,13 +801,13 @@ const ut = (i = {}) => {
801
801
  const t = JSON.parse(
802
802
  i._editable.replace(/^<!--#storyblok#/, "").replace(/-->$/, "")
803
803
  );
804
- return {
804
+ return t ? {
805
805
  "data-blok-c": JSON.stringify(t),
806
806
  "data-blok-uid": t.id + "-" + t.uid
807
- };
807
+ } : {};
808
808
  };
809
- let $;
810
- const E = "https://app.storyblok.com/f/storyblok-v2-latest.js", dt = (i, t, e = {}) => {
809
+ let $, R = "https://app.storyblok.com/f/storyblok-v2-latest.js";
810
+ const dt = (i, t, e = {}) => {
811
811
  var c;
812
812
  const r = !(typeof window > "u") && typeof window.storyblokRegisterEvent < "u", n = +new URL((c = window.location) == null ? void 0 : c.href).searchParams.get(
813
813
  "_storyblok"
@@ -824,22 +824,23 @@ const E = "https://app.storyblok.com/f/storyblok-v2-latest.js", dt = (i, t, e =
824
824
  });
825
825
  }
826
826
  }, gt = (i = {}) => {
827
- var u, p;
827
+ var p, d;
828
828
  const {
829
829
  bridge: t,
830
830
  accessToken: e,
831
831
  use: s = [],
832
832
  apiOptions: r = {},
833
- richText: o = {}
833
+ richText: o = {},
834
+ bridgeUrl: n
834
835
  } = i;
835
836
  r.accessToken = r.accessToken || e;
836
- const n = { bridge: t, apiOptions: r };
837
- let c = {};
838
- s.forEach((g) => {
839
- c = { ...c, ...g(n) };
840
- });
841
- const l = !(typeof window > "u") && ((p = (u = window.location) == null ? void 0 : u.search) == null ? void 0 : p.includes("_storyblok_tk"));
842
- return t !== !1 && l && S(E), $ = new b(o.schema), o.resolver && I($, o.resolver), c;
837
+ const c = { bridge: t, apiOptions: r };
838
+ let a = {};
839
+ s.forEach((m) => {
840
+ a = { ...a, ...m(c) };
841
+ }), n && (R = n);
842
+ const u = !(typeof window > "u") && ((d = (p = window.location) == null ? void 0 : p.search) == null ? void 0 : d.includes("_storyblok_tk"));
843
+ return t !== !1 && u && E(R), $ = new k(o.schema), o.resolver && I($, o.resolver), a;
843
844
  }, I = (i, t) => {
844
845
  i.addNode("blok", (e) => {
845
846
  let s = "";
@@ -857,10 +858,10 @@ const E = "https://app.storyblok.com/f/storyblok-v2-latest.js", dt = (i, t, e =
857
858
  );
858
859
  return;
859
860
  }
860
- return ht(i) ? "" : (t && (s = new b(t.schema), t.resolver && I(s, t.resolver)), s.render(i));
861
- }, mt = () => S(E);
861
+ return ht(i) ? "" : (t && (s = new k(t.schema), t.resolver && I(s, t.resolver)), s.render(i));
862
+ }, mt = () => E(R);
862
863
  export {
863
- b as RichTextResolver,
864
+ k as RichTextResolver,
864
865
  nt as RichTextSchema,
865
866
  ut as apiPlugin,
866
867
  ht as isRichTextEmpty,
@@ -26,6 +26,7 @@ export interface SbSDKOptions {
26
26
  use?: any[];
27
27
  apiOptions?: ISbConfig;
28
28
  richText?: SbRichTextOptions;
29
+ bridgeUrl?: string;
29
30
  }
30
31
  export interface ISbEventPayload<S extends ISbComponentType<string> = any> {
31
32
  action: "customEvent" | "published" | "input" | "change" | "unpublished" | "enterEditmode";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storyblok/js",
3
- "version": "2.2.11",
3
+ "version": "2.3.0",
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",
@@ -38,7 +38,7 @@
38
38
  "isomorphic-fetch": "^3.0.0",
39
39
  "start-server-and-test": "^1.15.2",
40
40
  "vite": "^4.0.4",
41
- "vitest": "^0.34.1"
41
+ "vitest": "^0.34.3"
42
42
  },
43
43
  "babel": {
44
44
  "presets": [