@storyblok/js 3.0.8 â 3.1.0-next.2
Sign up to get free protection for your applications and to get access to all the features.
- package/README.md +23 -23
- package/dist/storyblok-js.js +2 -2
- package/dist/storyblok-js.mjs +578 -410
- package/dist/types/index.d.ts +8 -1
- package/package.json +13 -4
package/README.md
CHANGED
@@ -30,11 +30,11 @@
|
|
30
30
|
</a>
|
31
31
|
</p>
|
32
32
|
|
33
|
-
##
|
33
|
+
## Kickstart a new project
|
34
34
|
|
35
|
-
|
35
|
+
Are you eager to dive into coding? **[Follow these steps to kickstart a new project with Storyblok and a JavaScript frontend framework](https://www.storyblok.com/technologies?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-js)**, and get started in just a few minutes!
|
36
36
|
|
37
|
-
|
37
|
+
## Installation
|
38
38
|
|
39
39
|
Install `@storyblok/js`:
|
40
40
|
|
@@ -45,7 +45,7 @@ npm install @storyblok/js
|
|
45
45
|
|
46
46
|
> â ī¸ This SDK uses the Fetch API under the hood. If your environment doesn't support it, you need to install a polyfill like [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch). More info on [storyblok-js-client docs](https://github.com/storyblok/storyblok-js-client#fetch-use-polyfill-if-needed---version-5).
|
47
47
|
|
48
|
-
|
48
|
+
### From a CDN
|
49
49
|
|
50
50
|
Install the file from the CDN:
|
51
51
|
|
@@ -53,7 +53,7 @@ Install the file from the CDN:
|
|
53
53
|
<script src="https://unpkg.com/@storyblok/js"></script>
|
54
54
|
```
|
55
55
|
|
56
|
-
|
56
|
+
## Initialization
|
57
57
|
|
58
58
|
Register the plugin on your application and add the [access token](https://www.storyblok.com/docs/api/content-delivery#topics/authentication?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-js) of your Storyblok space. You can also add the `apiPlugin` in case that you want to use the Storyblok API Client:
|
59
59
|
|
@@ -70,7 +70,7 @@ That's it! All the features are enabled for you: the _Api Client_ for interactin
|
|
70
70
|
|
71
71
|
> You can enable/disable some of these features if you don't need them, so you save some KB. Please read the "Features and API" section
|
72
72
|
|
73
|
-
|
73
|
+
### Region parameter
|
74
74
|
|
75
75
|
Possible values:
|
76
76
|
|
@@ -96,7 +96,7 @@ const { storyblokApi } = storyblokInit({
|
|
96
96
|
|
97
97
|
> Note: For spaces created in the United States or China, the `region` parameter **must** be specified.
|
98
98
|
|
99
|
-
|
99
|
+
## Getting Started
|
100
100
|
|
101
101
|
`@storyblok/js` does three actions when you initialize it:
|
102
102
|
|
@@ -104,7 +104,7 @@ const { storyblokApi } = storyblokInit({
|
|
104
104
|
- Loads [Storyblok Bridge](https://www.storyblok.com/docs/Guides/storyblok-latest-js?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-js) for real-time visual updates.
|
105
105
|
- Provides a `storyblokEditable` function to link editable components to the Storyblok Visual Editor.
|
106
106
|
|
107
|
-
|
107
|
+
### 1. Fetching Content
|
108
108
|
|
109
109
|
Inject `storyblokApi`:
|
110
110
|
|
@@ -121,7 +121,7 @@ const { data } = await storyblokApi.get("cdn/stories", { version: "draft" });
|
|
121
121
|
|
122
122
|
> Note: if you don't use `apiPlugin`, you can use your prefered method or function to fetch your data.
|
123
123
|
|
124
|
-
|
124
|
+
### 2. Listen to Storyblok Visual Editor events
|
125
125
|
|
126
126
|
Use `useStoryblokBridge` or `registerStoryblokBridge` to get the new story every time is triggered a `change` event from the Visual Editor. You need to pass the story id as first param, and a callback function as second param to update the new story:
|
127
127
|
|
@@ -145,11 +145,11 @@ You can pass [Bridge options](https://www.storyblok.com/docs/Guides/storyblok-la
|
|
145
145
|
```js
|
146
146
|
useStoryblokBridge(story.id, (story) => (state.story = story), {
|
147
147
|
resolveRelations: ["Article.author"],
|
148
|
-
resolveLinks: "url"
|
148
|
+
resolveLinks: "url",
|
149
149
|
});
|
150
150
|
```
|
151
151
|
|
152
|
-
|
152
|
+
### 3. Link your components to Storyblok Visual Editor
|
153
153
|
|
154
154
|
To link your app and Storyblok components together will depend on the framework you are using. But, in the end, you must add the `data-blok-c` and `data-blok-uid` attributes, and the `storyblok__outline` class.
|
155
155
|
|
@@ -172,11 +172,11 @@ const vEditableDirective = {
|
|
172
172
|
|
173
173
|
At this point, you'll have your app connected to Storyblok with the real-time editing experience fully enabled.
|
174
174
|
|
175
|
-
|
175
|
+
## Features and API
|
176
176
|
|
177
177
|
You can **choose the features to use** when you initialize the plugin. In that way, you can improve Web Performance by optimizing your page load and save some bytes.
|
178
178
|
|
179
|
-
|
179
|
+
### Storyblok API
|
180
180
|
|
181
181
|
You can use an `apiOptions` object. This is passed down to the (storyblok-js-client config object](https://github.com/storyblok/storyblok-js-client#class-storyblok):
|
182
182
|
|
@@ -197,7 +197,7 @@ If you prefer to use your own fetch method, just remove the `apiPlugin` and `sto
|
|
197
197
|
storyblokInit({});
|
198
198
|
```
|
199
199
|
|
200
|
-
|
200
|
+
### Storyblok Bridge
|
201
201
|
|
202
202
|
You can conditionally load it by using the `bridge` option. Very useful if you want to disable it in production:
|
203
203
|
|
@@ -217,7 +217,7 @@ sbBridge.on(["input", "published", "change"], (event) => {
|
|
217
217
|
});
|
218
218
|
```
|
219
219
|
|
220
|
-
|
220
|
+
### Rendering Rich Text
|
221
221
|
|
222
222
|
You can easily render rich text by using the `renderRichText` function that comes with `@storyblok/js`:
|
223
223
|
|
@@ -276,20 +276,20 @@ renderRichText(blok.richTextField, {
|
|
276
276
|
|
277
277
|
![A visual representation of the Storyblok JavaScript SDK Ecosystem](https://a.storyblok.com/f/88751/2400x1350/be4a4a4180/sdk-ecosystem.png/m/1200x0)
|
278
278
|
|
279
|
-
##
|
279
|
+
## Further Resources
|
280
280
|
|
281
|
-
-
|
282
|
-
-
|
283
|
-
-
|
281
|
+
- [Quick Start](https://www.storyblok.com/technologies?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-js)
|
282
|
+
- [API Documentation](https://www.storyblok.com/docs/api?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-js)
|
283
|
+
- [Developer Tutorials](https://www.storyblok.com/tutorials?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-js)
|
284
|
+
- [Developer Guides](https://www.storyblok.com/docs/guide/introduction?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-js)
|
285
|
+
- [FAQs](https://www.storyblok.com/faqs?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-js)
|
284
286
|
|
285
|
-
##
|
286
|
-
|
287
|
-
### Support
|
287
|
+
## Support
|
288
288
|
|
289
289
|
- Bugs or Feature Requests? [Submit an issue](/../../issues/new).
|
290
290
|
- Do you have questions about Storyblok or you need help? [Join our Discord Community](https://discord.gg/jKrbAMz).
|
291
291
|
|
292
|
-
|
292
|
+
## Contributing
|
293
293
|
|
294
294
|
Please see our [contributing guidelines](https://github.com/storyblok/.github/blob/main/contributing.md) and our [code of conduct](https://www.storyblok.com/trust-center#code-of-conduct?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-js).
|
295
295
|
This project use [semantic-release](https://semantic-release.gitbook.io/semantic-release/) for generate new versions by using commit messages and we use the Angular Convention to naming the commits. Check [this question](https://semantic-release.gitbook.io/semantic-release/support/faq#how-can-i-change-the-type-of-commits-that-trigger-a-release) about it in semantic-release FAQ
|
package/dist/storyblok-js.js
CHANGED
@@ -1,4 +1,4 @@
|
|
1
|
-
(function(
|
1
|
+
(function(m,E){typeof exports=="object"&&typeof module<"u"?E(exports):typeof define=="function"&&define.amd?define(["exports"],E):(m=typeof globalThis<"u"?globalThis:m||self,E(m.storyblok={}))})(this,function(m){"use strict";let E=!1;const U=[],H=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}E?r():U.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=>{U.forEach(n=>n()),E=!0,e(r)},document.getElementsByTagName("head")[0].appendChild(s)});var J=Object.defineProperty,K=(i,e,t)=>e in i?J(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,d=(i,e,t)=>(K(i,typeof e!="symbol"?e+"":e,t),t);function B(i){return!(i!==i||i===1/0||i===-1/0)}function Y(i,e,t){if(!B(e))throw new TypeError("Expected `limit` to be a finite number");if(!B(t))throw new TypeError("Expected `interval` to be a finite number");const s=[];let r=[],n=0;const o=function(){n++;const a=setTimeout(function(){n--,s.length>0&&o(),r=r.filter(function(u){return u!==a})},t);r.indexOf(a)<0&&r.push(a);const l=s.shift();l.resolve(i.apply(l.self,l.args))},c=function(...a){const l=this;return new Promise(function(u,p){s.push({resolve:u,reject:p,args:a,self:l}),n<e&&o()})};return c.abort=function(){r.forEach(clearTimeout),r=[],s.forEach(function(a){a.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),s.length=0},c}class j{constructor(){d(this,"isCDNUrl",(e="")=>e.indexOf("/cdn/")>-1),d(this,"getOptionsPage",(e,t=25,s=1)=>({...e,per_page:t,page:s})),d(this,"delay",e=>new Promise(t=>setTimeout(t,e))),d(this,"arrayFrom",(e=0,t)=>[...Array(e)].map(t)),d(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)}),d(this,"asyncMap",async(e,t)=>Promise.all(e.map(t))),d(this,"flatMap",(e=[],t)=>e.map(t).reduce((s,r)=>[...s,...r],[])),d(this,"escapeHTML",function(e){const t={"&":"&","<":"<",">":">",'"':""","'":"'"},s=/[&<>"']/g,r=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],c=s?"":encodeURIComponent(n);let a;typeof o=="object"?a=this.stringify(o,t?t+encodeURIComponent("["+c+"]"):c,Array.isArray(o)):a=(t?t+encodeURIComponent("["+c+"]"):c)+"="+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 X=function(i,e){const t={};for(const s in i){const r=i[s];e.indexOf(s)>-1&&r!==null&&(t[s]=r)}return t},W=i=>i==="email",Q=()=>({singleTag:"hr"}),Z=()=>({tag:"blockquote"}),ee=()=>({tag:"ul"}),te=i=>({tag:["pre",{tag:"code",attrs:i.attrs}]}),se=()=>({singleTag:"br"}),re=i=>({tag:`h${i.attrs.level}`}),ie=i=>({singleTag:[{tag:"img",attrs:X(i.attrs,["src","alt","title"])}]}),ne=()=>({tag:"li"}),oe=()=>({tag:"ol"}),ae=()=>({tag:"p"}),le=i=>({tag:[{tag:"span",attrs:{"data-type":"emoji","data-name":i.attrs.name,emoji:i.attrs.emoji}}]}),ce=()=>({tag:"b"}),he=()=>({tag:"s"}),ue=()=>({tag:"u"}),de=()=>({tag:"strong"}),pe=()=>({tag:"code"}),ge=()=>({tag:"i"}),fe=i=>{if(!i.attrs)return{tag:""};const e=new j().escapeHTML,t={...i.attrs},{linktype:s="url"}=i.attrs;if(delete t.linktype,t.href&&(t.href=e(i.attrs.href||"")),W(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}]}},me=i=>({tag:[{tag:"span",attrs:i.attrs}]}),ye=()=>({tag:"sub"}),be=()=>({tag:"sup"}),ke=i=>({tag:[{tag:"span",attrs:i.attrs}]}),ve=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:""}},D={nodes:{horizontal_rule:Q,blockquote:Z,bullet_list:ee,code_block:te,hard_break:se,heading:re,image:ie,list_item:ne,ordered_list:oe,paragraph:ae,emoji:le},marks:{bold:ce,strike:he,underline:ue,strong:de,code:pe,italic:ge,link:fe,styled:me,subscript:ye,superscript:be,anchor:ke,highlight:ve,textStyle:$e}},Te=function(i){const e={"&":"&","<":"<",">":">",'"':""","'":"'"},t=/[&<>"']/g,s=RegExp(t.source);return i&&s.test(i)?i.replace(t,r=>e[r]):i};class I{constructor(e){d(this,"marks"),d(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}){if(console.warn("Warning â ī¸: The RichTextResolver class is deprecated and will be removed in the next major release. Please use the `@storyblok/richtext` instead. https://github.com/storyblok/richtext/"),e&&e.content&&Array.isArray(e.content)){let s="";return e.content.forEach(r=>{s+=this.renderNode(r)}),t.optimizeImages?this.optimizeImages(s,t.optimizeImages):s}return console.warn(`The render method must receive an Object with a "content" field.
|
2
2
|
The "content" field must be an array of nodes as the type ISbRichtext.
|
3
3
|
ISbRichtext:
|
4
4
|
content?: ISbRichtext[]
|
@@ -21,4 +21,4 @@
|
|
21
21
|
}
|
22
22
|
],
|
23
23
|
type: 'doc'
|
24
|
-
}`),""}optimizeImages(t,e){let s=0,r=0,i="",o="";typeof e!="boolean"&&(typeof e.width=="number"&&e.width>0&&(i+=`width="${e.width}" `,s=e.width),typeof e.height=="number"&&e.height>0&&(i+=`height="${e.height}" `,r=e.height),(e.loading==="lazy"||e.loading==="eager")&&(i+=`loading="${e.loading}" `),typeof e.class=="string"&&e.class.length>0&&(i+=`class="${e.class}" `),e.filters&&(typeof e.filters.blur=="number"&&e.filters.blur>=0&&e.filters.blur<=100&&(o+=`:blur(${e.filters.blur})`),typeof e.filters.brightness=="number"&&e.filters.brightness>=-100&&e.filters.brightness<=100&&(o+=`:brightness(${e.filters.brightness})`),e.filters.fill&&(e.filters.fill.match(/[0-9A-Fa-f]{6}/g)||e.filters.fill==="transparent")&&(o+=`:fill(${e.filters.fill})`),e.filters.format&&["webp","png","jpeg"].includes(e.filters.format)&&(o+=`:format(${e.filters.format})`),typeof e.filters.grayscale=="boolean"&&e.filters.grayscale&&(o+=":grayscale()"),typeof e.filters.quality=="number"&&e.filters.quality>=0&&e.filters.quality<=100&&(o+=`:quality(${e.filters.quality})`),e.filters.rotate&&[90,180,270].includes(e.filters.rotate)&&(o+=`:rotate(${e.filters.rotate})`),o.length>0&&(o="/filters"+o))),i.length>0&&(t=t.replace(/<img/g,`<img ${i.trim()}`));const c=s>0||r>0||o.length>0?`${s}x${r}${o}`:"";return t=t.replace(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g,`a.storyblok.com/f/$1/$2.$3/m/${c}`),typeof e!="boolean"&&(e.sizes||e.srcset)&&(t=t.replace(/<img.*?src=["|'](.*?)["|']/g,a=>{var l,u;const p=a.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);if(p&&p.length>0){const f={srcset:(l=e.srcset)==null?void 0:l.map(g=>{if(typeof g=="number")return`//${p}/m/${g}x0${o} ${g}w`;if(typeof g=="object"&&g.length===2){let _=0,A=0;return typeof g[0]=="number"&&(_=g[0]),typeof g[1]=="number"&&(A=g[1]),`//${p}/m/${_}x${A}${o} ${_}w`}}).join(", "),sizes:(u=e.sizes)==null?void 0:u.map(g=>g).join(", ")};let m="";return f.srcset&&(m+=`srcset="${f.srcset}" `),f.sizes&&(m+=`sizes="${f.sizes}" `),a.replace(/<img/g,`<img ${m.trim()}`)}return a})),t}renderNode(t){const e=[];t.marks&&t.marks.forEach(r=>{const i=this.getMatchingMark(r);i&&i.tag!==""&&e.push(this.renderOpeningTag(i.tag))});const s=this.getMatchingNode(t);return s&&s.tag&&e.push(this.renderOpeningTag(s.tag)),t.content?t.content.forEach(r=>{e.push(this.renderNode(r))}):t.text?e.push(ht(t.text)):s&&s.singleTag?e.push(this.renderTag(s.singleTag," /")):s&&s.html?e.push(s.html):t.type==="emoji"&&e.push(this.renderEmoji(t)),s&&s.tag&&e.push(this.renderClosingTag(s.tag)),t.marks&&t.marks.slice(0).reverse().forEach(r=>{const i=this.getMatchingMark(r);i&&i.tag!==""&&e.push(this.renderClosingTag(i.tag))}),e.join("")}renderTag(t,e){return t.constructor===String?`<${t}${e}>`:t.map(s=>{if(s.constructor===String)return`<${s}${e}>`;{let r=`<${s.tag}`;if(s.attrs)for(const i in s.attrs){const o=s.attrs[i];o!==null&&(r+=` ${i}="${o}"`)}return`${r}${e}>`}}).join("")}renderOpeningTag(t){return this.renderTag(t,"")}renderClosingTag(t){return t.constructor===String?`</${t}>`:t.slice(0).reverse().map(e=>e.constructor===String?`</${e}>`:`</${e.tag}>`).join("")}getMatchingNode(t){const e=this.nodes[t.type];if(typeof e=="function")return e(t)}getMatchingMark(t){const e=this.marks[t.type];if(typeof e=="function")return e(t)}renderEmoji(t){if(t.attrs.emoji)return t.attrs.emoji;const e=[{tag:"img",attrs:{src:t.attrs.fallbackImage,draggable:"false",loading:"lazy",align:"absmiddle"}}];return this.renderTag(e," /")}}class ut{constructor(t){h(this,"baseURL"),h(this,"timeout"),h(this,"headers"),h(this,"responseInterceptor"),h(this,"fetch"),h(this,"ejectInterceptor"),h(this,"url"),h(this,"parameters"),h(this,"fetchOptions"),this.baseURL=t.baseURL,this.headers=t.headers||new Headers,this.timeout=t!=null&&t.timeout?t.timeout*1e3:0,this.responseInterceptor=t.responseInterceptor,this.fetch=(...e)=>t.fetch?t.fetch(...e):fetch(...e),this.ejectInterceptor=!1,this.url="",this.parameters={},this.fetchOptions={}}get(t,e){return this.url=t,this.parameters=e,this._methodHandler("get")}post(t,e){return this.url=t,this.parameters=e,this._methodHandler("post")}put(t,e){return this.url=t,this.parameters=e,this._methodHandler("put")}delete(t,e){return this.url=t,this.parameters=e,this._methodHandler("delete")}async _responseHandler(t){const e=[],s={data:{},headers:{},status:0,statusText:""};t.status!==204&&await t.json().then(r=>{s.data=r});for(const r of t.headers.entries())e[r[0]]=r[1];return s.headers={...e},s.status=t.status,s.statusText=t.statusText,s}async _methodHandler(t){let e=`${this.baseURL}${this.url}`,s=null;if(t==="get"){const a=new k;e=`${this.baseURL}${this.url}?${a.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const r=new URL(e),i=new AbortController,{signal:o}=i;let c;this.timeout&&(c=setTimeout(()=>i.abort(),this.timeout));try{const a=await this.fetch(`${r}`,{method:t,headers:this.headers,body:s,signal:o,...this.fetchOptions});this.timeout&&clearTimeout(c);const l=await this._responseHandler(a);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(l)):this._statusHandler(l)}catch(a){return{message:a}}}setFetchOptions(t={}){Object.keys(t).length>0&&"method"in t&&delete t.method,this.fetchOptions={...t}}eject(){this.ejectInterceptor=!0}_statusHandler(t){const e=/20[0-6]/g;return new Promise((s,r)=>{if(e.test(`${t.status}`))return s(t);const i={message:t.statusText,status:t.status,response:Array.isArray(t.data)?t.data[0]:t.data.error||t.data.slug};r(i)})}}const E="SB-Agent",R={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"6.0.0"};let w={};const y={};class dt{constructor(t,e){h(this,"client"),h(this,"maxRetries"),h(this,"throttle"),h(this,"accessToken"),h(this,"cache"),h(this,"helpers"),h(this,"resolveCounter"),h(this,"relations"),h(this,"links"),h(this,"richTextResolver"),h(this,"resolveNestedRelations"),h(this,"stringifiedStoriesCache");let s=t.endpoint||e;if(!s){const o=new k().getRegionURL,c=t.https===!1?"http":"https";t.oauthToken?s=`${c}://${o(t.region)}/v1`:s=`${c}://${o(t.region)}/v2`}const r=new Headers;if(r.set("Content-Type","application/json"),r.set("Accept","application/json"),t.headers)for(const o in t.headers)r.set(o,t.headers[o]);r.has(E)||(r.set(E,R.defaultAgentName),r.set(R.defaultAgentVersion,R.packageVersion));let i=5;t.oauthToken&&(r.set("Authorization",t.oauthToken),i=3),t.rateLimit&&(i=t.rateLimit),t.richTextSchema?this.richTextResolver=new v(t.richTextSchema):this.richTextResolver=new v,t.componentResolver&&this.setComponentResolver(t.componentResolver),this.maxRetries=t.maxRetries||5,this.throttle=M(this.throttledRequest,i,1e3),this.accessToken=t.accessToken||"",this.relations={},this.links={},this.cache=t.cache||{clear:"manual"},this.helpers=new k,this.resolveCounter=0,this.resolveNestedRelations=t.resolveNestedRelations||!0,this.stringifiedStoriesCache={},this.client=new ut({baseURL:s,timeout:t.timeout||0,headers:r,responseInterceptor:t.responseInterceptor,fetch:t.fetch})}setComponentResolver(t){this.richTextResolver.addNode("blok",e=>{let s="";return e.attrs.body&&e.attrs.body.forEach(r=>{s+=t(r.component,r)}),{html:s}})}parseParams(t){return t.token||(t.token=this.getToken()),t.cv||(t.cv=y[t.token]),Array.isArray(t.resolve_relations)&&(t.resolve_relations=t.resolve_relations.join(",")),typeof t.resolve_relations<"u"&&(t.resolve_level=2),t}factoryParamOptions(t,e){return this.helpers.isCDNUrl(t)?this.parseParams(e):e}makeRequest(t,e,s,r){const i=this.factoryParamOptions(t,this.helpers.getOptionsPage(e,s,r));return this.cacheResponse(t,i)}get(t,e,s){e||(e={});const r=`/${t}`,i=this.factoryParamOptions(r,e);return this.client.setFetchOptions(s),this.cacheResponse(r,i)}async getAll(t,e,s,r){const i=(e==null?void 0:e.per_page)||25,o=`/${t}`,c=o.split("/"),a=s||c[c.length-1],l=1,u=await this.makeRequest(o,e,i,l),p=u.total?Math.ceil(u.total/i):1;this.client.setFetchOptions(r);const f=await this.helpers.asyncMap(this.helpers.range(l,p),m=>this.makeRequest(o,e,i,m+1));return this.helpers.flatMap([u,...f],m=>Object.values(m.data[a]))}post(t,e,s){const r=`/${t}`;return this.client.setFetchOptions(s),Promise.resolve(this.throttle("post",r,e))}put(t,e,s){const r=`/${t}`;return this.client.setFetchOptions(s),Promise.resolve(this.throttle("put",r,e))}delete(t,e,s){const r=`/${t}`;return this.client.setFetchOptions(s),Promise.resolve(this.throttle("delete",r,e))}getStories(t,e){return this.client.setFetchOptions(e),this._addResolveLevel(t),this.get("cdn/stories",t)}getStory(t,e,s){return this.client.setFetchOptions(s),this._addResolveLevel(e),this.get(`cdn/stories/${t}`,e)}getToken(){return this.accessToken}ejectInterceptor(){this.client.eject()}_addResolveLevel(t){typeof t.resolve_relations<"u"&&(t.resolve_level=2)}_cleanCopy(t){return JSON.parse(JSON.stringify(t))}_insertLinks(t,e,s){const r=t[e];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(t,e){return this.relations[t][e]?(this.stringifiedStoriesCache[e]||(this.stringifiedStoriesCache[e]=JSON.stringify(this.relations[t][e])),JSON.parse(this.stringifiedStoriesCache[e])):e}_insertRelations(t,e,s,r){s.indexOf(`${t.component}.${e}`)>-1&&(typeof t[e]=="string"?t[e]=this.getStoryReference(r,t[e]):Array.isArray(t[e])&&(t[e]=t[e].map(i=>this.getStoryReference(r,i)).filter(Boolean)))}iterateTree(t,e,s){const r=i=>{if(i!=null){if(i.constructor===Array)for(let o=0;o<i.length;o++)r(i[o]);else if(i.constructor===Object){if(i._stopResolving)return;for(const o in i)(i.component&&i._uid||i.type==="link")&&(this._insertRelations(i,o,e,s),this._insertLinks(i,o,s)),r(i[o])}}};r(t.content)}async resolveLinks(t,e,s){let r=[];if(t.link_uuids){const i=t.link_uuids.length,o=[],c=50;for(let a=0;a<i;a+=c){const l=Math.min(i,a+c);o.push(t.link_uuids.slice(a,l))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:c,language:e.language,version:e.version,by_uuids:o[a].join(",")})).data.stories.forEach(l=>{r.push(l)})}else r=t.links;r.forEach(i=>{this.links[s][i.uuid]={...i,_stopResolving:!0}})}async resolveRelations(t,e,s){let r=[];if(t.rel_uuids){const i=t.rel_uuids.length,o=[],c=50;for(let a=0;a<i;a+=c){const l=Math.min(i,a+c);o.push(t.rel_uuids.slice(a,l))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:c,language:e.language,version:e.version,by_uuids:o[a].join(","),excluding_fields:e.excluding_fields})).data.stories.forEach(l=>{r.push(l)})}else r=t.rels;r&&r.length>0&&r.forEach(i=>{this.relations[s][i.uuid]={...i,_stopResolving:!0}})}async resolveStories(t,e,s){var r,i;let o=[];if(this.links[s]={},this.relations[s]={},typeof e.resolve_relations<"u"&&e.resolve_relations.length>0&&(typeof e.resolve_relations=="string"&&(o=e.resolve_relations.split(",")),await this.resolveRelations(t,e,s)),e.resolve_links&&["1","story","url","link"].indexOf(e.resolve_links)>-1&&((r=t.links)!=null&&r.length||(i=t.link_uuids)!=null&&i.length)&&await this.resolveLinks(t,e,s),this.resolveNestedRelations)for(const c in this.relations[s])this.iterateTree(this.relations[s][c],o,s);t.story?this.iterateTree(t.story,o,s):t.stories.forEach(c=>{this.iterateTree(c,o,s)}),this.stringifiedStoriesCache={},delete this.links[s],delete this.relations[s]}async cacheResponse(t,e,s){(typeof s>"u"||!s)&&(s=0);const r=this.helpers.stringify({url:t,params:e}),i=this.cacheProvider();if(this.cache.clear==="auto"&&e.version==="draft"&&await this.flushCache(),e.version==="published"&&t!="/cdn/spaces/me"){const o=await i.get(r);if(o)return Promise.resolve(o)}return new Promise(async(o,c)=>{var a;try{const l=await this.throttle("get",t,e);if(l.status!==200)return c(l);let u={data:l.data,headers:l.headers};if((a=l.headers)!=null&&a["per-page"]&&(u=Object.assign({},u,{perPage:l.headers["per-page"]?parseInt(l.headers["per-page"]):0,total:l.headers["per-page"]?parseInt(l.headers.total):0})),u.data.story||u.data.stories){const p=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(u.data,e,`${p}`)}return e.version==="published"&&t!="/cdn/spaces/me"&&await i.set(r,u),u.data.cv&&e.token&&(e.version==="draft"&&y[e.token]!=u.data.cv&&await this.flushCache(),y[e.token]=e.cv?e.cv:u.data.cv),o(u)}catch(l){if(l.response&&l.status===429&&(s=s?s+1:0,s<this.maxRetries))return console.log(`Hit rate limit. Retrying in ${s} seconds.`),await this.helpers.delay(1e3*s),this.cacheResponse(t,e,s).then(o).catch(c);c(l)}})}throttledRequest(t,e,s){return this.client[t](e,s)}cacheVersions(){return y}cacheVersion(){return y[this.accessToken]}setCacheVersion(t){this.accessToken&&(y[this.accessToken]=t)}clearCacheVersion(){this.accessToken&&(y[this.accessToken]=0)}cacheProvider(){switch(this.cache.type){case"memory":return{get(t){return Promise.resolve(w[t])},getAll(){return Promise.resolve(w)},set(t,e){return w[t]=e,Promise.resolve(void 0)},flush(){return w={},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 pt=(n={})=>{const{apiOptions:t}=n;if(!t.accessToken){console.error("You need to provide an access token to interact with Storyblok API. Read https://www.storyblok.com/docs/api/content-delivery#topics/authentication");return}return{storyblokApi:new dt(t)}},gt=n=>{if(typeof n!="object"||typeof n._editable>"u")return{};try{const t=JSON.parse(n._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return t?{"data-blok-c":JSON.stringify(t),"data-blok-uid":t.id+"-"+t.uid}:{}}catch{return{}}};let T,$="https://app.storyblok.com/f/storyblok-v2-latest.js";const I=(n,t,e={})=>{var c;const r=!(typeof window>"u")&&typeof window.storyblokRegisterEvent<"u",o=+new URL((c=window.location)==null?void 0:c.href).searchParams.get("_storyblok")===n;if(!(!r||!o)){if(!n){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(e).on(["input","published","change"],l=>{l.action==="input"&&l.story.id===n?t(l.story):(l.action==="change"||l.action==="published")&&l.storyId===n&&window.location.reload()})})}},ft=(n={})=>{var p,f;const{bridge:t,accessToken:e,use:s=[],apiOptions:r={},richText:i={},bridgeUrl:o}=n;r.accessToken=r.accessToken||e;const c={bridge:t,apiOptions:r};let a={};s.forEach(m=>{a={...a,...m(c)}}),o&&($=o);const u=!(typeof window>"u")&&((f=(p=window.location)==null?void 0:p.search)==null?void 0:f.includes("_storyblok_tk"));return t!==!1&&u&&j($),T=new v(i.schema),i.resolver&&P(T,i.resolver),a},P=(n,t)=>{n.addNode("blok",e=>{let s="";return e.attrs.body.forEach(r=>{s+=t(r.component,r)}),{html:s}})},C=n=>!n||!(n!=null&&n.content.some(t=>t.content||t.type==="blok"||t.type==="horizontal_rule")),mt=(n,t,e)=>{let s=e||T;if(!s){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return C(n)?"":(t&&(s=new v(t.schema),t.resolver&&P(s,t.resolver)),s.render(n))},yt=()=>j($);d.RichTextResolver=v,d.RichTextSchema=x,d.apiPlugin=pt,d.isRichTextEmpty=C,d.loadStoryblokBridge=yt,d.registerStoryblokBridge=I,d.renderRichText=mt,d.storyblokEditable=gt,d.storyblokInit=ft,d.useStoryblokBridge=I,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"})});
|
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-Fa-f]{6}/g)||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 c=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|tiff|bmp)/g,`a.storyblok.com/f/$1/$2.$3/m/${c}`),typeof t!="boolean"&&(t.sizes||t.srcset)&&(e=e.replace(/<img.*?src=["|'](.*?)["|']/g,a=>{var l,u;const p=a.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);if(p&&p.length>0){const y={srcset:(l=t.srcset)==null?void 0:l.map(b=>{if(typeof b=="number")return`//${p}/m/${b}x0${o} ${b}w`;if(typeof b=="object"&&b.length===2){let S=0,L=0;return typeof b[0]=="number"&&(S=b[0]),typeof b[1]=="number"&&(L=b[1]),`//${p}/m/${S}x${L}${o} ${S}w`}}).join(", "),sizes:(u=t.sizes)==null?void 0:u.map(b=>b).join(", ")};let $="";return y.srcset&&($+=`srcset="${y.srcset}" `),y.sizes&&($+=`sizes="${y.sizes}" `),a.replace(/<img/g,`<img ${$.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(Te(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){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," /")}}class Re{constructor(e){d(this,"baseURL"),d(this,"timeout"),d(this,"headers"),d(this,"responseInterceptor"),d(this,"fetch"),d(this,"ejectInterceptor"),d(this,"url"),d(this,"parameters"),d(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 j;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 c;this.timeout&&(c=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(c);const l=await this._responseHandler(a);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(l)):this._statusHandler(l)}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 z="SB-Agent",A={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"6.0.0"};let x={};const _={};class we{constructor(e,t){d(this,"client"),d(this,"maxRetries"),d(this,"retriesDelay"),d(this,"throttle"),d(this,"accessToken"),d(this,"cache"),d(this,"helpers"),d(this,"resolveCounter"),d(this,"relations"),d(this,"links"),d(this,"richTextResolver"),d(this,"resolveNestedRelations"),d(this,"stringifiedStoriesCache");let s=e.endpoint||t;if(!s){const o=new j().getRegionURL,c=e.https===!1?"http":"https";e.oauthToken?s=`${c}://${o(e.region)}/v1`:s=`${c}://${o(e.region)}/v2`}const r=new Headers;if(r.set("Content-Type","application/json"),r.set("Accept","application/json"),e.headers)for(const o in e.headers)r.set(o,e.headers[o]);r.has(z)||(r.set(z,A.defaultAgentName),r.set(A.defaultAgentVersion,A.packageVersion));let n=5;e.oauthToken&&(r.set("Authorization",e.oauthToken),n=3),e.rateLimit&&(n=e.rateLimit),e.richTextSchema?this.richTextResolver=new I(e.richTextSchema):this.richTextResolver=new I,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||10,this.retriesDelay=300,this.throttle=Y(this.throttledRequest,n,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new j,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.stringifiedStoriesCache={},this.client=new Re({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){const n=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,s,r));return this.cacheResponse(e,n)}get(e,t,s){t||(t={});const r=`/${e}`,n=this.factoryParamOptions(r,t);return this.client.setFetchOptions(s),this.cacheResponse(r,n)}async getAll(e,t,s,r){const n=(t==null?void 0:t.per_page)||25,o=`/${e}`,c=o.split("/"),a=s||c[c.length-1],l=1,u=await this.makeRequest(o,t,n,l),p=u.total?Math.ceil(u.total/n):1;this.client.setFetchOptions(r);const y=await this.helpers.asyncMap(this.helpers.range(l,p),$=>this.makeRequest(o,t,n,$+1));return this.helpers.flatMap([u,...y],$=>Object.values($.data[a]))}post(e,t,s){const r=`/${e}`;return this.client.setFetchOptions(s),Promise.resolve(this.throttle("post",r,t))}put(e,t,s){const r=`/${e}`;return this.client.setFetchOptions(s),Promise.resolve(this.throttle("put",r,t))}delete(e,t,s){const r=`/${e}`;return this.client.setFetchOptions(s),Promise.resolve(this.throttle("delete",r,t))}getStories(e,t){return this.client.setFetchOptions(t),this._addResolveLevel(e),this.get("cdn/stories",e)}getStory(e,t,s){return this.client.setFetchOptions(s),this._addResolveLevel(t),this.get(`cdn/stories/${e}`,t)}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.indexOf(`${e.component}.${t}`)>-1&&(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=[],c=50;for(let a=0;a<n;a+=c){const l=Math.min(n,a+c);o.push(e.link_uuids.slice(a,l))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:c,language:t.language,version:t.version,by_uuids:o[a].join(",")})).data.stories.forEach(l=>{r.push(l)})}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=[],c=50;for(let a=0;a<n;a+=c){const l=Math.min(n,a+c);o.push(e.rel_uuids.slice(a,l))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:c,language:t.language,version:t.version,by_uuids:o[a].join(","),excluding_fields:t.excluding_fields})).data.stories.forEach(l=>{r.push(l)})}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"].indexOf(t.resolve_links)>-1&&((r=e.links)!=null&&r.length||(n=e.link_uuids)!=null&&n.length)&&await this.resolveLinks(e,t,s),this.resolveNestedRelations)for(const c in this.relations[s])this.iterateTree(this.relations[s][c],o,s);e.story?this.iterateTree(e.story,o,s):e.stories.forEach(c=>{this.iterateTree(c,o,s)}),this.stringifiedStoriesCache={},delete this.links[s],delete this.relations[s]}async cacheResponse(e,t,s){const r=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 o=await n.get(r);if(o)return Promise.resolve(o)}return new Promise(async(o,c)=>{var a;try{const l=await this.throttle("get",e,t);if(l.status!==200)return c(l);let u={data:l.data,headers:l.headers};if((a=l.headers)!=null&&a["per-page"]&&(u=Object.assign({},u,{perPage:l.headers["per-page"]?parseInt(l.headers["per-page"]):0,total:l.headers["per-page"]?parseInt(l.headers.total):0})),u.data.story||u.data.stories){const p=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(u.data,t,`${p}`)}return t.version==="published"&&e!="/cdn/spaces/me"&&await n.set(r,u),u.data.cv&&t.token&&(t.version==="draft"&&_[t.token]!=u.data.cv&&await this.flushCache(),_[t.token]=t.cv?t.cv:u.data.cv),o(u)}catch(l){if(l.response&&l.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(o).catch(c);c(l)}})}throttledRequest(e,t,s){return 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(x[e])},getAll(){return Promise.resolve(x)},set(e,t){return x[e]=t,Promise.resolve(void 0)},flush(){return x={},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 Se=(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 we(e)}},_e=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{}}};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||{}),v=(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))(v||{}),C=(i=>(i.TEXT="text",i))(C||{}),O=(i=>(i.URL="url",i.STORY="story",i.ASSET="asset",i.EMAIL="email",i))(O||{});function Ee(i,e){if(!e)return{src:i,attrs:{}};let t=0,s=0;const r={},n=[];function o(a,l,u,p,y){typeof a!="number"||a<=l||a>=u?console.warn(`[SbRichText] - ${p.charAt(0).toUpperCase()+p.slice(1)} value must be a number between ${l} and ${u} (inclusive)`):y.push(`${p}(${a})`)}if(typeof e=="object"){if(typeof e.width=="number"&&e.width>0?(r.width=e.width,t=e.width):console.warn("[SbRichText] - 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("[SbRichText] - 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:l,brightness:u,fill:p,format:y,grayscale:$,quality:b,rotate:S}=a||{};l&&o(l,0,100,"blur",n),b&&o(b,0,100,"quality",n),u&&o(u,0,100,"brightness",n),p&&n.push(`fill(${p})`),$&&n.push("grayscale()"),S&&[0,90,180,270].includes(e.filters.rotate||0)&&n.push(`rotate(${S})`),y&&["webp","png","jpeg"].includes(y)&&n.push(`format(${y})`)}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[l,u]=a;return`${i}/m/${l}x${u}/${n.length>0?"filters:"+n.join(":"):""} ${l}w`}}).join(", ")),e.sizes&&(r.sizes=e.sizes.join(", "))}let c=`${i}/m/`;return t>0&&s>0&&(c=`${c}${t}x${s}/`),n.length>0&&(c=`${c}filters:${n.join(":")}`),{src:c,attrs:r}}const Ie=(i={})=>Object.keys(i).map(e=>`${e}="${i[e]}"`).join(" "),Oe=(i={})=>Object.keys(i).map(e=>`${e}: ${i[e]}`).join("; ");function je(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function xe(i,e={},t){const s=Ie(e);return`<${s?`${i} ${s}`:i}>${Array.isArray(t)?t.join(""):t||""}</${i}>`}function Le(i={}){let e=0;const{renderFn:t=xe,textFn:s=je,resolvers:r={},optimizeImages:n=!1}=i,o=h=>g=>t(h,{...g.attrs,key:`${h}-${e}`},g.children||null),c=h=>{const{src:g,alt:f,...T}=h.attrs||{};let R=g,w={};if(n){const{src:Me,attrs:Ue}=Ee(g,n);R=Me,w=Ue}const Ne={src:R,alt:f||"",key:`img-${e}`,...T,...w};return t("img",Ne,"")},a=h=>{const{level:g,...f}=h.attrs||{};return t(`h${g}`,{...f,key:`h${g}-${e}`},h.children)},l=h=>{var g,f,T,R;return t("span",{"data-type":"emoji","data-name":(g=h.attrs)==null?void 0:g.name,emoji:(f=h.attrs)==null?void 0:f.emoji,key:`emoji-${e}`},t("img",{src:(T=h.attrs)==null?void 0:T.fallbackImage,alt:(R=h.attrs)==null?void 0:R.alt,style:"width: 1.25em; height: 1.25em; vertical-align: text-top",draggable:"false",loading:"lazy"},""))},u=h=>t("pre",{...h.attrs,key:`code-${e}`},t("code",{key:`code-${e}`},h.children||"")),p=(h,g=!1)=>({text:f,attrs:T})=>t(h,g?{style:Oe(T),key:`${h}-${e}`}:{...T,key:`${h}-${e}`},f),y=h=>M(h),$=h=>{const{marks:g,...f}=h;return"text"in h?g?g.reduce((T,R)=>y({...R,text:T}),y({...f,children:f.children})):s(f.text):""},b=h=>{const{linktype:g,href:f,anchor:T,...R}=h.attrs||{};let w="";switch(g){case O.ASSET:case O.URL:w=f;break;case O.EMAIL:w=`mailto:${f}`;break;case O.STORY:w=f;break}return T&&(w=`${w}#${T}`),t("a",{...R,href:w,key:`a-${e}`},h.text)},S=h=>{var g,f;return console.warn("[SbRichtText] - 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"},"")},L=new Map([[k.DOCUMENT,o("div")],[k.HEADING,a],[k.PARAGRAPH,o("p")],[k.UL_LIST,o("ul")],[k.OL_LIST,o("ol")],[k.LIST_ITEM,o("li")],[k.IMAGE,c],[k.EMOJI,l],[k.CODE_BLOCK,u],[k.HR,o("hr")],[k.BR,o("br")],[k.QUOTE,o("blockquote")],[k.COMPONENT,S],[C.TEXT,$],[v.LINK,b],[v.ANCHOR,b],[v.STYLED,p("span",!0)],[v.BOLD,p("strong")],[v.TEXT_STYLE,p("span",!0)],[v.ITALIC,p("em")],[v.UNDERLINE,p("u")],[v.STRIKE,p("s")],[v.CODE,p("code")],[v.SUPERSCRIPT,p("sup")],[v.SUBSCRIPT,p("sub")],[v.HIGHLIGHT,p("mark")],...Object.entries(r).map(([h,g])=>[h,g])]);function V(h){e+=1;const g=L.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(M):void 0;return g({...h,children:f})}function M(h){return Array.isArray(h)?h.map(V):V(h)}return{render:M}}let P,N="https://app.storyblok.com/f/storyblok-v2-latest.js";const q=(i,e,t={})=>{var c;const r=!(typeof window>"u")&&typeof window.storyblokRegisterEvent<"u",o=+new URL((c=window.location)==null?void 0:c.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"],l=>{l.action==="input"&&l.story.id===i?e(l.story):(l.action==="change"||l.action==="published")&&l.storyId===i&&window.location.reload()})})}},Ae=(i={})=>{var p,y;const{bridge:e,accessToken:t,use:s=[],apiOptions:r={},richText:n={},bridgeUrl:o}=i;r.accessToken=r.accessToken||t;const c={bridge:e,apiOptions:r};let a={};s.forEach($=>{a={...a,...$(c)}}),o&&(N=o);const u=!(typeof window>"u")&&((y=(p=window.location)==null?void 0:p.search)==null?void 0:y.includes("_storyblok_tk"));return e!==!1&&u&&H(N),P=new I(n.schema),n.resolver&&F(P,n.resolver),a},F=(i,e)=>{i.addNode("blok",t=>{let s="";return t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})},G=i=>!i||!(i!=null&&i.content.some(e=>e.content||e.type==="blok"||e.type==="horizontal_rule")),Ce=(i,e,t)=>{let s=t||P;if(!s){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return G(i)?"":(e&&(s=new I(e.schema),e.resolver&&F(s,e.resolver)),s.render(i))},Pe=()=>H(N);m.BlockTypes=k,m.MarkTypes=v,m.RichTextResolver=I,m.RichTextSchema=D,m.TextTypes=C,m.apiPlugin=Se,m.isRichTextEmpty=G,m.loadStoryblokBridge=Pe,m.registerStoryblokBridge=q,m.renderRichText=Ce,m.richTextResolver=Le,m.storyblokEditable=_e,m.storyblokInit=Ae,m.useStoryblokBridge=q,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})});
|