storyblok-js-client
Advanced tools
Comparing version 5.13.0 to 5.14.0
@@ -1,2 +0,2 @@ | ||
(function(p,h){typeof exports=="object"&&typeof module<"u"?module.exports=h():typeof define=="function"&&define.amd?define(h):(p=typeof globalThis<"u"?globalThis:p||self,p.StoryblokJSClient=h())})(this,function(){"use strict";var D=Object.defineProperty;var z=(p,h,m)=>h in p?D(p,h,{enumerable:!0,configurable:!0,writable:!0,value:m}):p[h]=m;var u=(p,h,m)=>(z(p,typeof h!="symbol"?h+"":h,m),m);function p(i){return!(i!==i||i===1/0||i===-1/0)}function h(i,e,t){if(!p(e))throw new TypeError("Expected `limit` to be a finite number");if(!p(t))throw new TypeError("Expected `interval` to be a finite number");const s=[];let o=[],n=0;const r=function(){n++;const a=setTimeout(function(){n--,s.length>0&&r(),o=o.filter(function(d){return d!==a})},t);o.indexOf(a)<0&&o.push(a);const c=s.shift();c.resolve(i.apply(c.self,c.args))},l=function(...a){const c=this;return new Promise(function(d,b){s.push({resolve:d,reject:b,args:a,self:c}),n<e&&r()})};return l.abort=function(){o.forEach(clearTimeout),o=[],s.forEach(function(a){a.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),s.length=0},l}class m{constructor(){u(this,"isCDNUrl",(e="")=>e.indexOf("/cdn/")>-1);u(this,"getOptionsPage",(e,t=25,s=1)=>({...e,per_page:t,page:s}));u(this,"delay",e=>new Promise(t=>setTimeout(t,e)));u(this,"arrayFrom",(e=0,t)=>[...Array(e)].map(t));u(this,"range",(e=0,t=e)=>{const s=Math.abs(t-e)||0,o=e<t?1:-1;return this.arrayFrom(s,(n,r)=>r*o+e)});u(this,"asyncMap",async(e,t)=>Promise.all(e.map(t)));u(this,"flatMap",(e=[],t)=>e.map(t).reduce((s,o)=>[...s,...o],[]));u(this,"escapeHTML",function(e){const t={"&":"&","<":"<",">":">",'"':""","'":"'"},s=/[&<>"']/g,o=RegExp(s.source);return e&&o.test(e)?e.replace(s,n=>t[n]):e})}stringify(e,t,s){const o=[];for(const n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;const r=e[n],l=s?"":encodeURIComponent(n);let a;typeof r=="object"?a=this.stringify(r,t?t+encodeURIComponent("["+l+"]"):l,Array.isArray(r)):a=(t?t+encodeURIComponent("["+l+"]"):l)+"="+encodeURIComponent(r),o.push(a)}return o.join("&")}getRegionURL(e){const t="api.storyblok.com",s="api-us.storyblok.com",o="app.storyblokchina.cn";switch(e){case"us":return s;case"cn":return o;default:return t}}}const L=Object.freeze(Object.defineProperty({__proto__:null,SbHelpers:m},Symbol.toStringTag,{value:"Module"})),N=function(i,e){const t={};for(const s in i){const o=i[s];e.indexOf(s)>-1&&o!==null&&(t[s]=o)}return t},S=i=>i==="email",I={nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:i=>({tag:["pre",{tag:"code",attrs:i.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:i=>({tag:`h${i.attrs.level}`}),image:i=>({singleTag:[{tag:"img",attrs:N(i.attrs,["src","alt","title"])}]}),list_item:()=>({tag:"li"}),ordered_list:()=>({tag:"ol"}),paragraph:()=>({tag:"p"}),emoji:i=>({tag:[{tag:"span",attrs:{"data-type":"emoji","data-name":i.attrs.name,emoji:i.attrs.emoji}}]})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link:i=>{const e=new m().escapeHTML,t={...i.attrs},{linktype:s="url"}=i.attrs;if(t.href&&(t.href=e(i.attrs.href||"")),S(s)&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),t.custom){for(const o in t.custom)t[o]=t.custom[o];delete t.custom}return{tag:[{tag:"a",attrs:t}]}},styled:i=>({tag:[{tag:"span",attrs:i.attrs}]}),subscript:()=>({tag:"sub"}),superscript:()=>({tag:"sup"}),anchor:i=>({tag:[{tag:"span",attrs:i.attrs}]}),highlight:i=>{var t;return(t=i.attrs)!=null&&t.color?{tag:[{tag:"span",attrs:{style:`background-color:${i.attrs.color};`}}]}:{tag:""}},textStyle:i=>{var t;return(t=i.attrs)!=null&&t.color?{tag:[{tag:"span",attrs:{style:`color:${i.attrs.color}`}}]}:{tag:""}}}},U=function(i){const e={"&":"&","<":"<",">":">",'"':""","'":"'"},t=/[&<>"']/g,s=RegExp(t.source);return i&&s.test(i)?i.replace(t,o=>e[o]):i};class k{constructor(e){u(this,"marks");u(this,"nodes");e||(e=I),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(o=>{s+=this.renderNode(o)}),t.optimizeImages?this.optimizeImages(s,t.optimizeImages):s}return console.warn(`The render method must receive an Object with a "content" field. | ||
(function(p,h){typeof exports=="object"&&typeof module<"u"?module.exports=h():typeof define=="function"&&define.amd?define(h):(p=typeof globalThis<"u"?globalThis:p||self,p.StoryblokJSClient=h())})(this,function(){"use strict";var D=Object.defineProperty;var z=(p,h,m)=>h in p?D(p,h,{enumerable:!0,configurable:!0,writable:!0,value:m}):p[h]=m;var u=(p,h,m)=>(z(p,typeof h!="symbol"?h+"":h,m),m);function p(i){return!(i!==i||i===1/0||i===-1/0)}function h(i,e,t){if(!p(e))throw new TypeError("Expected `limit` to be a finite number");if(!p(t))throw new TypeError("Expected `interval` to be a finite number");const s=[];let o=[],n=0;const r=function(){n++;const a=setTimeout(function(){n--,s.length>0&&r(),o=o.filter(function(d){return d!==a})},t);o.indexOf(a)<0&&o.push(a);const c=s.shift();c.resolve(i.apply(c.self,c.args))},l=function(...a){const c=this;return new Promise(function(d,f){s.push({resolve:d,reject:f,args:a,self:c}),n<e&&r()})};return l.abort=function(){o.forEach(clearTimeout),o=[],s.forEach(function(a){a.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),s.length=0},l}class m{constructor(){u(this,"isCDNUrl",(e="")=>e.indexOf("/cdn/")>-1);u(this,"getOptionsPage",(e,t=25,s=1)=>({...e,per_page:t,page:s}));u(this,"delay",e=>new Promise(t=>setTimeout(t,e)));u(this,"arrayFrom",(e=0,t)=>[...Array(e)].map(t));u(this,"range",(e=0,t=e)=>{const s=Math.abs(t-e)||0,o=e<t?1:-1;return this.arrayFrom(s,(n,r)=>r*o+e)});u(this,"asyncMap",async(e,t)=>Promise.all(e.map(t)));u(this,"flatMap",(e=[],t)=>e.map(t).reduce((s,o)=>[...s,...o],[]));u(this,"escapeHTML",function(e){const t={"&":"&","<":"<",">":">",'"':""","'":"'"},s=/[&<>"']/g,o=RegExp(s.source);return e&&o.test(e)?e.replace(s,n=>t[n]):e})}stringify(e,t,s){const o=[];for(const n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;const r=e[n],l=s?"":encodeURIComponent(n);let a;typeof r=="object"?a=this.stringify(r,t?t+encodeURIComponent("["+l+"]"):l,Array.isArray(r)):a=(t?t+encodeURIComponent("["+l+"]"):l)+"="+encodeURIComponent(r),o.push(a)}return o.join("&")}getRegionURL(e){const t="api.storyblok.com",s="api-us.storyblok.com",o="app.storyblokchina.cn";switch(e){case"us":return s;case"cn":return o;default:return t}}}const L=Object.freeze(Object.defineProperty({__proto__:null,SbHelpers:m},Symbol.toStringTag,{value:"Module"})),N=function(i,e){const t={};for(const s in i){const o=i[s];e.indexOf(s)>-1&&o!==null&&(t[s]=o)}return t},S=i=>i==="email",I={nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:i=>({tag:["pre",{tag:"code",attrs:i.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:i=>({tag:`h${i.attrs.level}`}),image:i=>({singleTag:[{tag:"img",attrs:N(i.attrs,["src","alt","title"])}]}),list_item:()=>({tag:"li"}),ordered_list:()=>({tag:"ol"}),paragraph:()=>({tag:"p"}),emoji:i=>({tag:[{tag:"span",attrs:{"data-type":"emoji","data-name":i.attrs.name,emoji:i.attrs.emoji}}]})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link:i=>{const e=new m().escapeHTML,t={...i.attrs},{linktype:s="url"}=i.attrs;if(t.href&&(t.href=e(i.attrs.href||"")),S(s)&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),t.custom){for(const o in t.custom)t[o]=t.custom[o];delete t.custom}return{tag:[{tag:"a",attrs:t}]}},styled:i=>({tag:[{tag:"span",attrs:i.attrs}]}),subscript:()=>({tag:"sub"}),superscript:()=>({tag:"sup"}),anchor:i=>({tag:[{tag:"span",attrs:i.attrs}]}),highlight:i=>{var t;return(t=i.attrs)!=null&&t.color?{tag:[{tag:"span",attrs:{style:`background-color:${i.attrs.color};`}}]}:{tag:""}},textStyle:i=>{var t;return(t=i.attrs)!=null&&t.color?{tag:[{tag:"span",attrs:{style:`color:${i.attrs.color}`}}]}:{tag:""}}}},U=function(i){const e={"&":"&","<":"<",">":">",'"':""","'":"'"},t=/[&<>"']/g,s=RegExp(t.source);return i&&s.test(i)?i.replace(t,o=>e[o]):i};class k{constructor(e){u(this,"marks");u(this,"nodes");e||(e=I),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(o=>{s+=this.renderNode(o)}),t.optimizeImages?this.optimizeImages(s,t.optimizeImages):s}return console.warn(`The render method must receive an Object with a "content" field. | ||
The "content" field must be an array of nodes as the type ISbRichtext. | ||
@@ -24,2 +24,2 @@ ISbRichtext: | ||
type: 'doc' | ||
}`),""}optimizeImages(e,t){let s=0,o=0,n="",r="";typeof t!="boolean"&&(typeof t.width=="number"&&t.width>0&&(n+=`width="${t.width}" `,s=t.width),typeof t.height=="number"&&t.height>0&&(n+=`height="${t.height}" `,o=t.height),(t.loading==="lazy"||t.loading==="eager")&&(n+=`loading="${t.loading}" `),typeof t.class=="string"&&t.class.length>0&&(n+=`class="${t.class}" `),t.filters&&(typeof t.filters.blur=="number"&&t.filters.blur>=0&&t.filters.blur<=100&&(r+=`:blur(${t.filters.blur})`),typeof t.filters.brightness=="number"&&t.filters.brightness>=-100&&t.filters.brightness<=100&&(r+=`:brightness(${t.filters.brightness})`),t.filters.fill&&(t.filters.fill.match(/[0-9A-Fa-f]{6}/g)||t.filters.fill==="transparent")&&(r+=`:fill(${t.filters.fill})`),t.filters.format&&["webp","png","jpeg"].includes(t.filters.format)&&(r+=`:format(${t.filters.format})`),typeof t.filters.grayscale=="boolean"&&t.filters.grayscale&&(r+=":grayscale()"),typeof t.filters.quality=="number"&&t.filters.quality>=0&&t.filters.quality<=100&&(r+=`:quality(${t.filters.quality})`),t.filters.rotate&&[90,180,270].includes(t.filters.rotate)&&(r+=`:rotate(${t.filters.rotate})`),r.length>0&&(r="/filters"+r))),n.length>0&&(e=e.replace(/<img/g,`<img ${n.trim()}`));const l=s>0||o>0||r.length>0?`${s}x${o}${r}`:"";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 d,b;const c=a.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);if(c&&c.length>0){const _={srcset:(d=t.srcset)==null?void 0:d.map(f=>{if(typeof f=="number")return`//${c}/m/${f}x0${r} ${f}w`;if(typeof f=="object"&&f.length===2){let O=0,C=0;return typeof f[0]=="number"&&(O=f[0]),typeof f[1]=="number"&&(C=f[1]),`//${c}/m/${O}x${C}${r} ${O}w`}}).join(", "),sizes:(b=t.sizes)==null?void 0:b.map(f=>f).join(", ")};let R="";return _.srcset&&(R+=`srcset="${_.srcset}" `),_.sizes&&(R+=`sizes="${_.sizes}" `),a.replace(/<img/g,`<img ${R.trim()}`)}return a})),e}renderNode(e){const t=[];e.marks&&e.marks.forEach(o=>{const n=this.getMatchingMark(o);n&&n.tag!==""&&t.push(this.renderOpeningTag(n.tag))});const s=this.getMatchingNode(e);return s&&s.tag&&t.push(this.renderOpeningTag(s.tag)),e.content?e.content.forEach(o=>{t.push(this.renderNode(o))}):e.text?t.push(U(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(o=>{const n=this.getMatchingMark(o);n&&n.tag!==""&&t.push(this.renderClosingTag(n.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(o=>{if(o.constructor===String)return`<${o}${t}>`;{let n=`<${o.tag}`;if(o.attrs)for(const r in o.attrs){const l=o.attrs[r];l!==null&&(n+=` ${r}="${l}"`)}return`${n}${t}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(s=>s.constructor===String?`</${s}>`:`</${s.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 w{constructor(e){u(this,"baseURL");u(this,"timeout");u(this,"headers");u(this,"responseInterceptor");u(this,"fetch");u(this,"ejectInterceptor");u(this,"url");u(this,"parameters");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={}}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(o=>{s.data=o});for(const o of e.headers.entries())t[o[0]]=o[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 m;t=`${this.baseURL}${this.url}?${a.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const o=new URL(t),n=new AbortController,{signal:r}=n;let l;this.timeout&&(l=setTimeout(()=>n.abort(),this.timeout));try{const a=await this.fetch(`${o}`,{method:e,headers:this.headers,body:s,signal:r});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}}}eject(){this.ejectInterceptor=!0}_statusHandler(e){const t=/20[0-6]/g;return new Promise((s,o)=>{if(t.test(`${e.status}`))return s(e);const n={message:new Error(e.statusText),status:e.status,response:Array.isArray(e.data)?e.data[0]:e.data.error||e.data.slug};o(n)})}}const v="SB-Agent",E={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"5.13.0"};let y={};const g={};class T{constructor(e,t){u(this,"client");u(this,"maxRetries");u(this,"throttle");u(this,"accessToken");u(this,"cache");u(this,"helpers");u(this,"resolveCounter");u(this,"relations");u(this,"links");u(this,"richTextResolver");u(this,"resolveNestedRelations");let s=e.endpoint||t;if(!s){const r=new m().getRegionURL,l=e.https===!1?"http":"https";e.oauthToken?s=`${l}://${r(e.region)}/v1`:s=`${l}://${r(e.region)}/v2`}const o=new Headers;if(o.set("Content-Type","application/json"),o.set("Accept","application/json"),e.headers)for(const r in e.headers)o.set(r,e.headers[r]);o.has(v)||(o.set(v,E.defaultAgentName),o.set(E.defaultAgentVersion,E.packageVersion));let n=5;e.oauthToken&&(o.set("Authorization",e.oauthToken),n=3),e.rateLimit&&(n=e.rateLimit),e.richTextSchema?this.richTextResolver=new k(e.richTextSchema):this.richTextResolver=new k,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||5,this.throttle=h(this.throttledRequest,n,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new m,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.client=new w({baseURL:s,timeout:e.timeout||0,headers:o,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let s="";return t.attrs.body&&t.attrs.body.forEach(o=>{s+=e(o.component,o)}),{html:s}})}parseParams(e){return e.version||(e.version="published"),e.token||(e.token=this.getToken()),e.cv||(e.cv=g[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),e}factoryParamOptions(e,t){return this.helpers.isCDNUrl(e)?this.parseParams(t):t}makeRequest(e,t,s,o){const n=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,s,o));return this.cacheResponse(e,n)}get(e,t){t||(t={});const s=`/${e}`,o=this.factoryParamOptions(s,t);return this.cacheResponse(s,o)}async getAll(e,t,s){const o=(t==null?void 0:t.per_page)||25,n=`/${e}`,r=n.split("/"),l=s||r[r.length-1],a=1,c=await this.makeRequest(n,t,o,a),d=c.total?Math.ceil(c.total/o):1,b=await this.helpers.asyncMap(this.helpers.range(a,d),_=>this.makeRequest(n,t,o,_+1));return this.helpers.flatMap([c,...b],_=>Object.values(_.data[l]))}post(e,t){const s=`/${e}`;return Promise.resolve(this.throttle("post",s,t))}put(e,t){const s=`/${e}`;return Promise.resolve(this.throttle("put",s,t))}delete(e,t){const s=`/${e}`;return Promise.resolve(this.throttle("delete",s,t))}getStories(e){return this.get("cdn/stories",e)}getStory(e,t){return this.get(`cdn/stories/${e}`,t)}getToken(){return this.accessToken}ejectInterceptor(){this.client.eject()}_cleanCopy(e){return JSON.parse(JSON.stringify(e))}_insertLinks(e,t,s){const o=e[t];o&&o.fieldtype=="multilink"&&o.linktype=="story"&&typeof o.id=="string"&&this.links[s][o.id]?o.story=this._cleanCopy(this.links[s][o.id]):o&&o.linktype==="story"&&typeof o.uuid=="string"&&this.links[s][o.uuid]&&(o.story=this._cleanCopy(this.links[s][o.uuid]))}_insertRelations(e,t,s,o){if(s.indexOf(`${e.component}.${t}`)>-1){if(typeof e[t]=="string")this.relations[o][e[t]]&&(e[t]=this._cleanCopy(this.relations[o][e[t]]));else if(e[t]&&e[t].constructor===Array){const n=[];e[t].forEach(r=>{this.relations[o][r]&&n.push(this._cleanCopy(this.relations[o][r]))}),e[t]=n}}}iterateTree(e,t,s){const o=n=>{if(n!=null){if(n.constructor===Array)for(let r=0;r<n.length;r++)o(n[r]);else if(n.constructor===Object){if(n._stopResolving)return;for(const r in n)(n.component&&n._uid||n.type==="link")&&(this._insertRelations(n,r,t,s),this._insertLinks(n,r,s)),o(n[r])}}};o(e.content)}async resolveLinks(e,t,s){let o=[];if(e.link_uuids){const n=e.link_uuids.length,r=[],l=50;for(let a=0;a<n;a+=l){const c=Math.min(n,a+l);r.push(e.link_uuids.slice(a,c))}for(let a=0;a<r.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:r[a].join(",")})).data.stories.forEach(d=>{o.push(d)})}else o=e.links;o.forEach(n=>{this.links[s][n.uuid]={...n,_stopResolving:!0}})}async resolveRelations(e,t,s){let o=[];if(e.rel_uuids){const n=e.rel_uuids.length,r=[],l=50;for(let a=0;a<n;a+=l){const c=Math.min(n,a+l);r.push(e.rel_uuids.slice(a,c))}for(let a=0;a<r.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:r[a].join(",")})).data.stories.forEach(d=>{o.push(d)})}else o=e.rels;o&&o.length>0&&o.forEach(n=>{this.relations[s][n.uuid]={...n,_stopResolving:!0}})}async resolveStories(e,t,s){var n,r;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"].indexOf(t.resolve_links)>-1&&((n=e.links)!=null&&n.length||(r=e.link_uuids)!=null&&r.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)}),delete this.links[s],delete this.relations[s]}async cacheResponse(e,t,s){(typeof s>"u"||!s)&&(s=0);const o=this.helpers.stringify({url:e,params:t}),n=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&await this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const r=await n.get(o);if(r)return Promise.resolve(r)}return new Promise(async(r,l)=>{var a;try{const c=await this.throttle("get",e,t);let d={data:c.data,headers:c.headers};if((a=c.headers)!=null&&a["per-page"]&&(d=Object.assign({},d,{perPage:c.headers["per-page"]?parseInt(c.headers["per-page"]):0,total:c.headers["per-page"]?parseInt(c.headers.total):0})),d.data.story||d.data.stories){const b=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(d.data,t,`${b}`)}return t.version==="published"&&e!="/cdn/spaces/me"&&await n.set(o,d),d.data.cv&&t.token&&(t.version=="draft"&&g[t.token]!=d.data.cv&&await this.flushCache(),g[t.token]=d.data.cv),r(d)}catch(c){if(c.response&&c.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(e,t,s).then(r).catch(l);l(c.message)}})}throttledRequest(e,t,s){return this.client[e](t,s)}cacheVersions(){return g}cacheVersion(){return g[this.accessToken]}setCacheVersion(e){this.accessToken&&(g[this.accessToken]=e)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(y[e])},getAll(){return Promise.resolve(y)},set(e,t){return y[e]=t,Promise.resolve(void 0)},flush(){return y={},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 A=(i,e)=>{for(const t in e)i[t]=e[t]};return A(T,{RichtextResolver:k,SbFetch:w,RichTextSchema:I}),A(T,L),T}); | ||
}`),""}optimizeImages(e,t){let s=0,o=0,n="",r="";typeof t!="boolean"&&(typeof t.width=="number"&&t.width>0&&(n+=`width="${t.width}" `,s=t.width),typeof t.height=="number"&&t.height>0&&(n+=`height="${t.height}" `,o=t.height),(t.loading==="lazy"||t.loading==="eager")&&(n+=`loading="${t.loading}" `),typeof t.class=="string"&&t.class.length>0&&(n+=`class="${t.class}" `),t.filters&&(typeof t.filters.blur=="number"&&t.filters.blur>=0&&t.filters.blur<=100&&(r+=`:blur(${t.filters.blur})`),typeof t.filters.brightness=="number"&&t.filters.brightness>=-100&&t.filters.brightness<=100&&(r+=`:brightness(${t.filters.brightness})`),t.filters.fill&&(t.filters.fill.match(/[0-9A-Fa-f]{6}/g)||t.filters.fill==="transparent")&&(r+=`:fill(${t.filters.fill})`),t.filters.format&&["webp","png","jpeg"].includes(t.filters.format)&&(r+=`:format(${t.filters.format})`),typeof t.filters.grayscale=="boolean"&&t.filters.grayscale&&(r+=":grayscale()"),typeof t.filters.quality=="number"&&t.filters.quality>=0&&t.filters.quality<=100&&(r+=`:quality(${t.filters.quality})`),t.filters.rotate&&[90,180,270].includes(t.filters.rotate)&&(r+=`:rotate(${t.filters.rotate})`),r.length>0&&(r="/filters"+r))),n.length>0&&(e=e.replace(/<img/g,`<img ${n.trim()}`));const l=s>0||o>0||r.length>0?`${s}x${o}${r}`:"";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 d,f;const c=a.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);if(c&&c.length>0){const _={srcset:(d=t.srcset)==null?void 0:d.map(b=>{if(typeof b=="number")return`//${c}/m/${b}x0${r} ${b}w`;if(typeof b=="object"&&b.length===2){let O=0,C=0;return typeof b[0]=="number"&&(O=b[0]),typeof b[1]=="number"&&(C=b[1]),`//${c}/m/${O}x${C}${r} ${O}w`}}).join(", "),sizes:(f=t.sizes)==null?void 0:f.map(b=>b).join(", ")};let R="";return _.srcset&&(R+=`srcset="${_.srcset}" `),_.sizes&&(R+=`sizes="${_.sizes}" `),a.replace(/<img/g,`<img ${R.trim()}`)}return a})),e}renderNode(e){const t=[];e.marks&&e.marks.forEach(o=>{const n=this.getMatchingMark(o);n&&n.tag!==""&&t.push(this.renderOpeningTag(n.tag))});const s=this.getMatchingNode(e);return s&&s.tag&&t.push(this.renderOpeningTag(s.tag)),e.content?e.content.forEach(o=>{t.push(this.renderNode(o))}):e.text?t.push(U(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(o=>{const n=this.getMatchingMark(o);n&&n.tag!==""&&t.push(this.renderClosingTag(n.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(o=>{if(o.constructor===String)return`<${o}${t}>`;{let n=`<${o.tag}`;if(o.attrs)for(const r in o.attrs){const l=o.attrs[r];l!==null&&(n+=` ${r}="${l}"`)}return`${n}${t}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(s=>s.constructor===String?`</${s}>`:`</${s.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 w{constructor(e){u(this,"baseURL");u(this,"timeout");u(this,"headers");u(this,"responseInterceptor");u(this,"fetch");u(this,"ejectInterceptor");u(this,"url");u(this,"parameters");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={}}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(o=>{s.data=o});for(const o of e.headers.entries())t[o[0]]=o[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 m;t=`${this.baseURL}${this.url}?${a.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const o=new URL(t),n=new AbortController,{signal:r}=n;let l;this.timeout&&(l=setTimeout(()=>n.abort(),this.timeout));try{const a=await this.fetch(`${o}`,{method:e,headers:this.headers,body:s,signal:r});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}}}eject(){this.ejectInterceptor=!0}_statusHandler(e){const t=/20[0-6]/g;return new Promise((s,o)=>{if(t.test(`${e.status}`))return s(e);const n={message:new Error(e.statusText),status:e.status,response:Array.isArray(e.data)?e.data[0]:e.data.error||e.data.slug};o(n)})}}const v="SB-Agent",E={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"5.14.0"};let y={};const g={};class T{constructor(e,t){u(this,"client");u(this,"maxRetries");u(this,"throttle");u(this,"accessToken");u(this,"cache");u(this,"helpers");u(this,"resolveCounter");u(this,"relations");u(this,"links");u(this,"richTextResolver");u(this,"resolveNestedRelations");let s=e.endpoint||t;if(!s){const r=new m().getRegionURL,l=e.https===!1?"http":"https";e.oauthToken?s=`${l}://${r(e.region)}/v1`:s=`${l}://${r(e.region)}/v2`}const o=new Headers;if(o.set("Content-Type","application/json"),o.set("Accept","application/json"),e.headers)for(const r in e.headers)o.set(r,e.headers[r]);o.has(v)||(o.set(v,E.defaultAgentName),o.set(E.defaultAgentVersion,E.packageVersion));let n=5;e.oauthToken&&(o.set("Authorization",e.oauthToken),n=3),e.rateLimit&&(n=e.rateLimit),e.richTextSchema?this.richTextResolver=new k(e.richTextSchema):this.richTextResolver=new k,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||5,this.throttle=h(this.throttledRequest,n,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new m,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.client=new w({baseURL:s,timeout:e.timeout||0,headers:o,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let s="";return t.attrs.body&&t.attrs.body.forEach(o=>{s+=e(o.component,o)}),{html:s}})}parseParams(e){return e.version||(e.version="published"),e.token||(e.token=this.getToken()),e.cv||(e.cv=g[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),e}factoryParamOptions(e,t){return this.helpers.isCDNUrl(e)?this.parseParams(t):t}makeRequest(e,t,s,o){const n=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,s,o));return this.cacheResponse(e,n)}get(e,t){t||(t={});const s=`/${e}`,o=this.factoryParamOptions(s,t);return this.cacheResponse(s,o)}async getAll(e,t,s){const o=(t==null?void 0:t.per_page)||25,n=`/${e}`,r=n.split("/"),l=s||r[r.length-1],a=1,c=await this.makeRequest(n,t,o,a),d=c.total?Math.ceil(c.total/o):1,f=await this.helpers.asyncMap(this.helpers.range(a,d),_=>this.makeRequest(n,t,o,_+1));return this.helpers.flatMap([c,...f],_=>Object.values(_.data[l]))}post(e,t){const s=`/${e}`;return Promise.resolve(this.throttle("post",s,t))}put(e,t){const s=`/${e}`;return Promise.resolve(this.throttle("put",s,t))}delete(e,t){const s=`/${e}`;return Promise.resolve(this.throttle("delete",s,t))}getStories(e){return this.get("cdn/stories",e)}getStory(e,t){return this.get(`cdn/stories/${e}`,t)}getToken(){return this.accessToken}ejectInterceptor(){this.client.eject()}_cleanCopy(e){return JSON.parse(JSON.stringify(e))}_insertLinks(e,t,s){const o=e[t];o&&o.fieldtype=="multilink"&&o.linktype=="story"&&typeof o.id=="string"&&this.links[s][o.id]?o.story=this._cleanCopy(this.links[s][o.id]):o&&o.linktype==="story"&&typeof o.uuid=="string"&&this.links[s][o.uuid]&&(o.story=this._cleanCopy(this.links[s][o.uuid]))}_insertRelations(e,t,s,o){if(s.indexOf(`${e.component}.${t}`)>-1){if(typeof e[t]=="string")this.relations[o][e[t]]&&(e[t]=this._cleanCopy(this.relations[o][e[t]]));else if(e[t]&&e[t].constructor===Array){const n=[];e[t].forEach(r=>{this.relations[o][r]&&n.push(this._cleanCopy(this.relations[o][r]))}),e[t]=n}}}iterateTree(e,t,s){const o=n=>{if(n!=null){if(n.constructor===Array)for(let r=0;r<n.length;r++)o(n[r]);else if(n.constructor===Object){if(n._stopResolving)return;for(const r in n)(n.component&&n._uid||n.type==="link")&&(this._insertRelations(n,r,t,s),this._insertLinks(n,r,s)),o(n[r])}}};o(e.content)}async resolveLinks(e,t,s){let o=[];if(e.link_uuids){const n=e.link_uuids.length,r=[],l=50;for(let a=0;a<n;a+=l){const c=Math.min(n,a+l);r.push(e.link_uuids.slice(a,c))}for(let a=0;a<r.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:r[a].join(",")})).data.stories.forEach(d=>{o.push(d)})}else o=e.links;o.forEach(n=>{this.links[s][n.uuid]={...n,_stopResolving:!0}})}async resolveRelations(e,t,s){let o=[];if(e.rel_uuids){const n=e.rel_uuids.length,r=[],l=50;for(let a=0;a<n;a+=l){const c=Math.min(n,a+l);r.push(e.rel_uuids.slice(a,c))}for(let a=0;a<r.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:r[a].join(",")})).data.stories.forEach(d=>{o.push(d)})}else o=e.rels;o&&o.length>0&&o.forEach(n=>{this.relations[s][n.uuid]={...n,_stopResolving:!0}})}async resolveStories(e,t,s){var n,r;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&&((n=e.links)!=null&&n.length||(r=e.link_uuids)!=null&&r.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)}),delete this.links[s],delete this.relations[s]}async cacheResponse(e,t,s){(typeof s>"u"||!s)&&(s=0);const o=this.helpers.stringify({url:e,params:t}),n=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&await this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const r=await n.get(o);if(r)return Promise.resolve(r)}return new Promise(async(r,l)=>{var a;try{const c=await this.throttle("get",e,t);let d={data:c.data,headers:c.headers};if((a=c.headers)!=null&&a["per-page"]&&(d=Object.assign({},d,{perPage:c.headers["per-page"]?parseInt(c.headers["per-page"]):0,total:c.headers["per-page"]?parseInt(c.headers.total):0})),d.data.story||d.data.stories){const f=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(d.data,t,`${f}`)}return t.version==="published"&&e!="/cdn/spaces/me"&&await n.set(o,d),d.data.cv&&t.token&&(t.version=="draft"&&g[t.token]!=d.data.cv&&await this.flushCache(),g[t.token]=d.data.cv),r(d)}catch(c){if(c.response&&c.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(e,t,s).then(r).catch(l);l(c.message)}})}throttledRequest(e,t,s){return this.client[e](t,s)}cacheVersions(){return g}cacheVersion(){return g[this.accessToken]}setCacheVersion(e){this.accessToken&&(g[this.accessToken]=e)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(y[e])},getAll(){return Promise.resolve(y)},set(e,t){return y[e]=t,Promise.resolve(void 0)},flush(){return y={},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 A=(i,e)=>{for(const t in e)i[t]=e[t]};return A(T,{RichtextResolver:k,SbFetch:w,RichTextSchema:I}),A(T,L),T}); |
@@ -12,3 +12,3 @@ import { ResponseFn } from './sbFetch'; | ||
version?: 'draft' | 'published'; | ||
resolve_links?: 'url' | 'story' | '0' | '1' | 'link'; | ||
resolve_links?: 'link' | 'url' | 'story' | '0' | '1' | 'link'; | ||
resolve_relations?: string | string[]; | ||
@@ -44,3 +44,3 @@ resolve_assets?: number; | ||
version?: 'draft' | 'published'; | ||
resolve_links?: 'url' | 'story' | '0' | '1'; | ||
resolve_links?: 'link' | 'url' | 'story' | '0' | '1'; | ||
resolve_relations?: string | string[]; | ||
@@ -47,0 +47,0 @@ cv?: number; |
@@ -22,3 +22,3 @@ import { ISbStoriesParams, ISbResult, AsyncFn } from './interfaces'; | ||
version?: "draft" | "published" | undefined; | ||
resolve_links?: "url" | "story" | "0" | "1" | "link" | undefined; | ||
resolve_links?: "link" | "url" | "story" | "0" | "1" | undefined; | ||
resolve_relations?: string | string[] | undefined; | ||
@@ -25,0 +25,0 @@ resolve_assets?: number | undefined; |
{ | ||
"name": "storyblok-js-client", | ||
"version": "5.13.0", | ||
"version": "5.14.0", | ||
"description": "Universal JavaScript SDK for Storyblok's API", | ||
@@ -61,3 +61,3 @@ "license": "MIT", | ||
"eslint": "^8.27.0", | ||
"eslint-config-prettier": "^8.5.0", | ||
"eslint-config-prettier": "^9.0.0", | ||
"husky": "^8.0.2", | ||
@@ -68,3 +68,3 @@ "isomorphic-fetch": "^3.0.0", | ||
"vite": "^4.4.8", | ||
"vitest": "^0.32.0" | ||
"vitest": "^0.34.1" | ||
}, | ||
@@ -71,0 +71,0 @@ "release": { |
@@ -497,3 +497,3 @@ import throttledQueue from './throttlePromise' | ||
params.resolve_links && | ||
['1', 'story', 'url'].indexOf(params.resolve_links) > -1 && | ||
['1', 'story', 'url', 'link'].indexOf(params.resolve_links) > -1 && | ||
(responseData.links?.length || responseData.link_uuids?.length) | ||
@@ -500,0 +500,0 @@ ) { |
@@ -13,3 +13,3 @@ import { ResponseFn } from './sbFetch' | ||
version?: 'draft' | 'published' | ||
resolve_links?: 'url' | 'story' | '0' | '1' | 'link' | ||
resolve_links?: 'link' | 'url' | 'story' | '0' | '1' | 'link' | ||
resolve_relations?: string | string[] | ||
@@ -46,3 +46,3 @@ resolve_assets?: number | ||
version?: 'draft' | 'published' | ||
resolve_links?: 'url' | 'story' | '0' | '1' | ||
resolve_links?: 'link' | 'url' | 'story' | '0' | '1' | ||
resolve_relations?: string | string[] | ||
@@ -49,0 +49,0 @@ cv?: number |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
201835