Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

storyblok-js-client

Package Overview
Dependencies
Maintainers
7
Versions
197
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

storyblok-js-client - npm Package Compare versions

Comparing version 6.6.2 to 6.6.3

2

dist/index.umd.js

@@ -24,2 +24,2 @@ (function(g,f){typeof exports=="object"&&typeof module<"u"?module.exports=f():typeof define=="function"&&define.amd?define(f):(g=typeof globalThis<"u"?globalThis:g||self,g.StoryblokJSClient=f())})(this,function(){"use strict";var U=Object.defineProperty;var H=(g,f,d)=>f in g?U(g,f,{enumerable:!0,configurable:!0,writable:!0,value:d}):g[f]=d;var h=(g,f,d)=>(H(g,typeof f!="symbol"?f+"":f,d),d);function g(a){return!(a!==a||a===1/0||a===-1/0)}function f(a,e,t){if(!g(e))throw new TypeError("Expected `limit` to be a finite number");if(!g(t))throw new TypeError("Expected `interval` to be a finite number");const s=[];let r=[],i=0;const n=function(){i++;const o=setTimeout(function(){i--,s.length>0&&n(),r=r.filter(function(u){return u!==o})},t);r.indexOf(o)<0&&r.push(o);const c=s.shift();c.resolve(a.apply(c.self,c.args))},l=function(...o){const c=this;return new Promise(function(u,m){s.push({resolve:u,reject:m,args:o,self:c}),i<e&&n()})};return l.abort=function(){r.forEach(clearTimeout),r=[],s.forEach(function(o){o.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),s.length=0},l}class d{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,n)=>n*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={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},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 n=e[i],l=s?"":encodeURIComponent(i);let o;typeof n=="object"?o=this.stringify(n,t?t+encodeURIComponent("["+l+"]"):l,Array.isArray(n)):o=(t?t+encodeURIComponent("["+l+"]"):l)+"="+encodeURIComponent(n),r.push(o)}return r.join("&")}getRegionURL(e){const t="api.storyblok.com",s="api-us.storyblok.com",r="app.storyblokchina.cn",i="api-ap.storyblok.com",n="api-ca.storyblok.com";switch(e){case"us":return s;case"cn":return r;case"ap":return i;case"ca":return n;default:return t}}}const A=Object.freeze(Object.defineProperty({__proto__:null,SbHelpers:d},Symbol.toStringTag,{value:"Module"})),C=function(a,e){const t={};for(const s in a){const r=a[s];e.indexOf(s)>-1&&r!==null&&(t[s]=r)}return t},E=a=>a==="email",S={nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:a=>({tag:["pre",{tag:"code",attrs:a.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:a=>({tag:`h${a.attrs.level}`}),image:a=>({singleTag:[{tag:"img",attrs:C(a.attrs,["src","alt","title"])}]}),list_item:()=>({tag:"li"}),ordered_list:()=>({tag:"ol"}),paragraph:()=>({tag:"p"}),emoji:a=>({tag:[{tag:"span",attrs:{"data-type":"emoji","data-name":a.attrs.name,emoji:a.attrs.emoji}}]})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"s"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link:a=>{if(!a.attrs)return{tag:""};const e=new d().escapeHTML,t={...a.attrs},{linktype:s="url"}=a.attrs;if(delete t.linktype,t.href&&(t.href=e(a.attrs.href||"")),E(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}]}},styled:a=>({tag:[{tag:"span",attrs:a.attrs}]}),subscript:()=>({tag:"sub"}),superscript:()=>({tag:"sup"}),anchor:a=>({tag:[{tag:"span",attrs:a.attrs}]}),highlight:a=>{var t;return(t=a.attrs)!=null&&t.color?{tag:[{tag:"span",attrs:{style:`background-color:${a.attrs.color};`}}]}:{tag:""}},textStyle:a=>{var t;return(t=a.attrs)!=null&&t.color?{tag:[{tag:"span",attrs:{style:`color:${a.attrs.color}`}}]}:{tag:""}}}},L=function(a){const e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},t=/[&<>"']/g,s=RegExp(t.source);return a&&s.test(a)?a.replace(t,r=>e[r]):a};class R{constructor(e){h(this,"marks");h(this,"nodes");e||(e=S),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.

type: 'doc'
}`),""}optimizeImages(e,t){let s=0,r=0,i="",n="";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&&(n+=`:blur(${t.filters.blur})`),typeof t.filters.brightness=="number"&&t.filters.brightness>=-100&&t.filters.brightness<=100&&(n+=`:brightness(${t.filters.brightness})`),t.filters.fill&&(t.filters.fill.match(/[0-9A-Fa-f]{6}/g)||t.filters.fill==="transparent")&&(n+=`:fill(${t.filters.fill})`),t.filters.format&&["webp","png","jpeg"].includes(t.filters.format)&&(n+=`:format(${t.filters.format})`),typeof t.filters.grayscale=="boolean"&&t.filters.grayscale&&(n+=":grayscale()"),typeof t.filters.quality=="number"&&t.filters.quality>=0&&t.filters.quality<=100&&(n+=`:quality(${t.filters.quality})`),t.filters.rotate&&[90,180,270].includes(t.filters.rotate)&&(n+=`:rotate(${t.filters.rotate})`),n.length>0&&(n="/filters"+n))),i.length>0&&(e=e.replace(/<img/g,`<img ${i.trim()}`));const l=s>0||r>0||n.length>0?`${s}x${r}${n}`:"";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,o=>{var u,m;const c=o.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);if(c&&c.length>0){const b={srcset:(u=t.srcset)==null?void 0:u.map(p=>{if(typeof p=="number")return`//${c}/m/${p}x0${n} ${p}w`;if(typeof p=="object"&&p.length===2){let v=0,P=0;return typeof p[0]=="number"&&(v=p[0]),typeof p[1]=="number"&&(P=p[1]),`//${c}/m/${v}x${P}${n} ${v}w`}}).join(", "),sizes:(m=t.sizes)==null?void 0:m.map(p=>p).join(", ")};let y="";return b.srcset&&(y+=`srcset="${b.srcset}" `),b.sizes&&(y+=`sizes="${b.sizes}" `),o.replace(/<img/g,`<img ${y.trim()}`)}return o})),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(L(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(r=>{if(r.constructor===String)return`<${r}${t}>`;{let i=`<${r.tag}`;if(r.attrs)for(const n in r.attrs){const l=r.attrs[n];l!==null&&(i+=` ${n}="${l}"`)}return`${i}${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){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 o=new d;t=`${this.baseURL}${this.url}?${o.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const r=new URL(t),i=new AbortController,{signal:n}=i;let l;this.timeout&&(l=setTimeout(()=>i.abort(),this.timeout));try{const o=await fetch(`${r}`,{method:e,headers:this.headers,body:s,signal:n,...this.fetchOptions});this.timeout&&clearTimeout(l);const c=await this._responseHandler(o);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(c)):this._statusHandler(c)}catch(o){return{message:o}}}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)})}}var j={npm_package_version:"6.6.2"};const x="SB-Agent",T={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:j.npm_package_version};let _={};const k={};class ${constructor(e,t){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");h(this,"stringifiedStoriesCache");let s=e.endpoint||t;const r=new d().getRegionURL,i=e.https===!1?"http":"https";e.oauthToken?s=`${i}://${r(e.region)}/v1`:s=`${i}://${r(e.region)}/v2`;const n=new Headers;if(n.set("Content-Type","application/json"),n.set("Accept","application/json"),e.headers)for(const o in e.headers)n.set(o,e.headers[o]);n.has(x)||(n.set(x,T.defaultAgentName),n.set(T.defaultAgentVersion,T.packageVersion));let l=5;e.oauthToken&&(n.set("Authorization",e.oauthToken),l=3),e.rateLimit&&(l=e.rateLimit),e.richTextSchema?this.richTextResolver=new R(e.richTextSchema):this.richTextResolver=new R,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||5,this.throttle=f(this.throttledRequest,l,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new d,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.stringifiedStoriesCache={},this.client=new w({baseURL:s,timeout:e.timeout||0,headers:n,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=k[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,r){const i=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,s,r));return this.cacheResponse(e,i)}get(e,t,s){t||(t={});const r=`/${e}`,i=this.factoryParamOptions(r,t);return this.client.setFetchOptions(s),this.cacheResponse(r,i)}async getAll(e,t,s,r){const i=(t==null?void 0:t.per_page)||25,n=`/${e}`,l=n.split("/"),o=s||l[l.length-1],c=1,u=await this.makeRequest(n,t,i,c),m=u.total?Math.ceil(u.total/i):1;this.client.setFetchOptions(r);const b=await this.helpers.asyncMap(this.helpers.range(c,m),y=>this.makeRequest(n,t,i,y+1));return this.helpers.flatMap([u,...b],y=>Object.values(y.data[o]))}post(e,t,s){const r=`/${e}`;return this.client.setFetchOptions(s),Promise.resolve(this.throttle("post",r,t))}put(e,t,s){const r=`/${e}`;return this.client.setFetchOptions(s),Promise.resolve(this.throttle("put",r,t))}delete(e,t,s){const r=`/${e}`;return this.client.setFetchOptions(s),Promise.resolve(this.throttle("delete",r,t))}getStories(e,t){return this.client.setFetchOptions(t),this.get("cdn/stories",e)}getStory(e,t,s){return this.client.setFetchOptions(s),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 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 n=0;n<i.length;n++)r(i[n]);else if(i.constructor===Object){if(i._stopResolving)return;for(const n in i)(i.component&&i._uid||i.type==="link")&&(this._insertRelations(i,n,t,s),this._insertLinks(i,n,s)),r(i[n])}}};r(e.content)}async resolveLinks(e,t,s){let r=[];if(e.link_uuids){const i=e.link_uuids.length,n=[],l=50;for(let o=0;o<i;o+=l){const c=Math.min(i,o+l);n.push(e.link_uuids.slice(o,c))}for(let o=0;o<n.length;o++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:n[o].join(",")})).data.stories.forEach(u=>{r.push(u)})}else r=e.links;r.forEach(i=>{this.links[s][i.uuid]={...i,_stopResolving:!0}})}async resolveRelations(e,t,s){let r=[];if(e.rel_uuids){const i=e.rel_uuids.length,n=[],l=50;for(let o=0;o<i;o+=l){const c=Math.min(i,o+l);n.push(e.rel_uuids.slice(o,c))}for(let o=0;o<n.length;o++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:n[o].join(","),excluding_fields:t.excluding_fields})).data.stories.forEach(u=>{r.push(u)})}else r=e.rels;r&&r.length>0&&r.forEach(i=>{this.relations[s][i.uuid]={...i,_stopResolving:!0}})}async resolveStories(e,t,s){var i,n;let r=[];if(this.links[s]={},this.relations[s]={},typeof t.resolve_relations<"u"&&t.resolve_relations.length>0&&(typeof t.resolve_relations=="string"&&(r=t.resolve_relations.split(",")),await this.resolveRelations(e,t,s)),t.resolve_links&&["1","story","url","link"].indexOf(t.resolve_links)>-1&&((i=e.links)!=null&&i.length||(n=e.link_uuids)!=null&&n.length)&&await this.resolveLinks(e,t,s),this.resolveNestedRelations)for(const l in this.relations[s])this.iterateTree(this.relations[s][l],r,s);e.story?this.iterateTree(e.story,r,s):e.stories.forEach(l=>{this.iterateTree(l,r,s)}),this.stringifiedStoriesCache={},delete this.links[s],delete this.relations[s]}async cacheResponse(e,t,s){(typeof s>"u"||!s)&&(s=0);const r=this.helpers.stringify({url:e,params:t}),i=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&await this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const n=await i.get(r);if(n)return Promise.resolve(n)}return new Promise(async(n,l)=>{var o;try{const c=await this.throttle("get",e,t);if(c.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(n).catch(l);if(c.status!==200)return l(c);let u={data:c.data,headers:c.headers};if((o=c.headers)!=null&&o["per-page"]&&(u=Object.assign({},u,{perPage:c.headers["per-page"]?parseInt(c.headers["per-page"]):0,total:c.headers["per-page"]?parseInt(c.headers.total):0})),u.data.story||u.data.stories){const m=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(u.data,t,`${m}`)}return t.version==="published"&&e!="/cdn/spaces/me"&&await i.set(r,u),u.data.cv&&t.token&&(t.version==="draft"&&k[t.token]!=u.data.cv&&await this.flushCache(),k[t.token]=t.cv?t.cv:u.data.cv),n(u)}catch(c){l(c)}})}throttledRequest(e,t,s){return this.client[e](t,s)}cacheVersions(){return k}cacheVersion(){return k[this.accessToken]}setCacheVersion(e){this.accessToken&&(k[this.accessToken]=e)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(_[e])},getAll(){return Promise.resolve(_)},set(e,t){return _[e]=t,Promise.resolve(void 0)},flush(){return _={},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}}const O=(a,e)=>{for(const t in e)a[t]=e[t]};return O($,{RichtextResolver:R,SbFetch:w,RichTextSchema:S}),O($,A),$});
}`),""}optimizeImages(e,t){let s=0,r=0,i="",n="";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&&(n+=`:blur(${t.filters.blur})`),typeof t.filters.brightness=="number"&&t.filters.brightness>=-100&&t.filters.brightness<=100&&(n+=`:brightness(${t.filters.brightness})`),t.filters.fill&&(t.filters.fill.match(/[0-9A-Fa-f]{6}/g)||t.filters.fill==="transparent")&&(n+=`:fill(${t.filters.fill})`),t.filters.format&&["webp","png","jpeg"].includes(t.filters.format)&&(n+=`:format(${t.filters.format})`),typeof t.filters.grayscale=="boolean"&&t.filters.grayscale&&(n+=":grayscale()"),typeof t.filters.quality=="number"&&t.filters.quality>=0&&t.filters.quality<=100&&(n+=`:quality(${t.filters.quality})`),t.filters.rotate&&[90,180,270].includes(t.filters.rotate)&&(n+=`:rotate(${t.filters.rotate})`),n.length>0&&(n="/filters"+n))),i.length>0&&(e=e.replace(/<img/g,`<img ${i.trim()}`));const l=s>0||r>0||n.length>0?`${s}x${r}${n}`:"";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,o=>{var u,m;const c=o.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);if(c&&c.length>0){const b={srcset:(u=t.srcset)==null?void 0:u.map(p=>{if(typeof p=="number")return`//${c}/m/${p}x0${n} ${p}w`;if(typeof p=="object"&&p.length===2){let v=0,P=0;return typeof p[0]=="number"&&(v=p[0]),typeof p[1]=="number"&&(P=p[1]),`//${c}/m/${v}x${P}${n} ${v}w`}}).join(", "),sizes:(m=t.sizes)==null?void 0:m.map(p=>p).join(", ")};let y="";return b.srcset&&(y+=`srcset="${b.srcset}" `),b.sizes&&(y+=`sizes="${b.sizes}" `),o.replace(/<img/g,`<img ${y.trim()}`)}return o})),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(L(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(r=>{if(r.constructor===String)return`<${r}${t}>`;{let i=`<${r.tag}`;if(r.attrs)for(const n in r.attrs){const l=r.attrs[n];l!==null&&(i+=` ${n}="${l}"`)}return`${i}${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){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 o=new d;t=`${this.baseURL}${this.url}?${o.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const r=new URL(t),i=new AbortController,{signal:n}=i;let l;this.timeout&&(l=setTimeout(()=>i.abort(),this.timeout));try{const o=await fetch(`${r}`,{method:e,headers:this.headers,body:s,signal:n,...this.fetchOptions});this.timeout&&clearTimeout(l);const c=await this._responseHandler(o);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(c)):this._statusHandler(c)}catch(o){return{message:o}}}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)})}}var j={npm_package_version:"6.6.3"};const x="SB-Agent",T={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:j.npm_package_version};let _={};const k={};class ${constructor(e,t){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");h(this,"stringifiedStoriesCache");let s=e.endpoint||t;const r=new d().getRegionURL,i=e.https===!1?"http":"https";e.oauthToken?s=`${i}://${r(e.region)}/v1`:s=`${i}://${r(e.region)}/v2`;const n=new Headers;if(n.set("Content-Type","application/json"),n.set("Accept","application/json"),e.headers)for(const o in e.headers)n.set(o,e.headers[o]);n.has(x)||(n.set(x,T.defaultAgentName),n.set(T.defaultAgentVersion,T.packageVersion));let l=5;e.oauthToken&&(n.set("Authorization",e.oauthToken),l=3),e.rateLimit&&(l=e.rateLimit),e.richTextSchema?this.richTextResolver=new R(e.richTextSchema):this.richTextResolver=new R,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||5,this.throttle=f(this.throttledRequest,l,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new d,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.stringifiedStoriesCache={},this.client=new w({baseURL:s,timeout:e.timeout||0,headers:n,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=k[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,r){const i=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,s,r));return this.cacheResponse(e,i)}get(e,t,s){t||(t={});const r=`/${e}`,i=this.factoryParamOptions(r,t);return this.client.setFetchOptions(s),this.cacheResponse(r,i)}async getAll(e,t,s,r){const i=(t==null?void 0:t.per_page)||25,n=`/${e}`,l=n.split("/"),o=s||l[l.length-1],c=1,u=await this.makeRequest(n,t,i,c),m=u.total?Math.ceil(u.total/i):1;this.client.setFetchOptions(r);const b=await this.helpers.asyncMap(this.helpers.range(c,m),y=>this.makeRequest(n,t,i,y+1));return this.helpers.flatMap([u,...b],y=>Object.values(y.data[o]))}post(e,t,s){const r=`/${e}`;return this.client.setFetchOptions(s),Promise.resolve(this.throttle("post",r,t))}put(e,t,s){const r=`/${e}`;return this.client.setFetchOptions(s),Promise.resolve(this.throttle("put",r,t))}delete(e,t,s){const r=`/${e}`;return this.client.setFetchOptions(s),Promise.resolve(this.throttle("delete",r,t))}getStories(e,t){return this.client.setFetchOptions(t),this.get("cdn/stories",e)}getStory(e,t,s){return this.client.setFetchOptions(s),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 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 n=0;n<i.length;n++)r(i[n]);else if(i.constructor===Object){if(i._stopResolving)return;for(const n in i)(i.component&&i._uid||i.type==="link")&&(this._insertRelations(i,n,t,s),this._insertLinks(i,n,s)),r(i[n])}}};r(e.content)}async resolveLinks(e,t,s){let r=[];if(e.link_uuids){const i=e.link_uuids.length,n=[],l=50;for(let o=0;o<i;o+=l){const c=Math.min(i,o+l);n.push(e.link_uuids.slice(o,c))}for(let o=0;o<n.length;o++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:n[o].join(",")})).data.stories.forEach(u=>{r.push(u)})}else r=e.links;r.forEach(i=>{this.links[s][i.uuid]={...i,_stopResolving:!0}})}async resolveRelations(e,t,s){let r=[];if(e.rel_uuids){const i=e.rel_uuids.length,n=[],l=50;for(let o=0;o<i;o+=l){const c=Math.min(i,o+l);n.push(e.rel_uuids.slice(o,c))}for(let o=0;o<n.length;o++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:n[o].join(","),excluding_fields:t.excluding_fields})).data.stories.forEach(u=>{r.push(u)})}else r=e.rels;r&&r.length>0&&r.forEach(i=>{this.relations[s][i.uuid]={...i,_stopResolving:!0}})}async resolveStories(e,t,s){var i,n;let r=[];if(this.links[s]={},this.relations[s]={},typeof t.resolve_relations<"u"&&t.resolve_relations.length>0&&(typeof t.resolve_relations=="string"&&(r=t.resolve_relations.split(",")),await this.resolveRelations(e,t,s)),t.resolve_links&&["1","story","url","link"].indexOf(t.resolve_links)>-1&&((i=e.links)!=null&&i.length||(n=e.link_uuids)!=null&&n.length)&&await this.resolveLinks(e,t,s),this.resolveNestedRelations)for(const l in this.relations[s])this.iterateTree(this.relations[s][l],r,s);e.story?this.iterateTree(e.story,r,s):e.stories.forEach(l=>{this.iterateTree(l,r,s)}),this.stringifiedStoriesCache={},delete this.links[s],delete this.relations[s]}async cacheResponse(e,t,s){(typeof s>"u"||!s)&&(s=0);const r=this.helpers.stringify({url:e,params:t}),i=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&await this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const n=await i.get(r);if(n)return Promise.resolve(n)}return new Promise(async(n,l)=>{var o;try{const c=await this.throttle("get",e,t);if(c.status!==200)return l(c);let u={data:c.data,headers:c.headers};if((o=c.headers)!=null&&o["per-page"]&&(u=Object.assign({},u,{perPage:c.headers["per-page"]?parseInt(c.headers["per-page"]):0,total:c.headers["per-page"]?parseInt(c.headers.total):0})),u.data.story||u.data.stories){const m=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(u.data,t,`${m}`)}return t.version==="published"&&e!="/cdn/spaces/me"&&await i.set(r,u),u.data.cv&&t.token&&(t.version==="draft"&&k[t.token]!=u.data.cv&&await this.flushCache(),k[t.token]=t.cv?t.cv:u.data.cv),n(u)}catch(c){if(c.response&&c.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(n).catch(l);l(c)}})}throttledRequest(e,t,s){return this.client[e](t,s)}cacheVersions(){return k}cacheVersion(){return k[this.accessToken]}setCacheVersion(e){this.accessToken&&(k[this.accessToken]=e)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(_[e])},getAll(){return Promise.resolve(_)},set(e,t){return _[e]=t,Promise.resolve(void 0)},flush(){return _={},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}}const O=(a,e)=>{for(const t in e)a[t]=e[t]};return O($,{RichtextResolver:R,SbFetch:w,RichTextSchema:S}),O($,A),$});

@@ -0,1 +1,2 @@

import RichTextResolver from './richTextResolver';
import { ISbStoriesParams, ISbConfig, ISbResult, ISbStories, ISbStory, ISbStoryData, ISbStoryParams, ISbContentMangmntAPI, ISbCustomFetch } from './interfaces';

@@ -32,3 +33,3 @@ type ComponentResolverFn = {

links: LinksType;
richTextResolver: any;
richTextResolver: RichTextResolver;
resolveNestedRelations: boolean;

@@ -35,0 +36,0 @@ private stringifiedStoriesCache;

{
"name": "storyblok-js-client",
"version": "6.6.2",
"version": "6.6.3",
"description": "Universal JavaScript SDK for Storyblok's API",

@@ -5,0 +5,0 @@ "license": "MIT",

@@ -77,3 +77,3 @@ import throttledQueue from './throttlePromise'

public links: LinksType
public richTextResolver: any
public richTextResolver: RichTextResolver
public resolveNestedRelations: boolean

@@ -596,14 +596,2 @@ private stringifiedStoriesCache: Record<string, string>

const res = await this.throttle('get', url, params)
if (res.status === 429) {
retries = retries ? retries + 1 : 0
if (retries < this.maxRetries) {
console.log(`Hit rate limit. Retrying in ${retries} seconds.`)
await this.helpers.delay(1000 * retries)
return this.cacheResponse(url, params, retries)
.then(resolve)
.catch(reject)
}
}
if (res.status !== 200) {

@@ -645,2 +633,13 @@ return reject(res)

} catch (error: Error | any) {
if (error.response && error.status === 429) {
retries = retries ? retries + 1 : 0
if (retries < this.maxRetries) {
console.log(`Hit rate limit. Retrying in ${retries} seconds.`)
await this.helpers.delay(1000 * retries)
return this.cacheResponse(url, params, retries)
.then(resolve)
.catch(reject)
}
}
reject(error)

@@ -647,0 +646,0 @@ }

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc