@storyblok/astro
Advanced tools
Comparing version 1.0.1 to 1.1.0
@@ -1,8 +0,8 @@ | ||
(function(h,g){typeof exports=="object"&&typeof module<"u"?g(exports,require("axios")):typeof define=="function"&&define.amd?define(["exports","axios"],g):(h=typeof globalThis<"u"?globalThis:h||self,g(h.storyblokAstro={},h.axios))})(this,function(h,g){"use strict";const x=(n=>n&&typeof n=="object"&&"default"in n?n:{default:n})(g);function A(n){const e="virtual:storyblok-components",t="\0"+e;return{name:"vite-plugin-storyblok",async resolveId(r){if(r===e)return t},async load(r){if(r===t){const s=[];for await(const[o,a]of Object.entries(n)){const{id:i}=await this.resolve("/src/"+a+".astro");s.push(`import ${o} from "${i}"`)}return`${s.join(";")};export default {${Object.keys(n).join(",")}}`}}}}var P=Object.defineProperty,M=Object.defineProperties,C=Object.getOwnPropertyDescriptors,v=Object.getOwnPropertySymbols,I=Object.prototype.hasOwnProperty,N=Object.prototype.propertyIsEnumerable,T=(n,e,t)=>e in n?P(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,d=(n,e)=>{for(var t in e||(e={}))I.call(e,t)&&T(n,t,e[t]);if(v)for(var t of v(e))N.call(e,t)&&T(n,t,e[t]);return n},m=(n,e)=>M(n,C(e));let _=!1;const w=[],R=n=>new Promise((e,t)=>{if(typeof window>"u"||(window.storyblokRegisterEvent=s=>{if(window.location===window.parent.location){console.warn("You are not in Draft Mode or in the Visual Editor.");return}_?s():w.push(s)},document.getElementById("storyblok-javascript-bridge")))return;const r=document.createElement("script");r.async=!0,r.src=n,r.id="storyblok-javascript-bridge",r.onerror=s=>t(s),r.onload=s=>{w.forEach(o=>o()),_=!0,e(s)},document.getElementsByTagName("head")[0].appendChild(r)}),q=function(n,e){if(!n)return null;let t={};for(let r in n){let s=n[r];e.indexOf(r)>-1&&s!==null&&(t[r]=s)}return t},L=n=>n==="email";var B={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:q(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 e=d({},n.attrs),{linktype:t="url"}=n.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}]}},styled(n){return{tag:[{tag:"span",attrs:n.attrs}]}}}};const z=function(n){const e={"&":"&","<":"<",">":">",'"':""","'":"'"},t=/[&<>"']/g,r=RegExp(t.source);return n&&r.test(n)?n.replace(t,s=>e[s]):n};class ${constructor(e){e||(e=B),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.content&&Array.isArray(e.content)){let t="";return e.content.forEach(r=>{t+=this.renderNode(r)}),t}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(e){let t=[];e.marks&&e.marks.forEach(s=>{const o=this.getMatchingMark(s);o&&t.push(this.renderOpeningTag(o.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(z(e.text)):r&&r.singleTag?t.push(this.renderTag(r.singleTag," /")):r&&r.html&&t.push(r.html),r&&r.tag&&t.push(this.renderClosingTag(r.tag)),e.marks&&e.marks.slice(0).reverse().forEach(s=>{const o=this.getMatchingMark(s);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 o=`<${s.tag}`;if(s.attrs)for(let a in s.attrs){let i=s.attrs[a];i!==null&&(o+=` ${a}="${i}"`)}return`${o}${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){if(typeof this.nodes[e.type]=="function")return this.nodes[e.type](e)}getMatchingMark(e){if(typeof this.marks[e.type]=="function")return this.marks[e.type](e)}}/*! | ||
(function(h,g){typeof exports=="object"&&typeof module<"u"?g(exports,require("axios")):typeof define=="function"&&define.amd?define(["exports","axios"],g):(h=typeof globalThis<"u"?globalThis:h||self,g(h.storyblokAstro={},h.axios))})(this,function(h,g){"use strict";const A=(n=>n&&typeof n=="object"&&"default"in n?n:{default:n})(g);function P(n){const e="virtual:storyblok-components",t="\0"+e;return{name:"vite-plugin-storyblok",async resolveId(r){if(r===e)return t},async load(r){if(r===t){const s=[];for await(const[o,a]of Object.entries(n)){const{id:i}=await this.resolve("/src/"+a+".astro");s.push(`import ${o} from "${i}"`)}return`${s.join(";")};export default {${Object.keys(n).join(",")}}`}}}}var M=Object.defineProperty,I=Object.defineProperties,C=Object.getOwnPropertyDescriptors,v=Object.getOwnPropertySymbols,N=Object.prototype.hasOwnProperty,q=Object.prototype.propertyIsEnumerable,T=(n,e,t)=>e in n?M(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,d=(n,e)=>{for(var t in e||(e={}))N.call(e,t)&&T(n,t,e[t]);if(v)for(var t of v(e))q.call(e,t)&&T(n,t,e[t]);return n},k=(n,e)=>I(n,C(e));let _=!1;const w=[],R=n=>new Promise((e,t)=>{if(typeof window>"u"||(window.storyblokRegisterEvent=s=>{if(window.location===window.parent.location){console.warn("You are not in Draft Mode or in the Visual Editor.");return}_?s():w.push(s)},document.getElementById("storyblok-javascript-bridge")))return;const r=document.createElement("script");r.async=!0,r.src=n,r.id="storyblok-javascript-bridge",r.onerror=s=>t(s),r.onload=s=>{w.forEach(o=>o()),_=!0,e(s)},document.getElementsByTagName("head")[0].appendChild(r)}),L=function(n,e){if(!n)return null;let t={};for(let r in n){let s=n[r];e.indexOf(r)>-1&&s!==null&&(t[r]=s)}return t},B=n=>n==="email";var $={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:L(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 e=d({},n.attrs),{linktype:t="url"}=n.attrs;return B(t)&&(e.href=`mailto:${e.href}`),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),{tag:[{tag:"a",attrs:e}]}},styled(n){return{tag:[{tag:"span",attrs:n.attrs}]}}}};const z=function(n){const e={"&":"&","<":"<",">":">",'"':""","'":"'"},t=/[&<>"']/g,r=RegExp(t.source);return n&&r.test(n)?n.replace(t,s=>e[s]):n};class O{constructor(e){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.content&&Array.isArray(e.content)){let t="";return e.content.forEach(r=>{t+=this.renderNode(r)}),t}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(e){let t=[];e.marks&&e.marks.forEach(s=>{const o=this.getMatchingMark(s);o&&t.push(this.renderOpeningTag(o.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(z(e.text)):r&&r.singleTag?t.push(this.renderTag(r.singleTag," /")):r&&r.html&&t.push(r.html),r&&r.tag&&t.push(this.renderClosingTag(r.tag)),e.marks&&e.marks.slice(0).reverse().forEach(s=>{const o=this.getMatchingMark(s);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 o=`<${s.tag}`;if(s.attrs)for(let a in s.attrs){let i=s.attrs[a];i!==null&&(o+=` ${a}="${i}"`)}return`${o}${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){if(typeof this.nodes[e.type]=="function")return this.nodes[e.type](e)}getMatchingMark(e){if(typeof this.marks[e.type]=="function")return this.marks[e.type](e)}}/*! | ||
* storyblok-js-client v4.5.2 | ||
* Universal JavaScript SDK for Storyblok's API | ||
* (c) 2020-2022 Stobylok Team | ||
*/function O(n){return typeof n=="number"&&n==n&&n!==1/0&&n!==-1/0}function E(n,e,t){if(!O(e))throw new TypeError("Expected `limit` to be a finite number");if(!O(t))throw new TypeError("Expected `interval` to be a finite number");var r=[],s=[],o=0,a=function(){o++;var c=setTimeout(function(){o--,r.length>0&&a(),s=s.filter(function(u){return u!==c})},t);s.indexOf(c)<0&&s.push(c);var l=r.shift();l.resolve(n.apply(l.self,l.args))},i=function(){var c=arguments,l=this;return new Promise(function(u,f){r.push({resolve:u,reject:f,args:c,self:l}),o<e&&a()})};return i.abort=function(){s.forEach(clearTimeout),s=[],r.forEach(function(c){c.reject(new throttle.AbortError)}),r.length=0},i}E.AbortError=function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"};const U=function(n,e){if(!n)return null;let t={};for(let r in n){let s=n[r];e.indexOf(r)>-1&&s!==null&&(t[r]=s)}return t};var D={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:U(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 e=d({},n.attrs),{linktype:t="url"}=n.attrs;return t==="email"&&(e.href=`mailto:${e.href}`),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),{tag:[{tag:"a",attrs:e}]}},styled:n=>({tag:[{tag:"span",attrs:n.attrs}]})}};class H{constructor(e){e||(e=D),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.content&&Array.isArray(e.content)){let t="";return e.content.forEach(r=>{t+=this.renderNode(r)}),t}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(e){let t=[];e.marks&&e.marks.forEach(s=>{const o=this.getMatchingMark(s);o&&t.push(this.renderOpeningTag(o.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(function(s){const o={"&":"&","<":"<",">":">",'"':""","'":"'"},a=/[&<>"']/g,i=RegExp(a.source);return s&&i.test(s)?s.replace(a,c=>o[c]):s}(e.text)):r&&r.singleTag?t.push(this.renderTag(r.singleTag," /")):r&&r.html&&t.push(r.html),r&&r.tag&&t.push(this.renderClosingTag(r.tag)),e.marks&&e.marks.slice(0).reverse().forEach(s=>{const o=this.getMatchingMark(s);o&&t.push(this.renderClosingTag(o.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(r=>{if(r.constructor===String)return`<${r}${t}>`;{let s=`<${r.tag}`;if(r.attrs)for(let o in r.attrs){let a=r.attrs[o];a!==null&&(s+=` ${o}="${a}"`)}return`${s}${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){if(typeof this.nodes[e.type]=="function")return this.nodes[e.type](e)}getMatchingMark(e){if(typeof this.marks[e.type]=="function")return this.marks[e.type](e)}}const V=(n=0,e=n)=>{const t=Math.abs(e-n)||0,r=n<e?1:-1;return((s=0,o)=>[...Array(s)].map(o))(t,(s,o)=>o*r+n)},b=(n,e,t)=>{const r=[];for(const s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;const o=n[s],a=t?"":encodeURIComponent(s);let i;i=typeof o=="object"?b(o,e?e+encodeURIComponent("["+a+"]"):a,Array.isArray(o)):(e?e+encodeURIComponent("["+a+"]"):a)+"="+encodeURIComponent(o),r.push(i)}return r.join("&")};let y={},p={};class J{constructor(e,t){if(!t){let o=e.region?`-${e.region}`:"",a=e.https===!1?"http":"https";t=e.oauthToken===void 0?`${a}://api${o}.storyblok.com/v2`:`${a}://api${o}.storyblok.com/v1`}let r=Object.assign({},e.headers),s=5;e.oauthToken!==void 0&&(r.Authorization=e.oauthToken,s=3),e.rateLimit!==void 0&&(s=e.rateLimit),this.richTextResolver=new H(e.richTextSchema),typeof e.componentResolver=="function"&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||5,this.throttle=E(this.throttledRequest,s,1e3),this.accessToken=e.accessToken,this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.client=x.default.create({baseURL:t,timeout:e.timeout||0,headers:r,proxy:e.proxy||!1}),e.responseInterceptor&&this.client.interceptors.response.use(o=>e.responseInterceptor(o)),this.resolveNestedRelations=e.resolveNestedRelations||!0}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let r="";return t.attrs.body.forEach(s=>{r+=e(s.component,s)}),{html:r}})}parseParams(e={}){return e.version||(e.version="published"),e.token||(e.token=this.getToken()),e.cv||(e.cv=p[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),e}factoryParamOptions(e,t={}){return((r="")=>r.indexOf("/cdn/")>-1)(e)?this.parseParams(t):t}makeRequest(e,t,r,s){const o=this.factoryParamOptions(e,((a={},i=25,c=1)=>m(d({},a),{per_page:i,page:c}))(t,r,s));return this.cacheResponse(e,o)}get(e,t){let r=`/${e}`;const s=this.factoryParamOptions(r,t);return this.cacheResponse(r,s)}async getAll(e,t={},r){const s=t.per_page||25,o=`/${e}`,a=o.split("/");r=r||a[a.length-1];const i=await this.makeRequest(o,t,s,1),c=Math.ceil(i.total/s);return((l=[],u)=>l.map(u).reduce((f,ee)=>[...f,...ee],[]))([i,...await(async(l=[],u)=>Promise.all(l.map(u)))(V(1,c),async l=>this.makeRequest(o,t,s,l+1))],l=>Object.values(l.data[r]))}post(e,t){let r=`/${e}`;return this.throttle("post",r,t)}put(e,t){let r=`/${e}`;return this.throttle("put",r,t)}delete(e,t){let r=`/${e}`;return this.throttle("delete",r,t)}getStories(e){return this.get("cdn/stories",e)}getStory(e,t){return this.get(`cdn/stories/${e}`,t)}setToken(e){this.accessToken=e}getToken(){return this.accessToken}_cleanCopy(e){return JSON.parse(JSON.stringify(e))}_insertLinks(e,t){const r=e[t];r&&r.fieldtype=="multilink"&&r.linktype=="story"&&typeof r.id=="string"&&this.links[r.id]?r.story=this._cleanCopy(this.links[r.id]):r&&r.linktype==="story"&&typeof r.uuid=="string"&&this.links[r.uuid]&&(r.story=this._cleanCopy(this.links[r.uuid]))}_insertRelations(e,t,r){if(r.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].constructor===Array){let s=[];e[t].forEach(o=>{this.relations[o]&&s.push(this._cleanCopy(this.relations[o]))}),e[t]=s}}}_insertAssetsRelations(e,t){t.forEach(r=>{e.id===r.id&&(e.original=r,e.original.filename=e.filename,e.original.filename=e.original.filename.includes("https://s3.amazonaws.com/")?e.original.filename:e.original.filename.replace("https://","https://s3.amazonaws.com/"),delete e.original.s3_filename)})}iterateTree(e,t){let r=s=>{if(s!=null){if(s.constructor===Array)for(let o=0;o<s.length;o++)r(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,t),this._insertLinks(s,o)):"id"in s&&s.fieldtype==="asset"&&this._insertAssetsRelations(s,t),r(s[o])}}};r(e.content)}async resolveLinks(e,t){let r=[];if(e.link_uuids){const s=e.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(e.link_uuids.slice(i,c))}for(let i=0;i<o.length;i++)(await this.getStories({per_page:a,language:t.language,version:t.version,by_uuids:o[i].join(",")})).data.stories.forEach(c=>{r.push(c)})}else r=e.links;r.forEach(s=>{this.links[s.uuid]=m(d({},s),{_stopResolving:!0})})}async resolveRelations(e,t){let r=[];if(e.rel_uuids){const s=e.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(e.rel_uuids.slice(i,c))}for(let i=0;i<o.length;i++)(await this.getStories({per_page:a,language:t.language,version:t.version,by_uuids:o[i].join(",")})).data.stories.forEach(c=>{r.push(c)})}else r=e.rels;r.forEach(s=>{this.relations[s.uuid]=m(d({},s),{_stopResolving:!0})})}async resolveStories(e,t){let r=[];if(t.resolve_relations!==void 0&&t.resolve_relations.length>0&&(e.rels||e.rel_uuids)&&(r=t.resolve_relations.split(","),await this.resolveRelations(e,t)),["1","story","url"].indexOf(t.resolve_links)>-1&&(e.links||e.link_uuids)&&await this.resolveLinks(e,t),this.resolveNestedRelations)for(const s in this.relations)this.iterateTree(this.relations[s],r);e.story?this.iterateTree(e.story,r):e.stories.forEach(s=>{this.iterateTree(s,r)})}resolveAssetsRelations(e){const{assets:t,stories:r,story:s}=e;if(r)for(const o of r)this.iterateTree(o,t);else{if(!s)return e;this.iterateTree(s,t)}}cacheResponse(e,t,r){return r===void 0&&(r=0),new Promise(async(s,o)=>{let a=b({url:e,params:t}),i=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&await this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const l=await i.get(a);if(l)return s(l)}try{let l=await this.throttle("get",e,{params:t,paramsSerializer:f=>b(f)}),u={data:l.data,headers:l.headers};if(u.data.assets&&u.data.assets.length&&this.resolveAssetsRelations(u.data),l.headers["per-page"]&&(u=Object.assign({},u,{perPage:parseInt(l.headers["per-page"]),total:parseInt(l.headers.total)})),l.status!=200)return o(l);(u.data.story||u.data.stories)&&await this.resolveStories(u.data,t),t.version==="published"&&e!="/cdn/spaces/me"&&i.set(a,u),u.data.cv&&(t.version=="draft"&&p[t.token]!=u.data.cv&&this.flushCache(),p[t.token]=u.data.cv),s(u)}catch(l){if(l.response&&l.response.status===429&&(r+=1)<this.maxRetries)return console.log(`Hit rate limit. Retrying in ${r} seconds.`),await(c=1e3*r,new Promise(u=>setTimeout(u,c))),this.cacheResponse(e,t,r).then(s).catch(o);o(l)}var c})}throttledRequest(e,t,r){return this.client[e](t,r)}cacheVersions(){return p}cacheVersion(){return p[this.accessToken]}setCacheVersion(e){this.accessToken&&(p[this.accessToken]=e)}cacheProvider(){return this.cache.type==="memory"?{get:e=>y[e],getAll:()=>y,set(e,t){y[e]=t},flush(){y={}}}:{get(){},getAll(){},set(){},flush(){}}}async flushCache(){return await this.cacheProvider().flush(),this}}const F=(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 J(e)}};var Y=n=>{if(typeof n!="object"||typeof n._editable>"u")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 k;const j="https://app.storyblok.com/f/storyblok-v2-latest.js",K=(n={})=>{const{bridge:e,accessToken:t,use:r=[],apiOptions:s={},richText:o={}}=n;s.accessToken=s.accessToken||t;const a={bridge:e,apiOptions:s};let i={};return r.forEach(c=>{i=d(d({},i),c(a))}),e!==!1&&R(j),k=new $(o.schema),o.resolver&&S(k,o.resolver),i},S=(n,e)=>{n.addNode("blok",t=>{let r="";return t.attrs.body.forEach(s=>{r+=e(s.component,s)}),{html:r}})},G=(n,e)=>{if(!k){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}if(n==="")return"";if(!n)return console.warn(`${n} is not a valid Richtext object. This might be because the value of the richtext field is empty. | ||
*/function E(n){return typeof n=="number"&&n==n&&n!==1/0&&n!==-1/0}function S(n,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");var r=[],s=[],o=0,a=function(){o++;var c=setTimeout(function(){o--,r.length>0&&a(),s=s.filter(function(u){return u!==c})},t);s.indexOf(c)<0&&s.push(c);var l=r.shift();l.resolve(n.apply(l.self,l.args))},i=function(){var c=arguments,l=this;return new Promise(function(u,f){r.push({resolve:u,reject:f,args:c,self:l}),o<e&&a()})};return i.abort=function(){s.forEach(clearTimeout),s=[],r.forEach(function(c){c.reject(new throttle.AbortError)}),r.length=0},i}S.AbortError=function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"};const D=function(n,e){if(!n)return null;let t={};for(let r in n){let s=n[r];e.indexOf(r)>-1&&s!==null&&(t[r]=s)}return t};var U={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:D(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 e=d({},n.attrs),{linktype:t="url"}=n.attrs;return t==="email"&&(e.href=`mailto:${e.href}`),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),{tag:[{tag:"a",attrs:e}]}},styled:n=>({tag:[{tag:"span",attrs:n.attrs}]})}};class H{constructor(e){e||(e=U),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.content&&Array.isArray(e.content)){let t="";return e.content.forEach(r=>{t+=this.renderNode(r)}),t}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(e){let t=[];e.marks&&e.marks.forEach(s=>{const o=this.getMatchingMark(s);o&&t.push(this.renderOpeningTag(o.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(function(s){const o={"&":"&","<":"<",">":">",'"':""","'":"'"},a=/[&<>"']/g,i=RegExp(a.source);return s&&i.test(s)?s.replace(a,c=>o[c]):s}(e.text)):r&&r.singleTag?t.push(this.renderTag(r.singleTag," /")):r&&r.html&&t.push(r.html),r&&r.tag&&t.push(this.renderClosingTag(r.tag)),e.marks&&e.marks.slice(0).reverse().forEach(s=>{const o=this.getMatchingMark(s);o&&t.push(this.renderClosingTag(o.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(r=>{if(r.constructor===String)return`<${r}${t}>`;{let s=`<${r.tag}`;if(r.attrs)for(let o in r.attrs){let a=r.attrs[o];a!==null&&(s+=` ${o}="${a}"`)}return`${s}${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){if(typeof this.nodes[e.type]=="function")return this.nodes[e.type](e)}getMatchingMark(e){if(typeof this.marks[e.type]=="function")return this.marks[e.type](e)}}const V=(n=0,e=n)=>{const t=Math.abs(e-n)||0,r=n<e?1:-1;return((s=0,o)=>[...Array(s)].map(o))(t,(s,o)=>o*r+n)},m=(n,e,t)=>{const r=[];for(const s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;const o=n[s],a=t?"":encodeURIComponent(s);let i;i=typeof o=="object"?m(o,e?e+encodeURIComponent("["+a+"]"):a,Array.isArray(o)):(e?e+encodeURIComponent("["+a+"]"):a)+"="+encodeURIComponent(o),r.push(i)}return r.join("&")};let y={},p={};class J{constructor(e,t){if(!t){let o=e.region?`-${e.region}`:"",a=e.https===!1?"http":"https";t=e.oauthToken===void 0?`${a}://api${o}.storyblok.com/v2`:`${a}://api${o}.storyblok.com/v1`}let r=Object.assign({},e.headers),s=5;e.oauthToken!==void 0&&(r.Authorization=e.oauthToken,s=3),e.rateLimit!==void 0&&(s=e.rateLimit),this.richTextResolver=new H(e.richTextSchema),typeof e.componentResolver=="function"&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||5,this.throttle=S(this.throttledRequest,s,1e3),this.accessToken=e.accessToken,this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.client=A.default.create({baseURL:t,timeout:e.timeout||0,headers:r,proxy:e.proxy||!1}),e.responseInterceptor&&this.client.interceptors.response.use(o=>e.responseInterceptor(o)),this.resolveNestedRelations=e.resolveNestedRelations||!0}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let r="";return t.attrs.body.forEach(s=>{r+=e(s.component,s)}),{html:r}})}parseParams(e={}){return e.version||(e.version="published"),e.token||(e.token=this.getToken()),e.cv||(e.cv=p[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),e}factoryParamOptions(e,t={}){return((r="")=>r.indexOf("/cdn/")>-1)(e)?this.parseParams(t):t}makeRequest(e,t,r,s){const o=this.factoryParamOptions(e,((a={},i=25,c=1)=>k(d({},a),{per_page:i,page:c}))(t,r,s));return this.cacheResponse(e,o)}get(e,t){let r=`/${e}`;const s=this.factoryParamOptions(r,t);return this.cacheResponse(r,s)}async getAll(e,t={},r){const s=t.per_page||25,o=`/${e}`,a=o.split("/");r=r||a[a.length-1];const i=await this.makeRequest(o,t,s,1),c=Math.ceil(i.total/s);return((l=[],u)=>l.map(u).reduce((f,te)=>[...f,...te],[]))([i,...await(async(l=[],u)=>Promise.all(l.map(u)))(V(1,c),async l=>this.makeRequest(o,t,s,l+1))],l=>Object.values(l.data[r]))}post(e,t){let r=`/${e}`;return this.throttle("post",r,t)}put(e,t){let r=`/${e}`;return this.throttle("put",r,t)}delete(e,t){let r=`/${e}`;return this.throttle("delete",r,t)}getStories(e){return this.get("cdn/stories",e)}getStory(e,t){return this.get(`cdn/stories/${e}`,t)}setToken(e){this.accessToken=e}getToken(){return this.accessToken}_cleanCopy(e){return JSON.parse(JSON.stringify(e))}_insertLinks(e,t){const r=e[t];r&&r.fieldtype=="multilink"&&r.linktype=="story"&&typeof r.id=="string"&&this.links[r.id]?r.story=this._cleanCopy(this.links[r.id]):r&&r.linktype==="story"&&typeof r.uuid=="string"&&this.links[r.uuid]&&(r.story=this._cleanCopy(this.links[r.uuid]))}_insertRelations(e,t,r){if(r.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].constructor===Array){let s=[];e[t].forEach(o=>{this.relations[o]&&s.push(this._cleanCopy(this.relations[o]))}),e[t]=s}}}_insertAssetsRelations(e,t){t.forEach(r=>{e.id===r.id&&(e.original=r,e.original.filename=e.filename,e.original.filename=e.original.filename.includes("https://s3.amazonaws.com/")?e.original.filename:e.original.filename.replace("https://","https://s3.amazonaws.com/"),delete e.original.s3_filename)})}iterateTree(e,t){let r=s=>{if(s!=null){if(s.constructor===Array)for(let o=0;o<s.length;o++)r(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,t),this._insertLinks(s,o)):"id"in s&&s.fieldtype==="asset"&&this._insertAssetsRelations(s,t),r(s[o])}}};r(e.content)}async resolveLinks(e,t){let r=[];if(e.link_uuids){const s=e.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(e.link_uuids.slice(i,c))}for(let i=0;i<o.length;i++)(await this.getStories({per_page:a,language:t.language,version:t.version,by_uuids:o[i].join(",")})).data.stories.forEach(c=>{r.push(c)})}else r=e.links;r.forEach(s=>{this.links[s.uuid]=k(d({},s),{_stopResolving:!0})})}async resolveRelations(e,t){let r=[];if(e.rel_uuids){const s=e.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(e.rel_uuids.slice(i,c))}for(let i=0;i<o.length;i++)(await this.getStories({per_page:a,language:t.language,version:t.version,by_uuids:o[i].join(",")})).data.stories.forEach(c=>{r.push(c)})}else r=e.rels;r.forEach(s=>{this.relations[s.uuid]=k(d({},s),{_stopResolving:!0})})}async resolveStories(e,t){let r=[];if(t.resolve_relations!==void 0&&t.resolve_relations.length>0&&(e.rels||e.rel_uuids)&&(r=t.resolve_relations.split(","),await this.resolveRelations(e,t)),["1","story","url"].indexOf(t.resolve_links)>-1&&(e.links||e.link_uuids)&&await this.resolveLinks(e,t),this.resolveNestedRelations)for(const s in this.relations)this.iterateTree(this.relations[s],r);e.story?this.iterateTree(e.story,r):e.stories.forEach(s=>{this.iterateTree(s,r)})}resolveAssetsRelations(e){const{assets:t,stories:r,story:s}=e;if(r)for(const o of r)this.iterateTree(o,t);else{if(!s)return e;this.iterateTree(s,t)}}cacheResponse(e,t,r){return r===void 0&&(r=0),new Promise(async(s,o)=>{let a=m({url:e,params:t}),i=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&await this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const l=await i.get(a);if(l)return s(l)}try{let l=await this.throttle("get",e,{params:t,paramsSerializer:f=>m(f)}),u={data:l.data,headers:l.headers};if(u.data.assets&&u.data.assets.length&&this.resolveAssetsRelations(u.data),l.headers["per-page"]&&(u=Object.assign({},u,{perPage:parseInt(l.headers["per-page"]),total:parseInt(l.headers.total)})),l.status!=200)return o(l);(u.data.story||u.data.stories)&&await this.resolveStories(u.data,t),t.version==="published"&&e!="/cdn/spaces/me"&&i.set(a,u),u.data.cv&&(t.version=="draft"&&p[t.token]!=u.data.cv&&this.flushCache(),p[t.token]=u.data.cv),s(u)}catch(l){if(l.response&&l.response.status===429&&(r+=1)<this.maxRetries)return console.log(`Hit rate limit. Retrying in ${r} seconds.`),await(c=1e3*r,new Promise(u=>setTimeout(u,c))),this.cacheResponse(e,t,r).then(s).catch(o);o(l)}var c})}throttledRequest(e,t,r){return this.client[e](t,r)}cacheVersions(){return p}cacheVersion(){return p[this.accessToken]}setCacheVersion(e){this.accessToken&&(p[this.accessToken]=e)}cacheProvider(){return this.cache.type==="memory"?{get:e=>y[e],getAll:()=>y,set(e,t){y[e]=t},flush(){y={}}}:{get(){},getAll(){},set(){},flush(){}}}async flushCache(){return await this.cacheProvider().flush(),this}}const F=(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 J(e)}};var K=n=>{if(typeof n!="object"||typeof n._editable>"u")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 b;const j="https://app.storyblok.com/f/storyblok-v2-latest.js",Y=(n={})=>{const{bridge:e,accessToken:t,use:r=[],apiOptions:s={},richText:o={}}=n;s.accessToken=s.accessToken||t;const a={bridge:e,apiOptions:s};let i={};return r.forEach(c=>{i=d(d({},i),c(a))}),e!==!1&&R(j),b=new O(o.schema),o.resolver&&x(b,o.resolver),i},x=(n,e)=>{n.addNode("blok",t=>{let r="";return t.attrs.body.forEach(s=>{r+=e(s.component,s)}),{html:r}})},G=(n,e,t)=>{let r=t||b;if(!r){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return n===""?"":n?(e&&(r=new O(e.schema),e.resolver&&x(r,e.resolver)),r.render(n)):(console.warn(`${n} 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`),"";let t=k;return e&&(t=new $(e.schema),e.resolver&&S(t,e.resolver)),t.render(n)},Q=()=>R(j);function W(n,e,t){const{storyblokApi:r}=K({accessToken:n,use:e||[F],apiOptions:{...t}});globalThis.storyblokApiInstance=r}function X(){return globalThis.storyblokApiInstance||console.error("storyblokApiInstance has not been initialized correctly"),globalThis.storyblokApiInstance}function Z(n){return{name:"@storyblok/astro",hooks:{"astro:config:setup":({injectScript:e,updateConfig:t})=>{t({vite:{plugins:[A(n.components)]}}),W(n.accessToken,n.use,n.apiOptions),(n.bridge||!0)&&e("page",` | ||
For more info about the richtext object check https://github.com/storyblok/storyblok-js#rendering-rich-text`),"")},Q=()=>R(j);function W(n,e,t){const{storyblokApi:r}=Y({accessToken:n,use:e||[F],apiOptions:{...t}});globalThis.storyblokApiInstance=r}function X(){return globalThis.storyblokApiInstance||console.error("storyblokApiInstance has not been initialized correctly"),globalThis.storyblokApiInstance}function Z(n,e){const t=globalThis.storyblokApiInstance.richTextResolver;if(!t){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return G(n,e,t)}function ee(n){return{name:"@storyblok/astro",hooks:{"astro:config:setup":({injectScript:e,updateConfig:t})=>{var s;t({vite:{plugins:[P(n.components)]}}),W(n.accessToken,n.use,n.apiOptions),((s=n.bridge)!=null?s:!0)&&e("page",` | ||
import { loadStoryblokBridge } from "@storyblok/astro"; | ||
@@ -19,2 +19,2 @@ loadStoryblokBridge().then(() => { | ||
}); | ||
`)}}}}h.default=Z,h.loadStoryblokBridge=Q,h.renderRichText=G,h.storyblokEditable=Y,h.useStoryblokApi=X,Object.defineProperties(h,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}); | ||
`)}}}}h.RichTextSchema=$,h.default=ee,h.loadStoryblokBridge=Q,h.renderRichText=Z,h.storyblokEditable=K,h.useStoryblokApi=X,Object.defineProperties(h,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}); |
{ | ||
"name": "@storyblok/astro", | ||
"version": "1.0.1", | ||
"version": "1.1.0", | ||
"description": "UPDATE DESCRIPTION", | ||
@@ -30,3 +30,3 @@ "main": "./dist/storyblok-astro.js", | ||
"dependencies": { | ||
"@storyblok/js": "^1.8.3" | ||
"@storyblok/js": "^1.8.5" | ||
}, | ||
@@ -33,0 +33,0 @@ "devDependencies": { |
<div align="center"> | ||
<a href="https://www.storyblok.com?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-astro" align="center"> | ||
<img src="https://a.storyblok.com/f/88751/600x200/cc68aca8ea/storyblok-astro.jpg" width="300" height="100" alt="Storyblok + Astro"> | ||
<img src="https://a.storyblok.com/f/88751/1500x500/7974d6bc34/storyblok-astro.png" width="300" height="100" alt="Storyblok + Astro"> | ||
</a> | ||
@@ -64,3 +64,3 @@ <h1 align="center">@storyblok/astro</h1> | ||
When you initialize the module, you can pass all [_@storyblok/js_ options](https://github.com/storyblok/storyblok-js#features-and-api) | ||
When you initialize the module, you can pass all [_@storyblok/js_ options](https://github.com/storyblok/storyblok-js#features-and-api). For Spaces created in the United States, you have to set the `region` parameter accordingly `{ apiOptions: { region: 'us' } }`. | ||
@@ -230,2 +230,28 @@ ```js | ||
You can also set a **custom Schema and component resolver** by passing the options as the second parameter of the `renderRichText` function: | ||
```js | ||
import { RichTextSchema, renderRichText } from "@storyblok/astro"; | ||
import cloneDeep from "clone-deep"; | ||
const mySchema = cloneDeep(RichTextSchema); // you can make a copy of the default RichTextSchema | ||
// ... and edit the nodes and marks, or add your own. | ||
// Check the base RichTextSchema source here https://github.com/storyblok/storyblok-js-client/blob/master/source/schema.js | ||
const { blok } = Astro.props | ||
const renderedRichText = renderRichText(blok.text, { | ||
schema: mySchema, | ||
resolver: (component, blok) => { | ||
switch (component) { | ||
case "my-custom-component": | ||
return `<div class="my-component-class">${blok.text}</div>`; | ||
break; | ||
default: | ||
return `Component ${component} not found`; | ||
} | ||
}, | ||
}); | ||
``` | ||
## API | ||
@@ -232,0 +258,0 @@ |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
53730
775
281
Updated@storyblok/js@^1.8.5