@storyblok/js 3.0.10 → 3.0.11
Sign up to get free protection for your applications and to get access to all the features.
- package/dist/storyblok-js.js +2 -2
- package/dist/storyblok-js.mjs +30 -31
- package/package.json +4 -4
package/dist/storyblok-js.js
CHANGED
@@ -1,4 +1,4 @@
|
|
1
|
-
(function(p,b){typeof exports=="object"&&typeof module<"u"?b(exports):typeof define=="function"&&define.amd?define(["exports"],b):(p=typeof globalThis<"u"?globalThis:p||self,b(p.storyblok={}))})(this,function(p){"use strict";let b=!1;const S=[],j=n=>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}b?r():S.push(r)},document.getElementById("storyblok-javascript-bridge")))return;const s=document.createElement("script");s.async=!0,s.src=n,s.id="storyblok-javascript-bridge",s.onerror=r=>t(r),s.onload=r=>{S.forEach(i=>i()),b=!0,e(r)},document.getElementsByTagName("head")[0].appendChild(s)});var N=Object.defineProperty,L=(n,e,t)=>e in n?N(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,h=(n,e,t)=>
|
1
|
+
(function(p,b){typeof exports=="object"&&typeof module<"u"?b(exports):typeof define=="function"&&define.amd?define(["exports"],b):(p=typeof globalThis<"u"?globalThis:p||self,b(p.storyblok={}))})(this,function(p){"use strict";let b=!1;const S=[],j=n=>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}b?r():S.push(r)},document.getElementById("storyblok-javascript-bridge")))return;const s=document.createElement("script");s.async=!0,s.src=n,s.id="storyblok-javascript-bridge",s.onerror=r=>t(r),s.onload=r=>{S.forEach(i=>i()),b=!0,e(r)},document.getElementsByTagName("head")[0].appendChild(s)});var N=Object.defineProperty,L=(n,e,t)=>e in n?N(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,h=(n,e,t)=>L(n,typeof e!="symbol"?e+"":e,t);function x(n){return!(n!==n||n===1/0||n===-1/0)}function M(n,e,t){if(!x(e))throw new TypeError("Expected `limit` to be a finite number");if(!x(t))throw new TypeError("Expected `interval` to be a finite number");const s=[];let r=[],i=0;const o=function(){i++;const a=setTimeout(function(){i--,s.length>0&&o(),r=r.filter(function(u){return u!==a})},t);r.indexOf(a)<0&&r.push(a);const c=s.shift();c.resolve(n.apply(c.self,c.args))},l=function(...a){const c=this;return new Promise(function(u,d){s.push({resolve:u,reject:d,args:a,self:c}),i<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 k{constructor(){h(this,"isCDNUrl",(e="")=>e.indexOf("/cdn/")>-1),h(this,"getOptionsPage",(e,t=25,s=1)=>({...e,per_page:t,page:s})),h(this,"delay",e=>new Promise(t=>setTimeout(t,e))),h(this,"arrayFrom",(e=0,t)=>[...Array(e)].map(t)),h(this,"range",(e=0,t=e)=>{const s=Math.abs(t-e)||0,r=e<t?1:-1;return this.arrayFrom(s,(i,o)=>o*r+e)}),h(this,"asyncMap",async(e,t)=>Promise.all(e.map(t))),h(this,"flatMap",(e=[],t)=>e.map(t).reduce((s,r)=>[...s,...r],[])),h(this,"escapeHTML",function(e){const t={"&":"&","<":"<",">":">",'"':""","'":"'"},s=/[&<>"']/g,r=RegExp(s.source);return e&&r.test(e)?e.replace(s,i=>t[i]):e})}stringify(e,t,s){const r=[];for(const i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;const o=e[i],l=s?"":encodeURIComponent(i);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",i="api-ap.storyblok.com",o="api-ca.storyblok.com";switch(e){case"us":return s;case"cn":return r;case"ap":return i;case"ca":return o;default:return t}}}const z=function(n,e){const t={};for(const s in n){const r=n[s];e.indexOf(s)>-1&&r!==null&&(t[s]=r)}return t},U=n=>n==="email",B=()=>({singleTag:"hr"}),H=()=>({tag:"blockquote"}),q=()=>({tag:"ul"}),V=n=>({tag:["pre",{tag:"code",attrs:n.attrs}]}),D=()=>({singleTag:"br"}),J=n=>({tag:`h${n.attrs.level}`}),F=n=>({singleTag:[{tag:"img",attrs:z(n.attrs,["src","alt","title"])}]}),Y=()=>({tag:"li"}),K=()=>({tag:"ol"}),W=()=>({tag:"p"}),G=n=>({tag:[{tag:"span",attrs:{"data-type":"emoji","data-name":n.attrs.name,emoji:n.attrs.emoji}}]}),Q=()=>({tag:"b"}),X=()=>({tag:"s"}),Z=()=>({tag:"u"}),ee=()=>({tag:"strong"}),te=()=>({tag:"code"}),se=()=>({tag:"i"}),re=n=>{if(!n.attrs)return{tag:""};const e=new k().escapeHTML,t={...n.attrs},{linktype:s="url"}=n.attrs;if(delete t.linktype,t.href&&(t.href=e(n.attrs.href||"")),U(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}]}},ie=n=>({tag:[{tag:"span",attrs:n.attrs}]}),ne=()=>({tag:"sub"}),oe=()=>({tag:"sup"}),ae=n=>({tag:[{tag:"span",attrs:n.attrs}]}),le=n=>{var e;return(e=n.attrs)!=null&&e.color?{tag:[{tag:"span",attrs:{style:`background-color:${n.attrs.color};`}}]}:{tag:""}},ce=n=>{var e;return(e=n.attrs)!=null&&e.color?{tag:[{tag:"span",attrs:{style:`color:${n.attrs.color}`}}]}:{tag:""}},E={nodes:{horizontal_rule:B,blockquote:H,bullet_list:q,code_block:V,hard_break:D,heading:J,image:F,list_item:Y,ordered_list:K,paragraph:W,emoji:G},marks:{bold:Q,strike:X,underline:Z,strong:ee,code:te,italic:se,link:re,styled:ie,subscript:ne,superscript:oe,anchor:ae,highlight:le,textStyle:ce}},he=function(n){const e={"&":"&","<":"<",">":">",'"':""","'":"'"},t=/[&<>"']/g,s=RegExp(t.source);return n&&s.test(n)?n.replace(t,r=>e[r]):n};class ue{constructor(e){h(this,"marks"),h(this,"nodes"),e||(e=E),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(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,i="",o="";typeof t!="boolean"&&(typeof t.width=="number"&&t.width>0&&(i+=`width="${t.width}" `,s=t.width),typeof t.height=="number"&&t.height>0&&(i+=`height="${t.height}" `,r=t.height),(t.loading==="lazy"||t.loading==="eager")&&(i+=`loading="${t.loading}" `),typeof t.class=="string"&&t.class.length>0&&(i+=`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))),i.length>0&&(e=e.replace(/<img/g,`<img ${i.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 c,u;const d=a.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);if(d&&d.length>0){const g={srcset:(c=t.srcset)==null?void 0:c.map(f=>{if(typeof f=="number")return`//${d}/m/${f}x0${o} ${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]),`//${d}/m/${_}x${A}${o} ${_}w`}}).join(", "),sizes:(u=t.sizes)==null?void 0:u.map(f=>f).join(", ")};let m="";return g.srcset&&(m+=`srcset="${g.srcset}" `),g.sizes&&(m+=`sizes="${g.sizes}" `),a.replace(/<img/g,`<img ${m.trim()}`)}return a})),e}renderNode(e){const t=[];e.marks&&e.marks.forEach(r=>{const i=this.getMatchingMark(r);i&&i.tag!==""&&t.push(this.renderOpeningTag(i.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(he(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 i=this.getMatchingMark(r);i&&i.tag!==""&&t.push(this.renderClosingTag(i.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 i in s.attrs)if(Object.prototype.hasOwnProperty.call(s.attrs,i)){const o=s.attrs[i];o!==null&&(r+=` ${i}="${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," /")}}class ue{constructor(e){h(this,"baseURL"),h(this,"timeout"),h(this,"headers"),h(this,"responseInterceptor"),h(this,"fetch"),h(this,"ejectInterceptor"),h(this,"url"),h(this,"parameters"),h(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 k;t=`${this.baseURL}${this.url}?${a.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const r=new URL(t),i=new AbortController,{signal:o}=i;let l;this.timeout&&(l=setTimeout(()=>i.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 c=await this._responseHandler(a);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(c)):this._statusHandler(c)}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 i={message:e.statusText,status:e.status,response:Array.isArray(e.data)?e.data[0]:e.data.error||e.data.slug};r(i)})}}const E="SB-Agent",R={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"6.0.0"};let w={};const y={};class de{constructor(e,t){h(this,"client"),h(this,"maxRetries"),h(this,"retriesDelay"),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"),h(this,"stringifiedStoriesCache");let s=e.endpoint||t;if(!s){const o=new k().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;if(r.set("Content-Type","application/json"),r.set("Accept","application/json"),e.headers)for(const o in e.headers)r.set(o,e.headers[o]);r.has(E)||(r.set(E,R.defaultAgentName),r.set(R.defaultAgentVersion,R.packageVersion));let i=5;e.oauthToken&&(r.set("Authorization",e.oauthToken),i=3),e.rateLimit&&(i=e.rateLimit),e.richTextSchema?this.richTextResolver=new v(e.richTextSchema):this.richTextResolver=new v,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||10,this.retriesDelay=300,this.throttle=M(this.throttledRequest,i,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new k,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.stringifiedStoriesCache={},this.client=new ue({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=y[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,i){const o=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,s,r));return this.cacheResponse(e,o,void 0,i)}get(e,t,s){t||(t={});const r=`/${e}`,i=this.factoryParamOptions(r,t);return this.cacheResponse(r,i,void 0,s)}async getAll(e,t,s,r){const i=(t==null?void 0:t.per_page)||25,o=`/${e}`,l=o.split("/"),a=s||l[l.length-1],c=1,u=await this.makeRequest(o,t,i,c,r),d=u.total?Math.ceil(u.total/i):1,g=await this.helpers.asyncMap(this.helpers.range(c,d),m=>this.makeRequest(o,t,i,m+1,r));return this.helpers.flatMap([u,...g],m=>Object.values(m.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(i=>this.getStoryReference(r,i)).filter(Boolean)))}iterateTree(e,t,s){const r=i=>{if(i!=null){if(i.constructor===Array)for(let o=0;o<i.length;o++)r(i[o]);else if(i.constructor===Object){if(i._stopResolving)return;for(const o in i)(i.component&&i._uid||i.type==="link")&&(this._insertRelations(i,o,t,s),this._insertLinks(i,o,s)),r(i[o])}}};r(e.content)}async resolveLinks(e,t,s){let r=[];if(e.link_uuids){const i=e.link_uuids.length,o=[],l=50;for(let a=0;a<i;a+=l){const c=Math.min(i,a+l);o.push(e.link_uuids.slice(a,c))}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(c=>{r.push(c)})}else r=e.links;r.forEach(i=>{this.links[s][i.uuid]={...i,_stopResolving:!0}})}async resolveRelations(e,t,s){let r=[];if(e.rel_uuids){const i=e.rel_uuids.length,o=[],l=50;for(let a=0;a<i;a+=l){const c=Math.min(i,a+l);o.push(e.rel_uuids.slice(a,c))}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(c=>{r.push(c)})}else r=e.rels;r&&r.length>0&&r.forEach(i=>{this.relations[s][i.uuid]={...i,_stopResolving:!0}})}async resolveStories(e,t,s){var r,i;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||(i=e.link_uuids)!=null&&i.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 i=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(i);if(l)return Promise.resolve(l)}return new Promise(async(l,a)=>{var c;try{const u=await this.throttle("get",e,t,r);if(u.status!==200)return a(u);let d={data:u.data,headers:u.headers};if((c=u.headers)!=null&&c["per-page"]&&(d=Object.assign({},d,{perPage:u.headers["per-page"]?parseInt(u.headers["per-page"]):0,total:u.headers["per-page"]?parseInt(u.headers.total):0})),d.data.story||d.data.stories){const g=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(d.data,t,`${g}`)}return t.version==="published"&&e!="/cdn/spaces/me"&&await o.set(i,d),d.data.cv&&t.token&&(t.version==="draft"&&y[t.token]!=d.data.cv&&await this.flushCache(),y[t.token]=t.cv?t.cv:d.data.cv),l(d)}catch(u){if(u.response&&u.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(u)}})}throttledRequest(e,t,s,r){return this.client.setFetchOptions(r),this.client[e](t,s)}cacheVersions(){return y}cacheVersion(){return y[this.accessToken]}setCacheVersion(e){this.accessToken&&(y[this.accessToken]=e)}clearCacheVersion(){this.accessToken&&(y[this.accessToken]=0)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(w[e])},getAll(){return Promise.resolve(w)},set(e,t){return w[e]=t,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()},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 pe=(n={})=>{const{apiOptions:e}=n;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 de(e)}},ge=n=>{if(typeof n!="object"||typeof n._editable>"u")return{};try{const e=JSON.parse(n._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return e?{"data-blok-c":JSON.stringify(e),"data-blok-uid":e.id+"-"+e.uid}:{}}catch{return{}}};let T,$="https://app.storyblok.com/f/storyblok-v2-latest.js";const I=(n,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")===n;if(!(!r||!o)){if(!n){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(t).on(["input","published","change"],c=>{c.action==="input"&&c.story.id===n?e(c.story):(c.action==="change"||c.action==="published")&&c.storyId===n&&window.location.reload()})})}},fe=(n={})=>{var d,g;const{bridge:e,accessToken:t,use:s=[],apiOptions:r={},richText:i={},bridgeUrl:o}=n;r.accessToken=r.accessToken||t;const l={bridge:e,apiOptions:r};let a={};s.forEach(m=>{a={...a,...m(l)}}),o&&($=o);const u=!(typeof window>"u")&&((g=(d=window.location)==null?void 0:d.search)==null?void 0:g.includes("_storyblok_tk"));return e!==!1&&u&&j($),T=new v(i.schema),i.resolver&&P(T,i.resolver),a},P=(n,e)=>{n.addNode("blok",t=>{let s="";return t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})},C=n=>!n||!(n!=null&&n.content.some(e=>e.content||e.type==="blok"||e.type==="horizontal_rule")),me=(n,e,t)=>{let s=t||T;if(!s){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return C(n)?"":(e&&(s=new v(e.schema),e.resolver&&P(s,e.resolver)),s.render(n))},ye=()=>j($);p.RichTextResolver=v,p.RichTextSchema=O,p.apiPlugin=pe,p.isRichTextEmpty=C,p.loadStoryblokBridge=ye,p.registerStoryblokBridge=I,p.renderRichText=me,p.storyblokEditable=ge,p.storyblokInit=fe,p.useStoryblokBridge=I,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"})});
|
24
|
+
}`),""}optimizeImages(e,t){let s=0,r=0,i="",o="";typeof t!="boolean"&&(typeof t.width=="number"&&t.width>0&&(i+=`width="${t.width}" `,s=t.width),typeof t.height=="number"&&t.height>0&&(i+=`height="${t.height}" `,r=t.height),(t.loading==="lazy"||t.loading==="eager")&&(i+=`loading="${t.loading}" `),typeof t.class=="string"&&t.class.length>0&&(i+=`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))),i.length>0&&(e=e.replace(/<img/g,`<img ${i.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 c,u;const d=a.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);if(d&&d.length>0){const g={srcset:(c=t.srcset)==null?void 0:c.map(f=>{if(typeof f=="number")return`//${d}/m/${f}x0${o} ${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]),`//${d}/m/${_}x${A}${o} ${_}w`}}).join(", "),sizes:(u=t.sizes)==null?void 0:u.map(f=>f).join(", ")};let m="";return g.srcset&&(m+=`srcset="${g.srcset}" `),g.sizes&&(m+=`sizes="${g.sizes}" `),a.replace(/<img/g,`<img ${m.trim()}`)}return a})),e}renderNode(e){const t=[];e.marks&&e.marks.forEach(r=>{const i=this.getMatchingMark(r);i&&i.tag!==""&&t.push(this.renderOpeningTag(i.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(he(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 i=this.getMatchingMark(r);i&&i.tag!==""&&t.push(this.renderClosingTag(i.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 i in s.attrs)if(Object.prototype.hasOwnProperty.call(s.attrs,i)){const o=s.attrs[i];o!==null&&(r+=` ${i}="${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 v=ue;class de{constructor(e){h(this,"baseURL"),h(this,"timeout"),h(this,"headers"),h(this,"responseInterceptor"),h(this,"fetch"),h(this,"ejectInterceptor"),h(this,"url"),h(this,"parameters"),h(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 k;t=`${this.baseURL}${this.url}?${a.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const r=new URL(t),i=new AbortController,{signal:o}=i;let l;this.timeout&&(l=setTimeout(()=>i.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 c=await this._responseHandler(a);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(c)):this._statusHandler(c)}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 i={message:e.statusText,status:e.status,response:Array.isArray(e.data)?e.data[0]:e.data.error||e.data.slug};r(i)})}}const pe=de,O="SB-Agent",R={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"6.0.0"};let w={};const y={};class ge{constructor(e,t){h(this,"client"),h(this,"maxRetries"),h(this,"retriesDelay"),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"),h(this,"stringifiedStoriesCache");let s=e.endpoint||t;if(!s){const o=new k().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(O)||(r.set(O,R.defaultAgentName),r.set(R.defaultAgentVersion,R.packageVersion));let i=5;e.oauthToken&&(r.set("Authorization",e.oauthToken),i=3),e.rateLimit&&(i=e.rateLimit),e.richTextSchema?this.richTextResolver=new v(e.richTextSchema):this.richTextResolver=new v,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||10,this.retriesDelay=300,this.throttle=M(this.throttledRequest,i,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new k,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.stringifiedStoriesCache={},this.client=new pe({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=y[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,i){const o=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,s,r));return this.cacheResponse(e,o,void 0,i)}get(e,t,s){t||(t={});const r=`/${e}`,i=this.factoryParamOptions(r,t);return this.cacheResponse(r,i,void 0,s)}async getAll(e,t,s,r){const i=(t==null?void 0:t.per_page)||25,o=`/${e}`,l=o.split("/"),a=s||l[l.length-1],c=1,u=await this.makeRequest(o,t,i,c,r),d=u.total?Math.ceil(u.total/i):1,g=await this.helpers.asyncMap(this.helpers.range(c,d),m=>this.makeRequest(o,t,i,m+1,r));return this.helpers.flatMap([u,...g],m=>Object.values(m.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(i=>this.getStoryReference(r,i)).filter(Boolean)))}iterateTree(e,t,s){const r=i=>{if(i!=null){if(i.constructor===Array)for(let o=0;o<i.length;o++)r(i[o]);else if(i.constructor===Object){if(i._stopResolving)return;for(const o in i)(i.component&&i._uid||i.type==="link")&&(this._insertRelations(i,o,t,s),this._insertLinks(i,o,s)),r(i[o])}}};r(e.content)}async resolveLinks(e,t,s){let r=[];if(e.link_uuids){const i=e.link_uuids.length,o=[],l=50;for(let a=0;a<i;a+=l){const c=Math.min(i,a+l);o.push(e.link_uuids.slice(a,c))}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(c=>{r.push(c)})}else r=e.links;r.forEach(i=>{this.links[s][i.uuid]={...i,_stopResolving:!0}})}async resolveRelations(e,t,s){let r=[];if(e.rel_uuids){const i=e.rel_uuids.length,o=[],l=50;for(let a=0;a<i;a+=l){const c=Math.min(i,a+l);o.push(e.rel_uuids.slice(a,c))}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(c=>{r.push(c)})}else r=e.rels;r&&r.length>0&&r.forEach(i=>{this.relations[s][i.uuid]={...i,_stopResolving:!0}})}async resolveStories(e,t,s){var r,i;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||(i=e.link_uuids)!=null&&i.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 i=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(i);if(l)return Promise.resolve(l)}return new Promise(async(l,a)=>{var c;try{const u=await this.throttle("get",e,t,r);if(u.status!==200)return a(u);let d={data:u.data,headers:u.headers};if((c=u.headers)!=null&&c["per-page"]&&(d=Object.assign({},d,{perPage:u.headers["per-page"]?parseInt(u.headers["per-page"]):0,total:u.headers["per-page"]?parseInt(u.headers.total):0})),d.data.story||d.data.stories){const g=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(d.data,t,`${g}`)}return t.version==="published"&&e!="/cdn/spaces/me"&&await o.set(i,d),d.data.cv&&t.token&&(t.version==="draft"&&y[t.token]!=d.data.cv&&await this.flushCache(),y[t.token]=t.cv?t.cv:d.data.cv),l(d)}catch(u){if(u.response&&u.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(u)}})}throttledRequest(e,t,s,r){return this.client.setFetchOptions(r),this.client[e](t,s)}cacheVersions(){return y}cacheVersion(){return y[this.accessToken]}setCacheVersion(e){this.accessToken&&(y[this.accessToken]=e)}clearCacheVersion(){this.accessToken&&(y[this.accessToken]=0)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(w[e])},getAll(){return Promise.resolve(w)},set(e,t){return w[e]=t,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()},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 fe=(n={})=>{const{apiOptions:e}=n;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 ge(e)}},me=n=>{if(typeof n!="object"||typeof n._editable>"u")return{};try{const e=JSON.parse(n._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return e?{"data-blok-c":JSON.stringify(e),"data-blok-uid":e.id+"-"+e.uid}:{}}catch{return{}}};let T,$="https://app.storyblok.com/f/storyblok-v2-latest.js";const I=(n,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")===n;if(!(!r||!o)){if(!n){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(t).on(["input","published","change"],c=>{c.action==="input"&&c.story.id===n?e(c.story):(c.action==="change"||c.action==="published")&&c.storyId===n&&window.location.reload()})})}},ye=(n={})=>{var d,g;const{bridge:e,accessToken:t,use:s=[],apiOptions:r={},richText:i={},bridgeUrl:o}=n;r.accessToken=r.accessToken||t;const l={bridge:e,apiOptions:r};let a={};s.forEach(m=>{a={...a,...m(l)}}),o&&($=o);const u=!(typeof window>"u")&&((g=(d=window.location)==null?void 0:d.search)==null?void 0:g.includes("_storyblok_tk"));return e!==!1&&u&&j($),T=new v(i.schema),i.resolver&&P(T,i.resolver),a},P=(n,e)=>{n.addNode("blok",t=>{let s="";return t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})},C=n=>!n||!(n!=null&&n.content.some(e=>e.content||e.type==="blok"||e.type==="horizontal_rule")),be=(n,e,t)=>{let s=t||T;if(!s){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return C(n)?"":(e&&(s=new v(e.schema),e.resolver&&P(s,e.resolver)),s.render(n))},ve=()=>j($);p.RichTextResolver=v,p.RichTextSchema=E,p.apiPlugin=fe,p.isRichTextEmpty=C,p.loadStoryblokBridge=ve,p.registerStoryblokBridge=I,p.renderRichText=be,p.storyblokEditable=me,p.storyblokInit=ye,p.useStoryblokBridge=I,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"})});
|
package/dist/storyblok-js.mjs
CHANGED
@@ -1,5 +1,5 @@
|
|
1
1
|
let _ = !1;
|
2
|
-
const S = [],
|
2
|
+
const S = [], E = (n) => new Promise((e, t) => {
|
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.");
|
@@ -12,7 +12,7 @@ const S = [], O = (n) => new Promise((e, t) => {
|
|
12
12
|
S.forEach((i) => i()), _ = !0, e(r);
|
13
13
|
}, document.getElementsByTagName("head")[0].appendChild(s);
|
14
14
|
});
|
15
|
-
var I = Object.defineProperty, P = (n, e, t) => e in n ? I(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t, h = (n, e, t) =>
|
15
|
+
var I = Object.defineProperty, P = (n, e, t) => e in n ? I(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t, h = (n, e, t) => P(n, typeof e != "symbol" ? e + "" : e, t);
|
16
16
|
function j(n) {
|
17
17
|
return !(n !== n || n === 1 / 0 || n === -1 / 0);
|
18
18
|
}
|
@@ -280,7 +280,7 @@ const A = function(n, e) {
|
|
280
280
|
}, t = /[&<>"']/g, s = RegExp(t.source);
|
281
281
|
return n && s.test(n) ? n.replace(t, (r) => e[r]) : n;
|
282
282
|
};
|
283
|
-
class
|
283
|
+
class le {
|
284
284
|
constructor(e) {
|
285
285
|
h(this, "marks"), h(this, "nodes"), e || (e = oe), this.marks = e.marks || [], this.nodes = e.nodes || [];
|
286
286
|
}
|
@@ -418,7 +418,8 @@ class v {
|
|
418
418
|
return this.renderTag(t, " /");
|
419
419
|
}
|
420
420
|
}
|
421
|
-
|
421
|
+
const v = le;
|
422
|
+
class ce {
|
422
423
|
constructor(e) {
|
423
424
|
h(this, "baseURL"), h(this, "timeout"), h(this, "headers"), h(this, "responseInterceptor"), h(this, "fetch"), h(this, "ejectInterceptor"), h(this, "url"), h(this, "parameters"), h(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 = {};
|
424
425
|
}
|
@@ -505,14 +506,14 @@ class le {
|
|
505
506
|
});
|
506
507
|
}
|
507
508
|
}
|
508
|
-
const x = "SB-Agent", w = {
|
509
|
+
const he = ce, x = "SB-Agent", w = {
|
509
510
|
defaultAgentName: "SB-JS-CLIENT",
|
510
511
|
defaultAgentVersion: "SB-Agent-Version",
|
511
512
|
packageVersion: "6.0.0"
|
512
513
|
};
|
513
514
|
let y = {};
|
514
515
|
const m = {};
|
515
|
-
class
|
516
|
+
class ue {
|
516
517
|
/**
|
517
518
|
*
|
518
519
|
* @param config ISbConfig interface
|
@@ -526,15 +527,14 @@ class ce {
|
|
526
527
|
e.oauthToken ? s = `${l}://${o(e.region)}/v1` : s = `${l}://${o(e.region)}/v2`;
|
527
528
|
}
|
528
529
|
const r = new Headers();
|
529
|
-
|
530
|
-
|
531
|
-
|
532
|
-
r.has(x) || (r.set(x, w.defaultAgentName), r.set(
|
530
|
+
r.set("Content-Type", "application/json"), r.set("Accept", "application/json"), e.headers && e.headers.entries().toArray().forEach(([o, l]) => {
|
531
|
+
r.set(o, l);
|
532
|
+
}), r.has(x) || (r.set(x, w.defaultAgentName), r.set(
|
533
533
|
w.defaultAgentVersion,
|
534
534
|
w.packageVersion
|
535
535
|
));
|
536
536
|
let i = 5;
|
537
|
-
e.oauthToken && (r.set("Authorization", e.oauthToken), i = 3), e.rateLimit && (i = e.rateLimit), e.richTextSchema ? this.richTextResolver = new v(e.richTextSchema) : this.richTextResolver = new v(), e.componentResolver && this.setComponentResolver(e.componentResolver), this.maxRetries = e.maxRetries || 10, this.retriesDelay = 300, this.throttle = C(this.throttledRequest, i, 1e3), this.accessToken = e.accessToken || "", this.relations = {}, this.links = {}, this.cache = e.cache || { clear: "manual" }, this.helpers = new b(), this.resolveCounter = 0, this.resolveNestedRelations = e.resolveNestedRelations || !0, this.stringifiedStoriesCache = {}, this.client = new
|
537
|
+
e.oauthToken && (r.set("Authorization", e.oauthToken), i = 3), e.rateLimit && (i = e.rateLimit), e.richTextSchema ? this.richTextResolver = new v(e.richTextSchema) : this.richTextResolver = new v(), e.componentResolver && this.setComponentResolver(e.componentResolver), this.maxRetries = e.maxRetries || 10, this.retriesDelay = 300, this.throttle = C(this.throttledRequest, i, 1e3), this.accessToken = e.accessToken || "", this.relations = {}, this.links = {}, this.cache = e.cache || { clear: "manual" }, this.helpers = new b(), this.resolveCounter = 0, this.resolveNestedRelations = e.resolveNestedRelations || !0, this.stringifiedStoriesCache = {}, this.client = new he({
|
538
538
|
baseURL: s,
|
539
539
|
timeout: e.timeout || 0,
|
540
540
|
headers: r,
|
@@ -801,8 +801,7 @@ class ce {
|
|
801
801
|
}
|
802
802
|
};
|
803
803
|
case "custom":
|
804
|
-
if (this.cache.custom)
|
805
|
-
return this.cache.custom;
|
804
|
+
if (this.cache.custom) return this.cache.custom;
|
806
805
|
default:
|
807
806
|
return {
|
808
807
|
get() {
|
@@ -824,7 +823,7 @@ class ce {
|
|
824
823
|
return await this.cacheProvider().flush(), this.clearCacheVersion(), this;
|
825
824
|
}
|
826
825
|
}
|
827
|
-
const
|
826
|
+
const pe = (n = {}) => {
|
828
827
|
const { apiOptions: e } = n;
|
829
828
|
if (!e.accessToken) {
|
830
829
|
console.error(
|
@@ -832,8 +831,8 @@ const ue = (n = {}) => {
|
|
832
831
|
);
|
833
832
|
return;
|
834
833
|
}
|
835
|
-
return { storyblokApi: new
|
836
|
-
},
|
834
|
+
return { storyblokApi: new ue(e) };
|
835
|
+
}, ge = (n) => {
|
837
836
|
if (typeof n != "object" || typeof n._editable > "u")
|
838
837
|
return {};
|
839
838
|
try {
|
@@ -849,7 +848,7 @@ const ue = (n = {}) => {
|
|
849
848
|
}
|
850
849
|
};
|
851
850
|
let R, $ = "https://app.storyblok.com/f/storyblok-v2-latest.js";
|
852
|
-
const
|
851
|
+
const fe = (n, e, t = {}) => {
|
853
852
|
var l;
|
854
853
|
const r = !(typeof window > "u") && typeof window.storyblokRegisterEvent < "u", o = +new URL((l = window.location) == null ? void 0 : l.href).searchParams.get(
|
855
854
|
"_storyblok"
|
@@ -865,7 +864,7 @@ const pe = (n, e, t = {}) => {
|
|
865
864
|
});
|
866
865
|
});
|
867
866
|
}
|
868
|
-
},
|
867
|
+
}, me = (n = {}) => {
|
869
868
|
var d, p;
|
870
869
|
const {
|
871
870
|
bridge: e,
|
@@ -882,8 +881,8 @@ const pe = (n, e, t = {}) => {
|
|
882
881
|
a = { ...a, ...f(l) };
|
883
882
|
}), o && ($ = o);
|
884
883
|
const u = !(typeof window > "u") && ((p = (d = window.location) == null ? void 0 : d.search) == null ? void 0 : p.includes("_storyblok_tk"));
|
885
|
-
return e !== !1 && u &&
|
886
|
-
},
|
884
|
+
return e !== !1 && u && E($), R = new v(i.schema), i.resolver && O(R, i.resolver), a;
|
885
|
+
}, O = (n, e) => {
|
887
886
|
n.addNode("blok", (t) => {
|
888
887
|
let s = "";
|
889
888
|
return t.attrs.body.forEach((r) => {
|
@@ -892,7 +891,7 @@ const pe = (n, e, t = {}) => {
|
|
892
891
|
html: s
|
893
892
|
};
|
894
893
|
});
|
895
|
-
},
|
894
|
+
}, de = (n) => !n || !(n != null && n.content.some((e) => e.content || e.type === "blok" || e.type === "horizontal_rule")), ye = (n, e, t) => {
|
896
895
|
let s = t || R;
|
897
896
|
if (!s) {
|
898
897
|
console.error(
|
@@ -900,17 +899,17 @@ const pe = (n, e, t = {}) => {
|
|
900
899
|
);
|
901
900
|
return;
|
902
901
|
}
|
903
|
-
return
|
904
|
-
},
|
902
|
+
return de(n) ? "" : (e && (s = new v(e.schema), e.resolver && O(s, e.resolver)), s.render(n));
|
903
|
+
}, be = () => E($);
|
905
904
|
export {
|
906
905
|
v as RichTextResolver,
|
907
906
|
oe as RichTextSchema,
|
908
|
-
|
909
|
-
|
910
|
-
|
911
|
-
|
912
|
-
|
913
|
-
|
914
|
-
|
915
|
-
|
907
|
+
pe as apiPlugin,
|
908
|
+
de as isRichTextEmpty,
|
909
|
+
be as loadStoryblokBridge,
|
910
|
+
fe as registerStoryblokBridge,
|
911
|
+
ye as renderRichText,
|
912
|
+
ge as storyblokEditable,
|
913
|
+
me as storyblokInit,
|
914
|
+
fe as useStoryblokBridge
|
916
915
|
};
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "@storyblok/js",
|
3
|
-
"version": "3.0.
|
3
|
+
"version": "3.0.11",
|
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",
|
@@ -28,16 +28,16 @@
|
|
28
28
|
"prepublishOnly": "npm run build && cp ../README.md ./"
|
29
29
|
},
|
30
30
|
"dependencies": {
|
31
|
-
"storyblok-js-client": "^6.8.
|
31
|
+
"storyblok-js-client": "^6.8.4"
|
32
32
|
},
|
33
33
|
"devDependencies": {
|
34
34
|
"@tsconfig/recommended": "^1.0.7",
|
35
|
-
"cypress": "^13.
|
35
|
+
"cypress": "^13.13.3",
|
36
36
|
"eslint-plugin-cypress": "^2.15.1",
|
37
37
|
"eslint-plugin-jest": "^28.8.0",
|
38
38
|
"isomorphic-fetch": "^3.0.0",
|
39
39
|
"start-server-and-test": "^2.0.5",
|
40
|
-
"vite": "^5.4.
|
40
|
+
"vite": "^5.4.2",
|
41
41
|
"vitest": "^2.0.5"
|
42
42
|
},
|
43
43
|
"babel": {
|