@storyblok/js
Advanced tools
Comparing version 1.8.6 to 2.0.0
@@ -1,7 +0,3 @@ | ||
(function(h,d){typeof exports=="object"&&typeof module!="undefined"?d(exports,require("axios")):typeof define=="function"&&define.amd?define(["exports","axios"],d):(h=typeof globalThis!="undefined"?globalThis:h||self,d(h.storyblok={},h.e))})(this,function(h,d){"use strict";var K=Object.defineProperty,G=Object.defineProperties;var Q=Object.getOwnPropertyDescriptors;var M=Object.getOwnPropertySymbols;var W=Object.prototype.hasOwnProperty,X=Object.prototype.propertyIsEnumerable;var A=(h,d,g)=>d in h?K(h,d,{enumerable:!0,configurable:!0,writable:!0,value:g}):h[d]=g,f=(h,d)=>{for(var g in d||(d={}))W.call(d,g)&&A(h,g,d[g]);if(M)for(var g of M(d))X.call(d,g)&&A(h,g,d[g]);return h},k=(h,d)=>G(h,Q(d));function g(n){return n&&typeof n=="object"&&"default"in n?n:{default:n}}var C=g(d);let T=!1;const w=[],_=n=>new Promise((t,r)=>{if(typeof window=="undefined"||(window.storyblokRegisterEvent=s=>{if(window.location===window.parent.location){console.warn("You are not in Draft Mode or in the Visual Editor.");return}T?s():w.push(s)},document.getElementById("storyblok-javascript-bridge")))return;const e=document.createElement("script");e.async=!0,e.src=n,e.id="storyblok-javascript-bridge",e.onerror=s=>r(s),e.onload=s=>{w.forEach(o=>o()),T=!0,t(s)},document.getElementsByTagName("head")[0].appendChild(e)}),N=function(n,t){if(!n)return null;let r={};for(let e in n){let s=n[e];t.indexOf(e)>-1&&s!==null&&(r[e]=s)}return r},P=n=>n==="email";var R={nodes:{horizontal_rule(){return{singleTag:"hr"}},blockquote(){return{tag:"blockquote"}},bullet_list(){return{tag:"ul"}},code_block(n){return{tag:["pre",{tag:"code",attrs:n.attrs}]}},hard_break(){return{singleTag:"br"}},heading(n){return{tag:`h${n.attrs.level}`}},image(n){return{singleTag:[{tag:"img",attrs:N(n.attrs,["src","alt","title"])}]}},list_item(){return{tag:"li"}},ordered_list(){return{tag:"ol"}},paragraph(){return{tag:"p"}}},marks:{bold(){return{tag:"b"}},strike(){return{tag:"strike"}},underline(){return{tag:"u"}},strong(){return{tag:"strong"}},code(){return{tag:"code"}},italic(){return{tag:"i"}},link(n){const t=f({},n.attrs),{linktype:r="url"}=n.attrs;return P(r)&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),{tag:[{tag:"a",attrs:t}]}},styled(n){return{tag:[{tag:"span",attrs:n.attrs}]}}}};const I=function(n){const t={"&":"&","<":"<",">":">",'"':""","'":"'"},r=/[&<>"']/g,e=RegExp(r.source);return n&&e.test(n)?n.replace(r,s=>t[s]):n};class ${constructor(t){t||(t=R),this.marks=t.marks||[],this.nodes=t.nodes||[]}addNode(t,r){this.nodes[t]=r}addMark(t,r){this.marks[t]=r}render(t={}){if(t.content&&Array.isArray(t.content)){let r="";return t.content.forEach(e=>{r+=this.renderNode(e)}),r}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(t){let r=[];t.marks&&t.marks.forEach(s=>{const o=this.getMatchingMark(s);o&&r.push(this.renderOpeningTag(o.tag))});const e=this.getMatchingNode(t);return e&&e.tag&&r.push(this.renderOpeningTag(e.tag)),t.content?t.content.forEach(s=>{r.push(this.renderNode(s))}):t.text?r.push(I(t.text)):e&&e.singleTag?r.push(this.renderTag(e.singleTag," /")):e&&e.html&&r.push(e.html),e&&e.tag&&r.push(this.renderClosingTag(e.tag)),t.marks&&t.marks.slice(0).reverse().forEach(s=>{const o=this.getMatchingMark(s);o&&r.push(this.renderClosingTag(o.tag))}),r.join("")}renderTag(t,r){return t.constructor===String?`<${t}${r}>`:t.map(s=>{if(s.constructor===String)return`<${s}${r}>`;{let o=`<${s.tag}`;if(s.attrs)for(let a in s.attrs){let i=s.attrs[a];i!==null&&(o+=` ${a}="${i}"`)}return`${o}${r}>`}}).join("")}renderOpeningTag(t){return this.renderTag(t,"")}renderClosingTag(t){return t.constructor===String?`</${t}>`:t.slice(0).reverse().map(e=>e.constructor===String?`</${e}>`:`</${e.tag}>`).join("")}getMatchingNode(t){if(typeof this.nodes[t.type]=="function")return this.nodes[t.type](t)}getMatchingMark(t){if(typeof this.marks[t.type]=="function")return this.marks[t.type](t)}}/*! | ||
* storyblok-js-client v4.5.2 | ||
* Universal JavaScript SDK for Storyblok's API | ||
* (c) 2020-2022 Stobylok Team | ||
*/function E(n){return typeof n=="number"&&n==n&&n!==1/0&&n!==-1/0}function S(n,t,r){if(!E(t))throw new TypeError("Expected `limit` to be a finite number");if(!E(r))throw new TypeError("Expected `interval` to be a finite number");var e=[],s=[],o=0,a=function(){o++;var c=setTimeout(function(){o--,e.length>0&&a(),s=s.filter(function(u){return u!==c})},r);s.indexOf(c)<0&&s.push(c);var l=e.shift();l.resolve(n.apply(l.self,l.args))},i=function(){var c=arguments,l=this;return new Promise(function(u,y){e.push({resolve:u,reject:y,args:c,self:l}),o<t&&a()})};return i.abort=function(){s.forEach(clearTimeout),s=[],e.forEach(function(c){c.reject(new throttle.AbortError)}),e.length=0},i}S.AbortError=function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"};const q=function(n,t){if(!n)return null;let r={};for(let e in n){let s=n[e];t.indexOf(e)>-1&&s!==null&&(r[e]=s)}return r};var B={nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:n=>({tag:["pre",{tag:"code",attrs:n.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:n=>({tag:`h${n.attrs.level}`}),image:n=>({singleTag:[{tag:"img",attrs:q(n.attrs,["src","alt","title"])}]}),list_item:()=>({tag:"li"}),ordered_list:()=>({tag:"ol"}),paragraph:()=>({tag:"p"})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link(n){const t=f({},n.attrs),{linktype:r="url"}=n.attrs;return r==="email"&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),{tag:[{tag:"a",attrs:t}]}},styled:n=>({tag:[{tag:"span",attrs:n.attrs}]})}};class L{constructor(t){t||(t=B),this.marks=t.marks||[],this.nodes=t.nodes||[]}addNode(t,r){this.nodes[t]=r}addMark(t,r){this.marks[t]=r}render(t={}){if(t.content&&Array.isArray(t.content)){let r="";return t.content.forEach(e=>{r+=this.renderNode(e)}),r}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(t){let r=[];t.marks&&t.marks.forEach(s=>{const o=this.getMatchingMark(s);o&&r.push(this.renderOpeningTag(o.tag))});const e=this.getMatchingNode(t);return e&&e.tag&&r.push(this.renderOpeningTag(e.tag)),t.content?t.content.forEach(s=>{r.push(this.renderNode(s))}):t.text?r.push(function(s){const o={"&":"&","<":"<",">":">",'"':""","'":"'"},a=/[&<>"']/g,i=RegExp(a.source);return s&&i.test(s)?s.replace(a,c=>o[c]):s}(t.text)):e&&e.singleTag?r.push(this.renderTag(e.singleTag," /")):e&&e.html&&r.push(e.html),e&&e.tag&&r.push(this.renderClosingTag(e.tag)),t.marks&&t.marks.slice(0).reverse().forEach(s=>{const o=this.getMatchingMark(s);o&&r.push(this.renderClosingTag(o.tag))}),r.join("")}renderTag(t,r){return t.constructor===String?`<${t}${r}>`:t.map(e=>{if(e.constructor===String)return`<${e}${r}>`;{let s=`<${e.tag}`;if(e.attrs)for(let o in e.attrs){let a=e.attrs[o];a!==null&&(s+=` ${o}="${a}"`)}return`${s}${r}>`}}).join("")}renderOpeningTag(t){return this.renderTag(t,"")}renderClosingTag(t){return t.constructor===String?`</${t}>`:t.slice(0).reverse().map(r=>r.constructor===String?`</${r}>`:`</${r.tag}>`).join("")}getMatchingNode(t){if(typeof this.nodes[t.type]=="function")return this.nodes[t.type](t)}getMatchingMark(t){if(typeof this.marks[t.type]=="function")return this.marks[t.type](t)}}const z=(n=0,t=n)=>{const r=Math.abs(t-n)||0,e=n<t?1:-1;return((s=0,o)=>[...Array(s)].map(o))(r,(s,o)=>o*e+n)},b=(n,t,r)=>{const e=[];for(const s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;const o=n[s],a=r?"":encodeURIComponent(s);let i;i=typeof o=="object"?b(o,t?t+encodeURIComponent("["+a+"]"):a,Array.isArray(o)):(t?t+encodeURIComponent("["+a+"]"):a)+"="+encodeURIComponent(o),e.push(i)}return e.join("&")};let m={},p={};class U{constructor(t,r){if(!r){let o=t.region?`-${t.region}`:"",a=t.https===!1?"http":"https";r=t.oauthToken===void 0?`${a}://api${o}.storyblok.com/v2`:`${a}://api${o}.storyblok.com/v1`}let e=Object.assign({},t.headers),s=5;t.oauthToken!==void 0&&(e.Authorization=t.oauthToken,s=3),t.rateLimit!==void 0&&(s=t.rateLimit),this.richTextResolver=new L(t.richTextSchema),typeof t.componentResolver=="function"&&this.setComponentResolver(t.componentResolver),this.maxRetries=t.maxRetries||5,this.throttle=S(this.throttledRequest,s,1e3),this.accessToken=t.accessToken,this.relations={},this.links={},this.cache=t.cache||{clear:"manual"},this.client=C.default.create({baseURL:r,timeout:t.timeout||0,headers:e,proxy:t.proxy||!1}),t.responseInterceptor&&this.client.interceptors.response.use(o=>t.responseInterceptor(o)),this.resolveNestedRelations=t.resolveNestedRelations||!0}setComponentResolver(t){this.richTextResolver.addNode("blok",r=>{let e="";return r.attrs.body.forEach(s=>{e+=t(s.component,s)}),{html:e}})}parseParams(t={}){return t.version||(t.version="published"),t.token||(t.token=this.getToken()),t.cv||(t.cv=p[t.token]),Array.isArray(t.resolve_relations)&&(t.resolve_relations=t.resolve_relations.join(",")),t}factoryParamOptions(t,r={}){return((e="")=>e.indexOf("/cdn/")>-1)(t)?this.parseParams(r):r}makeRequest(t,r,e,s){const o=this.factoryParamOptions(t,((a={},i=25,c=1)=>k(f({},a),{per_page:i,page:c}))(r,e,s));return this.cacheResponse(t,o)}get(t,r){let e=`/${t}`;const s=this.factoryParamOptions(e,r);return this.cacheResponse(e,s)}async getAll(t,r={},e){const s=r.per_page||25,o=`/${t}`,a=o.split("/");e=e||a[a.length-1];const i=await this.makeRequest(o,r,s,1),c=i.total?Math.ceil(i.total/s):1;return((l=[],u)=>l.map(u).reduce((y,Y)=>[...y,...Y],[]))([i,...await(async(l=[],u)=>Promise.all(l.map(u)))(z(1,c),async l=>this.makeRequest(o,r,s,l+1))],l=>Object.values(l.data[e]))}post(t,r){let e=`/${t}`;return this.throttle("post",e,r)}put(t,r){let e=`/${t}`;return this.throttle("put",e,r)}delete(t,r){let e=`/${t}`;return this.throttle("delete",e,r)}getStories(t){return this.get("cdn/stories",t)}getStory(t,r){return this.get(`cdn/stories/${t}`,r)}setToken(t){this.accessToken=t}getToken(){return this.accessToken}_cleanCopy(t){return JSON.parse(JSON.stringify(t))}_insertLinks(t,r){const e=t[r];e&&e.fieldtype=="multilink"&&e.linktype=="story"&&typeof e.id=="string"&&this.links[e.id]?e.story=this._cleanCopy(this.links[e.id]):e&&e.linktype==="story"&&typeof e.uuid=="string"&&this.links[e.uuid]&&(e.story=this._cleanCopy(this.links[e.uuid]))}_insertRelations(t,r,e){if(e.indexOf(t.component+"."+r)>-1){if(typeof t[r]=="string")this.relations[t[r]]&&(t[r]=this._cleanCopy(this.relations[t[r]]));else if(t[r].constructor===Array){let s=[];t[r].forEach(o=>{this.relations[o]&&s.push(this._cleanCopy(this.relations[o]))}),t[r]=s}}}_insertAssetsRelations(t,r){r.forEach(e=>{t.id===e.id&&(t.original=e,t.original.filename=t.filename,t.original.filename=t.original.filename.includes("https://s3.amazonaws.com/")?t.original.filename:t.original.filename.replace("https://","https://s3.amazonaws.com/"),delete t.original.s3_filename)})}iterateTree(t,r){let e=s=>{if(s!=null){if(s.constructor===Array)for(let o=0;o<s.length;o++)e(s[o]);else if(s.constructor===Object){if(s._stopResolving)return;for(let o in s)s.component&&s._uid||s.type==="link"?(this._insertRelations(s,o,r),this._insertLinks(s,o)):"id"in s&&s.fieldtype==="asset"&&this._insertAssetsRelations(s,r),e(s[o])}}};e(t.content)}async resolveLinks(t,r){let e=[];if(t.link_uuids){const s=t.link_uuids.length;let o=[];const a=50;for(let i=0;i<s;i+=a){const c=Math.min(s,i+a);o.push(t.link_uuids.slice(i,c))}for(let i=0;i<o.length;i++)(await this.getStories({per_page:a,language:r.language,version:r.version,by_uuids:o[i].join(",")})).data.stories.forEach(c=>{e.push(c)})}else e=t.links;e.forEach(s=>{this.links[s.uuid]=k(f({},s),{_stopResolving:!0})})}async resolveRelations(t,r){let e=[];if(t.rel_uuids){const s=t.rel_uuids.length;let o=[];const a=50;for(let i=0;i<s;i+=a){const c=Math.min(s,i+a);o.push(t.rel_uuids.slice(i,c))}for(let i=0;i<o.length;i++)(await this.getStories({per_page:a,language:r.language,version:r.version,by_uuids:o[i].join(",")})).data.stories.forEach(c=>{e.push(c)})}else e=t.rels;e.forEach(s=>{this.relations[s.uuid]=k(f({},s),{_stopResolving:!0})})}async resolveStories(t,r){let e=[];if(r.resolve_relations!==void 0&&r.resolve_relations.length>0&&(t.rels||t.rel_uuids)&&(e=r.resolve_relations.split(","),await this.resolveRelations(t,r)),["1","story","url"].indexOf(r.resolve_links)>-1&&(t.links||t.link_uuids)&&await this.resolveLinks(t,r),this.resolveNestedRelations)for(const s in this.relations)this.iterateTree(this.relations[s],e);t.story?this.iterateTree(t.story,e):t.stories.forEach(s=>{this.iterateTree(s,e)})}resolveAssetsRelations(t){const{assets:r,stories:e,story:s}=t;if(e)for(const o of e)this.iterateTree(o,r);else{if(!s)return t;this.iterateTree(s,r)}}cacheResponse(t,r,e){return e===void 0&&(e=0),new Promise(async(s,o)=>{let a=b({url:t,params:r}),i=this.cacheProvider();if(this.cache.clear==="auto"&&r.version==="draft"&&await this.flushCache(),r.version==="published"&&t!="/cdn/spaces/me"){const l=await i.get(a);if(l)return s(l)}try{let l=await this.throttle("get",t,{params:r,paramsSerializer:y=>b(y)}),u={data:l.data,headers:l.headers};if(u.data.assets&&u.data.assets.length&&this.resolveAssetsRelations(u.data),u=Object.assign({},u,{perPage:l.headers["per-page"]?parseInt(l.headers["per-page"]):0,total:l.headers["per-page"]?parseInt(l.headers.total):0}),l.status!=200)return o(l);(u.data.story||u.data.stories)&&await this.resolveStories(u.data,r),r.version==="published"&&t!="/cdn/spaces/me"&&i.set(a,u),u.data.cv&&(r.version=="draft"&&p[r.token]!=u.data.cv&&this.flushCache(),p[r.token]=u.data.cv),s(u)}catch(l){if(l.response&&l.response.status===429&&(e+=1)<this.maxRetries)return console.log(`Hit rate limit. Retrying in ${e} seconds.`),await(c=1e3*e,new Promise(u=>setTimeout(u,c))),this.cacheResponse(t,r,e).then(s).catch(o);o(l)}var c})}throttledRequest(t,r,e){return this.client[t](r,e)}cacheVersions(){return p}cacheVersion(){return p[this.accessToken]}setCacheVersion(t){this.accessToken&&(p[this.accessToken]=t)}cacheProvider(){return this.cache.type==="memory"?{get:t=>m[t],getAll:()=>m,set(t,r){m[t]=r},flush(){m={}}}:{get(){},getAll(){},set(){},flush(){}}}async flushCache(){return await this.cacheProvider().flush(),this}}const H=(n={})=>{const{apiOptions:t}=n;if(!t.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 U(t)}};var D=n=>{if(typeof n!="object"||typeof n._editable=="undefined")return{};const t=JSON.parse(n._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(t),"data-blok-uid":t.id+"-"+t.uid}};let v;const j="https://app.storyblok.com/f/storyblok-v2-latest.js",x=(n,t,r={})=>{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(r).on(["input","published","change"],s=>{s.action==="input"&&s.story.id===n?t(s.story):(s.action==="change"||s.action==="published")&&s.storyId===n&&window.location.reload()})})}},J=(n={})=>{const{bridge:t,accessToken:r,use:e=[],apiOptions:s={},richText:o={}}=n;s.accessToken=s.accessToken||r;const a={bridge:t,apiOptions:s};let i={};return e.forEach(c=>{i=f(f({},i),c(a))}),t!==!1&&_(j),v=new $(o.schema),o.resolver&&O(v,o.resolver),i},O=(n,t)=>{n.addNode("blok",r=>{let e="";return r.attrs.body.forEach(s=>{e+=t(s.component,s)}),{html:e}})},V=(n,t,r)=>{let e=r||v;if(!e){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return n===""?"":n?(t&&(e=new $(t.schema),t.resolver&&O(e,t.resolver)),e.render(n)):(console.warn(`${n} is not a valid Richtext object. This might be because the value of the richtext field is empty. | ||
(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 O=Object.getOwnPropertySymbols;var pe=Object.prototype.hasOwnProperty,ge=Object.prototype.propertyIsEnumerable;var x=(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)&&x(h,g,u[g]);if(O)for(var g of O(u))ge.call(u,g)&&x(h,g,u[g]);return h},v=(h,u)=>ue(h,de(u));let u=!1;const g=[],R=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 I=Object.defineProperty,C=(o,e,t)=>e in o?I(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,c=(o,e,t)=>(C(o,typeof e!="symbol"?e+"":e,t),t);function E(o){return!(o!==o||o===1/0||o===-1/0)}function M(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 N=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},A=o=>o==="email",L=()=>({singleTag:"hr"}),U=()=>({tag:"blockquote"}),B=()=>({tag:"ul"}),H=o=>({tag:["pre",{tag:"code",attrs:o.attrs}]}),q=()=>({singleTag:"br"}),D=o=>({tag:`h${o.attrs.level}`}),J=o=>({singleTag:[{tag:"img",attrs:N(o.attrs,["src","alt","title"])}]}),F=()=>({tag:"li"}),V=()=>({tag:"ol"}),z=()=>({tag:"p"}),G=()=>({tag:"b"}),Y=()=>({tag:"strike"}),K=()=>({tag:"u"}),Q=()=>({tag:"strong"}),W=()=>({tag:"code"}),X=()=>({tag:"i"}),Z=o=>{const e=f({},o.attrs),{linktype:t="url"}=o.attrs;return A(t)&&(e.href=`mailto:${e.href}`),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),{tag:[{tag:"a",attrs:e}]}},ee=o=>({tag:[{tag:"span",attrs:o.attrs}]}),te={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:G,strike:Y,underline:K,strong:Q,code:W,italic:X,link:Z,styled:ee}},se=function(o){const e={"&":"&","<":"<",">":">",'"':""","'":"'"},t=/[&<>"']/g,s=RegExp(t.source);return o&&s.test(o)?o.replace(t,r=>e[r]):o};class k{constructor(e){c(this,"marks"),c(this,"nodes"),e||(e=te),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 ${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 y=(o=>(o.GET="get",o.DELETE="delete",o.POST="post",o.PUT="put",o))(y||{});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(y.GET)}post(e,t){return this.url=e,this.parameters=t,this._methodHandler(y.POST)}put(e,t){return this.url=e,this.parameters=t,this._methodHandler(y.PUT)}delete(e,t){return this.url=e,this.parameters=t,this._methodHandler(y.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 $;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 k(e.richTextSchema):this.richTextResolver=new k,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 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),_=>this.makeRequest(n,t,r,_+1));return this.helpers.flatMap([d,...w],_=>Object.values(_.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 j="https://app.storyblok.com/f/storyblok-v2-latest.js",S=(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&&R(j),T=new k(n.schema),n.resolver&&P(T,n.resolver),i},P=(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 k(e.schema),e.resolver&&P(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. | ||
For more info about the richtext object check https://github.com/storyblok/storyblok-js#rendering-rich-text`),"")},F=()=>_(j);h.RichTextSchema=R,h.apiPlugin=H,h.loadStoryblokBridge=F,h.registerStoryblokBridge=x,h.renderRichText=V,h.storyblokEditable=D,h.storyblokInit=J,h.useStoryblokBridge=x,Object.defineProperty(h,"__esModule",{value:!0}),h[Symbol.toStringTag]="Module"}); | ||
For more info about the richtext object check https://github.com/storyblok/storyblok-js#rendering-rich-text`),"")},ce=()=>R(j);h.apiPlugin=ne,h.loadStoryblokBridge=ce,h.registerStoryblokBridge=S,h.renderRichText=le,h.storyblokEditable=ie,h.storyblokInit=ae,h.useStoryblokBridge=S,Object.defineProperty(h,"__esModule",{value:!0}),h[Symbol.toStringTag]="Module"}); |
@@ -1,4 +0,4 @@ | ||
import { SbSDKOptions, StoryblokBridgeConfigV2, StoryData, SbInitResult, Richtext, StoryblokComponentType, SbRichTextOptions, RichtextInstance } from "./types"; | ||
export { default as RichTextSchema } from "storyblok-js-client/source/schema"; | ||
export declare const useStoryblokBridge: <T extends StoryblokComponentType<string> = any>(id: Number, cb: (newStory: StoryData<T>) => void, options?: StoryblokBridgeConfigV2) => void; | ||
import { SbSDKOptions, StoryblokBridgeConfigV2, ISbStoryData, SbInitResult, ISbRichtext, StoryblokComponentType, SbRichTextOptions } from "./types"; | ||
import { RichtextResolver } from "storyblok-js-client"; | ||
export declare const useStoryblokBridge: <T extends StoryblokComponentType<string> = any>(id: Number, cb: (newStory: ISbStoryData<T>) => void, options?: StoryblokBridgeConfigV2) => void; | ||
export { useStoryblokBridge as registerStoryblokBridge }; | ||
@@ -8,4 +8,4 @@ export { default as apiPlugin } from "./modules/api"; | ||
export declare const storyblokInit: (pluginOptions?: SbSDKOptions) => SbInitResult; | ||
export declare const renderRichText: (data: Richtext, options?: SbRichTextOptions, resolverInstance?: RichtextInstance) => string; | ||
export declare const renderRichText: (data: ISbRichtext, options?: SbRichTextOptions, resolverInstance?: RichtextResolver) => string; | ||
export declare const loadStoryblokBridge: () => Promise<unknown>; | ||
export * from "./types"; |
@@ -1,2 +0,2 @@ | ||
import StoryblokJSClient, { StoryblokConfig, StoryblokComponent } from "storyblok-js-client"; | ||
import StoryblokJSClient, { ISbConfig, ISbComponentType, ISbStoryData } from "storyblok-js-client"; | ||
export declare type StoryblokClient = StoryblokJSClient; | ||
@@ -16,8 +16,8 @@ declare global { | ||
export declare type SbBlokKeyDataTypes = string | number | object | boolean | undefined; | ||
export interface SbBlokData extends StoryblokComponent<string> { | ||
export interface SbBlokData extends ISbComponentType<string> { | ||
[index: string]: SbBlokKeyDataTypes; | ||
} | ||
export interface SbRichTextOptions { | ||
schema?: StoryblokConfig["richTextSchema"]; | ||
resolver?: StoryblokConfig["componentResolver"]; | ||
schema?: ISbConfig["richTextSchema"]; | ||
resolver?: ISbConfig["componentResolver"]; | ||
} | ||
@@ -28,5 +28,14 @@ export interface SbSDKOptions { | ||
use?: any[]; | ||
apiOptions?: StoryblokConfig; | ||
apiOptions?: ISbConfig; | ||
richText?: SbRichTextOptions; | ||
} | ||
export interface ISbEventPayload<S extends ISbComponentType<string> = any> { | ||
action: "customEvent" | "published" | "input" | "change" | "unpublished" | "enterEditmode"; | ||
event?: string; | ||
story?: ISbStoryData<S>; | ||
slug?: string; | ||
slugChanged?: boolean; | ||
storyId?: number; | ||
reload?: boolean; | ||
} | ||
export interface StoryblokBridgeConfigV2 { | ||
@@ -42,4 +51,15 @@ resolveRelations?: string[]; | ||
enterEditmode: () => void; | ||
on: (event: "customEvent" | "published" | "input" | "change" | "unpublished" | "enterEditmode" | string[], callback: (payload?: StoryblokEventPayload) => void) => void; | ||
on: (event: "customEvent" | "published" | "input" | "change" | "unpublished" | "enterEditmode" | string[], callback: (payload?: ISbEventPayload) => void) => void; | ||
} | ||
export type { StoryblokConfig, StoryblokCache, StoryblokCacheProvider, StoryblokResult, StoryblokManagmentApiResult, StoryblokComponent as StoryblokComponentType, StoryData, AlternateObject, Stories, Story, StoriesParams, StoryParams, Richtext, RichtextInstance, } from "storyblok-js-client"; | ||
export type { ISbConfig, // previously StoryblokConfig | ||
ISbCache, // previously StoryblokCache | ||
ISbResult, // previously StoryblokResult | ||
ISbResponse, ISbError, ISbNode, ISbSchema, ThrottleFn, AsyncFn, ArrayFn, ISbContentMangmntAPI, ISbManagmentApiResult, // previously StoryblokManagmentApiResult | ||
ISbStories, // previously Stories | ||
ISbStory, // previously Story | ||
ISbDimensions, ISbComponentType as StoryblokComponentType, ISbStoryData, // previously StoryData | ||
ISbAlternateObject, // previously AlternateObject | ||
ISbStoriesParams, // previously StoriesParams | ||
ISbStoryParams, // previously StoryParams | ||
ISbRichtext, // previously Richtext | ||
RichtextResolver, } from "storyblok-js-client"; |
{ | ||
"name": "@storyblok/js", | ||
"version": "1.8.6", | ||
"version": "2.0.0", | ||
"description": "SDK to integrate Storyblok into your project using JavaScript.", | ||
@@ -21,3 +21,3 @@ "main": "./dist/storyblok-js.js", | ||
"test": "npm run test:unit && npm run test:e2e", | ||
"test:unit": "jest __tests__", | ||
"test:unit": "vitest run", | ||
"test:e2e": "start-server-and-test cy:playground http-get://localhost:3000/ cy:run", | ||
@@ -31,16 +31,13 @@ "test:e2e-watch": "start-server-and-test cy:playground http-get://localhost:3000/ cy:open", | ||
"dependencies": { | ||
"storyblok-js-client": "^4.5.8" | ||
"storyblok-js-client": "^5.1.1" | ||
}, | ||
"devDependencies": { | ||
"@babel/core": "^7.19.0", | ||
"@babel/preset-env": "^7.19.0", | ||
"@tsconfig/recommended": "^1.0.1", | ||
"babel-jest": "^28.1.0", | ||
"cypress": "^9.6.1", | ||
"eslint-plugin-cypress": "^2.12.1", | ||
"eslint-plugin-jest": "^26.9.0", | ||
"jest": "^28.1.3", | ||
"jest-console": "^0.1.0", | ||
"isomorphic-fetch": "^3.0.0", | ||
"start-server-and-test": "^1.14.0", | ||
"vite": "^2.9.15" | ||
"vite": "^2.9.15", | ||
"vitest": "^0.25.3" | ||
}, | ||
@@ -47,0 +44,0 @@ "babel": { |
@@ -48,2 +48,4 @@ <div align="center"> | ||
> â ī¸ This SDK uses the Fetch API under the hood. If your environment doesn't support it, you need to install a polyfill like [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch). More info on [storyblok-js-client docs](https://github.com/storyblok/storyblok-js-client#fetch-use-polyfill-if-needed---version-5). | ||
#### From a CDN | ||
@@ -67,2 +69,6 @@ | ||
use: [apiPlugin], | ||
// if you are using a space located in US region, use apiOptions.region: | ||
// apiOptions: { | ||
// region: "us" // region code here | ||
// } | ||
}); | ||
@@ -69,0 +75,0 @@ ``` |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
8
0
271
55451
849
2
+ Addedstoryblok-js-client@5.14.4(transitive)
- Removedasynckit@0.4.0(transitive)
- Removedaxios@0.27.2(transitive)
- Removedcombined-stream@1.0.8(transitive)
- Removeddelayed-stream@1.0.0(transitive)
- Removedfollow-redirects@1.15.9(transitive)
- Removedform-data@4.0.1(transitive)
- Removedmime-db@1.52.0(transitive)
- Removedmime-types@2.1.35(transitive)
- Removedstoryblok-js-client@4.5.8(transitive)
Updatedstoryblok-js-client@^5.1.1