@storyblok/js 2.0.4 → 2.0.6
Sign up to get free protection for your applications and to get access to all the features.
- package/dist/storyblok-js.js +2 -2
- package/dist/storyblok-js.mjs +104 -100
- package/package.json +3 -3
package/dist/storyblok-js.js
CHANGED
@@ -1,3 +1,3 @@
|
|
1
|
-
(function(h,u){typeof exports=="object"&&typeof module!="undefined"?u(exports):typeof define=="function"&&define.amd?define(["exports"],u):(h=typeof globalThis!="undefined"?globalThis:h||self,u(h.storyblok={}))})(this,function(h){"use strict";var he=Object.defineProperty,ue=Object.defineProperties;var de=Object.getOwnPropertyDescriptors;var x=Object.getOwnPropertySymbols;var pe=Object.prototype.hasOwnProperty,ge=Object.prototype.propertyIsEnumerable;var I=(h,u,g)=>u in h?he(h,u,{enumerable:!0,configurable:!0,writable:!0,value:g}):h[u]=g,f=(h,u)=>{for(var g in u||(u={}))pe.call(u,g)&&I(h,g,u[g]);if(x)for(var g of x(u))ge.call(u,g)&&I(h,g,u[g]);return h},v=(h,u)=>ue(h,de(u));let u=!1;const g=[],_=o=>new Promise((e,t)=>{if(typeof window=="undefined"||(window.storyblokRegisterEvent=r=>{if(window.location===window.parent.location){console.warn("You are not in Draft Mode or in the Visual Editor.");return}u?r():g.push(r)},document.getElementById("storyblok-javascript-bridge")))return;const s=document.createElement("script");s.async=!0,s.src=o,s.id="storyblok-javascript-bridge",s.onerror=r=>t(r),s.onload=r=>{g.forEach(n=>n()),u=!0,e(r)},document.getElementsByTagName("head")[0].appendChild(s)});var C=Object.defineProperty,M=(o,e,t)=>e in o?C(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,c=(o,e,t)=>(M(o,typeof e!="symbol"?e+"":e,t),t);function E(o){return!(o!==o||o===1/0||o===-1/0)}function N(o,e,t){if(!E(e))throw new TypeError("Expected `limit` to be a finite number");if(!E(t))throw new TypeError("Expected `interval` to be a finite number");const s=[];let r=[],n=0;const a=function(){n++;const l=setTimeout(function(){n--,s.length>0&&a(),r=r.filter(function(p){return p!==l})},t);r.indexOf(l)<0&&r.push(l);const d=s.shift();d.resolve(o.apply(d.self,d.args))},i=function(...l){const d=this;return new Promise(function(p,w){s.push({resolve:p,reject:w,args:l,self:d}),n<e&&a()})};return i.abort=function(){r.forEach(clearTimeout),r=[],s.forEach(function(l){l.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),s.length=0},i}const A=function(o,e){const t={};for(const s in o){const r=o[s];e.indexOf(s)>-1&&r!==null&&(t[s]=r)}return t},L=o=>o==="email",U=()=>({singleTag:"hr"}),B=()=>({tag:"blockquote"}),H=()=>({tag:"ul"}),q=o=>({tag:["pre",{tag:"code",attrs:o.attrs}]}),D=()=>({singleTag:"br"}),J=o=>({tag:`h${o.attrs.level}`}),F=o=>({singleTag:[{tag:"img",attrs:A(o.attrs,["src","alt","title"])}]}),V=()=>({tag:"li"}),z=()=>({tag:"ol"}),G=()=>({tag:"p"}),Y=()=>({tag:"b"}),K=()=>({tag:"strike"}),Q=()=>({tag:"u"}),W=()=>({tag:"strong"}),X=()=>({tag:"code"}),Z=()=>({tag:"i"}),ee=o=>{const e=f({},o.attrs),{linktype:t="url"}=o.attrs;return L(t)&&(e.href=`mailto:${e.href}`),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),{tag:[{tag:"a",attrs:e}]}},te=o=>({tag:[{tag:"span",attrs:o.attrs}]}),$={nodes:{horizontal_rule:U,blockquote:B,bullet_list:H,code_block:q,hard_break:D,heading:J,image:F,list_item:V,ordered_list:z,paragraph:G},marks:{bold:Y,strike:K,underline:Q,strong:W,code:X,italic:Z,link:ee,styled:te}},se=function(o){const e={"&":"&","<":"<",">":">",'"':""","'":"'"},t=/[&<>"']/g,s=RegExp(t.source);return o&&s.test(o)?o.replace(t,r=>e[r]):o};class y{constructor(e){c(this,"marks"),c(this,"nodes"),e||(e=$),this.marks=e.marks||[],this.nodes=e.nodes||[]}addNode(e,t){this.nodes[e]=t}addMark(e,t){this.marks[e]=t}render(e){if(e&&e.content&&Array.isArray(e.content)){let t="";return e.content.forEach(s=>{t+=this.renderNode(s)}),t}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(e){const t=[];e.marks&&e.marks.forEach(r=>{const n=this.getMatchingMark(r);n&&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(r=>{t.push(this.renderNode(r))}):e.text?t.push(se(e.text)):s&&s.singleTag?t.push(this.renderTag(s.singleTag," /")):s&&s.html&&t.push(s.html),s&&s.tag&&t.push(this.renderClosingTag(s.tag)),e.marks&&e.marks.slice(0).reverse().forEach(r=>{const n=this.getMatchingMark(r);n&&t.push(this.renderClosingTag(n.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(s=>{if(s.constructor===String)return`<${s}${t}>`;{let r=`<${s.tag}`;if(s.attrs)for(const n in s.attrs){const a=s.attrs[n];a!==null&&(r+=` ${n}="${a}"`)}return`${r}${t}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(t=>t.constructor===String?`</${t}>`:`</${t.tag}>`).join("")}getMatchingNode(e){const t=this.nodes[e.type];if(typeof t=="function")return t(e)}getMatchingMark(e){const t=this.marks[e.type];if(typeof t=="function")return t(e)}}class j{constructor(){c(this,"isCDNUrl",(e="")=>e.indexOf("/cdn/")>-1),c(this,"getOptionsPage",(e,t=25,s=1)=>v(f({},e),{per_page:t,page:s})),c(this,"delay",e=>new Promise(t=>setTimeout(t,e))),c(this,"arrayFrom",(e=0,t)=>[...Array(e)].map(t)),c(this,"range",(e=0,t=e)=>{const s=Math.abs(t-e)||0,r=e<t?1:-1;return this.arrayFrom(s,(n,a)=>a*r+e)}),c(this,"asyncMap",async(e,t)=>Promise.all(e.map(t))),c(this,"flatMap",(e=[],t)=>e.map(t).reduce((s,r)=>[...s,...r],[]))}stringify(e,t,s){const r=[];for(const n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;const a=e[n],i=s?"":encodeURIComponent(n);let l;typeof a=="object"?l=this.stringify(a,t?t+encodeURIComponent("["+i+"]"):i,Array.isArray(a)):l=(t?t+encodeURIComponent("["+i+"]"):i)+"="+encodeURIComponent(a),r.push(l)}return r.join("&")}}var k=(o=>(o.GET="get",o.DELETE="delete",o.POST="post",o.PUT="put",o))(k||{});class re{constructor(e){c(this,"baseURL"),c(this,"timeout"),c(this,"headers"),c(this,"responseInterceptor"),c(this,"ejectInterceptor"),c(this,"url"),c(this,"parameters"),this.baseURL=e.baseURL,this.timeout=e.timeout?e.timeout*1e3:1e3,this.headers=e.headers||[],this.responseInterceptor=e.responseInterceptor,this.ejectInterceptor=!1,this.url="",this.parameters={}}get(e,t){return this.url=e,this.parameters=t,this._methodHandler(k.GET)}post(e,t){return this.url=e,this.parameters=t,this._methodHandler(k.POST)}put(e,t){return this.url=e,this.parameters=t,this._methodHandler(k.PUT)}delete(e,t){return this.url=e,this.parameters=t,this._methodHandler(k.DELETE)}async _responseHandler(e){const t=[],s={data:{},headers:{},status:0,statusText:""};await e.json().then(r=>{s.data=r});for(const r of e.headers.entries())t[r[0]]=r[1];return s.headers=f({},t),s.status=e.status,s.statusText=e.statusText,s}async _methodHandler(e){const t=new URL(`${this.baseURL}${this.url}`);let s=null;if(e==="get"){const i=new j;t.search=i.stringify(this.parameters)}else s=JSON.stringify(this.parameters);const r=new AbortController,{signal:n}=r,a=setTimeout(()=>r.abort(),this.timeout);try{const i=await fetch(`${t}`,{method:e,headers:this.headers,body:s,signal:n});clearTimeout(a);const l=await this._responseHandler(i);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(l)):this._statusHandler(l)}catch(i){return i}}eject(){this.ejectInterceptor=!0}_statusHandler(e){if(/20[01]/g.test(`${e.status}`))return e;throw{message:new Error(e.statusText||`status: ${e.status}`),response:e}}}let b={};const m={};class oe{constructor(e,t){if(c(this,"client"),c(this,"maxRetries"),c(this,"throttle"),c(this,"accessToken"),c(this,"cache"),c(this,"helpers"),c(this,"relations"),c(this,"links"),c(this,"richTextResolver"),c(this,"resolveNestedRelations"),!t){const n=e.region?`-${e.region}`:"",a=e.https?"https":"http";e.oauthToken?t=`${a}://api${n}.storyblok.com/v1`:t=`${a}://api${n}.storyblok.com/v2`}const s=Object.assign({},e.headers);let r=5;e.oauthToken&&(s.Authorization=e.oauthToken,r=3),e.rateLimit&&(r=e.rateLimit),e.richTextSchema?this.richTextResolver=new y(e.richTextSchema):this.richTextResolver=new y,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries,this.throttle=N(this.throttledRequest,r,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new j,this.resolveNestedRelations=!1,this.client=new re({baseURL:t,timeout:e.timeout||0,headers:s,responseInterceptor:e.responseInterceptor})}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let s="";return t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})}parseParams(e){return e.version||(e.version="published"),e.token||(e.token=this.getToken()),e.cv||(e.cv=m[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 n=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,s,r));return this.cacheResponse(e,n)}get(e,t){t||(t={});const s=`/${e}`,r=this.factoryParamOptions(s,t);return this.cacheResponse(s,r)}async getAll(e,t,s){const r=(t==null?void 0:t.per_page)||25,n=`/${e}`,a=n.split("/"),i=s||a[a.length-1],l=1,d=await this.makeRequest(n,t,r,l),p=d.total?Math.ceil(d.total/r):1,w=await this.helpers.asyncMap(this.helpers.range(l,p),R=>this.makeRequest(n,t,r,R+1));return this.helpers.flatMap([d,...w],R=>Object.values(R.data[i]))}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){const s=e[t];s&&s.fieldtype=="multilink"&&s.linktype=="story"&&typeof s.id=="string"&&this.links[s.id]?s.story=this._cleanCopy(this.links[s.id]):s&&s.linktype==="story"&&typeof s.uuid=="string"&&this.links[s.uuid]&&(s.story=this._cleanCopy(this.links[s.uuid]))}_insertRelations(e,t,s){if(s.indexOf(`${e.component}.${t}`)>-1){if(typeof e[t]=="string")this.relations[e[t]]&&(e[t]=this._cleanCopy(this.relations[e[t]]));else if(e[t]&&e[t].constructor===Array){const r=[];e[t].forEach(n=>{this.relations[n]&&r.push(this._cleanCopy(this.relations[n]))}),e[t]=r}}}iterateTree(e,t){const s=r=>{if(r!=null){if(r.constructor===Array)for(let n=0;n<r.length;n++)s(r[n]);else if(r.constructor===Object){if(r._stopResolving)return;for(const n in r)(r.component&&r._uid||r.type==="link")&&(this._insertRelations(r,n,t),this._insertLinks(r,n)),s(r[n])}}};s(e.content)}async resolveLinks(e,t){let s=[];if(e.link_uuids){const r=e.link_uuids.length,n=[],a=50;for(let i=0;i<r;i+=a){const l=Math.min(r,i+a);n.push(e.link_uuids.slice(i,l))}for(let i=0;i<n.length;i++)(await this.getStories({per_page:a,language:t.language,version:t.version,by_uuids:n[i].join(",")})).data.stories.forEach(l=>{s.push(l)})}else s=e.links;s.forEach(r=>{this.links[r.uuid]=v(f({},r),{_stopResolving:!0})})}async resolveRelations(e,t){let s=[];if(e.rel_uuids){const r=e.rel_uuids.length,n=[],a=50;for(let i=0;i<r;i+=a){const l=Math.min(r,i+a);n.push(e.rel_uuids.slice(i,l))}for(let i=0;i<n.length;i++)(await this.getStories({per_page:a,language:t.language,version:t.version,by_uuids:n[i].join(",")})).data.stories.forEach(l=>{s.push(l)})}else s=e.rels;s&&s.length>0&&s.forEach(r=>{this.relations[r.uuid]=v(f({},r),{_stopResolving:!0})})}async resolveStories(e,t){var s,r;let n=[];if(typeof t.resolve_relations<"u"&&t.resolve_relations.length>0&&(n=t.resolve_relations.split(","),await this.resolveRelations(e,t)),t.resolve_links&&["1","story","url"].indexOf(t.resolve_links)>-1&&(((s=e.links)==null?void 0:s.length)||((r=e.link_uuids)==null?void 0:r.length))&&await this.resolveLinks(e,t),this.resolveNestedRelations)for(const a in this.relations)this.iterateTree(this.relations[a],n);e.story?this.iterateTree(e.story,n):e.stories.forEach(a=>{this.iterateTree(a,n)})}cacheResponse(e,t,s){return new Promise((r,n)=>{const a=this.helpers.stringify({url:e,params:t}),i=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const l=i.get(a);if(l)return r(l)}try{(async()=>{var l;const d=await this.throttle("get",e,t);let p={data:d.data,headers:d.headers};if((l=d.headers)!=null&&l["per-page"]&&(p=Object.assign({},p,{perPage:d.headers["per-page"]?parseInt(d.headers["per-page"]):0,total:d.headers["per-page"]?parseInt(d.headers.total):0})),d.status!=200)return n(d);(p.data.story||p.data.stories)&&await this.resolveStories(p.data,t),t.version==="published"&&e!="/cdn/spaces/me"&&i.set(a,p),p.data.cv&&t.token&&(t.version=="draft"&&m[t.token]!=p.data.cv&&this.flushCache(),m[t.token]=p.data.cv),r(p)})()}catch{}})}throttledRequest(e,t,s){return this.client[e](t,s)}cacheVersions(){return m}cacheVersion(){return m[this.accessToken]}setCacheVersion(e){this.accessToken&&(m[this.accessToken]=e)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return b[e]},getAll(){return b},set(e,t){b[e]=t},flush(){b={}}};default:return{get(){},getAll(){},set(){},flush(){}}}}flushCache(){return this.cacheProvider().flush(),this}}const ne=(o={})=>{const{apiOptions:e}=o;if(!e.accessToken){console.error("You need to provide an access token to interact with Storyblok API. Read https://www.storyblok.com/docs/api/content-delivery#topics/authentication");return}return{storyblokApi:new oe(e)}};var ie=o=>{if(typeof o!="object"||typeof o._editable=="undefined")return{};const e=JSON.parse(o._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(e),"data-blok-uid":e.id+"-"+e.uid}};let T;const S="https://app.storyblok.com/f/storyblok-v2-latest.js",P=(o,e,t={})=>{if(typeof window!="undefined"){if(typeof window.storyblokRegisterEvent=="undefined"){console.error("Storyblok Bridge is disabled. Please enable it to use it. Read https://github.com/storyblok/storyblok-js");return}if(!o){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(t).on(["input","published","change"],r=>{r.action==="input"&&r.story.id===o?e(r.story):(r.action==="change"||r.action==="published")&&r.storyId===o&&window.location.reload()})})}},ae=(o={})=>{const{bridge:e,accessToken:t,use:s=[],apiOptions:r={},richText:n={}}=o;r.accessToken=r.accessToken||t;const a={bridge:e,apiOptions:r};let i={};return s.forEach(l=>{i=f(f({},i),l(a))}),e!==!1&&_(S),T=new y(n.schema),n.resolver&&O(T,n.resolver),i},O=(o,e)=>{o.addNode("blok",t=>{let s="";return t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})},le=(o,e,t)=>{let s=t||T;if(!s){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return o===""?"":o?(e&&(s=new y(e.schema),e.resolver&&O(s,e.resolver)),s.render(o)):(console.warn(`${o} is not a valid Richtext object. This might be because the value of the richtext field is empty.
|
1
|
+
(function(h,u){typeof exports=="object"&&typeof module!="undefined"?u(exports):typeof define=="function"&&define.amd?define(["exports"],u):(h=typeof globalThis!="undefined"?globalThis:h||self,u(h.storyblok={}))})(this,function(h){"use strict";var ce=Object.defineProperty,he=Object.defineProperties;var ue=Object.getOwnPropertyDescriptors;var O=Object.getOwnPropertySymbols;var de=Object.prototype.hasOwnProperty,pe=Object.prototype.propertyIsEnumerable;var P=(h,u,g)=>u in h?ce(h,u,{enumerable:!0,configurable:!0,writable:!0,value:g}):h[u]=g,f=(h,u)=>{for(var g in u||(u={}))de.call(u,g)&&P(h,g,u[g]);if(O)for(var g of O(u))pe.call(u,g)&&P(h,g,u[g]);return h},b=(h,u)=>he(h,ue(u));let u=!1;const g=[],R=n=>new Promise((e,t)=>{if(typeof window=="undefined"||(window.storyblokRegisterEvent=r=>{if(window.location===window.parent.location){console.warn("You are not in Draft Mode or in the Visual Editor.");return}u?r():g.push(r)},document.getElementById("storyblok-javascript-bridge")))return;const s=document.createElement("script");s.async=!0,s.src=n,s.id="storyblok-javascript-bridge",s.onerror=r=>t(r),s.onload=r=>{g.forEach(o=>o()),u=!0,e(r)},document.getElementsByTagName("head")[0].appendChild(s)});var I=Object.defineProperty,C=(n,e,t)=>e in n?I(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,c=(n,e,t)=>(C(n,typeof e!="symbol"?e+"":e,t),t);function _(n){return!(n!==n||n===1/0||n===-1/0)}function M(n,e,t){if(!_(e))throw new TypeError("Expected `limit` to be a finite number");if(!_(t))throw new TypeError("Expected `interval` to be a finite number");const s=[];let r=[],o=0;const i=function(){o++;const l=setTimeout(function(){o--,s.length>0&&i(),r=r.filter(function(p){return p!==l})},t);r.indexOf(l)<0&&r.push(l);const d=s.shift();d.resolve(n.apply(d.self,d.args))},a=function(...l){const d=this;return new Promise(function(p,T){s.push({resolve:p,reject:T,args:l,self:d}),o<e&&i()})};return a.abort=function(){r.forEach(clearTimeout),r=[],s.forEach(function(l){l.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),s.length=0},a}const A=function(n,e){const t={};for(const s in n){const r=n[s];e.indexOf(s)>-1&&r!==null&&(t[s]=r)}return t},N=n=>n==="email",L=()=>({singleTag:"hr"}),U=()=>({tag:"blockquote"}),B=()=>({tag:"ul"}),H=n=>({tag:["pre",{tag:"code",attrs:n.attrs}]}),q=()=>({singleTag:"br"}),D=n=>({tag:`h${n.attrs.level}`}),J=n=>({singleTag:[{tag:"img",attrs:A(n.attrs,["src","alt","title"])}]}),F=()=>({tag:"li"}),V=()=>({tag:"ol"}),z=()=>({tag:"p"}),Y=()=>({tag:"b"}),K=()=>({tag:"strike"}),Q=()=>({tag:"u"}),G=()=>({tag:"strong"}),W=()=>({tag:"code"}),X=()=>({tag:"i"}),Z=n=>{const e=f({},n.attrs),{linktype:t="url"}=n.attrs;return N(t)&&(e.href=`mailto:${e.href}`),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),{tag:[{tag:"a",attrs:e}]}},ee=n=>({tag:[{tag:"span",attrs:n.attrs}]}),j={nodes:{horizontal_rule:L,blockquote:U,bullet_list:B,code_block:H,hard_break:q,heading:D,image:J,list_item:F,ordered_list:V,paragraph:z},marks:{bold:Y,strike:K,underline:Q,strong:G,code:W,italic:X,link:Z,styled:ee}},te=function(n){const e={"&":"&","<":"<",">":">",'"':""","'":"'"},t=/[&<>"']/g,s=RegExp(t.source);return n&&s.test(n)?n.replace(t,r=>e[r]):n};class m{constructor(e){c(this,"marks"),c(this,"nodes"),e||(e=j),this.marks=e.marks||[],this.nodes=e.nodes||[]}addNode(e,t){this.nodes[e]=t}addMark(e,t){this.marks[e]=t}render(e){if(e&&e.content&&Array.isArray(e.content)){let t="";return e.content.forEach(s=>{t+=this.renderNode(s)}),t}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(e){const t=[];e.marks&&e.marks.forEach(r=>{const o=this.getMatchingMark(r);o&&t.push(this.renderOpeningTag(o.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(te(e.text)):s&&s.singleTag?t.push(this.renderTag(s.singleTag," /")):s&&s.html&&t.push(s.html),s&&s.tag&&t.push(this.renderClosingTag(s.tag)),e.marks&&e.marks.slice(0).reverse().forEach(r=>{const o=this.getMatchingMark(r);o&&t.push(this.renderClosingTag(o.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(s=>{if(s.constructor===String)return`<${s}${t}>`;{let r=`<${s.tag}`;if(s.attrs)for(const o in s.attrs){const i=s.attrs[o];i!==null&&(r+=` ${o}="${i}"`)}return`${r}${t}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(t=>t.constructor===String?`</${t}>`:`</${t.tag}>`).join("")}getMatchingNode(e){const t=this.nodes[e.type];if(typeof t=="function")return t(e)}getMatchingMark(e){const t=this.marks[e.type];if(typeof t=="function")return t(e)}}class ${constructor(){c(this,"isCDNUrl",(e="")=>e.indexOf("/cdn/")>-1),c(this,"getOptionsPage",(e,t=25,s=1)=>b(f({},e),{per_page:t,page:s})),c(this,"delay",e=>new Promise(t=>setTimeout(t,e))),c(this,"arrayFrom",(e=0,t)=>[...Array(e)].map(t)),c(this,"range",(e=0,t=e)=>{const s=Math.abs(t-e)||0,r=e<t?1:-1;return this.arrayFrom(s,(o,i)=>i*r+e)}),c(this,"asyncMap",async(e,t)=>Promise.all(e.map(t))),c(this,"flatMap",(e=[],t)=>e.map(t).reduce((s,r)=>[...s,...r],[]))}stringify(e,t,s){const r=[];for(const o in e){if(!Object.prototype.hasOwnProperty.call(e,o))continue;const i=e[o],a=s?"":encodeURIComponent(o);let l;typeof i=="object"?l=this.stringify(i,t?t+encodeURIComponent("["+a+"]"):a,Array.isArray(i)):l=(t?t+encodeURIComponent("["+a+"]"):a)+"="+encodeURIComponent(i),r.push(l)}return r.join("&")}}class se{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"),this.baseURL=e.baseURL,this.headers=e.headers||[],this.timeout=e.timeout?e.timeout*1e3:1e3,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:""};await e.json().then(r=>{s.data=r});for(const r of e.headers.entries())t[r[0]]=r[1];return s.headers=f({},t),s.status=e.status,s.statusText=e.statusText,s}async _methodHandler(e){const t=new URL(`${this.baseURL}${this.url}`);let s=null;if(e==="get"){const a=new $;t.search=a.stringify(this.parameters)}else s=JSON.stringify(this.parameters);const r=new AbortController,{signal:o}=r,i=setTimeout(()=>r.abort(),this.timeout);try{const a=await this.fetch(`${t}`,{method:e,headers:this.headers,body:s,signal:o});clearTimeout(i);const l=await this._responseHandler(a);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(l)):this._statusHandler(l)}catch(a){return a}}eject(){this.ejectInterceptor=!0}_statusHandler(e){if(/20[01]/g.test(`${e.status}`))return e;throw{message:new Error(e.statusText||`status: ${e.status}`),response:e}}}let k={};const y={};class re{constructor(e,t){if(c(this,"client"),c(this,"maxRetries"),c(this,"throttle"),c(this,"accessToken"),c(this,"cache"),c(this,"helpers"),c(this,"relations"),c(this,"links"),c(this,"richTextResolver"),c(this,"resolveNestedRelations"),!t){const o=e.region?`-${e.region}`:"",i=e.https===!1?"http":"https";e.oauthToken?t=`${i}://api${o}.storyblok.com/v1`:t=`${i}://api${o}.storyblok.com/v2`}const s=new Headers;s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.forEach((o,i)=>{e.headers&&e.headers[i]&&s.set(i,e.headers[i])});let r=5;e.oauthToken&&(s.set("Authorization",e.oauthToken),r=3),e.rateLimit&&(r=e.rateLimit),e.richTextSchema?this.richTextResolver=new m(e.richTextSchema):this.richTextResolver=new m,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries,this.throttle=M(this.throttledRequest,r,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new $,this.resolveNestedRelations=!1,this.client=new se({baseURL:t,timeout:e.timeout||0,headers:s,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let s="";return t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})}parseParams(e){return e.version||(e.version="published"),e.token||(e.token=this.getToken()),e.cv||(e.cv=y[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),e}factoryParamOptions(e,t){return this.helpers.isCDNUrl(e)?this.parseParams(t):t}makeRequest(e,t,s,r){const o=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,s,r));return this.cacheResponse(e,o)}get(e,t){t||(t={});const s=`/${e}`,r=this.factoryParamOptions(s,t);return this.cacheResponse(s,r)}async getAll(e,t,s){const r=(t==null?void 0:t.per_page)||25,o=`/${e}`,i=o.split("/"),a=s||i[i.length-1],l=1,d=await this.makeRequest(o,t,r,l),p=d.total?Math.ceil(d.total/r):1,T=await this.helpers.asyncMap(this.helpers.range(l,p),w=>this.makeRequest(o,t,r,w+1));return this.helpers.flatMap([d,...T],w=>Object.values(w.data[a]))}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){const s=e[t];s&&s.fieldtype=="multilink"&&s.linktype=="story"&&typeof s.id=="string"&&this.links[s.id]?s.story=this._cleanCopy(this.links[s.id]):s&&s.linktype==="story"&&typeof s.uuid=="string"&&this.links[s.uuid]&&(s.story=this._cleanCopy(this.links[s.uuid]))}_insertRelations(e,t,s){if(s.indexOf(`${e.component}.${t}`)>-1){if(typeof e[t]=="string")this.relations[e[t]]&&(e[t]=this._cleanCopy(this.relations[e[t]]));else if(e[t]&&e[t].constructor===Array){const r=[];e[t].forEach(o=>{this.relations[o]&&r.push(this._cleanCopy(this.relations[o]))}),e[t]=r}}}iterateTree(e,t){const s=r=>{if(r!=null){if(r.constructor===Array)for(let o=0;o<r.length;o++)s(r[o]);else if(r.constructor===Object){if(r._stopResolving)return;for(const o in r)(r.component&&r._uid||r.type==="link")&&(this._insertRelations(r,o,t),this._insertLinks(r,o)),s(r[o])}}};s(e.content)}async resolveLinks(e,t){let s=[];if(e.link_uuids){const r=e.link_uuids.length,o=[],i=50;for(let a=0;a<r;a+=i){const l=Math.min(r,a+i);o.push(e.link_uuids.slice(a,l))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:i,language:t.language,version:t.version,by_uuids:o[a].join(",")})).data.stories.forEach(l=>{s.push(l)})}else s=e.links;s.forEach(r=>{this.links[r.uuid]=b(f({},r),{_stopResolving:!0})})}async resolveRelations(e,t){let s=[];if(e.rel_uuids){const r=e.rel_uuids.length,o=[],i=50;for(let a=0;a<r;a+=i){const l=Math.min(r,a+i);o.push(e.rel_uuids.slice(a,l))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:i,language:t.language,version:t.version,by_uuids:o[a].join(",")})).data.stories.forEach(l=>{s.push(l)})}else s=e.rels;s&&s.length>0&&s.forEach(r=>{this.relations[r.uuid]=b(f({},r),{_stopResolving:!0})})}async resolveStories(e,t){var s,r;let o=[];if(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)),t.resolve_links&&["1","story","url"].indexOf(t.resolve_links)>-1&&(((s=e.links)==null?void 0:s.length)||((r=e.link_uuids)==null?void 0:r.length))&&await this.resolveLinks(e,t),this.resolveNestedRelations)for(const i in this.relations)this.iterateTree(this.relations[i],o);e.story?this.iterateTree(e.story,o):e.stories.forEach(i=>{this.iterateTree(i,o)})}cacheResponse(e,t,s){return new Promise((r,o)=>{const i=this.helpers.stringify({url:e,params:t}),a=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const l=a.get(i);if(l)return r(l)}try{(async()=>{var l;const d=await this.throttle("get",e,t);let p={data:d.data,headers:d.headers};if((l=d.headers)!=null&&l["per-page"]&&(p=Object.assign({},p,{perPage:d.headers["per-page"]?parseInt(d.headers["per-page"]):0,total:d.headers["per-page"]?parseInt(d.headers.total):0})),d.status!=200)return o(d);(p.data.story||p.data.stories)&&await this.resolveStories(p.data,t),t.version==="published"&&e!="/cdn/spaces/me"&&a.set(i,p),p.data.cv&&t.token&&(t.version=="draft"&&y[t.token]!=p.data.cv&&this.flushCache(),y[t.token]=p.data.cv),r(p)})()}catch{}})}throttledRequest(e,t,s){return this.client[e](t,s)}cacheVersions(){return y}cacheVersion(){return y[this.accessToken]}setCacheVersion(e){this.accessToken&&(y[this.accessToken]=e)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return k[e]},getAll(){return k},set(e,t){k[e]=t},flush(){k={}}};default:return{get(){},getAll(){},set(){},flush(){}}}}flushCache(){return this.cacheProvider().flush(),this}}const oe=(n={})=>{const{apiOptions:e}=n;if(!e.accessToken){console.error("You need to provide an access token to interact with Storyblok API. Read https://www.storyblok.com/docs/api/content-delivery#topics/authentication");return}return{storyblokApi:new re(e)}};var ne=n=>{if(typeof n!="object"||typeof n._editable=="undefined")return{};const e=JSON.parse(n._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(e),"data-blok-uid":e.id+"-"+e.uid}};let v;const E="https://app.storyblok.com/f/storyblok-v2-latest.js",S=(n,e,t={})=>{if(typeof window!="undefined"){if(typeof window.storyblokRegisterEvent=="undefined"){console.error("Storyblok Bridge is disabled. Please enable it to use it. Read https://github.com/storyblok/storyblok-js");return}if(!n){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(t).on(["input","published","change"],r=>{r.action==="input"&&r.story.id===n?e(r.story):(r.action==="change"||r.action==="published")&&r.storyId===n&&window.location.reload()})})}},ie=(n={})=>{const{bridge:e,accessToken:t,use:s=[],apiOptions:r={},richText:o={}}=n;r.accessToken=r.accessToken||t;const i={bridge:e,apiOptions:r};let a={};return s.forEach(l=>{a=f(f({},a),l(i))}),e!==!1&&R(E),v=new m(o.schema),o.resolver&&x(v,o.resolver),a},x=(n,e)=>{n.addNode("blok",t=>{let s="";return t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})},ae=(n,e,t)=>{let s=t||v;if(!s){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return n===""?"":n?(e&&(s=new m(e.schema),e.resolver&&x(s,e.resolver)),s.render(n)):(console.warn(`${n} is not a valid Richtext object. This might be because the value of the richtext field is empty.
|
2
2
|
|
3
|
-
For more info about the richtext object check https://github.com/storyblok/storyblok-js#rendering-rich-text`),"")},
|
3
|
+
For more info about the richtext object check https://github.com/storyblok/storyblok-js#rendering-rich-text`),"")},le=()=>R(E);h.RichTextResolver=m,h.RichTextSchema=j,h.apiPlugin=oe,h.loadStoryblokBridge=le,h.registerStoryblokBridge=S,h.renderRichText=ae,h.storyblokEditable=ne,h.storyblokInit=ie,h.useStoryblokBridge=S,Object.defineProperty(h,"__esModule",{value:!0}),h[Symbol.toStringTag]="Module"});
|
package/dist/storyblok-js.mjs
CHANGED
@@ -49,37 +49,37 @@ const loadBridge = (src) => {
|
|
49
49
|
});
|
50
50
|
};
|
51
51
|
var m = Object.defineProperty;
|
52
|
-
var
|
53
|
-
var l = (
|
54
|
-
function
|
55
|
-
return !(
|
52
|
+
var T = (c, t, e) => t in c ? m(c, t, { enumerable: true, configurable: true, writable: true, value: e }) : c[t] = e;
|
53
|
+
var l = (c, t, e) => (T(c, typeof t != "symbol" ? t + "" : t, e), e);
|
54
|
+
function k(c) {
|
55
|
+
return !(c !== c || c === 1 / 0 || c === -1 / 0);
|
56
56
|
}
|
57
|
-
function _(
|
58
|
-
if (!
|
57
|
+
function _(c, t, e) {
|
58
|
+
if (!k(t))
|
59
59
|
throw new TypeError("Expected `limit` to be a finite number");
|
60
|
-
if (!
|
60
|
+
if (!k(e))
|
61
61
|
throw new TypeError("Expected `interval` to be a finite number");
|
62
62
|
const s = [];
|
63
63
|
let r = [], n = 0;
|
64
|
-
const
|
64
|
+
const i = function() {
|
65
65
|
n++;
|
66
66
|
const a = setTimeout(function() {
|
67
|
-
n--, s.length > 0 &&
|
67
|
+
n--, s.length > 0 && i(), r = r.filter(function(u) {
|
68
68
|
return u !== a;
|
69
69
|
});
|
70
70
|
}, e);
|
71
71
|
r.indexOf(a) < 0 && r.push(a);
|
72
72
|
const h = s.shift();
|
73
|
-
h.resolve(
|
73
|
+
h.resolve(c.apply(h.self, h.args));
|
74
74
|
}, o = function(...a) {
|
75
75
|
const h = this;
|
76
|
-
return new Promise(function(u,
|
76
|
+
return new Promise(function(u, p) {
|
77
77
|
s.push({
|
78
78
|
resolve: u,
|
79
|
-
reject:
|
79
|
+
reject: p,
|
80
80
|
args: a,
|
81
81
|
self: h
|
82
|
-
}), n < t &&
|
82
|
+
}), n < t && i();
|
83
83
|
});
|
84
84
|
};
|
85
85
|
return o.abort = function() {
|
@@ -90,41 +90,41 @@ function _(i, t, e) {
|
|
90
90
|
}), s.length = 0;
|
91
91
|
}, o;
|
92
92
|
}
|
93
|
-
const
|
93
|
+
const R = function(c, t) {
|
94
94
|
const e = {};
|
95
|
-
for (const s in
|
96
|
-
const r =
|
95
|
+
for (const s in c) {
|
96
|
+
const r = c[s];
|
97
97
|
t.indexOf(s) > -1 && r !== null && (e[s] = r);
|
98
98
|
}
|
99
99
|
return e;
|
100
|
-
},
|
100
|
+
}, b = (c) => c === "email", w = () => ({
|
101
101
|
singleTag: "hr"
|
102
|
-
}),
|
102
|
+
}), $ = () => ({
|
103
103
|
tag: "blockquote"
|
104
104
|
}), x = () => ({
|
105
105
|
tag: "ul"
|
106
|
-
}),
|
106
|
+
}), E = (c) => ({
|
107
107
|
tag: [
|
108
108
|
"pre",
|
109
109
|
{
|
110
110
|
tag: "code",
|
111
|
-
attrs:
|
111
|
+
attrs: c.attrs
|
112
112
|
}
|
113
113
|
]
|
114
|
-
}),
|
114
|
+
}), P = () => ({
|
115
115
|
singleTag: "br"
|
116
|
-
}), S = (
|
117
|
-
tag: `h${
|
118
|
-
}), C = (
|
116
|
+
}), S = (c) => ({
|
117
|
+
tag: `h${c.attrs.level}`
|
118
|
+
}), C = (c) => ({
|
119
119
|
singleTag: [
|
120
120
|
{
|
121
121
|
tag: "img",
|
122
|
-
attrs:
|
122
|
+
attrs: R(c.attrs, ["src", "alt", "title"])
|
123
123
|
}
|
124
124
|
]
|
125
|
-
}),
|
125
|
+
}), O = () => ({
|
126
126
|
tag: "li"
|
127
|
-
}),
|
127
|
+
}), M = () => ({
|
128
128
|
tag: "ol"
|
129
129
|
}), H = () => ({
|
130
130
|
tag: "p"
|
@@ -132,17 +132,17 @@ const b = function(i, t) {
|
|
132
132
|
tag: "b"
|
133
133
|
}), I = () => ({
|
134
134
|
tag: "strike"
|
135
|
-
}),
|
135
|
+
}), L = () => ({
|
136
136
|
tag: "u"
|
137
137
|
}), N = () => ({
|
138
138
|
tag: "strong"
|
139
|
-
}),
|
139
|
+
}), U = () => ({
|
140
140
|
tag: "code"
|
141
|
-
}),
|
141
|
+
}), q = () => ({
|
142
142
|
tag: "i"
|
143
|
-
}),
|
144
|
-
const t = __spreadValues({},
|
145
|
-
return
|
143
|
+
}), z = (c) => {
|
144
|
+
const t = __spreadValues({}, c.attrs), { linktype: e = "url" } = c.attrs;
|
145
|
+
return b(e) && (t.href = `mailto:${t.href}`), t.anchor && (t.href = `${t.href}#${t.anchor}`, delete t.anchor), {
|
146
146
|
tag: [
|
147
147
|
{
|
148
148
|
tag: "a",
|
@@ -150,37 +150,37 @@ const b = function(i, t) {
|
|
150
150
|
}
|
151
151
|
]
|
152
152
|
};
|
153
|
-
},
|
153
|
+
}, j = (c) => ({
|
154
154
|
tag: [
|
155
155
|
{
|
156
156
|
tag: "span",
|
157
|
-
attrs:
|
157
|
+
attrs: c.attrs
|
158
158
|
}
|
159
159
|
]
|
160
|
-
}),
|
160
|
+
}), F = {
|
161
161
|
nodes: {
|
162
162
|
horizontal_rule: w,
|
163
|
-
blockquote:
|
163
|
+
blockquote: $,
|
164
164
|
bullet_list: x,
|
165
|
-
code_block:
|
166
|
-
hard_break:
|
165
|
+
code_block: E,
|
166
|
+
hard_break: P,
|
167
167
|
heading: S,
|
168
168
|
image: C,
|
169
|
-
list_item:
|
170
|
-
ordered_list:
|
169
|
+
list_item: O,
|
170
|
+
ordered_list: M,
|
171
171
|
paragraph: H
|
172
172
|
},
|
173
173
|
marks: {
|
174
174
|
bold: A,
|
175
175
|
strike: I,
|
176
|
-
underline:
|
176
|
+
underline: L,
|
177
177
|
strong: N,
|
178
|
-
code:
|
179
|
-
italic:
|
180
|
-
link:
|
181
|
-
styled:
|
178
|
+
code: U,
|
179
|
+
italic: q,
|
180
|
+
link: z,
|
181
|
+
styled: j
|
182
182
|
}
|
183
|
-
},
|
183
|
+
}, V = function(c) {
|
184
184
|
const t = {
|
185
185
|
"&": "&",
|
186
186
|
"<": "<",
|
@@ -188,13 +188,13 @@ const b = function(i, t) {
|
|
188
188
|
'"': """,
|
189
189
|
"'": "'"
|
190
190
|
}, e = /[&<>"']/g, s = RegExp(e.source);
|
191
|
-
return
|
191
|
+
return c && s.test(c) ? c.replace(e, (r) => t[r]) : c;
|
192
192
|
};
|
193
|
-
class
|
193
|
+
class y {
|
194
194
|
constructor(t) {
|
195
195
|
l(this, "marks");
|
196
196
|
l(this, "nodes");
|
197
|
-
t || (t =
|
197
|
+
t || (t = F), this.marks = t.marks || [], this.nodes = t.nodes || [];
|
198
198
|
}
|
199
199
|
addNode(t, e) {
|
200
200
|
this.nodes[t] = e;
|
@@ -220,7 +220,7 @@ class v {
|
|
220
220
|
const s = this.getMatchingNode(t);
|
221
221
|
return s && s.tag && e.push(this.renderOpeningTag(s.tag)), t.content ? t.content.forEach((r) => {
|
222
222
|
e.push(this.renderNode(r));
|
223
|
-
}) : t.text ? e.push(
|
223
|
+
}) : t.text ? e.push(V(t.text)) : s && s.singleTag ? e.push(this.renderTag(s.singleTag, " /")) : s && s.html && e.push(s.html), s && s.tag && e.push(this.renderClosingTag(s.tag)), t.marks && t.marks.slice(0).reverse().forEach((r) => {
|
224
224
|
const n = this.getMatchingMark(r);
|
225
225
|
n && e.push(this.renderClosingTag(n.tag));
|
226
226
|
}), e.join("");
|
@@ -232,9 +232,9 @@ class v {
|
|
232
232
|
{
|
233
233
|
let n = `<${r.tag}`;
|
234
234
|
if (r.attrs)
|
235
|
-
for (const
|
236
|
-
const o = r.attrs[
|
237
|
-
o !== null && (n += ` ${
|
235
|
+
for (const i in r.attrs) {
|
236
|
+
const o = r.attrs[i];
|
237
|
+
o !== null && (n += ` ${i}="${o}"`);
|
238
238
|
}
|
239
239
|
return `${n}${e}>`;
|
240
240
|
}
|
@@ -257,7 +257,7 @@ class v {
|
|
257
257
|
return e(t);
|
258
258
|
}
|
259
259
|
}
|
260
|
-
class
|
260
|
+
class v {
|
261
261
|
constructor() {
|
262
262
|
l(this, "isCDNUrl", (t = "") => t.indexOf("/cdn/") > -1);
|
263
263
|
l(this, "getOptionsPage", (t, e = 25, s = 1) => __spreadProps(__spreadValues({}, t), {
|
@@ -268,7 +268,7 @@ class T {
|
|
268
268
|
l(this, "arrayFrom", (t = 0, e) => [...Array(t)].map(e));
|
269
269
|
l(this, "range", (t = 0, e = t) => {
|
270
270
|
const s = Math.abs(e - t) || 0, r = t < e ? 1 : -1;
|
271
|
-
return this.arrayFrom(s, (n,
|
271
|
+
return this.arrayFrom(s, (n, i) => i * r + t);
|
272
272
|
});
|
273
273
|
l(this, "asyncMap", async (t, e) => Promise.all(t.map(e)));
|
274
274
|
l(this, "flatMap", (t = [], e) => t.map(e).reduce((s, r) => [...s, ...r], []));
|
@@ -278,36 +278,36 @@ class T {
|
|
278
278
|
for (const n in t) {
|
279
279
|
if (!Object.prototype.hasOwnProperty.call(t, n))
|
280
280
|
continue;
|
281
|
-
const
|
281
|
+
const i = t[n], o = s ? "" : encodeURIComponent(n);
|
282
282
|
let a;
|
283
|
-
typeof
|
283
|
+
typeof i == "object" ? a = this.stringify(i, e ? e + encodeURIComponent("[" + o + "]") : o, Array.isArray(i)) : a = (e ? e + encodeURIComponent("[" + o + "]") : o) + "=" + encodeURIComponent(i), r.push(a);
|
284
284
|
}
|
285
285
|
return r.join("&");
|
286
286
|
}
|
287
287
|
}
|
288
|
-
|
289
|
-
class G {
|
288
|
+
class J {
|
290
289
|
constructor(t) {
|
291
290
|
l(this, "baseURL");
|
292
291
|
l(this, "timeout");
|
293
292
|
l(this, "headers");
|
294
293
|
l(this, "responseInterceptor");
|
294
|
+
l(this, "fetch");
|
295
295
|
l(this, "ejectInterceptor");
|
296
296
|
l(this, "url");
|
297
297
|
l(this, "parameters");
|
298
|
-
this.baseURL = t.baseURL, this.timeout = t.timeout ? t.timeout * 1e3 : 1e3, this.
|
298
|
+
this.baseURL = t.baseURL, this.headers = t.headers || [], this.timeout = t.timeout ? t.timeout * 1e3 : 1e3, this.responseInterceptor = t.responseInterceptor, this.fetch = (...e) => t.fetch ? t.fetch(...e) : fetch(...e), this.ejectInterceptor = false, this.url = "", this.parameters = {};
|
299
299
|
}
|
300
300
|
get(t, e) {
|
301
|
-
return this.url = t, this.parameters = e, this._methodHandler(
|
301
|
+
return this.url = t, this.parameters = e, this._methodHandler("get");
|
302
302
|
}
|
303
303
|
post(t, e) {
|
304
|
-
return this.url = t, this.parameters = e, this._methodHandler(
|
304
|
+
return this.url = t, this.parameters = e, this._methodHandler("post");
|
305
305
|
}
|
306
306
|
put(t, e) {
|
307
|
-
return this.url = t, this.parameters = e, this._methodHandler(
|
307
|
+
return this.url = t, this.parameters = e, this._methodHandler("put");
|
308
308
|
}
|
309
309
|
delete(t, e) {
|
310
|
-
return this.url = t, this.parameters = e, this._methodHandler(
|
310
|
+
return this.url = t, this.parameters = e, this._methodHandler("delete");
|
311
311
|
}
|
312
312
|
async _responseHandler(t) {
|
313
313
|
const e = [], s = {
|
@@ -327,19 +327,19 @@ class G {
|
|
327
327
|
const e = new URL(`${this.baseURL}${this.url}`);
|
328
328
|
let s = null;
|
329
329
|
if (t === "get") {
|
330
|
-
const o = new
|
330
|
+
const o = new v();
|
331
331
|
e.search = o.stringify(this.parameters);
|
332
332
|
} else
|
333
333
|
s = JSON.stringify(this.parameters);
|
334
|
-
const r = new AbortController(), { signal: n } = r,
|
334
|
+
const r = new AbortController(), { signal: n } = r, i = setTimeout(() => r.abort(), this.timeout);
|
335
335
|
try {
|
336
|
-
const o = await fetch(`${e}`, {
|
336
|
+
const o = await this.fetch(`${e}`, {
|
337
337
|
method: t,
|
338
338
|
headers: this.headers,
|
339
339
|
body: s,
|
340
340
|
signal: n
|
341
341
|
});
|
342
|
-
clearTimeout(
|
342
|
+
clearTimeout(i);
|
343
343
|
const a = await this._responseHandler(o);
|
344
344
|
return this.responseInterceptor && !this.ejectInterceptor ? this._statusHandler(this.responseInterceptor(a)) : this._statusHandler(a);
|
345
345
|
} catch (o) {
|
@@ -358,7 +358,7 @@ class G {
|
|
358
358
|
};
|
359
359
|
}
|
360
360
|
}
|
361
|
-
let
|
361
|
+
let f = {};
|
362
362
|
const d = {};
|
363
363
|
class Q {
|
364
364
|
constructor(t, e) {
|
@@ -373,16 +373,20 @@ class Q {
|
|
373
373
|
l(this, "richTextResolver");
|
374
374
|
l(this, "resolveNestedRelations");
|
375
375
|
if (!e) {
|
376
|
-
const n = t.region ? `-${t.region}` : "",
|
377
|
-
t.oauthToken ? e = `${
|
376
|
+
const n = t.region ? `-${t.region}` : "", i = t.https === false ? "http" : "https";
|
377
|
+
t.oauthToken ? e = `${i}://api${n}.storyblok.com/v1` : e = `${i}://api${n}.storyblok.com/v2`;
|
378
378
|
}
|
379
|
-
const s =
|
379
|
+
const s = new Headers();
|
380
|
+
s.set("Content-Type", "application/json"), s.set("Accept", "application/json"), s.forEach((n, i) => {
|
381
|
+
t.headers && t.headers[i] && s.set(i, t.headers[i]);
|
382
|
+
});
|
380
383
|
let r = 5;
|
381
|
-
t.oauthToken && (s.Authorization
|
384
|
+
t.oauthToken && (s.set("Authorization", t.oauthToken), r = 3), t.rateLimit && (r = t.rateLimit), t.richTextSchema ? this.richTextResolver = new y(t.richTextSchema) : this.richTextResolver = new y(), t.componentResolver && this.setComponentResolver(t.componentResolver), this.maxRetries = t.maxRetries, this.throttle = _(this.throttledRequest, r, 1e3), this.accessToken = t.accessToken || "", this.relations = {}, this.links = {}, this.cache = t.cache || { clear: "manual" }, this.helpers = new v(), this.resolveNestedRelations = false, this.client = new J({
|
382
385
|
baseURL: e,
|
383
386
|
timeout: t.timeout || 0,
|
384
387
|
headers: s,
|
385
|
-
responseInterceptor: t.responseInterceptor
|
388
|
+
responseInterceptor: t.responseInterceptor,
|
389
|
+
fetch: t.fetch
|
386
390
|
});
|
387
391
|
}
|
388
392
|
setComponentResolver(t) {
|
@@ -411,8 +415,8 @@ class Q {
|
|
411
415
|
return this.cacheResponse(s, r);
|
412
416
|
}
|
413
417
|
async getAll(t, e, s) {
|
414
|
-
const r = (e == null ? void 0 : e.per_page) || 25, n = `/${t}`,
|
415
|
-
return this.helpers.flatMap([h, ...
|
418
|
+
const r = (e == null ? void 0 : e.per_page) || 25, n = `/${t}`, i = n.split("/"), o = s || i[i.length - 1], a = 1, h = await this.makeRequest(n, e, r, a), u = h.total ? Math.ceil(h.total / r) : 1, p = await this.helpers.asyncMap(this.helpers.range(a, u), (g) => this.makeRequest(n, e, r, g + 1));
|
419
|
+
return this.helpers.flatMap([h, ...p], (g) => Object.values(g.data[o]));
|
416
420
|
}
|
417
421
|
post(t, e) {
|
418
422
|
const s = `/${t}`;
|
@@ -476,14 +480,14 @@ class Q {
|
|
476
480
|
async resolveLinks(t, e) {
|
477
481
|
let s = [];
|
478
482
|
if (t.link_uuids) {
|
479
|
-
const r = t.link_uuids.length, n = [],
|
480
|
-
for (let o = 0; o < r; o +=
|
481
|
-
const a = Math.min(r, o +
|
483
|
+
const r = t.link_uuids.length, n = [], i = 50;
|
484
|
+
for (let o = 0; o < r; o += i) {
|
485
|
+
const a = Math.min(r, o + i);
|
482
486
|
n.push(t.link_uuids.slice(o, a));
|
483
487
|
}
|
484
488
|
for (let o = 0; o < n.length; o++)
|
485
489
|
(await this.getStories({
|
486
|
-
per_page:
|
490
|
+
per_page: i,
|
487
491
|
language: e.language,
|
488
492
|
version: e.version,
|
489
493
|
by_uuids: n[o].join(",")
|
@@ -499,14 +503,14 @@ class Q {
|
|
499
503
|
async resolveRelations(t, e) {
|
500
504
|
let s = [];
|
501
505
|
if (t.rel_uuids) {
|
502
|
-
const r = t.rel_uuids.length, n = [],
|
503
|
-
for (let o = 0; o < r; o +=
|
504
|
-
const a = Math.min(r, o +
|
506
|
+
const r = t.rel_uuids.length, n = [], i = 50;
|
507
|
+
for (let o = 0; o < r; o += i) {
|
508
|
+
const a = Math.min(r, o + i);
|
505
509
|
n.push(t.rel_uuids.slice(o, a));
|
506
510
|
}
|
507
511
|
for (let o = 0; o < n.length; o++)
|
508
512
|
(await this.getStories({
|
509
|
-
per_page:
|
513
|
+
per_page: i,
|
510
514
|
language: e.language,
|
511
515
|
version: e.version,
|
512
516
|
by_uuids: n[o].join(",")
|
@@ -522,18 +526,18 @@ class Q {
|
|
522
526
|
async resolveStories(t, e) {
|
523
527
|
var r, n;
|
524
528
|
let s = [];
|
525
|
-
if (typeof e.resolve_relations < "u" && e.resolve_relations.length > 0 && (s = e.resolve_relations.split(","), await this.resolveRelations(t, e)), e.resolve_links && ["1", "story", "url"].indexOf(e.resolve_links) > -1 && (((r = t.links) == null ? void 0 : r.length) || ((n = t.link_uuids) == null ? void 0 : n.length)) && await this.resolveLinks(t, e), this.resolveNestedRelations)
|
526
|
-
for (const
|
527
|
-
this.iterateTree(this.relations[
|
528
|
-
t.story ? this.iterateTree(t.story, s) : t.stories.forEach((
|
529
|
-
this.iterateTree(
|
529
|
+
if (typeof e.resolve_relations < "u" && e.resolve_relations.length > 0 && (typeof e.resolve_relations == "string" && (s = e.resolve_relations.split(",")), await this.resolveRelations(t, e)), e.resolve_links && ["1", "story", "url"].indexOf(e.resolve_links) > -1 && (((r = t.links) == null ? void 0 : r.length) || ((n = t.link_uuids) == null ? void 0 : n.length)) && await this.resolveLinks(t, e), this.resolveNestedRelations)
|
530
|
+
for (const i in this.relations)
|
531
|
+
this.iterateTree(this.relations[i], s);
|
532
|
+
t.story ? this.iterateTree(t.story, s) : t.stories.forEach((i) => {
|
533
|
+
this.iterateTree(i, s);
|
530
534
|
});
|
531
535
|
}
|
532
536
|
cacheResponse(t, e, s) {
|
533
537
|
return new Promise((r, n) => {
|
534
|
-
const
|
538
|
+
const i = this.helpers.stringify({ url: t, params: e }), o = this.cacheProvider();
|
535
539
|
if (this.cache.clear === "auto" && e.version === "draft" && this.flushCache(), e.version === "published" && t != "/cdn/spaces/me") {
|
536
|
-
const a = o.get(
|
540
|
+
const a = o.get(i);
|
537
541
|
if (a)
|
538
542
|
return r(a);
|
539
543
|
}
|
@@ -547,7 +551,7 @@ class Q {
|
|
547
551
|
total: a.headers["per-page"] ? parseInt(a.headers.total) : 0
|
548
552
|
})), a.status != 200)
|
549
553
|
return n(a);
|
550
|
-
(h.data.story || h.data.stories) && await this.resolveStories(h.data, e), e.version === "published" && t != "/cdn/spaces/me" && o.set(
|
554
|
+
(h.data.story || h.data.stories) && await this.resolveStories(h.data, e), e.version === "published" && t != "/cdn/spaces/me" && o.set(i, h), h.data.cv && e.token && (e.version == "draft" && d[e.token] != h.data.cv && this.flushCache(), d[e.token] = h.data.cv), r(h);
|
551
555
|
})();
|
552
556
|
} catch {
|
553
557
|
}
|
@@ -570,16 +574,16 @@ class Q {
|
|
570
574
|
case "memory":
|
571
575
|
return {
|
572
576
|
get(t) {
|
573
|
-
return
|
577
|
+
return f[t];
|
574
578
|
},
|
575
579
|
getAll() {
|
576
|
-
return
|
580
|
+
return f;
|
577
581
|
},
|
578
582
|
set(t, e) {
|
579
|
-
|
583
|
+
f[t] = e;
|
580
584
|
},
|
581
585
|
flush() {
|
582
|
-
|
586
|
+
f = {};
|
583
587
|
}
|
584
588
|
};
|
585
589
|
default:
|
@@ -660,7 +664,7 @@ const storyblokInit = (pluginOptions = {}) => {
|
|
660
664
|
if (bridge !== false) {
|
661
665
|
loadBridge(bridgeLatest);
|
662
666
|
}
|
663
|
-
richTextResolver = new
|
667
|
+
richTextResolver = new y(richText.schema);
|
664
668
|
if (richText.resolver) {
|
665
669
|
setComponentResolver(richTextResolver, richText.resolver);
|
666
670
|
}
|
@@ -692,7 +696,7 @@ const renderRichText = (data, options, resolverInstance) => {
|
|
692
696
|
return "";
|
693
697
|
}
|
694
698
|
if (options) {
|
695
|
-
localResolver = new
|
699
|
+
localResolver = new y(options.schema);
|
696
700
|
if (options.resolver) {
|
697
701
|
setComponentResolver(localResolver, options.resolver);
|
698
702
|
}
|
@@ -700,4 +704,4 @@ const renderRichText = (data, options, resolverInstance) => {
|
|
700
704
|
return localResolver.render(data);
|
701
705
|
};
|
702
706
|
const loadStoryblokBridge = () => loadBridge(bridgeLatest);
|
703
|
-
export {
|
707
|
+
export { y as RichTextResolver, F as RichTextSchema, apiFactory as apiPlugin, loadStoryblokBridge, useStoryblokBridge as registerStoryblokBridge, renderRichText, editable as storyblokEditable, storyblokInit, useStoryblokBridge };
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "@storyblok/js",
|
3
|
-
"version": "2.0.
|
3
|
+
"version": "2.0.6",
|
4
4
|
"description": "SDK to integrate Storyblok into your project using JavaScript.",
|
5
5
|
"main": "./dist/storyblok-js.js",
|
6
6
|
"module": "./dist/storyblok-js.mjs",
|
@@ -27,7 +27,7 @@
|
|
27
27
|
"prepublishOnly": "npm run build && cp ../README.md ./"
|
28
28
|
},
|
29
29
|
"dependencies": {
|
30
|
-
"storyblok-js-client": "^5.
|
30
|
+
"storyblok-js-client": "^5.2.5"
|
31
31
|
},
|
32
32
|
"devDependencies": {
|
33
33
|
"@tsconfig/recommended": "^1.0.1",
|
@@ -37,7 +37,7 @@
|
|
37
37
|
"isomorphic-fetch": "^3.0.0",
|
38
38
|
"start-server-and-test": "^1.14.0",
|
39
39
|
"vite": "^2.9.15",
|
40
|
-
"vitest": "^0.
|
40
|
+
"vitest": "^0.26.3"
|
41
41
|
},
|
42
42
|
"babel": {
|
43
43
|
"presets": [
|