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

storyblok-js-client

Package Overview
Dependencies
Maintainers
0
Versions
200
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.10.3 to 6.10.4

2

dist/index.umd.js

@@ -24,2 +24,2 @@ (function(g,d){typeof exports=="object"&&typeof module<"u"?module.exports=d():typeof define=="function"&&define.amd?define(d):(g=typeof globalThis<"u"?globalThis:g||self,g.StoryblokJSClient=d())})(this,function(){"use strict";var N=Object.defineProperty;var H=(g,d,y)=>d in g?N(g,d,{enumerable:!0,configurable:!0,writable:!0,value:y}):g[d]=y;var c=(g,d,y)=>H(g,typeof d!="symbol"?d+"":d,y);class g extends Error{constructor(e){super(e),this.name="AbortError"}}function d(a,e,t){if(!Number.isFinite(e))throw new TypeError("Expected `limit` to be a finite number");if(!Number.isFinite(t))throw new TypeError("Expected `interval` to be a finite number");const r=[];let s=[],i=0,n=!1;const l=async()=>{i++;const h=r.shift();if(h)try{const f=await a(...h.args);h.resolve(f)}catch(f){h.reject(f)}const u=setTimeout(()=>{i--,r.length>0&&l(),s=s.filter(f=>f!==u)},t);s.includes(u)||s.push(u)},o=(...h)=>n?Promise.reject(new Error("Throttled function is already aborted and not accepting new promises")):new Promise((u,f)=>{r.push({resolve:u,reject:f,args:h}),i<e&&l()});return o.abort=()=>{n=!0,s.forEach(clearTimeout),s=[],r.forEach(h=>h.reject(()=>new g("Throttle function aborted"))),r.length=0},o}class y{constructor(){c(this,"isCDNUrl",(e="")=>e.includes("/cdn/"));c(this,"getOptionsPage",(e,t=25,r=1)=>({...e,per_page:t,page:r}));c(this,"delay",e=>new Promise(t=>setTimeout(t,e)));c(this,"arrayFrom",(e=0,t)=>Array.from({length:e},t));c(this,"range",(e=0,t=e)=>{const r=Math.abs(t-e)||0,s=e<t?1:-1;return this.arrayFrom(r,(i,n)=>n*s+e)});c(this,"asyncMap",async(e,t)=>Promise.all(e.map(t)));c(this,"flatMap",(e=[],t)=>e.map(t).reduce((r,s)=>[...r,...s],[]));c(this,"escapeHTML",function(e){const t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},r=/[&<>"']/g,s=new RegExp(r.source);return e&&s.test(e)?e.replace(r,i=>t[i]):e})}stringify(e,t,r){const s=[];for(const i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;const n=e[i],l=r?"":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)}`,s.push(o)}return s.join("&")}getRegionURL(e){const t="api.storyblok.com",r="api-us.storyblok.com",s="app.storyblokchina.cn",i="api-ap.storyblok.com",n="api-ca.storyblok.com";switch(e){case"us":return r;case"cn":return s;case"ap":return i;case"ca":return n;default:return t}}}const E=Object.freeze(Object.defineProperty({__proto__:null,SbHelpers:y},Symbol.toStringTag,{value:"Module"})),L=function(a,e){const t={};for(const r in a){const s=a[r];e.includes(r)&&s!==null&&(t[r]=s)}return t},O=a=>a==="email",w={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:L(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 y().escapeHTML,t={...a.attrs},{linktype:r="url"}=a.attrs;if(delete t.linktype,t.href&&(t.href=e(a.attrs.href||"")),O(r)&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),t.custom){for(const s in t.custom)t[s]=t.custom[s];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:""}}}},j=function(a){const e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},t=/[&<>"']/g,r=new RegExp(t.source);return a&&r.test(a)?a.replace(t,s=>e[s]):a};let S=!1;class R{constructor(e){c(this,"marks");c(this,"nodes");e||(e=w),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},r=!0){if(!S&&r&&(console.warn("Warning ⚠️: The RichTextResolver class is deprecated and will be removed in the next major release. Please use the `@storyblok/richtext` package instead. https://github.com/storyblok/richtext/"),S=!0),e&&e.content&&Array.isArray(e.content)){let s="";return e.content.forEach(i=>{s+=this.renderNode(i)}),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 r=0,s=0,i="",n="";typeof t!="boolean"&&(typeof t.width=="number"&&t.width>0&&(i+=`width="${t.width}" `,r=t.width),typeof t.height=="number"&&t.height>0&&(i+=`height="${t.height}" `,s=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-F]{6}/gi)||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=r>0||s>0||n.length>0?`${r}x${s}${n}`:"";return e=e.replace(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|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,f;const h=o.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|bmp)/g);if(h&&h.length>0){const m={srcset:(u=t.srcset)==null?void 0:u.map(p=>{if(typeof p=="number")return`//${h}/m/${p}x0${n} ${p}w`;if(typeof p=="object"&&p.length===2){let $=0,C=0;return typeof p[0]=="number"&&($=p[0]),typeof p[1]=="number"&&(C=p[1]),`//${h}/m/${$}x${C}${n} ${$}w`}return""}).join(", "),sizes:(f=t.sizes)==null?void 0:f.map(p=>p).join(", ")};let v="";return m.srcset&&(v+=`srcset="${m.srcset}" `),m.sizes&&(v+=`sizes="${m.sizes}" `),o.replace(/<img/g,`<img ${v.trim()}`)}return o})),e}renderNode(e){const t=[];e.marks&&e.marks.forEach(s=>{const i=this.getMatchingMark(s);i&&i.tag!==""&&t.push(this.renderOpeningTag(i.tag))});const r=this.getMatchingNode(e);return r&&r.tag&&t.push(this.renderOpeningTag(r.tag)),e.content?e.content.forEach(s=>{t.push(this.renderNode(s))}):e.text?t.push(j(e.text)):r&&r.singleTag?t.push(this.renderTag(r.singleTag," /")):r&&r.html?t.push(r.html):e.type==="emoji"&&t.push(this.renderEmoji(e)),r&&r.tag&&t.push(this.renderClosingTag(r.tag)),e.marks&&e.marks.slice(0).reverse().forEach(s=>{const i=this.getMatchingMark(s);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 i=`<${s.tag}`;if(s.attrs){for(const n in s.attrs)if(Object.prototype.hasOwnProperty.call(s.attrs,n)){const l=s.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(r=>r.constructor===String?`</${r}>`:`</${r.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 x{constructor(e){c(this,"baseURL");c(this,"timeout");c(this,"headers");c(this,"responseInterceptor");c(this,"fetch");c(this,"ejectInterceptor");c(this,"url");c(this,"parameters");c(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=[],r={data:{},headers:{},status:0,statusText:""};e.status!==204&&await e.json().then(s=>{r.data=s});for(const s of e.headers.entries())t[s[0]]=s[1];return r.headers={...t},r.status=e.status,r.statusText=e.statusText,r}async _methodHandler(e){let t=`${this.baseURL}${this.url}`,r=null;if(e==="get"){const o=new y;t=`${this.baseURL}${this.url}?${o.stringify(this.parameters)}`}else r=JSON.stringify(this.parameters);const s=new URL(t),i=new AbortController,{signal:n}=i;let l;this.timeout&&(l=setTimeout(()=>i.abort(),this.timeout));try{const o=await this.fetch(`${s}`,{method:e,headers:this.headers,body:r,signal:n,...this.fetchOptions});this.timeout&&clearTimeout(l);const h=await this._responseHandler(o);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(h)):this._statusHandler(h)}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((r,s)=>{if(t.test(`${e.status}`))return r(e);const i={message:e.statusText,status:e.status,response:Array.isArray(e.data)?e.data[0]:e.data.error||e.data.slug};s(i)})}}const P="SB-Agent",_={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"6.0.0"};let k={};const b={};class T{constructor(e,t){c(this,"client");c(this,"maxRetries");c(this,"retriesDelay");c(this,"throttle");c(this,"accessToken");c(this,"cache");c(this,"helpers");c(this,"resolveCounter");c(this,"relations");c(this,"links");c(this,"richTextResolver");c(this,"resolveNestedRelations");c(this,"stringifiedStoriesCache");let r=e.endpoint||t;if(!r){const n=new y().getRegionURL,l=e.https===!1?"http":"https";e.oauthToken?r=`${l}://${n(e.region)}/v1`:r=`${l}://${n(e.region)}/v2`}const s=new Headers;s.set("Content-Type","application/json"),s.set("Accept","application/json"),e.headers&&(e.headers.constructor.name==="Headers"?e.headers.entries().toArray():Object.entries(e.headers)).forEach(([l,o])=>{s.set(l,o)}),s.has(P)||(s.set(P,_.defaultAgentName),s.set(_.defaultAgentVersion,_.packageVersion));let i=5;e.oauthToken&&(s.set("Authorization",e.oauthToken),i=3),e.rateLimit&&(i=e.rateLimit),e.richTextSchema?this.richTextResolver=new R(e.richTextSchema):this.richTextResolver=new R,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||10,this.retriesDelay=300,this.throttle=d(this.throttledRequest.bind(this),i,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new y,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.stringifiedStoriesCache={},this.client=new x({baseURL:r,timeout:e.timeout||0,headers:s,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let r="";return t.attrs.body&&t.attrs.body.forEach(s=>{r+=e(s.component,s)}),{html:r}})}parseParams(e){return e.token||(e.token=this.getToken()),e.cv||(e.cv=b[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,r,s,i){const n=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,r,s));return this.cacheResponse(e,n,void 0,i)}get(e,t,r){t||(t={});const s=`/${e}`,i=this.factoryParamOptions(s,t);return this.cacheResponse(s,i,void 0,r)}async getAll(e,t,r,s){const i=(t==null?void 0:t.per_page)||25,n=`/${e}`.replace(/\/$/,""),l=r??n.substring(n.lastIndexOf("/")+1),o=1,h=await this.makeRequest(n,t,i,o,s),u=h.total?Math.ceil(h.total/i):1,f=await this.helpers.asyncMap(this.helpers.range(o,u),m=>this.makeRequest(n,t,i,m+1,s));return this.helpers.flatMap([h,...f],m=>Object.values(m.data[l]))}post(e,t,r){const s=`/${e}`;return Promise.resolve(this.throttle("post",s,t,r))}put(e,t,r){const s=`/${e}`;return Promise.resolve(this.throttle("put",s,t,r))}delete(e,t,r){const s=`/${e}`;return Promise.resolve(this.throttle("delete",s,t,r))}getStories(e,t){return this._addResolveLevel(e),this.get("cdn/stories",e,t)}getStory(e,t,r){return this._addResolveLevel(t),this.get(`cdn/stories/${e}`,t,r)}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,r){const s=e[t];s&&s.fieldtype==="multilink"&&s.linktype==="story"&&typeof s.id=="string"&&this.links[r][s.id]?s.story=this._cleanCopy(this.links[r][s.id]):s&&s.linktype==="story"&&typeof s.uuid=="string"&&this.links[r][s.uuid]&&(s.story=this._cleanCopy(this.links[r][s.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,r,s){r.includes(`${e.component}.${t}`)&&(typeof e[t]=="string"?e[t]=this.getStoryReference(s,e[t]):Array.isArray(e[t])&&(e[t]=e[t].map(i=>this.getStoryReference(s,i)).filter(Boolean)))}iterateTree(e,t,r){const s=i=>{if(i!=null){if(i.constructor===Array)for(let n=0;n<i.length;n++)s(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,r),this._insertLinks(i,n,r)),s(i[n])}}};s(e.content)}async resolveLinks(e,t,r){let s=[];if(e.link_uuids){const i=e.link_uuids.length,n=[],l=50;for(let o=0;o<i;o+=l){const h=Math.min(i,o+l);n.push(e.link_uuids.slice(o,h))}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=>{s.push(u)})}else s=e.links;s.forEach(i=>{this.links[r][i.uuid]={...i,_stopResolving:!0}})}async resolveRelations(e,t,r){let s=[];if(e.rel_uuids){const i=e.rel_uuids.length,n=[],l=50;for(let o=0;o<i;o+=l){const h=Math.min(i,o+l);n.push(e.rel_uuids.slice(o,h))}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=>{s.push(u)})}else s=e.rels;s&&s.length>0&&s.forEach(i=>{this.relations[r][i.uuid]={...i,_stopResolving:!0}})}async resolveStories(e,t,r){var i,n;let s=[];if(this.links[r]={},this.relations[r]={},typeof t.resolve_relations<"u"&&t.resolve_relations.length>0&&(typeof t.resolve_relations=="string"&&(s=t.resolve_relations.split(",")),await this.resolveRelations(e,t,r)),t.resolve_links&&["1","story","url","link"].includes(t.resolve_links)&&((i=e.links)!=null&&i.length||(n=e.link_uuids)!=null&&n.length)&&await this.resolveLinks(e,t,r),this.resolveNestedRelations)for(const l in this.relations[r])this.iterateTree(this.relations[r][l],s,r);e.story?this.iterateTree(e.story,s,r):e.stories.forEach(l=>{this.iterateTree(l,s,r)}),this.stringifiedStoriesCache={},delete this.links[r],delete this.relations[r]}async cacheResponse(e,t,r,s){const i=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 l=await n.get(i);if(l)return Promise.resolve(l)}return new Promise(async(l,o)=>{var h;try{const u=await this.throttle("get",e,t,s);if(u.status!==200)return o(u);let f={data:u.data,headers:u.headers};if((h=u.headers)!=null&&h["per-page"]&&(f=Object.assign({},f,{perPage:u.headers["per-page"]?Number.parseInt(u.headers["per-page"]):0,total:u.headers["per-page"]?Number.parseInt(u.headers.total):0})),f.data.story||f.data.stories){const m=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(f.data,t,`${m}`)}return t.version==="published"&&e!=="/cdn/spaces/me"&&await n.set(i,f),f.data.cv&&t.token&&b[t.token]!==f.data.cv&&(await this.flushCache(),b[t.token]=f.data.cv),l(f)}catch(u){if(u.response&&u.status===429&&(r=typeof r>"u"?0:r+1,r<this.maxRetries))return console.log(`Hit rate limit. Retrying in ${this.retriesDelay/1e3} seconds.`),await this.helpers.delay(this.retriesDelay),this.cacheResponse(e,t,r).then(l).catch(o);o(u)}})}throttledRequest(e,t,r,s){return this.client.setFetchOptions(s),this.client[e](t,r)}cacheVersions(){return b}cacheVersion(){return b[this.accessToken]}setCacheVersion(e){this.accessToken&&(b[this.accessToken]=e)}clearCacheVersion(){this.accessToken&&(b[this.accessToken]=0)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(k[e])},getAll(){return Promise.resolve(k)},set(e,t){return k[e]=t,Promise.resolve(void 0)},flush(){return k={},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 A=(a,e)=>{for(const t in e)a[t]=e[t]};return A(T,{RichtextResolver:R,SbFetch:x,RichTextSchema:w}),A(T,E),T});
}`),""}optimizeImages(e,t){let r=0,s=0,i="",n="";typeof t!="boolean"&&(typeof t.width=="number"&&t.width>0&&(i+=`width="${t.width}" `,r=t.width),typeof t.height=="number"&&t.height>0&&(i+=`height="${t.height}" `,s=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-F]{6}/gi)||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=r>0||s>0||n.length>0?`${r}x${s}${n}`:"";return e=e.replace(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|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,f;const h=o.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|bmp)/g);if(h&&h.length>0){const m={srcset:(u=t.srcset)==null?void 0:u.map(p=>{if(typeof p=="number")return`//${h}/m/${p}x0${n} ${p}w`;if(typeof p=="object"&&p.length===2){let $=0,C=0;return typeof p[0]=="number"&&($=p[0]),typeof p[1]=="number"&&(C=p[1]),`//${h}/m/${$}x${C}${n} ${$}w`}return""}).join(", "),sizes:(f=t.sizes)==null?void 0:f.map(p=>p).join(", ")};let v="";return m.srcset&&(v+=`srcset="${m.srcset}" `),m.sizes&&(v+=`sizes="${m.sizes}" `),o.replace(/<img/g,`<img ${v.trim()}`)}return o})),e}renderNode(e){const t=[];e.marks&&e.marks.forEach(s=>{const i=this.getMatchingMark(s);i&&i.tag!==""&&t.push(this.renderOpeningTag(i.tag))});const r=this.getMatchingNode(e);return r&&r.tag&&t.push(this.renderOpeningTag(r.tag)),e.content?e.content.forEach(s=>{t.push(this.renderNode(s))}):e.text?t.push(j(e.text)):r&&r.singleTag?t.push(this.renderTag(r.singleTag," /")):r&&r.html?t.push(r.html):e.type==="emoji"&&t.push(this.renderEmoji(e)),r&&r.tag&&t.push(this.renderClosingTag(r.tag)),e.marks&&e.marks.slice(0).reverse().forEach(s=>{const i=this.getMatchingMark(s);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 i=`<${s.tag}`;if(s.attrs){for(const n in s.attrs)if(Object.prototype.hasOwnProperty.call(s.attrs,n)){const l=s.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(r=>r.constructor===String?`</${r}>`:`</${r.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 x{constructor(e){c(this,"baseURL");c(this,"timeout");c(this,"headers");c(this,"responseInterceptor");c(this,"fetch");c(this,"ejectInterceptor");c(this,"url");c(this,"parameters");c(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=[],r={data:{},headers:{},status:0,statusText:""};e.status!==204&&await e.json().then(s=>{r.data=s});for(const s of e.headers.entries())t[s[0]]=s[1];return r.headers={...t},r.status=e.status,r.statusText=e.statusText,r}async _methodHandler(e){let t=`${this.baseURL}${this.url}`,r=null;if(e==="get"){const o=new y;t=`${this.baseURL}${this.url}?${o.stringify(this.parameters)}`}else r=JSON.stringify(this.parameters);const s=new URL(t),i=new AbortController,{signal:n}=i;let l;this.timeout&&(l=setTimeout(()=>i.abort(),this.timeout));try{const o=await this.fetch(`${s}`,{method:e,headers:this.headers,body:r,signal:n,...this.fetchOptions});this.timeout&&clearTimeout(l);const h=await this._responseHandler(o);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(h)):this._statusHandler(h)}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((r,s)=>{if(t.test(`${e.status}`))return r(e);const i={message:e.statusText,status:e.status,response:Array.isArray(e.data)?e.data[0]:e.data.error||e.data.slug};s(i)})}}const P="SB-Agent",_={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"6.0.0"};let k={};const b={};class T{constructor(e,t){c(this,"client");c(this,"maxRetries");c(this,"retriesDelay");c(this,"throttle");c(this,"accessToken");c(this,"cache");c(this,"helpers");c(this,"resolveCounter");c(this,"relations");c(this,"links");c(this,"richTextResolver");c(this,"resolveNestedRelations");c(this,"stringifiedStoriesCache");let r=e.endpoint||t;if(!r){const n=new y().getRegionURL,l=e.https===!1?"http":"https";e.oauthToken?r=`${l}://${n(e.region)}/v1`:r=`${l}://${n(e.region)}/v2`}const s=new Headers;s.set("Content-Type","application/json"),s.set("Accept","application/json"),e.headers&&(e.headers.constructor.name==="Headers"?e.headers.entries().toArray():Object.entries(e.headers)).forEach(([l,o])=>{s.set(l,o)}),s.has(P)||(s.set(P,_.defaultAgentName),s.set(_.defaultAgentVersion,_.packageVersion));let i=5;e.oauthToken&&(s.set("Authorization",e.oauthToken),i=3),e.rateLimit&&(i=e.rateLimit),e.richTextSchema?this.richTextResolver=new R(e.richTextSchema):this.richTextResolver=new R,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||10,this.retriesDelay=300,this.throttle=d(this.throttledRequest.bind(this),i,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new y,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.stringifiedStoriesCache={},this.client=new x({baseURL:r,timeout:e.timeout||0,headers:s,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let r="";return t.attrs.body&&t.attrs.body.forEach(s=>{r+=e(s.component,s)}),{html:r}})}parseParams(e){return e.token||(e.token=this.getToken()),e.cv||(e.cv=b[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,r,s,i){const n=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,r,s));return this.cacheResponse(e,n,void 0,i)}get(e,t,r){t||(t={});const s=`/${e}`,i=this.factoryParamOptions(s,t);return this.cacheResponse(s,i,void 0,r)}async getAll(e,t,r,s){const i=(t==null?void 0:t.per_page)||25,n=`/${e}`.replace(/\/$/,""),l=r??n.substring(n.lastIndexOf("/")+1),o=1,h=await this.makeRequest(n,t,i,o,s),u=h.total?Math.ceil(h.total/i):1,f=await this.helpers.asyncMap(this.helpers.range(o,u),m=>this.makeRequest(n,t,i,m+1,s));return this.helpers.flatMap([h,...f],m=>Object.values(m.data[l]))}post(e,t,r){const s=`/${e}`;return Promise.resolve(this.throttle("post",s,t,r))}put(e,t,r){const s=`/${e}`;return Promise.resolve(this.throttle("put",s,t,r))}delete(e,t,r){t||(t={});const s=`/${e}`;return Promise.resolve(this.throttle("delete",s,t,r))}getStories(e,t){return this._addResolveLevel(e),this.get("cdn/stories",e,t)}getStory(e,t,r){return this._addResolveLevel(t),this.get(`cdn/stories/${e}`,t,r)}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,r){const s=e[t];s&&s.fieldtype==="multilink"&&s.linktype==="story"&&typeof s.id=="string"&&this.links[r][s.id]?s.story=this._cleanCopy(this.links[r][s.id]):s&&s.linktype==="story"&&typeof s.uuid=="string"&&this.links[r][s.uuid]&&(s.story=this._cleanCopy(this.links[r][s.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,r,s){r.includes(`${e.component}.${t}`)&&(typeof e[t]=="string"?e[t]=this.getStoryReference(s,e[t]):Array.isArray(e[t])&&(e[t]=e[t].map(i=>this.getStoryReference(s,i)).filter(Boolean)))}iterateTree(e,t,r){const s=i=>{if(i!=null){if(i.constructor===Array)for(let n=0;n<i.length;n++)s(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,r),this._insertLinks(i,n,r)),s(i[n])}}};s(e.content)}async resolveLinks(e,t,r){let s=[];if(e.link_uuids){const i=e.link_uuids.length,n=[],l=50;for(let o=0;o<i;o+=l){const h=Math.min(i,o+l);n.push(e.link_uuids.slice(o,h))}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=>{s.push(u)})}else s=e.links;s.forEach(i=>{this.links[r][i.uuid]={...i,_stopResolving:!0}})}async resolveRelations(e,t,r){let s=[];if(e.rel_uuids){const i=e.rel_uuids.length,n=[],l=50;for(let o=0;o<i;o+=l){const h=Math.min(i,o+l);n.push(e.rel_uuids.slice(o,h))}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=>{s.push(u)})}else s=e.rels;s&&s.length>0&&s.forEach(i=>{this.relations[r][i.uuid]={...i,_stopResolving:!0}})}async resolveStories(e,t,r){var i,n;let s=[];if(this.links[r]={},this.relations[r]={},typeof t.resolve_relations<"u"&&t.resolve_relations.length>0&&(typeof t.resolve_relations=="string"&&(s=t.resolve_relations.split(",")),await this.resolveRelations(e,t,r)),t.resolve_links&&["1","story","url","link"].includes(t.resolve_links)&&((i=e.links)!=null&&i.length||(n=e.link_uuids)!=null&&n.length)&&await this.resolveLinks(e,t,r),this.resolveNestedRelations)for(const l in this.relations[r])this.iterateTree(this.relations[r][l],s,r);e.story?this.iterateTree(e.story,s,r):e.stories.forEach(l=>{this.iterateTree(l,s,r)}),this.stringifiedStoriesCache={},delete this.links[r],delete this.relations[r]}async cacheResponse(e,t,r,s){const i=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 l=await n.get(i);if(l)return Promise.resolve(l)}return new Promise(async(l,o)=>{var h;try{const u=await this.throttle("get",e,t,s);if(u.status!==200)return o(u);let f={data:u.data,headers:u.headers};if((h=u.headers)!=null&&h["per-page"]&&(f=Object.assign({},f,{perPage:u.headers["per-page"]?Number.parseInt(u.headers["per-page"]):0,total:u.headers["per-page"]?Number.parseInt(u.headers.total):0})),f.data.story||f.data.stories){const m=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(f.data,t,`${m}`)}return t.version==="published"&&e!=="/cdn/spaces/me"&&await n.set(i,f),f.data.cv&&t.token&&b[t.token]!==f.data.cv&&(await this.flushCache(),b[t.token]=f.data.cv),l(f)}catch(u){if(u.response&&u.status===429&&(r=typeof r>"u"?0:r+1,r<this.maxRetries))return console.log(`Hit rate limit. Retrying in ${this.retriesDelay/1e3} seconds.`),await this.helpers.delay(this.retriesDelay),this.cacheResponse(e,t,r).then(l).catch(o);o(u)}})}throttledRequest(e,t,r,s){return this.client.setFetchOptions(s),this.client[e](t,r)}cacheVersions(){return b}cacheVersion(){return b[this.accessToken]}setCacheVersion(e){this.accessToken&&(b[this.accessToken]=e)}clearCacheVersion(){this.accessToken&&(b[this.accessToken]=0)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(k[e])},getAll(){return Promise.resolve(k)},set(e,t){return k[e]=t,Promise.resolve(void 0)},flush(){return k={},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 A=(a,e)=>{for(const t in e)a[t]=e[t]};return A(T,{RichtextResolver:R,SbFetch:x,RichTextSchema:w}),A(T,E),T});

@@ -32,3 +32,3 @@ import type { ISbCustomFetch, ISbError, ISbResponse, ISbStoriesParams } from './interfaces';

put(url: string, params: ISbStoriesParams): Promise<ISbResponse | ISbError>;
delete(url: string, params: ISbStoriesParams): Promise<ISbResponse | ISbError>;
delete(url: string, params?: ISbStoriesParams): Promise<ISbResponse | ISbError>;
private _responseHandler;

@@ -35,0 +35,0 @@ private _methodHandler;

@@ -73,3 +73,3 @@ import type { AsyncFn, ISbResult, ISbStoriesParams } from './interfaces';

path?: string | undefined;
pinned?: ("1" | boolean) | undefined;
pinned?: "1" | boolean | undefined;
position?: number | undefined;

@@ -76,0 +76,0 @@ published?: boolean | undefined;

{
"name": "storyblok-js-client",
"version": "6.10.3",
"packageManager": "pnpm@9.12.3",
"version": "6.10.4",
"packageManager": "pnpm@9.15.0",
"description": "Universal JavaScript SDK for Storyblok's API",

@@ -53,3 +53,5 @@ "author": "Alexander Feiglstorfer <delooks@gmail.com>",

"build": "node vite.build.mjs && tsc",
"demo": "vite serve playground",
"playground": "pnpm run --filter ./playground/vanilla dev",
"playground:svelte": "pnpm run --filter ./playground/svelte dev",
"playground:next": "pnpm run --filter ./playground/nextjs dev",
"dev:umd": "npx serve ./",

@@ -63,20 +65,20 @@ "test": "vitest run",

"devDependencies": {
"@commitlint/cli": "^19.5.0",
"@commitlint/config-conventional": "^19.5.0",
"@commitlint/cli": "^19.6.0",
"@commitlint/config-conventional": "^19.6.0",
"@storyblok/eslint-config": "^0.3.0",
"@tsconfig/recommended": "^1.0.8",
"@typescript-eslint/eslint-plugin": "^8.14.0",
"@typescript-eslint/parser": "^8.14.0",
"@vitest/coverage-v8": "^2.1.4",
"@vitest/ui": "^2.1.4",
"eslint": "^9.14.0",
"@typescript-eslint/eslint-plugin": "^8.17.0",
"@typescript-eslint/parser": "^8.17.0",
"@vitest/coverage-v8": "^2.1.8",
"@vitest/ui": "^2.1.8",
"eslint": "^9.16.0",
"eslint-config-prettier": "^9.1.0",
"isomorphic-fetch": "^3.0.0",
"kolorist": "^1.8.0",
"prettier": "^3.3.3",
"typescript": "^5.6.3",
"prettier": "^3.4.2",
"typescript": "^5.7.2",
"vite": "^5.4.11",
"vite-plugin-banner": "^0.8.0",
"vite-plugin-dts": "^4.3.0",
"vitest": "^2.1.4"
"vitest": "^2.1.8"
},

@@ -83,0 +85,0 @@ "release": {

@@ -79,3 +79,3 @@ <div align="center">

});
Storyblok.delete(`spaces/${spaceId}/stories/1`, null);
Storyblok.delete(`spaces/${spaceId}/stories/1`);
```

@@ -406,3 +406,3 @@

```javascript
Storyblok.delete('spaces/<YOUR_SPACE_ID>/stories/1', null)
Storyblok.delete('spaces/<YOUR_SPACE_ID>/stories/1')
.then((response) => {

@@ -409,0 +409,0 @@ console.log(response)

@@ -303,2 +303,5 @@ import throttledQueue from './throttlePromise';

): Promise<ISbResponseData> {
if (!params) {
params = {} as ISbStoriesParams;
}
const url = `/${slug}`;

@@ -305,0 +308,0 @@

@@ -112,3 +112,3 @@ import { afterEach, describe, expect, it, vi } from 'vitest';

mockFetch.mockResolvedValue(response);
await sbFetch.delete('stories/1', {});
await sbFetch.delete('stories/1');
expect(mockFetch).toHaveBeenCalledWith(

@@ -115,0 +115,0 @@ 'https://api.storyblok.com/v2/stories/1',

@@ -71,5 +71,5 @@ import { SbHelpers } from './sbHelpers';

public delete(url: string, params: ISbStoriesParams) {
public delete(url: string, params?: ISbStoriesParams) {
this.url = url;
this.parameters = params;
this.parameters = params ?? {} as ISbStoriesParams;
return this._methodHandler('delete');

@@ -76,0 +76,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