@storyblok/js 3.5.0 → 4.0.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/README.md CHANGED
@@ -218,58 +218,45 @@ sbBridge.on(['input', 'published', 'change'], (event) => {
218
218
 
219
219
  ### Rendering Rich Text
220
220
 
221
- You can easily render rich text by using the `renderRichText` function that comes with `@storyblok/js`:
221
+ You can easily render rich text by using the `renderRichText` method. This function is a wrapper of the `render` method of the [`@storyblok/richtext` package](https://github.com/storyblok/richtext).
222
222
 
223
- ```js
224
- import { renderRichText } from '@storyblok/js';
223
+ ```ts
224
+ import { apiPlugin, storyblokInit, renderRichText } from '@storyblok/js';
225
225
 
226
- const renderedRichText = renderRichText(blok.richtext);
227
- ```
226
+ const { storyblokApi } = storyblokInit({
227
+ accessToken: 'YOUR_ACCESS_TOKEN',
228
+ use: [apiPlugin],
229
+ });
228
230
 
229
- You can set a **custom Schema and component resolver globally** at init time by using the `richText` init option:
231
+ const { data } = await storyblokApi!.get('cdn/stories/richtext');
230
232
 
231
- ```js
232
- import { RichTextSchema, storyblokInit } from '@storyblok/js';
233
- import cloneDeep from 'clone-deep';
234
-
235
- const mySchema = cloneDeep(RichTextSchema); // you can make a copy of the default RichTextSchema
236
- // ... and edit the nodes and marks, or add your own.
237
- // Check the base RichTextSchema source here https://github.com/storyblok/storyblok-js-client/blob/master/source/schema.js
238
-
239
- storyblokInit({
240
- accessToken: '<your-token>',
241
- richText: {
242
- schema: mySchema,
243
- resolver: (component, blok) => {
244
- switch (component) {
245
- case 'my-custom-component':
246
- return `<div class="my-component-class">${blok.text}</div>`;
247
- default:
248
- return 'Resolver not defined';
249
- }
250
- },
251
- },
252
- });
233
+ const html = renderRichText(data.story.content.body);
253
234
  ```
254
235
 
255
- You can also set a **custom Schema and component resolver only once** by passing the options as the second parameter to `renderRichText` function:
236
+ #### Overwrite resolvers
256
237
 
257
- ```js
258
- import { renderRichText } from '@storyblok/js';
259
-
260
- renderRichText(blok.richTextField, {
261
- schema: mySchema,
262
- resolver: (component, blok) => {
263
- switch (component) {
264
- case 'my-custom-component':
265
- return `<div class="my-component-class">${blok.text}</div>`;
266
- default:
267
- return `Component ${component} not found`;
268
- }
238
+ You can overwrite the default resolvers by passing a custom `resolvers` object to the `renderRichText` function.
239
+
240
+ ```ts
241
+ import { apiPlugin, storyblokInit, renderRichText } from '@storyblok/js';
242
+
243
+ const { storyblokApi } = storyblokInit({
244
+ accessToken: 'YOUR_ACCESS_TOKEN',
245
+ use: [apiPlugin],
246
+ });
247
+ const { data } = await storyblokApi!.get('cdn/stories/richtext');
248
+
249
+ const html = renderRichText(data.story.content.body, {
250
+ resolvers: {
251
+ [MarkTypes.LINK]: (node) => {
252
+ return `<button href="${node.attrs?.href}" target="${node.attrs?.target}">${node.content[0].text}</button>`;
253
+ },
269
254
  },
270
255
  });
271
256
  ```
272
257
 
258
+ For more options available, like optimizing images, please refer to the [@storyblok/richtext documentation](https://github.com/storyblok/richtext?tab=readme-ov-file#optimize-images).
259
+
273
260
  ## The Storyblok JavaScript SDK Ecosystem
274
261
 
275
262
  ![A visual representation of the Storyblok JavaScript SDK Ecosystem](https://a.storyblok.com/f/88751/2400x1350/be4a4a4180/sdk-ecosystem.png/m/1200x0)
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { ISbRichtext, ISbStoryData, SbInitResult, SbRichTextOptions, SbSDKOptions, StoryblokBridgeConfigV2, StoryblokComponentType } from './types';
2
- import { RichtextResolver } from 'storyblok-js-client';
1
+ import { StoryblokRichTextNode, StoryblokRichTextOptions } from '@storyblok/richtext';
2
+ import { ISbStoryData, SbInitResult, SbSDKOptions, StoryblokBridgeConfigV2, StoryblokComponentType } from './types';
3
3
  export interface StoryblokBridgeEvent {
4
4
  action: string;
5
5
  storyId: number;
@@ -7,12 +7,16 @@ export interface StoryblokBridgeEvent {
7
7
  }
8
8
  export declare const useStoryblokBridge: <T extends StoryblokComponentType<string> = any>(id: number, cb: (newStory: ISbStoryData<T>) => void, options?: StoryblokBridgeConfigV2) => void;
9
9
  export declare const storyblokInit: (pluginOptions?: SbSDKOptions) => SbInitResult;
10
- export declare const isRichTextEmpty: (data?: ISbRichtext) => boolean;
11
- export declare const renderRichText: (data?: ISbRichtext, options?: SbRichTextOptions, resolverInstance?: RichtextResolver) => string | undefined;
10
+ /**
11
+ * Render Rich Text
12
+ * @param data - The rich text data to render
13
+ * @param options - The options for the rich text
14
+ * @returns The rendered rich text
15
+ */
16
+ export declare function renderRichText<T = string>(data: StoryblokRichTextNode<T>, options?: StoryblokRichTextOptions<T>): T | undefined;
12
17
  export declare const loadStoryblokBridge: () => Promise<unknown>;
13
18
  export { useStoryblokBridge as registerStoryblokBridge };
14
19
  export { default as apiPlugin } from './api';
15
20
  export { default as storyblokEditable } from './editable';
16
21
  export * from './types';
17
22
  export { BlockTypes, MarkTypes, richTextResolver, type StoryblokRichTextDocumentNode, type StoryblokRichTextImageOptimizationOptions, type StoryblokRichTextNode, type StoryblokRichTextNodeResolver, type StoryblokRichTextNodeTypes, type StoryblokRichTextOptions, type StoryblokRichTextResolvers, TextTypes, } from '@storyblok/richtext';
18
- export { RichtextResolver as RichTextResolver, RichtextSchema as RichTextSchema, } from 'storyblok-js-client';
@@ -4,27 +4,4 @@
4
4
  * description: SDK to integrate Storyblok into your project using JavaScript.
5
5
  * author: undefined
6
6
  */
7
- (function(v,I){typeof exports=="object"&&typeof module<"u"?I(exports):typeof define=="function"&&define.amd?define(["exports"],I):(v=typeof globalThis<"u"?globalThis:v||self,I(v.storyblok={}))})(this,function(v){"use strict";let I=!1;const q=[],F=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():q.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=>{q.forEach(n=>n()),I=!0,e(r)},document.getElementsByTagName("head")[0].appendChild(s)});var Z=Object.defineProperty,ee=(i,e,t)=>e in i?Z(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,m=(i,e,t)=>ee(i,typeof e!="symbol"?e+"":e,t);class te extends Error{constructor(e){super(e),this.name="AbortError"}}function se(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 c=async()=>{n++;const h=s.shift();if(h)try{const d=await i(...h.args);h.resolve(d)}catch(d){h.reject(d)}const u=setTimeout(()=>{n--,s.length>0&&c(),r=r.filter(d=>d!==u)},t);r.includes(u)||r.push(u)},a=(...h)=>o?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:h}),n<e&&c()});return a.abort=()=>{o=!0,r.forEach(clearTimeout),r=[],s.forEach(h=>h.reject(()=>new te("Throttle function aborted"))),s.length=0},a}class x{constructor(){m(this,"isCDNUrl",(e="")=>e.includes("/cdn/")),m(this,"getOptionsPage",(e,t=25,s=1)=>({...e,per_page:t,page:s})),m(this,"delay",e=>new Promise(t=>setTimeout(t,e))),m(this,"arrayFrom",(e=0,t)=>Array.from({length:e},t)),m(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)}),m(this,"asyncMap",async(e,t)=>Promise.all(e.map(t))),m(this,"flatMap",(e=[],t)=>e.map(t).reduce((s,r)=>[...s,...r],[])),m(this,"escapeHTML",function(e){const t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},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];if(o==null)continue;const 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 re=function(i,e){const t={};for(const s in i){const r=i[s];e.includes(s)&&r!==null&&(t[s]=r)}return t},ie=i=>i==="email",ne=()=>({singleTag:"hr"}),oe=()=>({tag:"blockquote"}),ae=()=>({tag:"ul"}),le=i=>({tag:["pre",{tag:"code",attrs:i.attrs}]}),ce=()=>({singleTag:"br"}),he=i=>({tag:`h${i.attrs.level}`}),ue=i=>({singleTag:[{tag:"img",attrs:re(i.attrs,["src","alt","title"])}]}),de=()=>({tag:"li"}),pe=()=>({tag:"ol"}),ge=()=>({tag:"p"}),fe=i=>({tag:[{tag:"span",attrs:{"data-type":"emoji","data-name":i.attrs.name,emoji:i.attrs.emoji}}]}),me=()=>({tag:"b"}),ye=()=>({tag:"s"}),be=()=>({tag:"u"}),ke=()=>({tag:"strong"}),ve=()=>({tag:"code"}),$e=()=>({tag:"i"}),Te=i=>{if(!i.attrs)return{tag:""};const e=new x().escapeHTML,t={...i.attrs},{linktype:s="url"}=i.attrs;if(delete t.linktype,t.href&&(t.href=e(i.attrs.href||"")),ie(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}]}},we=i=>({tag:[{tag:"span",attrs:i.attrs}]}),Re=()=>({tag:"sub"}),Ee=()=>({tag:"sup"}),_e=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:""}},Ae=i=>{var e;return(e=i.attrs)!=null&&e.color?{tag:[{tag:"span",attrs:{style:`color:${i.attrs.color}`}}]}:{tag:""}},G={nodes:{horizontal_rule:ne,blockquote:oe,bullet_list:ae,code_block:le,hard_break:ce,heading:he,image:ue,list_item:de,ordered_list:pe,paragraph:ge,emoji:fe},marks:{bold:me,strike:ye,underline:be,strong:ke,code:ve,italic:$e,link:Te,styled:we,subscript:Re,superscript:Ee,anchor:_e,highlight:Se,textStyle:Ae}},je=function(i){const e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},t=/[&<>"']/g,s=new RegExp(t.source);return i&&s.test(i)?i.replace(t,r=>e[r]):i};let J=!1;class O{constructor(e){m(this,"marks"),m(this,"nodes"),e||(e=G),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(!J&&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/"),J=!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.
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,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 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|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 h,u;const d=a.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|bmp)/g);if(d&&d.length>0){const b={srcset:(h=t.srcset)==null?void 0:h.map(y=>{if(typeof y=="number")return`//${d}/m/${y}x0${o} ${y}w`;if(typeof y=="object"&&y.length===2){let A=0,N=0;return typeof y[0]=="number"&&(A=y[0]),typeof y[1]=="number"&&(N=y[1]),`//${d}/m/${A}x${N}${o} ${A}w`}return""}).join(", "),sizes:(u=t.sizes)==null?void 0:u.map(y=>y).join(", ")};let S="";return b.srcset&&(S+=`srcset="${b.srcset}" `),b.sizes&&(S+=`sizes="${b.sizes}" `),a.replace(/<img/g,`<img ${S.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(je(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," /")}}class Ie{constructor(e){m(this,"baseURL"),m(this,"timeout"),m(this,"headers"),m(this,"responseInterceptor"),m(this,"fetch"),m(this,"ejectInterceptor"),m(this,"url"),m(this,"parameters"),m(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 x;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 h=await this._responseHandler(a);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(h)):this._statusHandler(h)}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 V="SB-Agent",H={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"6.0.0"};let C={};const j={};class Oe{constructor(e,t){m(this,"client"),m(this,"maxRetries"),m(this,"retriesDelay"),m(this,"throttle"),m(this,"accessToken"),m(this,"cache"),m(this,"helpers"),m(this,"resolveCounter"),m(this,"relations"),m(this,"links"),m(this,"richTextResolver"),m(this,"resolveNestedRelations"),m(this,"stringifiedStoriesCache"),m(this,"inlineAssets");let s=e.endpoint||t;if(!s){const o=new x().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;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,c])=>{r.set(o,c)}),r.has(V)||(r.set(V,H.defaultAgentName),r.set(H.defaultAgentVersion,H.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=se(this.throttledRequest.bind(this),n,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new x,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.stringifiedStoriesCache={},this.inlineAssets=e.inlineAssets||!1,this.client=new Ie({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=j[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(/\/$/,""),c=s??o.substring(o.lastIndexOf("/")+1),a=1,h=await this.makeRequest(o,t,n,a,r),u=h.total?Math.ceil(h.total/n):1,d=await this.helpers.asyncMap(this.helpers.range(a,u),b=>this.makeRequest(o,t,n,b+1,r));return this.helpers.flatMap([h,...d],b=>Object.values(b.data[c]))}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(n=>this.getStoryReference(s,n)).filter(Boolean))}_insertRelations(e,t,s,r){if(Array.isArray(s)?s.find(o=>o.endsWith(`.${t}`)):s.endsWith(`.${t}`)){this._resolveField(e,t,r);return}const n=e.component?`${e.component}.${t}`:t;(Array.isArray(s)?s.includes(n):s===n)&&this._resolveField(e,t,r)}iterateTree(e,t,s){const r=(n,o="")=>{if(!(!n||n._stopResolving)){if(Array.isArray(n))n.forEach((c,a)=>r(c,`${o}[${a}]`));else if(typeof n=="object")for(const c in n){const a=o?`${o}.${c}`:c;(n.component&&n._uid||n.type==="link")&&(this._insertRelations(n,c,t,s),this._insertLinks(n,c,s)),r(n[c],a)}}};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 h=Math.min(n,a+c);o.push(e.link_uuids.slice(a,h))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:c,language:t.language,version:t.version,starts_with:t.starts_with,by_uuids:o[a].join(",")})).data.stories.forEach(h=>{r.push(h)})}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 h=Math.min(n,a+c);o.push(e.rel_uuids.slice(a,h))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:c,language:t.language,version:t.version,starts_with:t.starts_with,by_uuids:o[a].join(","),excluding_fields:t.excluding_fields})).data.stories.forEach(h=>{r.push(h)});r.length>0&&(e.rels=r,delete e.rel_uuids)}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 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,r){const n=this.helpers.stringify({url:e,params:t}),o=this.cacheProvider();if(t.version==="published"&&e!=="/cdn/spaces/me"){const c=await o.get(n);if(c)return Promise.resolve(c)}return new Promise(async(c,a)=>{var h;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((h=u.headers)!=null&&h["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 S=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(d.data,t,`${S}`),d=await this.processInlineAssets(d)}t.version==="published"&&e!=="/cdn/spaces/me"&&await o.set(n,d);const b=this.cache.clear==="onpreview"&&t.version==="draft"||this.cache.clear==="auto";return t.token&&d.data.cv&&(b&&j[t.token]&&j[t.token]!==d.data.cv&&await this.flushCache(),j[t.token]=d.data.cv),c(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(c).catch(a);a(u)}})}throttledRequest(e,t,s,r){return this.client.setFetchOptions(r),this.client[e](t,s)}cacheVersions(){return j}cacheVersion(){return j[this.accessToken]}setCacheVersion(e){this.accessToken&&(j[this.accessToken]=e)}clearCacheVersion(){this.accessToken&&(j[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}async processInlineAssets(e){if(!this.inlineAssets)return e;const t=s=>{if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(n=>t(n));let r={...s};r.fieldtype==="asset"&&Array.isArray(e.data.assets)&&(r={...r,...e.data.assets.find(n=>n.id===r.id)});for(const n in r)typeof r[n]=="object"&&(r[n]=t(r[n]));return r};return e.data.story&&(e.data.story.content=t(e.data.story.content)),e.data.stories&&(e.data.stories=e.data.stories.map(s=>(s.content=t(s.content),s))),e}}const Le=(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 Oe(e)}},xe=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={},n=[];function o(a,h,u,d,b){typeof a!="number"||a<=h||a>=u?console.warn(`[StoryblokRichText] - ${d.charAt(0).toUpperCase()+d.slice(1)} value must be a number between ${h} and ${u} (inclusive)`):b.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:h,brightness:u,fill:d,format:b,grayscale:S,quality:y,rotate:A}=a||{};h&&o(h,0,100,"blur",n),y&&o(y,0,100,"quality",n),u&&o(u,0,100,"brightness",n),d&&n.push(`fill(${d})`),S&&n.push("grayscale()"),A&&[0,90,180,270].includes(e.filters.rotate||0)&&n.push(`rotate(${A})`),b&&["webp","png","jpeg"].includes(b)&&n.push(`format(${b})`)}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[h,u]=a;return`${i}/m/${h}x${u}/${n.length>0?`filters:${n.join(":")}`:""} ${h}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 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}}var $=(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.TABLE="table",i.TABLE_ROW="tableRow",i.TABLE_CELL="tableCell",i.TABLE_HEADER="tableHeader",i))($||{}),E=(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))(E||{}),B=(i=>(i.TEXT="text",i))(B||{}),L=(i=>(i.URL="url",i.STORY="story",i.ASSET="asset",i.EMAIL="email",i))(L||{});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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}const P=i=>Object.fromEntries(Object.entries(i).filter(([e,t])=>t!==void 0));function K(i,e={},t){const s=Ne(e),r=s?`${i} ${s}`:i,n=Array.isArray(t)?t.join(""):t||"";if(i){if(Pe.includes(i))return`<${r}>`}else return n;return`<${r}>${n}</${i}>`}function Be(i={}){const e=new Map,{renderFn:t=K,textFn:s=He,resolvers:r={},optimizeImages:n=!1,keyedResolvers:o=!1}=i,c=t!==K,a=()=>({render:(l,p={},g)=>{if(o&&l){const f=e.get(l)||0;e.set(l,f+1),p.key=`${l}-${f}`}return t(l,p,g)}}),h=l=>(p,g)=>{const f=p.attrs||{};return g.render(l,f,p.children||null)},u=(l,p)=>{const{src:g,alt:f,title:k,srcset:R,sizes:T}=l.attrs||{};let w=g,_={};if(n){const{src:We,attrs:Xe}=Ce(g,n);w=We,_=Xe}const Ye={src:w,alt:f,title:k,srcset:R,sizes:T,..._};return p.render("img",P(Ye))},d=(l,p)=>{const{level:g,...f}=l.attrs||{};return p.render(`h${g}`,f,l.children)},b=(l,p)=>{var g,f,k,R;const T=p.render("img",{src:(g=l.attrs)==null?void 0:g.fallbackImage,alt:(f=l.attrs)==null?void 0:f.alt,style:"width: 1.25em; height: 1.25em; vertical-align: text-top",draggable:"false",loading:"lazy"});return p.render("span",{"data-type":"emoji","data-name":(k=l.attrs)==null?void 0:k.name,"data-emoji":(R=l.attrs)==null?void 0:R.emoji},T)},S=(l,p)=>p.render("pre",l.attrs||{},p.render("code",{},l.children||"")),y=(l,p=!1)=>({text:g,attrs:f},k)=>{const{class:R,id:T,...w}=f||{},_=p?{class:R,id:T,style:Me(w)||void 0}:f||{};return k.render(l,P(_),g)},A=l=>D(l),N=l=>{const{marks:p,...g}=l;if("text"in l){if(p)return p.reduce((k,R)=>A({...R,text:k}),A({...g,children:g.children}));const f=l.attrs||{};if(o){const k=e.get("txt")||0;e.set("txt",k+1),f.key=`txt-${k}`}return s(g.text,f)}return""},Q=(l,p)=>{const{linktype:g,href:f,anchor:k,...R}=l.attrs||{};let T="";switch(g){case L.ASSET:case L.URL:T=f;break;case L.EMAIL:T=`mailto:${f}`;break;case L.STORY:T=f,k&&(T=`${T}#${k}`);break;default:T=f;break}const w={...R};return T&&(w.href=T),p.render("a",w,l.text)},qe=(l,p)=>{var g,f;return console.warn("[StoryblokRichtText] - BLOK resolver is not available for vanilla usage"),p.render("span",{blok:(g=l==null?void 0:l.attrs)==null?void 0:g.body[0],id:(f=l.attrs)==null?void 0:f.id,style:"display: none"})},Fe=(l,p)=>{const g={},f=p.render("tbody",{},l.children);return p.render("table",g,f)},Ge=(l,p)=>{const g={};return p.render("tr",g,l.children)},Je=(l,p)=>{const{colspan:g,rowspan:f,colwidth:k,backgroundColor:R,...T}=l.attrs||{},w={...T};g>1&&(w.colspan=g),f>1&&(w.rowspan=f);const _=[];return k&&_.push(`width: ${k}px;`),R&&_.push(`background-color: ${R};`),_.length>0&&(w.style=_.join(" ")),p.render("td",P(w),l.children)},Ve=(l,p)=>{const{colspan:g,rowspan:f,colwidth:k,backgroundColor:R,...T}=l.attrs||{},w={...T};g>1&&(w.colspan=g),f>1&&(w.rowspan=f);const _=[];return k&&_.push(`width: ${k}px;`),R&&_.push(`background-color: ${R};`),_.length>0&&(w.style=_.join(" ")),p.render("th",P(w),l.children)},Ke=new Map([[$.DOCUMENT,h("")],[$.HEADING,d],[$.PARAGRAPH,h("p")],[$.UL_LIST,h("ul")],[$.OL_LIST,h("ol")],[$.LIST_ITEM,h("li")],[$.IMAGE,u],[$.EMOJI,b],[$.CODE_BLOCK,S],[$.HR,h("hr")],[$.BR,h("br")],[$.QUOTE,h("blockquote")],[$.COMPONENT,qe],[B.TEXT,N],[E.LINK,Q],[E.ANCHOR,Q],[E.STYLED,y("span",!0)],[E.BOLD,y("strong")],[E.TEXT_STYLE,y("span",!0)],[E.ITALIC,y("em")],[E.UNDERLINE,y("u")],[E.STRIKE,y("s")],[E.CODE,y("code")],[E.SUPERSCRIPT,y("sup")],[E.SUBSCRIPT,y("sub")],[E.HIGHLIGHT,y("mark")],[$.TABLE,Fe],[$.TABLE_ROW,Ge],[$.TABLE_CELL,Je],[$.TABLE_HEADER,Ve],...Object.entries(r).map(([l,p])=>[l,p])]);function M(l){const p=Ke.get(l.type);if(!p)return console.error("<Storyblok>",`No resolver found for node type ${l.type}`),"";const g=a();if(l.type==="text")return p(l,g);const f=l.content?l.content.map(D):void 0;return p({...l,children:f},g)}function D(l){return l.type==="doc"?c?l.content.map(M):l.content.map(M).join(""):Array.isArray(l)?l.map(M):M(l)}return{render:D}}let U,z="https://app.storyblok.com/f/storyblok-v2-latest.js";const Y=(i,e,t={})=>{var c;const r=!(typeof window>"u")&&typeof window.storyblokRegisterEvent<"u",n=new URL((c=window.location)==null?void 0:c.href).searchParams.get("_storyblok"),o=n!==null&&+n===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"],h=>{var u;h&&(h.action==="input"&&((u=h.story)==null?void 0:u.id)===i?e(h.story):(h.action==="change"||h.action==="published")&&h.storyId===i&&window.location.reload())})})}},W=(i,e)=>{i.addNode("blok",t=>{let s="";return t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})},Ue=(i={})=>{var d,b;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(S=>{a={...a,...S(c)}}),o&&(z=o);const u=!(typeof window>"u")&&((b=(d=window.location)==null?void 0:d.search)==null?void 0:b.includes("_storyblok_tk"));return e!==!1&&u&&F(z),U=new O(n.schema),n.resolver&&W(U,n.resolver),a},X=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"))},ze=(i,e,t)=>{let s=t||U;if(!s){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return X(i)?"":(e&&(s=new O(e.schema),e.resolver&&W(s,e.resolver)),s.render(i,{},!1))},De=()=>F(z);v.BlockTypes=$,v.MarkTypes=E,v.RichTextResolver=O,v.RichTextSchema=G,v.TextTypes=B,v.apiPlugin=Le,v.isRichTextEmpty=X,v.loadStoryblokBridge=De,v.registerStoryblokBridge=Y,v.renderRichText=ze,v.richTextResolver=Be,v.storyblokEditable=xe,v.storyblokInit=Ue,v.useStoryblokBridge=Y,Object.defineProperty(v,Symbol.toStringTag,{value:"Module"})});
7
+ (function(w,S){typeof exports=="object"&&typeof module<"u"?S(exports):typeof define=="function"&&define.amd?define(["exports"],S):(w=typeof globalThis<"u"?globalThis:w||self,S(w.storyblok={}))})(this,function(w){"use strict";function S(r,e){if(!e)return{src:r,attrs:{}};let t=0,o=0;const s={},n=[];function a(h,c,d,y,$){typeof h!="number"||h<=c||h>=d?console.warn(`[StoryblokRichText] - ${y.charAt(0).toUpperCase()+y.slice(1)} value must be a number between ${c} and ${d} (inclusive)`):$.push(`${y}(${h})`)}if(typeof e=="object"){if(typeof e.width=="number"&&e.width>0?(s.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?(s.height=e.height,o=e.height):console.warn("[StoryblokRichText] - Height value must be a number greater than 0"),e.loading&&["lazy","eager"].includes(e.loading)&&(s.loading=e.loading),e.class&&(s.class=e.class),e.filters){const{filters:h}=e||{},{blur:c,brightness:d,fill:y,format:$,grayscale:L,quality:E,rotate:O}=h||{};c&&a(c,0,100,"blur",n),E&&a(E,0,100,"quality",n),d&&a(d,0,100,"brightness",n),y&&n.push(`fill(${y})`),L&&n.push("grayscale()"),O&&[0,90,180,270].includes(e.filters.rotate||0)&&n.push(`rotate(${O})`),$&&["webp","png","jpeg"].includes($)&&n.push(`format(${$})`)}e.srcset&&(s.srcset=e.srcset.map(h=>{if(typeof h=="number")return`${r}/m/${h}x0/${n.length>0?`filters:${n.join(":")}`:""} ${h}w`;if(Array.isArray(h)&&h.length===2){const[c,d]=h;return`${r}/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&&(s.sizes=e.sizes.join(", "))}let l=`${r}/m/`;return t>0&&o>0&&(l=`${l}${t}x${o}/`),n.length>0&&(l=`${l}filters:${n.join(":")}`),{src:l,attrs:s}}var b=(r=>(r.DOCUMENT="doc",r.HEADING="heading",r.PARAGRAPH="paragraph",r.QUOTE="blockquote",r.OL_LIST="ordered_list",r.UL_LIST="bullet_list",r.LIST_ITEM="list_item",r.CODE_BLOCK="code_block",r.HR="horizontal_rule",r.BR="hard_break",r.IMAGE="image",r.EMOJI="emoji",r.COMPONENT="blok",r.TABLE="table",r.TABLE_ROW="tableRow",r.TABLE_CELL="tableCell",r.TABLE_HEADER="tableHeader",r))(b||{}),_=(r=>(r.BOLD="bold",r.STRONG="strong",r.STRIKE="strike",r.UNDERLINE="underline",r.ITALIC="italic",r.CODE="code",r.LINK="link",r.ANCHOR="anchor",r.STYLED="styled",r.SUPERSCRIPT="superscript",r.SUBSCRIPT="subscript",r.TEXT_STYLE="textStyle",r.HIGHLIGHT="highlight",r))(_||{}),N=(r=>(r.TEXT="text",r))(N||{}),I=(r=>(r.URL="url",r.STORY="story",r.ASSET="asset",r.EMAIL="email",r))(I||{});const K=["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"],W=(r={})=>Object.keys(r).map(e=>`${e}="${r[e]}"`).join(" "),X=(r={})=>Object.keys(r).map(e=>`${e}: ${r[e]}`).join("; ");function Q(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}const j=r=>Object.fromEntries(Object.entries(r).filter(([e,t])=>t!==void 0));function D(r,e={},t){const o=W(e),s=o?`${r} ${o}`:r,n=Array.isArray(t)?t.join(""):t||"";if(r){if(K.includes(r))return`<${s}>`}else return n;return`<${s}>${n}</${r}>`}function M(r={}){const e=new Map,{renderFn:t=D,textFn:o=Q,resolvers:s={},optimizeImages:n=!1,keyedResolvers:a=!1}=r,l=t!==D,h=()=>({render:(i,u={},p)=>{if(a&&i){const f=e.get(i)||0;e.set(i,f+1),u.key=`${i}-${f}`}return t(i,u,p)}}),c=i=>(u,p)=>{const f=u.attrs||{};return p.render(i,f,u.children||null)},d=(i,u)=>{const{src:p,alt:f,title:m,srcset:T,sizes:v}=i.attrs||{};let k=p,R={};if(n){const{src:Ee,attrs:Ae}=S(p,n);k=Ee,R=Ae}const Re={src:k,alt:f,title:m,srcset:T,sizes:v,...R};return u.render("img",j(Re))},y=(i,u)=>{const{level:p,...f}=i.attrs||{};return u.render(`h${p}`,f,i.children)},$=(i,u)=>{var p,f,m,T;const v=u.render("img",{src:(p=i.attrs)==null?void 0:p.fallbackImage,alt:(f=i.attrs)==null?void 0:f.alt,style:"width: 1.25em; height: 1.25em; vertical-align: text-top",draggable:"false",loading:"lazy"});return u.render("span",{"data-type":"emoji","data-name":(m=i.attrs)==null?void 0:m.name,"data-emoji":(T=i.attrs)==null?void 0:T.emoji},v)},L=(i,u)=>u.render("pre",i.attrs||{},u.render("code",{},i.children||"")),E=(i,u=!1)=>({text:p,attrs:f},m)=>{const{class:T,id:v,...k}=f||{},R=u?{class:T,id:v,style:X(k)||void 0}:f||{};return m.render(i,j(R),p)},O=i=>U(i),be=i=>{const{marks:u,...p}=i;if("text"in i){if(u)return u.reduce((m,T)=>O({...T,text:m}),O({...p,children:p.children}));const f=i.attrs||{};if(a){const m=e.get("txt")||0;e.set("txt",m+1),f.key=`txt-${m}`}return o(p.text,f)}return""},Y=(i,u)=>{const{linktype:p,href:f,anchor:m,...T}=i.attrs||{};let v="";switch(p){case I.ASSET:case I.URL:v=f;break;case I.EMAIL:v=`mailto:${f}`;break;case I.STORY:v=f,m&&(v=`${v}#${m}`);break;default:v=f;break}const k={...T};return v&&(k.href=v),u.render("a",k,i.text)},ve=(i,u)=>{var p,f;return console.warn("[StoryblokRichtText] - BLOK resolver is not available for vanilla usage"),u.render("span",{blok:(p=i==null?void 0:i.attrs)==null?void 0:p.body[0],id:(f=i.attrs)==null?void 0:f.id,style:"display: none"})},ke=(i,u)=>{const p={},f=u.render("tbody",{},i.children);return u.render("table",p,f)},we=(i,u)=>{const p={};return u.render("tr",p,i.children)},Te=(i,u)=>{const{colspan:p,rowspan:f,colwidth:m,backgroundColor:T,...v}=i.attrs||{},k={...v};p>1&&(k.colspan=p),f>1&&(k.rowspan=f);const R=[];return m&&R.push(`width: ${m}px;`),T&&R.push(`background-color: ${T};`),R.length>0&&(k.style=R.join(" ")),u.render("td",j(k),i.children)},$e=(i,u)=>{const{colspan:p,rowspan:f,colwidth:m,backgroundColor:T,...v}=i.attrs||{},k={...v};p>1&&(k.colspan=p),f>1&&(k.rowspan=f);const R=[];return m&&R.push(`width: ${m}px;`),T&&R.push(`background-color: ${T};`),R.length>0&&(k.style=R.join(" ")),u.render("th",j(k),i.children)},_e=new Map([[b.DOCUMENT,c("")],[b.HEADING,y],[b.PARAGRAPH,c("p")],[b.UL_LIST,c("ul")],[b.OL_LIST,c("ol")],[b.LIST_ITEM,c("li")],[b.IMAGE,d],[b.EMOJI,$],[b.CODE_BLOCK,L],[b.HR,c("hr")],[b.BR,c("br")],[b.QUOTE,c("blockquote")],[b.COMPONENT,ve],[N.TEXT,be],[_.LINK,Y],[_.ANCHOR,Y],[_.STYLED,E("span",!0)],[_.BOLD,E("strong")],[_.TEXT_STYLE,E("span",!0)],[_.ITALIC,E("em")],[_.UNDERLINE,E("u")],[_.STRIKE,E("s")],[_.CODE,E("code")],[_.SUPERSCRIPT,E("sup")],[_.SUBSCRIPT,E("sub")],[_.HIGHLIGHT,E("mark")],[b.TABLE,ke],[b.TABLE_ROW,we],[b.TABLE_CELL,Te],[b.TABLE_HEADER,$e],...Object.entries(s).map(([i,u])=>[i,u])]);function P(i){const u=_e.get(i.type);if(!u)return console.error("<Storyblok>",`No resolver found for node type ${i.type}`),"";const p=h();if(i.type==="text")return u(i,p);const f=i.content?i.content.map(U):void 0;return u({...i,children:f},p)}function U(i){return i.type==="doc"?l?i.content.map(P):i.content.map(P).join(""):Array.isArray(i)?i.map(P):P(i)}return{render:U}}let z=!1;const F=[],G=r=>new Promise((e,t)=>{if(typeof window>"u"||(window.storyblokRegisterEvent=s=>{if(window.location===window.parent.location){console.warn("You are not in Draft Mode or in the Visual Editor.");return}z?s():F.push(s)},document.getElementById("storyblok-javascript-bridge")))return;const o=document.createElement("script");o.async=!0,o.src=r,o.id="storyblok-javascript-bridge",o.onerror=s=>t(s),o.onload=s=>{F.forEach(n=>n()),z=!0,e(s)},document.getElementsByTagName("head")[0].appendChild(o)});var Z=Object.defineProperty,ee=(r,e,t)=>e in r?Z(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,g=(r,e,t)=>ee(r,typeof e!="symbol"?e+"":e,t);class te extends Error{constructor(e){super(e),this.name="AbortError"}}function se(r,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 o=[];let s=[],n=0,a=!1;const l=async()=>{n++;const c=o.shift();if(c)try{const y=await r(...c.args);c.resolve(y)}catch(y){c.reject(y)}const d=setTimeout(()=>{n--,o.length>0&&l(),s=s.filter(y=>y!==d)},t);s.includes(d)||s.push(d)},h=(...c)=>a?Promise.reject(new Error("Throttled function is already aborted and not accepting new promises")):new Promise((d,y)=>{o.push({resolve:d,reject:y,args:c}),n<e&&l()});return h.abort=()=>{a=!0,s.forEach(clearTimeout),s=[],o.forEach(c=>c.reject(()=>new te("Throttle function aborted"))),o.length=0},h}const re=(r="")=>r.includes("/cdn/"),oe=(r,e=25,t=1)=>({...r,per_page:e,page:t}),ne=r=>new Promise(e=>setTimeout(e,r)),ie=(r=0,e)=>Array.from({length:r},e),ae=(r=0,e=r)=>{const t=Math.abs(e-r)||0,o=r<e?1:-1;return ie(t,(s,n)=>n*o+r)},le=async(r,e)=>Promise.all(r.map(e)),ce=(r=[],e)=>r.map(e).reduce((t,o)=>[...t,...o],[]),B=(r,e,t)=>{const o=[];for(const s in r){if(!Object.prototype.hasOwnProperty.call(r,s))continue;const n=r[s];if(n==null)continue;const a=t?"":encodeURIComponent(s);let l;typeof n=="object"?l=B(n,e?e+encodeURIComponent(`[${a}]`):a,Array.isArray(n)):l=`${e?e+encodeURIComponent(`[${a}]`):a}=${encodeURIComponent(n)}`,o.push(l)}return o.join("&")},V=r=>{const e={eu:"api.storyblok.com",us:"api-us.storyblok.com",cn:"app.storyblokchina.cn",ap:"api-ap.storyblok.com",ca:"api-ca.storyblok.com"};return e[r]??e.eu};class he{constructor(e){g(this,"baseURL"),g(this,"timeout"),g(this,"headers"),g(this,"responseInterceptor"),g(this,"fetch"),g(this,"ejectInterceptor"),g(this,"url"),g(this,"parameters"),g(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=[],o={data:{},headers:{},status:0,statusText:""};e.status!==204&&await e.json().then(s=>{o.data=s});for(const s of e.headers.entries())t[s[0]]=s[1];return o.headers={...t},o.status=e.status,o.statusText=e.statusText,o}async _methodHandler(e){let t=`${this.baseURL}${this.url}`,o=null;e==="get"?t=`${this.baseURL}${this.url}?${B(this.parameters)}`:o=JSON.stringify(this.parameters);const s=new URL(t),n=new AbortController,{signal:a}=n;let l;this.timeout&&(l=setTimeout(()=>n.abort(),this.timeout));try{const h=await this.fetch(`${s}`,{method:e,headers:this.headers,body:o,signal:a,...this.fetchOptions});this.timeout&&clearTimeout(l);const c=await this._responseHandler(h);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(c)):this._statusHandler(c)}catch(h){return{message:h}}}setFetchOptions(e={}){Object.keys(e).length>0&&"method"in e&&delete e.method,this.fetchOptions={...e}}eject(){this.ejectInterceptor=!0}_normalizeErrorMessage(e){if(Array.isArray(e))return e[0]||"Unknown error";if(e&&typeof e=="object"){if(e.error)return e.error;for(const t in e){if(Array.isArray(e[t]))return`${t}: ${e[t][0]}`;if(typeof e[t]=="string")return`${t}: ${e[t]}`}if(e.slug)return e.slug}return"Unknown error"}_statusHandler(e){const t=/20[0-6]/g;return new Promise((o,s)=>{if(t.test(`${e.status}`))return o(e);const n={message:this._normalizeErrorMessage(e.data),status:e.status,response:e};s(n)})}}const q="SB-Agent",x={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"6.0.0"},ue={DRAFT:"draft"};let C={};const A={};class de{constructor(e,t){g(this,"client"),g(this,"maxRetries"),g(this,"retriesDelay"),g(this,"throttle"),g(this,"accessToken"),g(this,"cache"),g(this,"resolveCounter"),g(this,"relations"),g(this,"links"),g(this,"version"),g(this,"richTextResolver"),g(this,"resolveNestedRelations"),g(this,"stringifiedStoriesCache"),g(this,"inlineAssets");let o=e.endpoint||t;if(!o){const a=e.https===!1?"http":"https";e.oauthToken?o=`${a}://${V(e.region)}/v1`:o=`${a}://${V(e.region)}/v2`}const s=new Headers;s.set("Content-Type","application/json"),s.set("Accept","application/json"),e.headers&&(e.headers.constructor.name==="Headers"?e.headers.entries().toArray():Object.entries(e.headers)).forEach(([a,l])=>{s.set(a,l)}),s.has(q)||(s.set(q,x.defaultAgentName),s.set(x.defaultAgentVersion,x.packageVersion));let n=5;e.oauthToken&&(s.set("Authorization",e.oauthToken),n=3),e.rateLimit&&(n=e.rateLimit),this.maxRetries=e.maxRetries||10,this.retriesDelay=300,this.throttle=se(this.throttledRequest.bind(this),n,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.stringifiedStoriesCache={},this.version=e.version||ue.DRAFT,this.inlineAssets=e.inlineAssets||!1,this.client=new he({baseURL:o,timeout:e.timeout||0,headers:s,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}parseParams(e){return e.token||(e.token=this.getToken()),e.cv||(e.cv=A[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 re(e)?this.parseParams(t):t}makeRequest(e,t,o,s,n){const a=this.factoryParamOptions(e,oe(t,o,s));return this.cacheResponse(e,a,void 0,n)}get(e,t={},o){t||(t={});const s=`/${e}`;t.version=t.version||this.version;const n=this.factoryParamOptions(s,t);return this.cacheResponse(s,n,void 0,o)}async getAll(e,t={},o,s){const n=(t==null?void 0:t.per_page)||25,a=`/${e}`.replace(/\/$/,""),l=o??a.substring(a.lastIndexOf("/")+1);t.version=t.version||this.version;const h=1,c=await this.makeRequest(a,t,n,h,s),d=c.total?Math.ceil(c.total/n):1,y=await le(ae(h,d),$=>this.makeRequest(a,t,n,$+1,s));return ce([c,...y],$=>Object.values($.data[l]))}post(e,t={},o){const s=`/${e}`;return this.throttle("post",s,t,o)}put(e,t={},o){const s=`/${e}`;return this.throttle("put",s,t,o)}delete(e,t={},o){t||(t={});const s=`/${e}`;return this.throttle("delete",s,t,o)}getStories(e={},t){return this._addResolveLevel(e),this.get("cdn/stories",e,t)}getStory(e,t={},o){return this._addResolveLevel(t),this.get(`cdn/stories/${e}`,t,o)}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,o){const s=e[t];s&&s.fieldtype==="multilink"&&s.linktype==="story"&&typeof s.id=="string"&&this.links[o][s.id]?s.story=this._cleanCopy(this.links[o][s.id]):s&&s.linktype==="story"&&typeof s.uuid=="string"&&this.links[o][s.uuid]&&(s.story=this._cleanCopy(this.links[o][s.uuid]))}getStoryReference(e,t){return this.relations[e][t]?JSON.parse(this.stringifiedStoriesCache[t]||JSON.stringify(this.relations[e][t])):t}_resolveField(e,t,o){const s=e[t];typeof s=="string"?e[t]=this.getStoryReference(o,s):Array.isArray(s)&&(e[t]=s.map(n=>this.getStoryReference(o,n)).filter(Boolean))}_insertRelations(e,t,o,s){if(Array.isArray(o)?o.find(a=>a.endsWith(`.${t}`)):o.endsWith(`.${t}`)){this._resolveField(e,t,s);return}const n=e.component?`${e.component}.${t}`:t;(Array.isArray(o)?o.includes(n):o===n)&&this._resolveField(e,t,s)}iterateTree(e,t,o){const s=(n,a="")=>{if(!(!n||n._stopResolving)){if(Array.isArray(n))n.forEach((l,h)=>s(l,`${a}[${h}]`));else if(typeof n=="object")for(const l in n){const h=a?`${a}.${l}`:l;(n.component&&n._uid||n.type==="link")&&(this._insertRelations(n,l,t,o),this._insertLinks(n,l,o)),s(n[l],h)}}};s(e.content)}async resolveLinks(e,t,o){let s=[];if(e.link_uuids){const n=e.link_uuids.length,a=[],l=50;for(let h=0;h<n;h+=l){const c=Math.min(n,h+l);a.push(e.link_uuids.slice(h,c))}for(let h=0;h<a.length;h++)(await this.getStories({per_page:l,language:t.language,version:t.version,starts_with:t.starts_with,by_uuids:a[h].join(",")})).data.stories.forEach(c=>{s.push(c)})}else s=e.links;s.forEach(n=>{this.links[o][n.uuid]={...n,_stopResolving:!0}})}async resolveRelations(e,t,o){let s=[];if(e.rel_uuids){const n=e.rel_uuids.length,a=[],l=50;for(let h=0;h<n;h+=l){const c=Math.min(n,h+l);a.push(e.rel_uuids.slice(h,c))}for(let h=0;h<a.length;h++)(await this.getStories({per_page:l,language:t.language,version:t.version,starts_with:t.starts_with,by_uuids:a[h].join(","),excluding_fields:t.excluding_fields})).data.stories.forEach(c=>{s.push(c)});s.length>0&&(e.rels=s,delete e.rel_uuids)}else s=e.rels;s&&s.length>0&&s.forEach(n=>{this.relations[o][n.uuid]={...n,_stopResolving:!0}})}async resolveStories(e,t,o){var s,n;let a=[];if(this.links[o]={},this.relations[o]={},typeof t.resolve_relations<"u"&&t.resolve_relations.length>0&&(typeof t.resolve_relations=="string"&&(a=t.resolve_relations.split(",")),await this.resolveRelations(e,t,o)),t.resolve_links&&["1","story","url","link"].includes(t.resolve_links)&&((s=e.links)!=null&&s.length||(n=e.link_uuids)!=null&&n.length)&&await this.resolveLinks(e,t,o),this.resolveNestedRelations)for(const l in this.relations[o])this.iterateTree(this.relations[o][l],a,o);e.story?this.iterateTree(e.story,a,o):e.stories.forEach(l=>{this.iterateTree(l,a,o)}),this.stringifiedStoriesCache={},delete this.links[o],delete this.relations[o]}async cacheResponse(e,t,o,s){const n=B({url:e,params:t}),a=this.cacheProvider();if(t.version==="published"&&e!=="/cdn/spaces/me"){const l=await a.get(n);if(l)return Promise.resolve(l)}return new Promise(async(l,h)=>{var c;try{const d=await this.throttle("get",e,t,s);if(d.status!==200)return h(d);let y={data:d.data,headers:d.headers};if((c=d.headers)!=null&&c["per-page"]&&(y=Object.assign({},y,{perPage:d.headers["per-page"]?Number.parseInt(d.headers["per-page"]):0,total:d.headers["per-page"]?Number.parseInt(d.headers.total):0})),y.data.story||y.data.stories){const L=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(y.data,t,`${L}`),y=await this.processInlineAssets(y)}t.version==="published"&&e!=="/cdn/spaces/me"&&await a.set(n,y);const $=this.cache.clear==="onpreview"&&t.version==="draft"||this.cache.clear==="auto";return t.token&&y.data.cv&&($&&A[t.token]&&A[t.token]!==y.data.cv&&await this.flushCache(),A[t.token]=y.data.cv),l(y)}catch(d){if(d.response&&d.status===429&&(o=typeof o>"u"?0:o+1,o<this.maxRetries))return console.log(`Hit rate limit. Retrying in ${this.retriesDelay/1e3} seconds.`),await ne(this.retriesDelay),this.cacheResponse(e,t,o).then(l).catch(h);h(d)}})}throttledRequest(e,t,o,s){return this.client.setFetchOptions(s),this.client[e](t,o)}cacheVersions(){return A}cacheVersion(){return A[this.accessToken]}setCacheVersion(e){this.accessToken&&(A[this.accessToken]=e)}clearCacheVersion(){this.accessToken&&(A[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}async processInlineAssets(e){if(!this.inlineAssets)return e;const t=o=>{if(!o||typeof o!="object")return o;if(Array.isArray(o))return o.map(n=>t(n));let s={...o};s.fieldtype==="asset"&&Array.isArray(e.data.assets)&&(s={...s,...e.data.assets.find(n=>n.id===s.id)});for(const n in s)typeof s[n]=="object"&&(s[n]=t(s[n]));return s};return e.data.story&&(e.data.story.content=t(e.data.story.content)),e.data.stories&&(e.data.stories=e.data.stories.map(o=>(o.content=t(o.content),o))),e}}const pe=(r={})=>{const{apiOptions:e}=r;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 de(e)}},fe=r=>{if(typeof r!="object"||typeof r._editable>"u")return{};try{const e=JSON.parse(r._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return e?{"data-blok-c":JSON.stringify(e),"data-blok-uid":`${e.id}-${e.uid}`}:{}}catch{return{}}};let H="https://app.storyblok.com/f/storyblok-v2-latest.js";const J=(r,e,t={})=>{var l;const s=!(typeof window>"u")&&typeof window.storyblokRegisterEvent<"u",n=new URL((l=window.location)==null?void 0:l.href).searchParams.get("_storyblok"),a=n!==null&&+n===r;if(!(!s||!a)){if(!r){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 d;c&&(c.action==="input"&&((d=c.story)==null?void 0:d.id)===r?e(c.story):(c.action==="change"||c.action==="published")&&c.storyId===r&&window.location.reload())})})}},ye=(r={})=>{var d,y;const{bridge:e,accessToken:t,use:o=[],apiOptions:s={},bridgeUrl:n}=r;s.accessToken=s.accessToken||t;const a={bridge:e,apiOptions:s};let l={};o.forEach($=>{l={...l,...$(a)}}),n&&(H=n);const c=!(typeof window>"u")&&((y=(d=window.location)==null?void 0:d.search)==null?void 0:y.includes("_storyblok_tk"));return e!==!1&&c&&G(H),l};function ge(r,e){return M(e).render(r)}const me=()=>G(H);w.BlockTypes=b,w.MarkTypes=_,w.TextTypes=N,w.apiPlugin=pe,w.loadStoryblokBridge=me,w.registerStoryblokBridge=J,w.renderRichText=ge,w.richTextResolver=M,w.storyblokEditable=fe,w.storyblokInit=ye,w.useStoryblokBridge=J,Object.defineProperty(w,Symbol.toStringTag,{value:"Module"})});