@storyblok/js 3.1.9 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +35 -36
- package/dist/{types/modules/api.d.ts → api.d.ts} +1 -1
- package/dist/editable.d.ts +9 -0
- package/dist/index.d.ts +18 -0
- package/dist/{storyblok-js.mjs → storyblok-js.es.js} +429 -378
- package/dist/storyblok-js.umd.js +30 -0
- package/dist/types/index.d.ts +64 -13
- package/package.json +43 -59
- package/dist/storyblok-js.js +0 -24
- package/dist/types/modules/editable.d.ts +0 -9
- package/dist/types/types.d.ts +0 -63
- /package/dist/{types/modules/bridge.d.ts → bridge.d.ts} +0 -0
@@ -0,0 +1,30 @@
|
|
1
|
+
/**
|
2
|
+
* name: @storyblok/js
|
3
|
+
* (c) 2024
|
4
|
+
* description: SDK to integrate Storyblok into your project using JavaScript.
|
5
|
+
* author: undefined
|
6
|
+
*/
|
7
|
+
(function(y,I){typeof exports=="object"&&typeof module<"u"?I(exports):typeof define=="function"&&define.amd?define(["exports"],I):(y=typeof globalThis<"u"?globalThis:y||self,I(y.storyblok={}))})(this,function(y){"use strict";let I=!1;const B=[],D=i=>new Promise((e,t)=>{if(typeof window>"u"||(window.storyblokRegisterEvent=r=>{if(window.location===window.parent.location){console.warn("You are not in Draft Mode or in the Visual Editor.");return}I?r():B.push(r)},document.getElementById("storyblok-javascript-bridge")))return;const s=document.createElement("script");s.async=!0,s.src=i,s.id="storyblok-javascript-bridge",s.onerror=r=>t(r),s.onload=r=>{B.forEach(o=>o()),I=!0,e(r)},document.getElementsByTagName("head")[0].appendChild(s)});var X=Object.defineProperty,Q=(i,e,t)=>e in i?X(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,p=(i,e,t)=>Q(i,typeof e!="symbol"?e+"":e,t);class Z extends Error{constructor(e){super(e),this.name="AbortError"}}function ee(i,e,t){if(!Number.isFinite(e))throw new TypeError("Expected `limit` to be a finite number");if(!Number.isFinite(t))throw new TypeError("Expected `interval` to be a finite number");const s=[];let r=[],o=0,n=!1;const l=async()=>{o++;const c=s.shift();if(c)try{const d=await i(...c.args);c.resolve(d)}catch(d){c.reject(d)}const u=setTimeout(()=>{o--,s.length>0&&l(),r=r.filter(d=>d!==u)},t);r.includes(u)||r.push(u)},a=(...c)=>n?Promise.reject(new Error("Throttled function is already aborted and not accepting new promises")):new Promise((u,d)=>{s.push({resolve:u,reject:d,args:c}),o<e&&l()});return a.abort=()=>{n=!0,r.forEach(clearTimeout),r=[],s.forEach(c=>c.reject(()=>new Z("Throttle function aborted"))),s.length=0},a}class L{constructor(){p(this,"isCDNUrl",(e="")=>e.includes("/cdn/")),p(this,"getOptionsPage",(e,t=25,s=1)=>({...e,per_page:t,page:s})),p(this,"delay",e=>new Promise(t=>setTimeout(t,e))),p(this,"arrayFrom",(e=0,t)=>Array.from({length:e},t)),p(this,"range",(e=0,t=e)=>{const s=Math.abs(t-e)||0,r=e<t?1:-1;return this.arrayFrom(s,(o,n)=>n*r+e)}),p(this,"asyncMap",async(e,t)=>Promise.all(e.map(t))),p(this,"flatMap",(e=[],t)=>e.map(t).reduce((s,r)=>[...s,...r],[])),p(this,"escapeHTML",function(e){const t={"&":"&","<":"<",">":">",'"':""","'":"'"},s=/[&<>"']/g,r=new RegExp(s.source);return e&&r.test(e)?e.replace(s,o=>t[o]):e})}stringify(e,t,s){const r=[];for(const o in e){if(!Object.prototype.hasOwnProperty.call(e,o))continue;const n=e[o],l=s?"":encodeURIComponent(o);let a;typeof n=="object"?a=this.stringify(n,t?t+encodeURIComponent(`[${l}]`):l,Array.isArray(n)):a=`${t?t+encodeURIComponent(`[${l}]`):l}=${encodeURIComponent(n)}`,r.push(a)}return r.join("&")}getRegionURL(e){const t="api.storyblok.com",s="api-us.storyblok.com",r="app.storyblokchina.cn",o="api-ap.storyblok.com",n="api-ca.storyblok.com";switch(e){case"us":return s;case"cn":return r;case"ap":return o;case"ca":return n;default:return t}}}const te=function(i,e){const t={};for(const s in i){const r=i[s];e.includes(s)&&r!==null&&(t[s]=r)}return t},se=i=>i==="email",re=()=>({singleTag:"hr"}),ie=()=>({tag:"blockquote"}),oe=()=>({tag:"ul"}),ne=i=>({tag:["pre",{tag:"code",attrs:i.attrs}]}),ae=()=>({singleTag:"br"}),le=i=>({tag:`h${i.attrs.level}`}),ce=i=>({singleTag:[{tag:"img",attrs:te(i.attrs,["src","alt","title"])}]}),he=()=>({tag:"li"}),ue=()=>({tag:"ol"}),de=()=>({tag:"p"}),pe=i=>({tag:[{tag:"span",attrs:{"data-type":"emoji","data-name":i.attrs.name,emoji:i.attrs.emoji}}]}),ge=()=>({tag:"b"}),fe=()=>({tag:"s"}),me=()=>({tag:"u"}),ye=()=>({tag:"strong"}),be=()=>({tag:"code"}),ke=()=>({tag:"i"}),ve=i=>{if(!i.attrs)return{tag:""};const e=new L().escapeHTML,t={...i.attrs},{linktype:s="url"}=i.attrs;if(delete t.linktype,t.href&&(t.href=e(i.attrs.href||"")),se(s)&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),t.custom){for(const r in t.custom)t[r]=t.custom[r];delete t.custom}return{tag:[{tag:"a",attrs:t}]}},$e=i=>({tag:[{tag:"span",attrs:i.attrs}]}),Te=()=>({tag:"sub"}),we=()=>({tag:"sup"}),Re=i=>({tag:[{tag:"span",attrs:i.attrs}]}),Se=i=>{var e;return(e=i.attrs)!=null&&e.color?{tag:[{tag:"span",attrs:{style:`background-color:${i.attrs.color};`}}]}:{tag:""}},_e=i=>{var e;return(e=i.attrs)!=null&&e.color?{tag:[{tag:"span",attrs:{style:`color:${i.attrs.color}`}}]}:{tag:""}},q={nodes:{horizontal_rule:re,blockquote:ie,bullet_list:oe,code_block:ne,hard_break:ae,heading:le,image:ce,list_item:he,ordered_list:ue,paragraph:de,emoji:pe},marks:{bold:ge,strike:fe,underline:me,strong:ye,code:be,italic:ke,link:ve,styled:$e,subscript:Te,superscript:we,anchor:Re,highlight:Se,textStyle:_e}},Ee=function(i){const e={"&":"&","<":"<",">":">",'"':""","'":"'"},t=/[&<>"']/g,s=new RegExp(t.source);return i&&s.test(i)?i.replace(t,r=>e[r]):i};let F=!1;class je{constructor(e){p(this,"marks"),p(this,"nodes"),e||(e=q),this.marks=e.marks||[],this.nodes=e.nodes||[]}addNode(e,t){this.nodes[e]=t}addMark(e,t){this.marks[e]=t}render(e,t={optimizeImages:!1},s=!0){if(!F&&s&&(console.warn("Warning ⚠️: The RichTextResolver class is deprecated and will be removed in the next major release. Please use the `@storyblok/richtext` package instead. https://github.com/storyblok/richtext/"),F=!0),e&&e.content&&Array.isArray(e.content)){let r="";return e.content.forEach(o=>{r+=this.renderNode(o)}),t.optimizeImages?this.optimizeImages(r,t.optimizeImages):r}return console.warn(`The render method must receive an Object with a "content" field.
|
8
|
+
The "content" field must be an array of nodes as the type ISbRichtext.
|
9
|
+
ISbRichtext:
|
10
|
+
content?: ISbRichtext[]
|
11
|
+
marks?: ISbRichtext[]
|
12
|
+
attrs?: any
|
13
|
+
text?: string
|
14
|
+
type: string
|
15
|
+
|
16
|
+
Example:
|
17
|
+
{
|
18
|
+
content: [
|
19
|
+
{
|
20
|
+
content: [
|
21
|
+
{
|
22
|
+
text: 'Hello World',
|
23
|
+
type: 'text'
|
24
|
+
}
|
25
|
+
],
|
26
|
+
type: 'paragraph'
|
27
|
+
}
|
28
|
+
],
|
29
|
+
type: 'doc'
|
30
|
+
}`),""}optimizeImages(e,t){let s=0,r=0,o="",n="";typeof t!="boolean"&&(typeof t.width=="number"&&t.width>0&&(o+=`width="${t.width}" `,s=t.width),typeof t.height=="number"&&t.height>0&&(o+=`height="${t.height}" `,r=t.height),(t.loading==="lazy"||t.loading==="eager")&&(o+=`loading="${t.loading}" `),typeof t.class=="string"&&t.class.length>0&&(o+=`class="${t.class}" `),t.filters&&(typeof t.filters.blur=="number"&&t.filters.blur>=0&&t.filters.blur<=100&&(n+=`:blur(${t.filters.blur})`),typeof t.filters.brightness=="number"&&t.filters.brightness>=-100&&t.filters.brightness<=100&&(n+=`:brightness(${t.filters.brightness})`),t.filters.fill&&(t.filters.fill.match(/[0-9A-F]{6}/gi)||t.filters.fill==="transparent")&&(n+=`:fill(${t.filters.fill})`),t.filters.format&&["webp","png","jpeg"].includes(t.filters.format)&&(n+=`:format(${t.filters.format})`),typeof t.filters.grayscale=="boolean"&&t.filters.grayscale&&(n+=":grayscale()"),typeof t.filters.quality=="number"&&t.filters.quality>=0&&t.filters.quality<=100&&(n+=`:quality(${t.filters.quality})`),t.filters.rotate&&[90,180,270].includes(t.filters.rotate)&&(n+=`:rotate(${t.filters.rotate})`),n.length>0&&(n=`/filters${n}`))),o.length>0&&(e=e.replace(/<img/g,`<img ${o.trim()}`));const l=s>0||r>0||n.length>0?`${s}x${r}${n}`:"";return e=e.replace(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|bmp)/g,`a.storyblok.com/f/$1/$2.$3/m/${l}`),typeof t!="boolean"&&(t.sizes||t.srcset)&&(e=e.replace(/<img.*?src=["|'](.*?)["|']/g,a=>{var c,u;const d=a.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|bmp)/g);if(d&&d.length>0){const m={srcset:(c=t.srcset)==null?void 0:c.map(k=>{if(typeof k=="number")return`//${d}/m/${k}x0${n} ${k}w`;if(typeof k=="object"&&k.length===2){let _=0,x=0;return typeof k[0]=="number"&&(_=k[0]),typeof k[1]=="number"&&(x=k[1]),`//${d}/m/${_}x${x}${n} ${_}w`}return""}).join(", "),sizes:(u=t.sizes)==null?void 0:u.map(k=>k).join(", ")};let b="";return m.srcset&&(b+=`srcset="${m.srcset}" `),m.sizes&&(b+=`sizes="${m.sizes}" `),a.replace(/<img/g,`<img ${b.trim()}`)}return a})),e}renderNode(e){const t=[];e.marks&&e.marks.forEach(r=>{const o=this.getMatchingMark(r);o&&o.tag!==""&&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(Ee(e.text)):s&&s.singleTag?t.push(this.renderTag(s.singleTag," /")):s&&s.html?t.push(s.html):e.type==="emoji"&&t.push(this.renderEmoji(e)),s&&s.tag&&t.push(this.renderClosingTag(s.tag)),e.marks&&e.marks.slice(0).reverse().forEach(r=>{const o=this.getMatchingMark(r);o&&o.tag!==""&&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)if(Object.prototype.hasOwnProperty.call(s.attrs,o)){const n=s.attrs[o];n!==null&&(r+=` ${o}="${n}"`)}}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)}renderEmoji(e){if(e.attrs.emoji)return e.attrs.emoji;const t=[{tag:"img",attrs:{src:e.attrs.fallbackImage,draggable:"false",loading:"lazy",align:"absmiddle"}}];return this.renderTag(t," /")}}const O=je;class Ie{constructor(e){p(this,"baseURL"),p(this,"timeout"),p(this,"headers"),p(this,"responseInterceptor"),p(this,"fetch"),p(this,"ejectInterceptor"),p(this,"url"),p(this,"parameters"),p(this,"fetchOptions"),this.baseURL=e.baseURL,this.headers=e.headers||new Headers,this.timeout=e!=null&&e.timeout?e.timeout*1e3:0,this.responseInterceptor=e.responseInterceptor,this.fetch=(...t)=>e.fetch?e.fetch(...t):fetch(...t),this.ejectInterceptor=!1,this.url="",this.parameters={},this.fetchOptions={}}get(e,t){return this.url=e,this.parameters=t,this._methodHandler("get")}post(e,t){return this.url=e,this.parameters=t,this._methodHandler("post")}put(e,t){return this.url=e,this.parameters=t,this._methodHandler("put")}delete(e,t){return this.url=e,this.parameters=t??{},this._methodHandler("delete")}async _responseHandler(e){const t=[],s={data:{},headers:{},status:0,statusText:""};e.status!==204&&await e.json().then(r=>{s.data=r});for(const r of e.headers.entries())t[r[0]]=r[1];return s.headers={...t},s.status=e.status,s.statusText=e.statusText,s}async _methodHandler(e){let t=`${this.baseURL}${this.url}`,s=null;if(e==="get"){const a=new L;t=`${this.baseURL}${this.url}?${a.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const r=new URL(t),o=new AbortController,{signal:n}=o;let l;this.timeout&&(l=setTimeout(()=>o.abort(),this.timeout));try{const a=await this.fetch(`${r}`,{method:e,headers:this.headers,body:s,signal:n,...this.fetchOptions});this.timeout&&clearTimeout(l);const c=await this._responseHandler(a);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(c)):this._statusHandler(c)}catch(a){return{message:a}}}setFetchOptions(e={}){Object.keys(e).length>0&&"method"in e&&delete e.method,this.fetchOptions={...e}}eject(){this.ejectInterceptor=!0}_statusHandler(e){const t=/20[0-6]/g;return new Promise((s,r)=>{if(t.test(`${e.status}`))return s(e);const o={message:e.statusText,status:e.status,response:Array.isArray(e.data)?e.data[0]:e.data.error||e.data.slug};r(o)})}}const Oe=Ie,G="SB-Agent",N={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"6.0.0"};let C={};const E={};class Ae{constructor(e,t){p(this,"client"),p(this,"maxRetries"),p(this,"retriesDelay"),p(this,"throttle"),p(this,"accessToken"),p(this,"cache"),p(this,"helpers"),p(this,"resolveCounter"),p(this,"relations"),p(this,"links"),p(this,"richTextResolver"),p(this,"resolveNestedRelations"),p(this,"stringifiedStoriesCache");let s=e.endpoint||t;if(!s){const n=new L().getRegionURL,l=e.https===!1?"http":"https";e.oauthToken?s=`${l}://${n(e.region)}/v1`:s=`${l}://${n(e.region)}/v2`}const r=new Headers;r.set("Content-Type","application/json"),r.set("Accept","application/json"),e.headers&&(e.headers.constructor.name==="Headers"?e.headers.entries().toArray():Object.entries(e.headers)).forEach(([n,l])=>{r.set(n,l)}),r.has(G)||(r.set(G,N.defaultAgentName),r.set(N.defaultAgentVersion,N.packageVersion));let o=5;e.oauthToken&&(r.set("Authorization",e.oauthToken),o=3),e.rateLimit&&(o=e.rateLimit),e.richTextSchema?this.richTextResolver=new O(e.richTextSchema):this.richTextResolver=new O,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||10,this.retriesDelay=300,this.throttle=ee(this.throttledRequest.bind(this),o,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new L,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.stringifiedStoriesCache={},this.client=new Oe({baseURL:s,timeout:e.timeout||0,headers:r,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let s="";return t.attrs.body&&t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})}parseParams(e){return e.token||(e.token=this.getToken()),e.cv||(e.cv=E[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),typeof e.resolve_relations<"u"&&(e.resolve_level=2),e}factoryParamOptions(e,t){return this.helpers.isCDNUrl(e)?this.parseParams(t):t}makeRequest(e,t,s,r,o){const n=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,s,r));return this.cacheResponse(e,n,void 0,o)}get(e,t,s){t||(t={});const r=`/${e}`,o=this.factoryParamOptions(r,t);return this.cacheResponse(r,o,void 0,s)}async getAll(e,t,s,r){const o=(t==null?void 0:t.per_page)||25,n=`/${e}`.replace(/\/$/,""),l=s??n.substring(n.lastIndexOf("/")+1),a=1,c=await this.makeRequest(n,t,o,a,r),u=c.total?Math.ceil(c.total/o):1,d=await this.helpers.asyncMap(this.helpers.range(a,u),m=>this.makeRequest(n,t,o,m+1,r));return this.helpers.flatMap([c,...d],m=>Object.values(m.data[l]))}post(e,t,s){const r=`/${e}`;return Promise.resolve(this.throttle("post",r,t,s))}put(e,t,s){const r=`/${e}`;return Promise.resolve(this.throttle("put",r,t,s))}delete(e,t,s){t||(t={});const r=`/${e}`;return Promise.resolve(this.throttle("delete",r,t,s))}getStories(e,t){return this._addResolveLevel(e),this.get("cdn/stories",e,t)}getStory(e,t,s){return this._addResolveLevel(t),this.get(`cdn/stories/${e}`,t,s)}getToken(){return this.accessToken}ejectInterceptor(){this.client.eject()}_addResolveLevel(e){typeof e.resolve_relations<"u"&&(e.resolve_level=2)}_cleanCopy(e){return JSON.parse(JSON.stringify(e))}_insertLinks(e,t,s){const r=e[t];r&&r.fieldtype==="multilink"&&r.linktype==="story"&&typeof r.id=="string"&&this.links[s][r.id]?r.story=this._cleanCopy(this.links[s][r.id]):r&&r.linktype==="story"&&typeof r.uuid=="string"&&this.links[s][r.uuid]&&(r.story=this._cleanCopy(this.links[s][r.uuid]))}getStoryReference(e,t){return this.relations[e][t]?JSON.parse(this.stringifiedStoriesCache[t]||JSON.stringify(this.relations[e][t])):t}_resolveField(e,t,s){const r=e[t];typeof r=="string"?e[t]=this.getStoryReference(s,r):Array.isArray(r)&&(e[t]=r.map(o=>this.getStoryReference(s,o)).filter(Boolean))}_insertRelations(e,t,s,r){if(Array.isArray(s)?s.find(n=>n.endsWith(`.${t}`)):s.endsWith(`.${t}`)){this._resolveField(e,t,r);return}const o=e.component?`${e.component}.${t}`:t;(Array.isArray(s)?s.includes(o):s===o)&&this._resolveField(e,t,r)}iterateTree(e,t,s){const r=(o,n="")=>{if(!(!o||o._stopResolving)){if(Array.isArray(o))o.forEach((l,a)=>r(l,`${n}[${a}]`));else if(typeof o=="object")for(const l in o){const a=n?`${n}.${l}`:l;(o.component&&o._uid||o.type==="link")&&(this._insertRelations(o,l,t,s),this._insertLinks(o,l,s)),r(o[l],a)}}};r(e.content)}async resolveLinks(e,t,s){let r=[];if(e.link_uuids){const o=e.link_uuids.length,n=[],l=50;for(let a=0;a<o;a+=l){const c=Math.min(o,a+l);n.push(e.link_uuids.slice(a,c))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:n[a].join(",")})).data.stories.forEach(c=>{r.push(c)})}else r=e.links;r.forEach(o=>{this.links[s][o.uuid]={...o,_stopResolving:!0}})}async resolveRelations(e,t,s){let r=[];if(e.rel_uuids){const o=e.rel_uuids.length,n=[],l=50;for(let a=0;a<o;a+=l){const c=Math.min(o,a+l);n.push(e.rel_uuids.slice(a,c))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:n[a].join(","),excluding_fields:t.excluding_fields})).data.stories.forEach(c=>{r.push(c)})}else r=e.rels;r&&r.length>0&&r.forEach(o=>{this.relations[s][o.uuid]={...o,_stopResolving:!0}})}async resolveStories(e,t,s){var r,o;let n=[];if(this.links[s]={},this.relations[s]={},typeof t.resolve_relations<"u"&&t.resolve_relations.length>0&&(typeof t.resolve_relations=="string"&&(n=t.resolve_relations.split(",")),await this.resolveRelations(e,t,s)),t.resolve_links&&["1","story","url","link"].includes(t.resolve_links)&&((r=e.links)!=null&&r.length||(o=e.link_uuids)!=null&&o.length)&&await this.resolveLinks(e,t,s),this.resolveNestedRelations)for(const l in this.relations[s])this.iterateTree(this.relations[s][l],n,s);e.story?this.iterateTree(e.story,n,s):e.stories.forEach(l=>{this.iterateTree(l,n,s)}),this.stringifiedStoriesCache={},delete this.links[s],delete this.relations[s]}async cacheResponse(e,t,s,r){const o=this.helpers.stringify({url:e,params:t}),n=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&await this.flushCache(),t.version==="published"&&e!=="/cdn/spaces/me"){const l=await n.get(o);if(l)return Promise.resolve(l)}return new Promise(async(l,a)=>{var c;try{const u=await this.throttle("get",e,t,r);if(u.status!==200)return a(u);let d={data:u.data,headers:u.headers};if((c=u.headers)!=null&&c["per-page"]&&(d=Object.assign({},d,{perPage:u.headers["per-page"]?Number.parseInt(u.headers["per-page"]):0,total:u.headers["per-page"]?Number.parseInt(u.headers.total):0})),d.data.story||d.data.stories){const m=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(d.data,t,`${m}`)}return t.version==="published"&&e!=="/cdn/spaces/me"&&await n.set(o,d),d.data.cv&&t.token&&E[t.token]!==d.data.cv&&(await this.flushCache(),E[t.token]=d.data.cv),l(d)}catch(u){if(u.response&&u.status===429&&(s=typeof s>"u"?0:s+1,s<this.maxRetries))return console.log(`Hit rate limit. Retrying in ${this.retriesDelay/1e3} seconds.`),await this.helpers.delay(this.retriesDelay),this.cacheResponse(e,t,s).then(l).catch(a);a(u)}})}throttledRequest(e,t,s,r){return this.client.setFetchOptions(r),this.client[e](t,s)}cacheVersions(){return E}cacheVersion(){return E[this.accessToken]}setCacheVersion(e){this.accessToken&&(E[this.accessToken]=e)}clearCacheVersion(){this.accessToken&&(E[this.accessToken]=0)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(C[e])},getAll(){return Promise.resolve(C)},set(e,t){return C[e]=t,Promise.resolve(void 0)},flush(){return C={},Promise.resolve(void 0)}};case"custom":if(this.cache.custom)return this.cache.custom;default:return{get(){return Promise.resolve()},getAll(){return Promise.resolve(void 0)},set(){return Promise.resolve(void 0)},flush(){return Promise.resolve(void 0)}}}}async flushCache(){return await this.cacheProvider().flush(),this.clearCacheVersion(),this}}const xe=(i={})=>{const{apiOptions:e}=i;if(!e||!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 Ae(e)}},Le=i=>{if(typeof i!="object"||typeof i._editable>"u")return{};try{const e=JSON.parse(i._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return e?{"data-blok-c":JSON.stringify(e),"data-blok-uid":`${e.id}-${e.uid}`}:{}}catch{return{}}};function Ce(i,e){if(!e)return{src:i,attrs:{}};let t=0,s=0;const r={},o=[];function n(a,c,u,d,m){typeof a!="number"||a<=c||a>=u?console.warn(`[StoryblokRichText] - ${d.charAt(0).toUpperCase()+d.slice(1)} value must be a number between ${c} and ${u} (inclusive)`):m.push(`${d}(${a})`)}if(typeof e=="object"){if(typeof e.width=="number"&&e.width>0?(r.width=e.width,t=e.width):console.warn("[StoryblokRichText] - Width value must be a number greater than 0"),e.height&&typeof e.height=="number"&&e.height>0?(r.height=e.height,s=e.height):console.warn("[StoryblokRichText] - Height value must be a number greater than 0"),e.loading&&["lazy","eager"].includes(e.loading)&&(r.loading=e.loading),e.class&&(r.class=e.class),e.filters){const{filters:a}=e||{},{blur:c,brightness:u,fill:d,format:m,grayscale:b,quality:k,rotate:_}=a||{};c&&n(c,0,100,"blur",o),k&&n(k,0,100,"quality",o),u&&n(u,0,100,"brightness",o),d&&o.push(`fill(${d})`),b&&o.push("grayscale()"),_&&[0,90,180,270].includes(e.filters.rotate||0)&&o.push(`rotate(${_})`),m&&["webp","png","jpeg"].includes(m)&&o.push(`format(${m})`)}e.srcset&&(r.srcset=e.srcset.map(a=>{if(typeof a=="number")return`${i}/m/${a}x0/${o.length>0?`filters:${o.join(":")}`:""} ${a}w`;if(Array.isArray(a)&&a.length===2){const[c,u]=a;return`${i}/m/${c}x${u}/${o.length>0?`filters:${o.join(":")}`:""} ${c}w`}else{console.warn("[StoryblokRichText] - srcset entry must be a number or a tuple of two numbers");return}}).join(", ")),e.sizes&&(r.sizes=e.sizes.join(", "))}let l=`${i}/m/`;return t>0&&s>0&&(l=`${l}${t}x${s}/`),o.length>0&&(l=`${l}filters:${o.join(":")}`),{src:l,attrs:r}}var v=(i=>(i.DOCUMENT="doc",i.HEADING="heading",i.PARAGRAPH="paragraph",i.QUOTE="blockquote",i.OL_LIST="ordered_list",i.UL_LIST="bullet_list",i.LIST_ITEM="list_item",i.CODE_BLOCK="code_block",i.HR="horizontal_rule",i.BR="hard_break",i.IMAGE="image",i.EMOJI="emoji",i.COMPONENT="blok",i))(v||{}),T=(i=>(i.BOLD="bold",i.STRONG="strong",i.STRIKE="strike",i.UNDERLINE="underline",i.ITALIC="italic",i.CODE="code",i.LINK="link",i.ANCHOR="anchor",i.STYLED="styled",i.SUPERSCRIPT="superscript",i.SUBSCRIPT="subscript",i.TEXT_STYLE="textStyle",i.HIGHLIGHT="highlight",i))(T||{}),M=(i=>(i.TEXT="text",i))(M||{}),A=(i=>(i.URL="url",i.STORY="story",i.ASSET="asset",i.EMAIL="email",i))(A||{});const Pe=["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"],Ne=(i={})=>Object.keys(i).map(e=>`${e}="${i[e]}"`).join(" "),Me=(i={})=>Object.keys(i).map(e=>`${e}: ${i[e]}`).join("; ");function He(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}const V=i=>Object.fromEntries(Object.entries(i).filter(([e,t])=>t!==void 0));function J(i,e={},t){const s=Ne(e),r=s?`${i} ${s}`:i,o=Array.isArray(t)?t.join(""):t||"";if(i){if(Pe.includes(i))return`<${r}>`}else return o;return`<${r}>${o}</${i}>`}function Ue(i={}){let e=0;const{renderFn:t=J,textFn:s=He,resolvers:r={},optimizeImages:o=!1,keyedResolvers:n=!1}=i,l=t!==J,a=h=>g=>{const f=g.attrs||{};return n&&(f.key=`${h}-${e}`),t(h,f,g.children||null)},c=h=>{const{src:g,alt:f,title:$,srcset:S,sizes:w}=h.attrs||{};let R=g,j={};if(o){const{src:Ve,attrs:Je}=Ce(g,o);R=Ve,j=Je}n&&(j={...j,key:`img-${e}`});const Ge={src:R,alt:f,title:$,srcset:S,sizes:w,...j};return t("img",V(Ge))},u=h=>{const{level:g,...f}=h.attrs||{},$={...f};return n&&($.key=`h${g}-${e}`),t(`h${g}`,$,h.children)},d=h=>{var g,f,$,S;const w=t("img",{src:(g=h.attrs)==null?void 0:g.fallbackImage,alt:(f=h.attrs)==null?void 0:f.alt,style:"width: 1.25em; height: 1.25em; vertical-align: text-top",draggable:"false",loading:"lazy"}),R={"data-type":"emoji","data-name":($=h.attrs)==null?void 0:$.name,"data-emoji":(S=h.attrs)==null?void 0:S.emoji};return n&&(R.key=`emoji-${e}`),t("span",R,w)},m=h=>t("pre",{...h.attrs,key:`code-${e}`},t("code",{key:`code-${e}`},h.children||"")),b=(h,g=!1)=>({text:f,attrs:$})=>{const{class:S,id:w,...R}=$||{},j=g?{class:S,id:w,style:Me(R)||void 0}:$||{};return n&&(j.key=`${h}-${e}`),t(h,V(j),f)},k=h=>z(h),_=h=>{const{marks:g,...f}=h;return"text"in h?g?g.reduce(($,S)=>k({...S,text:$}),k({...f,children:f.children})):s(f.text):""},x=h=>{const{linktype:g,href:f,anchor:$,...S}=h.attrs||{};let w="";switch(g){case A.ASSET:case A.URL:w=f;break;case A.EMAIL:w=`mailto:${f}`;break;case A.STORY:w=f,$&&(w=`${w}#${$}`);break;default:w=f;break}const R={...S};return w&&(R.href=w),n&&(R.key=`a-${e}`),t("a",R,h.text)},qe=h=>{var g,f;return console.warn("[StoryblokRichtText] - BLOK resolver is not available for vanilla usage"),t("span",{blok:(g=h==null?void 0:h.attrs)==null?void 0:g.body[0],id:(f=h.attrs)==null?void 0:f.id,key:`component-${e}`,style:"display: none"})},Fe=new Map([[v.DOCUMENT,a("")],[v.HEADING,u],[v.PARAGRAPH,a("p")],[v.UL_LIST,a("ul")],[v.OL_LIST,a("ol")],[v.LIST_ITEM,a("li")],[v.IMAGE,c],[v.EMOJI,d],[v.CODE_BLOCK,m],[v.HR,a("hr")],[v.BR,a("br")],[v.QUOTE,a("blockquote")],[v.COMPONENT,qe],[M.TEXT,_],[T.LINK,x],[T.ANCHOR,x],[T.STYLED,b("span",!0)],[T.BOLD,b("strong")],[T.TEXT_STYLE,b("span",!0)],[T.ITALIC,b("em")],[T.UNDERLINE,b("u")],[T.STRIKE,b("s")],[T.CODE,b("code")],[T.SUPERSCRIPT,b("sup")],[T.SUBSCRIPT,b("sub")],[T.HIGHLIGHT,b("mark")],...Object.entries(r).map(([h,g])=>[h,g])]);function P(h){e+=1;const g=Fe.get(h.type);if(!g)return console.error("<Storyblok>",`No resolver found for node type ${h.type}`),"";if(h.type==="text")return g(h);const f=h.content?h.content.map(z):void 0;return g({...h,children:f})}function z(h){return h.type==="doc"?l?h.content.map(P):h.content.map(P).join(""):Array.isArray(h)?h.map(P):P(h)}return{render:z}}let H,U="https://app.storyblok.com/f/storyblok-v2-latest.js";const K=(i,e,t={})=>{var l;const r=!(typeof window>"u")&&typeof window.storyblokRegisterEvent<"u",o=new URL((l=window.location)==null?void 0:l.href).searchParams.get("_storyblok"),n=o!==null&&+o===i;if(!(!r||!n)){if(!i){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(t).on(["input","published","change"],c=>{var u;c&&(c.action==="input"&&((u=c.story)==null?void 0:u.id)===i?e(c.story):(c.action==="change"||c.action==="published")&&c.storyId===i&&window.location.reload())})})}},Y=(i,e)=>{i.addNode("blok",t=>{let s="";return t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})},ze=(i={})=>{var d,m;const{bridge:e,accessToken:t,use:s=[],apiOptions:r={},richText:o={},bridgeUrl:n}=i;r.accessToken=r.accessToken||t;const l={bridge:e,apiOptions:r};let a={};s.forEach(b=>{a={...a,...b(l)}}),n&&(U=n);const u=!(typeof window>"u")&&((m=(d=window.location)==null?void 0:d.search)==null?void 0:m.includes("_storyblok_tk"));return e!==!1&&u&&D(U),H=new O(o.schema),o.resolver&&Y(H,o.resolver),a},W=i=>{var e;return!i||!((e=i==null?void 0:i.content)!=null&&e.some(t=>t.content||t.type==="blok"||t.type==="horizontal_rule"))},Be=(i,e,t)=>{let s=t||H;if(!s){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return W(i)?"":(e&&(s=new O(e.schema),e.resolver&&Y(s,e.resolver)),s.render(i,{},!1))},De=()=>D(U);y.BlockTypes=v,y.MarkTypes=T,y.RichTextResolver=O,y.RichTextSchema=q,y.TextTypes=M,y.apiPlugin=xe,y.isRichTextEmpty=W,y.loadStoryblokBridge=De,y.registerStoryblokBridge=K,y.renderRichText=Be,y.richTextResolver=Ue,y.storyblokEditable=Le,y.storyblokInit=ze,y.useStoryblokBridge=K,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"})});
|
package/dist/types/index.d.ts
CHANGED
@@ -1,13 +1,64 @@
|
|
1
|
-
import {
|
2
|
-
|
3
|
-
|
4
|
-
|
5
|
-
|
6
|
-
|
7
|
-
|
8
|
-
|
9
|
-
|
10
|
-
|
11
|
-
export
|
12
|
-
|
13
|
-
|
1
|
+
import { ISbComponentType, ISbConfig, ISbStoryData, default as StoryblokJSClient } from 'storyblok-js-client';
|
2
|
+
export type StoryblokClient = StoryblokJSClient;
|
3
|
+
declare global {
|
4
|
+
interface Window {
|
5
|
+
storyblokRegisterEvent: (cb: () => void) => void;
|
6
|
+
StoryblokBridge: {
|
7
|
+
new (options?: StoryblokBridgeConfigV2): StoryblokBridgeV2;
|
8
|
+
};
|
9
|
+
}
|
10
|
+
}
|
11
|
+
export interface SbInitResult {
|
12
|
+
storyblokApi?: StoryblokClient;
|
13
|
+
}
|
14
|
+
export type SbPluginFactory = (options: SbSDKOptions) => any;
|
15
|
+
export type SbBlokKeyDataTypes = string | number | object | boolean | undefined;
|
16
|
+
export interface SbBlokData extends ISbComponentType<string> {
|
17
|
+
[index: string]: SbBlokKeyDataTypes;
|
18
|
+
}
|
19
|
+
export interface SbRichTextOptions {
|
20
|
+
schema?: ISbConfig['richTextSchema'];
|
21
|
+
resolver?: ISbConfig['componentResolver'];
|
22
|
+
}
|
23
|
+
export interface SbSDKOptions {
|
24
|
+
bridge?: boolean;
|
25
|
+
accessToken?: string;
|
26
|
+
use?: any[];
|
27
|
+
apiOptions?: ISbConfig;
|
28
|
+
richText?: SbRichTextOptions;
|
29
|
+
bridgeUrl?: string;
|
30
|
+
}
|
31
|
+
export interface ISbEventPayload<S extends ISbComponentType<string> = any> {
|
32
|
+
action: 'customEvent' | 'published' | 'input' | 'change' | 'unpublished' | 'enterEditmode';
|
33
|
+
event?: string;
|
34
|
+
story?: ISbStoryData<S>;
|
35
|
+
slug?: string;
|
36
|
+
slugChanged?: boolean;
|
37
|
+
storyId?: number;
|
38
|
+
reload?: boolean;
|
39
|
+
}
|
40
|
+
export interface StoryblokBridgeConfigV2 {
|
41
|
+
resolveRelations?: string | string[];
|
42
|
+
customParent?: string;
|
43
|
+
preventClicks?: boolean;
|
44
|
+
language?: string;
|
45
|
+
resolveLinks?: 'url' | 'story' | '0' | '1' | 'link';
|
46
|
+
}
|
47
|
+
export interface StoryblokBridgeV2 {
|
48
|
+
pingEditor: (event: any) => void;
|
49
|
+
isInEditor: () => boolean;
|
50
|
+
enterEditmode: () => void;
|
51
|
+
on: (event: 'customEvent' | 'published' | 'input' | 'change' | 'unpublished' | 'enterEditmode' | string[], callback: (payload?: ISbEventPayload) => void) => void;
|
52
|
+
}
|
53
|
+
export type { ArrayFn, AsyncFn, ISbAlternateObject, // previously AlternateObject
|
54
|
+
ISbCache, // previously StoryblokCache
|
55
|
+
ISbComponentType as StoryblokComponentType, ISbConfig, // previously StoryblokConfig
|
56
|
+
ISbContentMangmntAPI, ISbDimensions, ISbError, ISbManagmentApiResult, // previously StoryblokManagmentApiResult
|
57
|
+
ISbNode, ISbResponse, ISbResult, // previously StoryblokResult
|
58
|
+
ISbRichtext, // previously Richtext
|
59
|
+
ISbSchema, ISbStories, // previously Stories
|
60
|
+
ISbStoriesParams, // previously StoriesParams
|
61
|
+
ISbStory, // previously Story
|
62
|
+
ISbStoryData, // previously StoryData
|
63
|
+
ISbStoryParams, // previously StoryParams
|
64
|
+
ISbThrottle, ISbThrottledRequest, } from 'storyblok-js-client';
|
package/package.json
CHANGED
@@ -1,13 +1,10 @@
|
|
1
1
|
{
|
2
2
|
"name": "@storyblok/js",
|
3
|
-
"
|
3
|
+
"type": "module",
|
4
|
+
"version": "3.2.0",
|
5
|
+
"packageManager": "pnpm@9.12.2",
|
4
6
|
"description": "SDK to integrate Storyblok into your project using JavaScript.",
|
5
|
-
"
|
6
|
-
"module": "./dist/storyblok-js.mjs",
|
7
|
-
"types": "./dist/types/index.d.ts",
|
8
|
-
"files": [
|
9
|
-
"dist"
|
10
|
-
],
|
7
|
+
"license": "MIT",
|
11
8
|
"exports": {
|
12
9
|
".": {
|
13
10
|
"types": "./dist/types/index.d.ts",
|
@@ -15,76 +12,63 @@
|
|
15
12
|
"require": "./dist/storyblok-js.js"
|
16
13
|
}
|
17
14
|
},
|
15
|
+
"main": "./dist/storyblok-js.js",
|
16
|
+
"module": "./dist/storyblok-js.mjs",
|
17
|
+
"types": "./dist/types/index.d.ts",
|
18
|
+
"files": [
|
19
|
+
"dist"
|
20
|
+
],
|
18
21
|
"scripts": {
|
19
|
-
"dev": "vite
|
20
|
-
"build": "
|
21
|
-
"test
|
22
|
-
"test:unit": "vitest run",
|
22
|
+
"dev": "vite",
|
23
|
+
"build": "tsc && vite build",
|
24
|
+
"test:unit": "vitest",
|
25
|
+
"test:unit:ci": "vitest run",
|
26
|
+
"test:unit:ui": "vitest --ui",
|
23
27
|
"test:e2e": "start-server-and-test cy:playground http://localhost:5173/ cy:run",
|
24
28
|
"test:e2e-watch": "start-server-and-test cy:playground http://localhost:5173/ cy:open",
|
25
|
-
"cy:playground": "
|
29
|
+
"cy:playground": "pnpm --filter='./playground/vanilla' dev",
|
30
|
+
"lint": "eslint .",
|
31
|
+
"lint:fix": "eslint . --fix",
|
26
32
|
"cy:run": "cypress run",
|
27
|
-
"cy:open": "cypress open"
|
28
|
-
"prepublishOnly": "npm run build && cp ../README.md ./"
|
33
|
+
"cy:open": "cypress open"
|
29
34
|
},
|
30
35
|
"dependencies": {
|
31
|
-
"@storyblok/richtext": "
|
32
|
-
"storyblok-js-client": "
|
36
|
+
"@storyblok/richtext": "3.0.2",
|
37
|
+
"storyblok-js-client": "6.10.6"
|
33
38
|
},
|
34
39
|
"devDependencies": {
|
40
|
+
"@commitlint/cli": "^19.6.0",
|
41
|
+
"@commitlint/config-conventional": "^19.6.0",
|
42
|
+
"@storyblok/eslint-config": "^0.3.0",
|
35
43
|
"@tsconfig/recommended": "^1.0.8",
|
36
|
-
"
|
37
|
-
"
|
38
|
-
"eslint
|
44
|
+
"@types/node": "^22.10.1",
|
45
|
+
"cypress": "^13.16.1",
|
46
|
+
"eslint": "^9.16.0",
|
47
|
+
"eslint-plugin-cypress": "^4.1.0",
|
39
48
|
"isomorphic-fetch": "^3.0.0",
|
49
|
+
"kolorist": "^1.8.0",
|
50
|
+
"pathe": "^1.1.2",
|
51
|
+
"simple-git-hooks": "^2.11.1",
|
40
52
|
"start-server-and-test": "^2.0.8",
|
41
|
-
"
|
53
|
+
"typescript": "^5.7.2",
|
54
|
+
"vite": "^6.0.1",
|
55
|
+
"vite-plugin-banner": "^0.8.0",
|
56
|
+
"vite-plugin-dts": "^4.3.0",
|
57
|
+
"vite-plugin-qrcode": "^0.2.3",
|
42
58
|
"vitest": "^2.1.5"
|
43
59
|
},
|
44
|
-
"
|
45
|
-
"
|
46
|
-
|
47
|
-
"@babel/preset-env",
|
48
|
-
{
|
49
|
-
"targets": {
|
50
|
-
"node": "current"
|
51
|
-
}
|
52
|
-
}
|
53
|
-
]
|
60
|
+
"commitlint": {
|
61
|
+
"extends": [
|
62
|
+
"@commitlint/config-conventional"
|
54
63
|
]
|
55
64
|
},
|
56
|
-
"jest": {
|
57
|
-
"moduleFileExtensions": [
|
58
|
-
"js",
|
59
|
-
"json"
|
60
|
-
],
|
61
|
-
"transform": {
|
62
|
-
"^.+\\.js$": "babel-jest"
|
63
|
-
}
|
64
|
-
},
|
65
65
|
"release": {
|
66
66
|
"branches": [
|
67
|
-
"main"
|
68
|
-
{
|
69
|
-
"name": "next",
|
70
|
-
"prerelease": true
|
71
|
-
},
|
72
|
-
{
|
73
|
-
"name": "beta",
|
74
|
-
"prerelease": true
|
75
|
-
}
|
67
|
+
"main"
|
76
68
|
]
|
77
69
|
},
|
78
|
-
"
|
79
|
-
"
|
80
|
-
"
|
81
|
-
},
|
82
|
-
"author": "Storyblok",
|
83
|
-
"bugs": {
|
84
|
-
"url": "https://github.com/storyblok/storyblok-js/issues"
|
85
|
-
},
|
86
|
-
"homepage": "https://github.com/storyblok/storyblok-js",
|
87
|
-
"publishConfig": {
|
88
|
-
"access": "public"
|
70
|
+
"simple-git-hooks": {
|
71
|
+
"pre-commit": "pnpm lint",
|
72
|
+
"pre-push": "pnpm commitlint --last --verbose"
|
89
73
|
}
|
90
74
|
}
|
package/dist/storyblok-js.js
DELETED
@@ -1,24 +0,0 @@
|
|
1
|
-
(function(y,j){typeof exports=="object"&&typeof module<"u"?j(exports):typeof define=="function"&&define.amd?define(["exports"],j):(y=typeof globalThis<"u"?globalThis:y||self,j(y.storyblok={}))})(this,function(y){"use strict";let j=!1;const z=[],B=i=>new Promise((e,t)=>{if(typeof window>"u"||(window.storyblokRegisterEvent=r=>{if(window.location===window.parent.location){console.warn("You are not in Draft Mode or in the Visual Editor.");return}j?r():z.push(r)},document.getElementById("storyblok-javascript-bridge")))return;const s=document.createElement("script");s.async=!0,s.src=i,s.id="storyblok-javascript-bridge",s.onerror=r=>t(r),s.onload=r=>{z.forEach(n=>n()),j=!0,e(r)},document.getElementsByTagName("head")[0].appendChild(s)});var X=Object.defineProperty,W=(i,e,t)=>e in i?X(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,p=(i,e,t)=>W(i,typeof e!="symbol"?e+"":e,t);class Q extends Error{constructor(e){super(e),this.name="AbortError"}}function Z(i,e,t){if(!Number.isFinite(e))throw new TypeError("Expected `limit` to be a finite number");if(!Number.isFinite(t))throw new TypeError("Expected `interval` to be a finite number");const s=[];let r=[],n=0,o=!1;const l=async()=>{n++;const c=s.shift();if(c)try{const u=await i(...c.args);c.resolve(u)}catch(u){c.reject(u)}const d=setTimeout(()=>{n--,s.length>0&&l(),r=r.filter(u=>u!==d)},t);r.includes(d)||r.push(d)},a=(...c)=>o?Promise.reject(new Error("Throttled function is already aborted and not accepting new promises")):new Promise((d,u)=>{s.push({resolve:d,reject:u,args:c}),n<e&&l()});return a.abort=()=>{o=!0,r.forEach(clearTimeout),r=[],s.forEach(c=>c.reject(()=>new Q("Throttle function aborted"))),s.length=0},a}let L=class{constructor(){p(this,"isCDNUrl",(e="")=>e.includes("/cdn/")),p(this,"getOptionsPage",(e,t=25,s=1)=>({...e,per_page:t,page:s})),p(this,"delay",e=>new Promise(t=>setTimeout(t,e))),p(this,"arrayFrom",(e=0,t)=>Array.from({length:e},t)),p(this,"range",(e=0,t=e)=>{const s=Math.abs(t-e)||0,r=e<t?1:-1;return this.arrayFrom(s,(n,o)=>o*r+e)}),p(this,"asyncMap",async(e,t)=>Promise.all(e.map(t))),p(this,"flatMap",(e=[],t)=>e.map(t).reduce((s,r)=>[...s,...r],[])),p(this,"escapeHTML",function(e){const t={"&":"&","<":"<",">":">",'"':""","'":"'"},s=/[&<>"']/g,r=new RegExp(s.source);return e&&r.test(e)?e.replace(s,n=>t[n]):e})}stringify(e,t,s){const r=[];for(const n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;const o=e[n],l=s?"":encodeURIComponent(n);let a;typeof o=="object"?a=this.stringify(o,t?t+encodeURIComponent(`[${l}]`):l,Array.isArray(o)):a=`${t?t+encodeURIComponent(`[${l}]`):l}=${encodeURIComponent(o)}`,r.push(a)}return r.join("&")}getRegionURL(e){const t="api.storyblok.com",s="api-us.storyblok.com",r="app.storyblokchina.cn",n="api-ap.storyblok.com",o="api-ca.storyblok.com";switch(e){case"us":return s;case"cn":return r;case"ap":return n;case"ca":return o;default:return t}}};const ee=function(i,e){const t={};for(const s in i){const r=i[s];e.includes(s)&&r!==null&&(t[s]=r)}return t},te=i=>i==="email",se=()=>({singleTag:"hr"}),re=()=>({tag:"blockquote"}),ie=()=>({tag:"ul"}),ne=i=>({tag:["pre",{tag:"code",attrs:i.attrs}]}),oe=()=>({singleTag:"br"}),ae=i=>({tag:`h${i.attrs.level}`}),le=i=>({singleTag:[{tag:"img",attrs:ee(i.attrs,["src","alt","title"])}]}),ce=()=>({tag:"li"}),he=()=>({tag:"ol"}),ue=()=>({tag:"p"}),de=i=>({tag:[{tag:"span",attrs:{"data-type":"emoji","data-name":i.attrs.name,emoji:i.attrs.emoji}}]}),pe=()=>({tag:"b"}),ge=()=>({tag:"s"}),fe=()=>({tag:"u"}),me=()=>({tag:"strong"}),ye=()=>({tag:"code"}),be=()=>({tag:"i"}),ke=i=>{if(!i.attrs)return{tag:""};const e=new L().escapeHTML,t={...i.attrs},{linktype:s="url"}=i.attrs;if(delete t.linktype,t.href&&(t.href=e(i.attrs.href||"")),te(s)&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),t.custom){for(const r in t.custom)t[r]=t.custom[r];delete t.custom}return{tag:[{tag:"a",attrs:t}]}},ve=i=>({tag:[{tag:"span",attrs:i.attrs}]}),$e=()=>({tag:"sub"}),Te=()=>({tag:"sup"}),we=i=>({tag:[{tag:"span",attrs:i.attrs}]}),Re=i=>{var e;return(e=i.attrs)!=null&&e.color?{tag:[{tag:"span",attrs:{style:`background-color:${i.attrs.color};`}}]}:{tag:""}},Se=i=>{var e;return(e=i.attrs)!=null&&e.color?{tag:[{tag:"span",attrs:{style:`color:${i.attrs.color}`}}]}:{tag:""}},D={nodes:{horizontal_rule:se,blockquote:re,bullet_list:ie,code_block:ne,hard_break:oe,heading:ae,image:le,list_item:ce,ordered_list:he,paragraph:ue,emoji:de},marks:{bold:pe,strike:ge,underline:fe,strong:me,code:ye,italic:be,link:ke,styled:ve,subscript:$e,superscript:Te,anchor:we,highlight:Re,textStyle:Se}},_e=function(i){const e={"&":"&","<":"<",">":">",'"':""","'":"'"},t=/[&<>"']/g,s=new RegExp(t.source);return i&&s.test(i)?i.replace(t,r=>e[r]):i};let q=!1;class Ee{constructor(e){p(this,"marks"),p(this,"nodes"),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,t={optimizeImages:!1},s=!0){if(!q&&s&&(console.warn("Warning ⚠️: The RichTextResolver class is deprecated and will be removed in the next major release. Please use the `@storyblok/richtext` package instead. https://github.com/storyblok/richtext/"),q=!0),e&&e.content&&Array.isArray(e.content)){let r="";return e.content.forEach(n=>{r+=this.renderNode(n)}),t.optimizeImages?this.optimizeImages(r,t.optimizeImages):r}return console.warn(`The render method must receive an Object with a "content" field.
|
2
|
-
The "content" field must be an array of nodes as the type ISbRichtext.
|
3
|
-
ISbRichtext:
|
4
|
-
content?: ISbRichtext[]
|
5
|
-
marks?: ISbRichtext[]
|
6
|
-
attrs?: any
|
7
|
-
text?: string
|
8
|
-
type: string
|
9
|
-
|
10
|
-
Example:
|
11
|
-
{
|
12
|
-
content: [
|
13
|
-
{
|
14
|
-
content: [
|
15
|
-
{
|
16
|
-
text: 'Hello World',
|
17
|
-
type: 'text'
|
18
|
-
}
|
19
|
-
],
|
20
|
-
type: 'paragraph'
|
21
|
-
}
|
22
|
-
],
|
23
|
-
type: 'doc'
|
24
|
-
}`),""}optimizeImages(e,t){let s=0,r=0,n="",o="";typeof t!="boolean"&&(typeof t.width=="number"&&t.width>0&&(n+=`width="${t.width}" `,s=t.width),typeof t.height=="number"&&t.height>0&&(n+=`height="${t.height}" `,r=t.height),(t.loading==="lazy"||t.loading==="eager")&&(n+=`loading="${t.loading}" `),typeof t.class=="string"&&t.class.length>0&&(n+=`class="${t.class}" `),t.filters&&(typeof t.filters.blur=="number"&&t.filters.blur>=0&&t.filters.blur<=100&&(o+=`:blur(${t.filters.blur})`),typeof t.filters.brightness=="number"&&t.filters.brightness>=-100&&t.filters.brightness<=100&&(o+=`:brightness(${t.filters.brightness})`),t.filters.fill&&(t.filters.fill.match(/[0-9A-F]{6}/gi)||t.filters.fill==="transparent")&&(o+=`:fill(${t.filters.fill})`),t.filters.format&&["webp","png","jpeg"].includes(t.filters.format)&&(o+=`:format(${t.filters.format})`),typeof t.filters.grayscale=="boolean"&&t.filters.grayscale&&(o+=":grayscale()"),typeof t.filters.quality=="number"&&t.filters.quality>=0&&t.filters.quality<=100&&(o+=`:quality(${t.filters.quality})`),t.filters.rotate&&[90,180,270].includes(t.filters.rotate)&&(o+=`:rotate(${t.filters.rotate})`),o.length>0&&(o=`/filters${o}`))),n.length>0&&(e=e.replace(/<img/g,`<img ${n.trim()}`));const l=s>0||r>0||o.length>0?`${s}x${r}${o}`:"";return e=e.replace(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|bmp)/g,`a.storyblok.com/f/$1/$2.$3/m/${l}`),typeof t!="boolean"&&(t.sizes||t.srcset)&&(e=e.replace(/<img.*?src=["|'](.*?)["|']/g,a=>{var c,d;const u=a.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|bmp)/g);if(u&&u.length>0){const g={srcset:(c=t.srcset)==null?void 0:c.map(b=>{if(typeof b=="number")return`//${u}/m/${b}x0${o} ${b}w`;if(typeof b=="object"&&b.length===2){let S=0,C=0;return typeof b[0]=="number"&&(S=b[0]),typeof b[1]=="number"&&(C=b[1]),`//${u}/m/${S}x${C}${o} ${S}w`}return""}).join(", "),sizes:(d=t.sizes)==null?void 0:d.map(b=>b).join(", ")};let w="";return g.srcset&&(w+=`srcset="${g.srcset}" `),g.sizes&&(w+=`sizes="${g.sizes}" `),a.replace(/<img/g,`<img ${w.trim()}`)}return a})),e}renderNode(e){const t=[];e.marks&&e.marks.forEach(r=>{const n=this.getMatchingMark(r);n&&n.tag!==""&&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(_e(e.text)):s&&s.singleTag?t.push(this.renderTag(s.singleTag," /")):s&&s.html?t.push(s.html):e.type==="emoji"&&t.push(this.renderEmoji(e)),s&&s.tag&&t.push(this.renderClosingTag(s.tag)),e.marks&&e.marks.slice(0).reverse().forEach(r=>{const n=this.getMatchingMark(r);n&&n.tag!==""&&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)if(Object.prototype.hasOwnProperty.call(s.attrs,n)){const o=s.attrs[n];o!==null&&(r+=` ${n}="${o}"`)}}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)}renderEmoji(e){if(e.attrs.emoji)return e.attrs.emoji;const t=[{tag:"img",attrs:{src:e.attrs.fallbackImage,draggable:"false",loading:"lazy",align:"absmiddle"}}];return this.renderTag(t," /")}}const O=Ee;class Ie{constructor(e){p(this,"baseURL"),p(this,"timeout"),p(this,"headers"),p(this,"responseInterceptor"),p(this,"fetch"),p(this,"ejectInterceptor"),p(this,"url"),p(this,"parameters"),p(this,"fetchOptions"),this.baseURL=e.baseURL,this.headers=e.headers||new Headers,this.timeout=e!=null&&e.timeout?e.timeout*1e3:0,this.responseInterceptor=e.responseInterceptor,this.fetch=(...t)=>e.fetch?e.fetch(...t):fetch(...t),this.ejectInterceptor=!1,this.url="",this.parameters={},this.fetchOptions={}}get(e,t){return this.url=e,this.parameters=t,this._methodHandler("get")}post(e,t){return this.url=e,this.parameters=t,this._methodHandler("post")}put(e,t){return this.url=e,this.parameters=t,this._methodHandler("put")}delete(e,t){return this.url=e,this.parameters=t,this._methodHandler("delete")}async _responseHandler(e){const t=[],s={data:{},headers:{},status:0,statusText:""};e.status!==204&&await e.json().then(r=>{s.data=r});for(const r of e.headers.entries())t[r[0]]=r[1];return s.headers={...t},s.status=e.status,s.statusText=e.statusText,s}async _methodHandler(e){let t=`${this.baseURL}${this.url}`,s=null;if(e==="get"){const a=new L;t=`${this.baseURL}${this.url}?${a.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const r=new URL(t),n=new AbortController,{signal:o}=n;let l;this.timeout&&(l=setTimeout(()=>n.abort(),this.timeout));try{const a=await this.fetch(`${r}`,{method:e,headers:this.headers,body:s,signal:o,...this.fetchOptions});this.timeout&&clearTimeout(l);const c=await this._responseHandler(a);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(c)):this._statusHandler(c)}catch(a){return{message:a}}}setFetchOptions(e={}){Object.keys(e).length>0&&"method"in e&&delete e.method,this.fetchOptions={...e}}eject(){this.ejectInterceptor=!0}_statusHandler(e){const t=/20[0-6]/g;return new Promise((s,r)=>{if(t.test(`${e.status}`))return s(e);const n={message:e.statusText,status:e.status,response:Array.isArray(e.data)?e.data[0]:e.data.error||e.data.slug};r(n)})}}const je=Ie,G="SB-Agent",P={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"6.0.0"};let A={};const _={};class Oe{constructor(e,t){p(this,"client"),p(this,"maxRetries"),p(this,"retriesDelay"),p(this,"throttle"),p(this,"accessToken"),p(this,"cache"),p(this,"helpers"),p(this,"resolveCounter"),p(this,"relations"),p(this,"links"),p(this,"richTextResolver"),p(this,"resolveNestedRelations"),p(this,"stringifiedStoriesCache");let s=e.endpoint||t;if(!s){const o=new L().getRegionURL,l=e.https===!1?"http":"https";e.oauthToken?s=`${l}://${o(e.region)}/v1`:s=`${l}://${o(e.region)}/v2`}const r=new Headers;r.set("Content-Type","application/json"),r.set("Accept","application/json"),e.headers&&(e.headers.constructor.name==="Headers"?e.headers.entries().toArray():Object.entries(e.headers)).forEach(([o,l])=>{r.set(o,l)}),r.has(G)||(r.set(G,P.defaultAgentName),r.set(P.defaultAgentVersion,P.packageVersion));let n=5;e.oauthToken&&(r.set("Authorization",e.oauthToken),n=3),e.rateLimit&&(n=e.rateLimit),e.richTextSchema?this.richTextResolver=new O(e.richTextSchema):this.richTextResolver=new O,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||10,this.retriesDelay=300,this.throttle=Z(this.throttledRequest.bind(this),n,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new L,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.stringifiedStoriesCache={},this.client=new je({baseURL:s,timeout:e.timeout||0,headers:r,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let s="";return t.attrs.body&&t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})}parseParams(e){return e.token||(e.token=this.getToken()),e.cv||(e.cv=_[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),typeof e.resolve_relations<"u"&&(e.resolve_level=2),e}factoryParamOptions(e,t){return this.helpers.isCDNUrl(e)?this.parseParams(t):t}makeRequest(e,t,s,r,n){const o=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,s,r));return this.cacheResponse(e,o,void 0,n)}get(e,t,s){t||(t={});const r=`/${e}`,n=this.factoryParamOptions(r,t);return this.cacheResponse(r,n,void 0,s)}async getAll(e,t,s,r){const n=(t==null?void 0:t.per_page)||25,o=`/${e}`.replace(/\/$/,""),l=s??o.substring(o.lastIndexOf("/")+1),a=1,c=await this.makeRequest(o,t,n,a,r),d=c.total?Math.ceil(c.total/n):1,u=await this.helpers.asyncMap(this.helpers.range(a,d),g=>this.makeRequest(o,t,n,g+1,r));return this.helpers.flatMap([c,...u],g=>Object.values(g.data[l]))}post(e,t,s){const r=`/${e}`;return Promise.resolve(this.throttle("post",r,t,s))}put(e,t,s){const r=`/${e}`;return Promise.resolve(this.throttle("put",r,t,s))}delete(e,t,s){const r=`/${e}`;return Promise.resolve(this.throttle("delete",r,t,s))}getStories(e,t){return this._addResolveLevel(e),this.get("cdn/stories",e,t)}getStory(e,t,s){return this._addResolveLevel(t),this.get(`cdn/stories/${e}`,t,s)}getToken(){return this.accessToken}ejectInterceptor(){this.client.eject()}_addResolveLevel(e){typeof e.resolve_relations<"u"&&(e.resolve_level=2)}_cleanCopy(e){return JSON.parse(JSON.stringify(e))}_insertLinks(e,t,s){const r=e[t];r&&r.fieldtype==="multilink"&&r.linktype==="story"&&typeof r.id=="string"&&this.links[s][r.id]?r.story=this._cleanCopy(this.links[s][r.id]):r&&r.linktype==="story"&&typeof r.uuid=="string"&&this.links[s][r.uuid]&&(r.story=this._cleanCopy(this.links[s][r.uuid]))}getStoryReference(e,t){return this.relations[e][t]?(this.stringifiedStoriesCache[t]||(this.stringifiedStoriesCache[t]=JSON.stringify(this.relations[e][t])),JSON.parse(this.stringifiedStoriesCache[t])):t}_insertRelations(e,t,s,r){s.includes(`${e.component}.${t}`)&&(typeof e[t]=="string"?e[t]=this.getStoryReference(r,e[t]):Array.isArray(e[t])&&(e[t]=e[t].map(n=>this.getStoryReference(r,n)).filter(Boolean)))}iterateTree(e,t,s){const r=n=>{if(n!=null){if(n.constructor===Array)for(let o=0;o<n.length;o++)r(n[o]);else if(n.constructor===Object){if(n._stopResolving)return;for(const o in n)(n.component&&n._uid||n.type==="link")&&(this._insertRelations(n,o,t,s),this._insertLinks(n,o,s)),r(n[o])}}};r(e.content)}async resolveLinks(e,t,s){let r=[];if(e.link_uuids){const n=e.link_uuids.length,o=[],l=50;for(let a=0;a<n;a+=l){const c=Math.min(n,a+l);o.push(e.link_uuids.slice(a,c))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:o[a].join(",")})).data.stories.forEach(c=>{r.push(c)})}else r=e.links;r.forEach(n=>{this.links[s][n.uuid]={...n,_stopResolving:!0}})}async resolveRelations(e,t,s){let r=[];if(e.rel_uuids){const n=e.rel_uuids.length,o=[],l=50;for(let a=0;a<n;a+=l){const c=Math.min(n,a+l);o.push(e.rel_uuids.slice(a,c))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:o[a].join(","),excluding_fields:t.excluding_fields})).data.stories.forEach(c=>{r.push(c)})}else r=e.rels;r&&r.length>0&&r.forEach(n=>{this.relations[s][n.uuid]={...n,_stopResolving:!0}})}async resolveStories(e,t,s){var r,n;let o=[];if(this.links[s]={},this.relations[s]={},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,s)),t.resolve_links&&["1","story","url","link"].includes(t.resolve_links)&&((r=e.links)!=null&&r.length||(n=e.link_uuids)!=null&&n.length)&&await this.resolveLinks(e,t,s),this.resolveNestedRelations)for(const l in this.relations[s])this.iterateTree(this.relations[s][l],o,s);e.story?this.iterateTree(e.story,o,s):e.stories.forEach(l=>{this.iterateTree(l,o,s)}),this.stringifiedStoriesCache={},delete this.links[s],delete this.relations[s]}async cacheResponse(e,t,s,r){const n=this.helpers.stringify({url:e,params:t}),o=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&await this.flushCache(),t.version==="published"&&e!=="/cdn/spaces/me"){const l=await o.get(n);if(l)return Promise.resolve(l)}return new Promise(async(l,a)=>{var c;try{const d=await this.throttle("get",e,t,r);if(d.status!==200)return a(d);let u={data:d.data,headers:d.headers};if((c=d.headers)!=null&&c["per-page"]&&(u=Object.assign({},u,{perPage:d.headers["per-page"]?Number.parseInt(d.headers["per-page"]):0,total:d.headers["per-page"]?Number.parseInt(d.headers.total):0})),u.data.story||u.data.stories){const g=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(u.data,t,`${g}`)}return t.version==="published"&&e!=="/cdn/spaces/me"&&await o.set(n,u),u.data.cv&&t.token&&_[t.token]!==u.data.cv&&(await this.flushCache(),_[t.token]=u.data.cv),l(u)}catch(d){if(d.response&&d.status===429&&(s=typeof s>"u"?0:s+1,s<this.maxRetries))return console.log(`Hit rate limit. Retrying in ${this.retriesDelay/1e3} seconds.`),await this.helpers.delay(this.retriesDelay),this.cacheResponse(e,t,s).then(l).catch(a);a(d)}})}throttledRequest(e,t,s,r){return this.client.setFetchOptions(r),this.client[e](t,s)}cacheVersions(){return _}cacheVersion(){return _[this.accessToken]}setCacheVersion(e){this.accessToken&&(_[this.accessToken]=e)}clearCacheVersion(){this.accessToken&&(_[this.accessToken]=0)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(A[e])},getAll(){return Promise.resolve(A)},set(e,t){return A[e]=t,Promise.resolve(void 0)},flush(){return A={},Promise.resolve(void 0)}};case"custom":if(this.cache.custom)return this.cache.custom;default:return{get(){return Promise.resolve()},getAll(){return Promise.resolve(void 0)},set(){return Promise.resolve(void 0)},flush(){return Promise.resolve(void 0)}}}}async flushCache(){return await this.cacheProvider().flush(),this.clearCacheVersion(),this}}const xe=(i={})=>{const{apiOptions:e}=i;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)}},Le=i=>{if(typeof i!="object"||typeof i._editable>"u")return{};try{const e=JSON.parse(i._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return e?{"data-blok-c":JSON.stringify(e),"data-blok-uid":e.id+"-"+e.uid}:{}}catch{return{}}};function Ae(i,e){if(!e)return{src:i,attrs:{}};let t=0,s=0;const r={},n=[];function o(a,c,d,u,g){typeof a!="number"||a<=c||a>=d?console.warn(`[StoryblokRichText] - ${u.charAt(0).toUpperCase()+u.slice(1)} value must be a number between ${c} and ${d} (inclusive)`):g.push(`${u}(${a})`)}if(typeof e=="object"){if(typeof e.width=="number"&&e.width>0?(r.width=e.width,t=e.width):console.warn("[StoryblokRichText] - Width value must be a number greater than 0"),e.height&&typeof e.height=="number"&&e.height>0?(r.height=e.height,s=e.height):console.warn("[StoryblokRichText] - Height value must be a number greater than 0"),e.loading&&["lazy","eager"].includes(e.loading)&&(r.loading=e.loading),e.class&&(r.class=e.class),e.filters){const{filters:a}=e||{},{blur:c,brightness:d,fill:u,format:g,grayscale:w,quality:b,rotate:S}=a||{};c&&o(c,0,100,"blur",n),b&&o(b,0,100,"quality",n),d&&o(d,0,100,"brightness",n),u&&n.push(`fill(${u})`),w&&n.push("grayscale()"),S&&[0,90,180,270].includes(e.filters.rotate||0)&&n.push(`rotate(${S})`),g&&["webp","png","jpeg"].includes(g)&&n.push(`format(${g})`)}e.srcset&&(r.srcset=e.srcset.map(a=>{if(typeof a=="number")return`${i}/m/${a}x0/${n.length>0?`filters:${n.join(":")}`:""} ${a}w`;if(Array.isArray(a)&&a.length===2){const[c,d]=a;return`${i}/m/${c}x${d}/${n.length>0?`filters:${n.join(":")}`:""} ${c}w`}else{console.warn("[StoryblokRichText] - srcset entry must be a number or a tuple of two numbers");return}}).join(", ")),e.sizes&&(r.sizes=e.sizes.join(", "))}let l=`${i}/m/`;return t>0&&s>0&&(l=`${l}${t}x${s}/`),n.length>0&&(l=`${l}filters:${n.join(":")}`),{src:l,attrs:r}}var k=(i=>(i.DOCUMENT="doc",i.HEADING="heading",i.PARAGRAPH="paragraph",i.QUOTE="blockquote",i.OL_LIST="ordered_list",i.UL_LIST="bullet_list",i.LIST_ITEM="list_item",i.CODE_BLOCK="code_block",i.HR="horizontal_rule",i.BR="hard_break",i.IMAGE="image",i.EMOJI="emoji",i.COMPONENT="blok",i))(k||{}),$=(i=>(i.BOLD="bold",i.STRONG="strong",i.STRIKE="strike",i.UNDERLINE="underline",i.ITALIC="italic",i.CODE="code",i.LINK="link",i.ANCHOR="anchor",i.STYLED="styled",i.SUPERSCRIPT="superscript",i.SUBSCRIPT="subscript",i.TEXT_STYLE="textStyle",i.HIGHLIGHT="highlight",i))($||{}),N=(i=>(i.TEXT="text",i))(N||{}),x=(i=>(i.URL="url",i.STORY="story",i.ASSET="asset",i.EMAIL="email",i))(x||{});const Ce=["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"],Pe=(i={})=>Object.keys(i).map(e=>`${e}="${i[e]}"`).join(" "),Ne=(i={})=>Object.keys(i).map(e=>`${e}: ${i[e]}`).join("; ");function Me(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}const F=i=>Object.fromEntries(Object.entries(i).filter(([e,t])=>t!==void 0));function He(i,e={},t){const s=Pe(e),r=s?`${i} ${s}`:i;return Ce.includes(i)?`<${r}>`:`<${r}>${Array.isArray(t)?t.join(""):t||""}</${i}>`}function Ue(i={}){let e=0;const{renderFn:t=He,textFn:s=Me,resolvers:r={},optimizeImages:n=!1,keyedResolvers:o=!1}=i,l=h=>f=>{const m=f.attrs||{};return o&&(m.key=`${h}-${e}`),t(h,m,f.children||null)},a=h=>{const{src:f,alt:m,title:v,srcset:R,sizes:T}=h.attrs||{};let E=f,I={};if(n){const{src:Fe,attrs:Ve}=Ae(f,n);E=Fe,I=Ve}o&&(I={...I,key:`img-${e}`});const Ge={src:E,alt:m,title:v,srcset:R,sizes:T,...I};return t("img",F(Ge))},c=h=>{const{level:f,...m}=h.attrs||{},v={...m};return o&&(v.key=`h${f}-${e}`),t(`h${f}`,v,h.children)},d=h=>{var f,m,v,R;const T=t("img",{src:(f=h.attrs)==null?void 0:f.fallbackImage,alt:(m=h.attrs)==null?void 0:m.alt,style:"width: 1.25em; height: 1.25em; vertical-align: text-top",draggable:"false",loading:"lazy"}),E={"data-type":"emoji","data-name":(v=h.attrs)==null?void 0:v.name,"data-emoji":(R=h.attrs)==null?void 0:R.emoji};return o&&(E.key=`emoji-${e}`),t("span",E,T)},u=h=>t("pre",{...h.attrs,key:`code-${e}`},t("code",{key:`code-${e}`},h.children||"")),g=(h,f=!1)=>({text:m,attrs:v})=>{const{class:R,id:T,...E}=v||{},I=f?{class:R,id:T,style:Ne(E)||void 0}:v||{};return o&&(I.key=`${h}-${e}`),t(h,F(I),m)},w=h=>U(h),b=h=>{const{marks:f,...m}=h;return"text"in h?f?f.reduce((v,R)=>w({...R,text:v}),w({...m,children:m.children})):s(m.text):""},S=h=>{const{linktype:f,href:m,anchor:v,...R}=h.attrs||{};let T="";switch(f){case x.ASSET:case x.URL:T=m;break;case x.EMAIL:T=`mailto:${m}`;break;case x.STORY:T=m;break}return v&&(T=`${T}#${v}`),t("a",{...R,href:T,key:`a-${e}`},h.text)},C=h=>{var f,m;return console.warn("[StoryblokRichtText] - BLOK resolver is not available for vanilla usage"),t("span",{blok:(f=h==null?void 0:h.attrs)==null?void 0:f.body[0],id:(m=h.attrs)==null?void 0:m.id,key:`component-${e}`,style:"display: none"})},qe=new Map([[k.DOCUMENT,l("div")],[k.HEADING,c],[k.PARAGRAPH,l("p")],[k.UL_LIST,l("ul")],[k.OL_LIST,l("ol")],[k.LIST_ITEM,l("li")],[k.IMAGE,a],[k.EMOJI,d],[k.CODE_BLOCK,u],[k.HR,l("hr")],[k.BR,l("br")],[k.QUOTE,l("blockquote")],[k.COMPONENT,C],[N.TEXT,b],[$.LINK,S],[$.ANCHOR,S],[$.STYLED,g("span",!0)],[$.BOLD,g("strong")],[$.TEXT_STYLE,g("span",!0)],[$.ITALIC,g("em")],[$.UNDERLINE,g("u")],[$.STRIKE,g("s")],[$.CODE,g("code")],[$.SUPERSCRIPT,g("sup")],[$.SUBSCRIPT,g("sub")],[$.HIGHLIGHT,g("mark")],...Object.entries(r).map(([h,f])=>[h,f])]);function Y(h){e+=1;const f=qe.get(h.type);if(!f)return console.error("<Storyblok>",`No resolver found for node type ${h.type}`),"";if(h.type==="text")return f(h);const m=h.content?h.content.map(U):void 0;return f({...h,children:m})}function U(h){return Array.isArray(h)?h.map(Y):Y(h)}return{render:U}}let M,H="https://app.storyblok.com/f/storyblok-v2-latest.js";const V=(i,e,t={})=>{var l;const r=!(typeof window>"u")&&typeof window.storyblokRegisterEvent<"u",o=+new URL((l=window.location)==null?void 0:l.href).searchParams.get("_storyblok")===i;if(!(!r||!o)){if(!i){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(t).on(["input","published","change"],c=>{c.action==="input"&&c.story.id===i?e(c.story):(c.action==="change"||c.action==="published")&&c.storyId===i&&window.location.reload()})})}},ze=(i={})=>{var u,g;const{bridge:e,accessToken:t,use:s=[],apiOptions:r={},richText:n={},bridgeUrl:o}=i;r.accessToken=r.accessToken||t;const l={bridge:e,apiOptions:r};let a={};s.forEach(w=>{a={...a,...w(l)}}),o&&(H=o);const d=!(typeof window>"u")&&((g=(u=window.location)==null?void 0:u.search)==null?void 0:g.includes("_storyblok_tk"));return e!==!1&&d&&B(H),M=new O(n.schema),n.resolver&&J(M,n.resolver),a},J=(i,e)=>{i.addNode("blok",t=>{let s="";return t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})},K=i=>!i||!(i!=null&&i.content.some(e=>e.content||e.type==="blok"||e.type==="horizontal_rule")),Be=(i,e,t)=>{let s=t||M;if(!s){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return K(i)?"":(e&&(s=new O(e.schema),e.resolver&&J(s,e.resolver)),s.render(i,{},!1))},De=()=>B(H);y.BlockTypes=k,y.MarkTypes=$,y.RichTextResolver=O,y.RichTextSchema=D,y.TextTypes=N,y.apiPlugin=xe,y.isRichTextEmpty=K,y.loadStoryblokBridge=De,y.registerStoryblokBridge=V,y.renderRichText=Be,y.richTextResolver=Ue,y.storyblokEditable=Le,y.storyblokInit=ze,y.useStoryblokBridge=V,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"})});
|
package/dist/types/types.d.ts
DELETED
@@ -1,63 +0,0 @@
|
|
1
|
-
import StoryblokJSClient, { ISbConfig, ISbComponentType, ISbStoryData } from "storyblok-js-client";
|
2
|
-
export type StoryblokClient = StoryblokJSClient;
|
3
|
-
declare global {
|
4
|
-
interface Window {
|
5
|
-
storyblokRegisterEvent: (cb: Function) => void;
|
6
|
-
StoryblokBridge: {
|
7
|
-
new (options?: StoryblokBridgeConfigV2): StoryblokBridgeV2;
|
8
|
-
};
|
9
|
-
}
|
10
|
-
}
|
11
|
-
export interface SbInitResult {
|
12
|
-
storyblokApi?: StoryblokClient;
|
13
|
-
}
|
14
|
-
export type SbPluginFactory = (options: SbSDKOptions) => any;
|
15
|
-
export type SbBlokKeyDataTypes = string | number | object | boolean | undefined;
|
16
|
-
export interface SbBlokData extends ISbComponentType<string> {
|
17
|
-
[index: string]: SbBlokKeyDataTypes;
|
18
|
-
}
|
19
|
-
export interface SbRichTextOptions {
|
20
|
-
schema?: ISbConfig["richTextSchema"];
|
21
|
-
resolver?: ISbConfig["componentResolver"];
|
22
|
-
}
|
23
|
-
export interface SbSDKOptions {
|
24
|
-
bridge?: boolean;
|
25
|
-
accessToken?: string;
|
26
|
-
use?: any[];
|
27
|
-
apiOptions?: ISbConfig;
|
28
|
-
richText?: SbRichTextOptions;
|
29
|
-
bridgeUrl?: string;
|
30
|
-
}
|
31
|
-
export interface ISbEventPayload<S extends ISbComponentType<string> = any> {
|
32
|
-
action: "customEvent" | "published" | "input" | "change" | "unpublished" | "enterEditmode";
|
33
|
-
event?: string;
|
34
|
-
story?: ISbStoryData<S>;
|
35
|
-
slug?: string;
|
36
|
-
slugChanged?: boolean;
|
37
|
-
storyId?: number;
|
38
|
-
reload?: boolean;
|
39
|
-
}
|
40
|
-
export interface StoryblokBridgeConfigV2 {
|
41
|
-
resolveRelations?: string | string[];
|
42
|
-
customParent?: string;
|
43
|
-
preventClicks?: boolean;
|
44
|
-
language?: string;
|
45
|
-
resolveLinks?: "url" | "story" | "0" | "1" | "link";
|
46
|
-
}
|
47
|
-
export interface StoryblokBridgeV2 {
|
48
|
-
pingEditor: (event: any) => void;
|
49
|
-
isInEditor: () => boolean;
|
50
|
-
enterEditmode: () => void;
|
51
|
-
on: (event: "customEvent" | "published" | "input" | "change" | "unpublished" | "enterEditmode" | string[], callback: (payload?: ISbEventPayload) => void) => void;
|
52
|
-
}
|
53
|
-
export type { ISbConfig, // previously StoryblokConfig
|
54
|
-
ISbCache, // previously StoryblokCache
|
55
|
-
ISbResult, // previously StoryblokResult
|
56
|
-
ISbResponse, ISbError, ISbNode, ISbSchema, ISbThrottle, ISbThrottledRequest, AsyncFn, ArrayFn, ISbContentMangmntAPI, ISbManagmentApiResult, // previously StoryblokManagmentApiResult
|
57
|
-
ISbStories, // previously Stories
|
58
|
-
ISbStory, // previously Story
|
59
|
-
ISbDimensions, ISbComponentType as StoryblokComponentType, ISbStoryData, // previously StoryData
|
60
|
-
ISbAlternateObject, // previously AlternateObject
|
61
|
-
ISbStoriesParams, // previously StoriesParams
|
62
|
-
ISbStoryParams, // previously StoryParams
|
63
|
-
ISbRichtext, } from "storyblok-js-client";
|
File without changes
|