@storyblok/vue 8.0.9-next.1 → 8.1.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 +92 -0
- package/dist/StoryblokComponent.vue.d.ts +1 -4
- package/dist/components/StoryblokRichText.vue.d.ts +12 -0
- package/dist/composables/useStoryblokRichText.d.ts +9 -0
- package/dist/index.d.ts +5 -13
- package/dist/storyblok-vue.js +3 -3
- package/dist/storyblok-vue.mjs +634 -428
- package/dist/types.d.ts +21 -2
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -130,6 +130,98 @@ Check the available [apiOptions](https://www.storyblok.com/docs/api/content-deli
|
|
|
130
130
|
|
|
131
131
|
### Rendering Rich Text
|
|
132
132
|
|
|
133
|
+
You can render rich-text fields by using the `StoryblokRichtext` component:
|
|
134
|
+
|
|
135
|
+
```html
|
|
136
|
+
<script setup>
|
|
137
|
+
import { StoryblokRichtext } from "@storyblok/vue";
|
|
138
|
+
</script>
|
|
139
|
+
|
|
140
|
+
<template>
|
|
141
|
+
<StoryblokRichtext :doc="blok.articleContent" />
|
|
142
|
+
</template>
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
#### Overriding the default resolvers
|
|
146
|
+
|
|
147
|
+
You can override the default resolvers by passing a `resolver` prop to the `StoryblokRichText` component, for example, to use vue-router links or add a custom codeblok component: :
|
|
148
|
+
|
|
149
|
+
```html
|
|
150
|
+
<script setup>
|
|
151
|
+
import { type VNode, h } from "vue";
|
|
152
|
+
import { StoryblokRichText, BlockTypes, MarkTypes, type StoryblokRichTextNode } from "@storyblok/vue";
|
|
153
|
+
import { RouterLink } from "vue-router";
|
|
154
|
+
import CodeBlok from "./components/CodeBlok.vue";
|
|
155
|
+
|
|
156
|
+
const resolvers = {
|
|
157
|
+
// RouterLink example:
|
|
158
|
+
[MarkTypes.LINK]: (node: StoryblokRichTextNode<VNode>) => {
|
|
159
|
+
return node.attrs?.linktype === 'STORY'
|
|
160
|
+
? h(RouterLink, {
|
|
161
|
+
to: node.attrs?.href,
|
|
162
|
+
target: node.attrs?.target,
|
|
163
|
+
}, node.text)
|
|
164
|
+
: h('a', {
|
|
165
|
+
href: node.attrs?.href,
|
|
166
|
+
target: node.attrs?.target,
|
|
167
|
+
}, node.text)
|
|
168
|
+
},
|
|
169
|
+
// Custom code block component example:
|
|
170
|
+
[BlockTypes.CODE_BLOCK]: (node: Node) => {
|
|
171
|
+
return h(CodeBlock, {
|
|
172
|
+
class: node?.attrs?.class,
|
|
173
|
+
}, node.children)
|
|
174
|
+
},
|
|
175
|
+
}
|
|
176
|
+
</script>
|
|
177
|
+
|
|
178
|
+
<template>
|
|
179
|
+
<StoryblokRichText :doc="blok.articleContent" :resolvers="resolvers" />
|
|
180
|
+
</template>
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Or you can have more control by using the `useStoryblokRichText` composable:
|
|
184
|
+
|
|
185
|
+
```html
|
|
186
|
+
<script setup>
|
|
187
|
+
import { type VNode, h } from "vue";
|
|
188
|
+
import { useStoryblokRichText, BlockTypes, MarkTypes, type StoryblokRichTextNode } from "@storyblok/vue";
|
|
189
|
+
import { RouterLink } from "vue-router";
|
|
190
|
+
|
|
191
|
+
const resolvers = {
|
|
192
|
+
// RouterLink example:
|
|
193
|
+
[MarkTypes.LINK]: (node: StoryblokRichTextNode<VNode>) => {
|
|
194
|
+
return node.attrs?.linktype === 'STORY'
|
|
195
|
+
? h(RouterLink, {
|
|
196
|
+
to: node.attrs?.href,
|
|
197
|
+
target: node.attrs?.target,
|
|
198
|
+
}, node.text)
|
|
199
|
+
: h('a', {
|
|
200
|
+
href: node.attrs?.href,
|
|
201
|
+
target: node.attrs?.target,
|
|
202
|
+
}, node.text)
|
|
203
|
+
},
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const { render } = useStoryblokRichText({
|
|
207
|
+
resolvers,
|
|
208
|
+
})
|
|
209
|
+
|
|
210
|
+
const html = render(blok.articleContent);
|
|
211
|
+
</script>
|
|
212
|
+
|
|
213
|
+
<template>
|
|
214
|
+
<div v-html="html"></div>
|
|
215
|
+
</template>
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
For more incredible options you can pass to the `useStoryblokRichtext, please consult the [Full options](https://github.com/storyblok/richtext?tab=readme-ov-file#options) documentation.
|
|
219
|
+
|
|
220
|
+
### Legacy Rich Text Resolver
|
|
221
|
+
|
|
222
|
+
> [!WARNING]
|
|
223
|
+
> The legacy `richTextResolver` is soon to be deprecated. We recommend migrating to the new `useRichText` composable described above instead.
|
|
224
|
+
|
|
133
225
|
You can easily render rich text by using the `renderRichText` function that comes with `@storyblok/vue` and a Vue computed property:
|
|
134
226
|
|
|
135
227
|
```html
|
|
@@ -1,7 +1,4 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
export interface SbComponentProps {
|
|
3
|
-
blok: SbBlokData;
|
|
4
|
-
}
|
|
1
|
+
import type { SbComponentProps } from "./types";
|
|
5
2
|
declare const _default: import("vue").DefineComponent<__VLS_TypePropsToRuntimeProps<SbComponentProps>, {
|
|
6
3
|
value: import("vue").Ref<any>;
|
|
7
4
|
}, unknown, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<import("vue").ExtractPropTypes<__VLS_TypePropsToRuntimeProps<SbComponentProps>>>, {}, {}>;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { StoryblokRichTextProps } from "../types";
|
|
2
|
+
declare const _default: import("vue").DefineComponent<__VLS_TypePropsToRuntimeProps<StoryblokRichTextProps>, {}, unknown, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<import("vue").ExtractPropTypes<__VLS_TypePropsToRuntimeProps<StoryblokRichTextProps>>>, {}, {}>;
|
|
3
|
+
export default _default;
|
|
4
|
+
type __VLS_NonUndefinedable<T> = T extends undefined ? never : T;
|
|
5
|
+
type __VLS_TypePropsToRuntimeProps<T> = {
|
|
6
|
+
[K in keyof T]-?: {} extends Pick<T, K> ? {
|
|
7
|
+
type: import('vue').PropType<__VLS_NonUndefinedable<T[K]>>;
|
|
8
|
+
} : {
|
|
9
|
+
type: import('vue').PropType<T[K]>;
|
|
10
|
+
required: true;
|
|
11
|
+
};
|
|
12
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { VNode } from "vue";
|
|
2
|
+
import type { StoryblokRichTextNode, StoryblokRichTextOptions } from "@storyblok/js";
|
|
3
|
+
export declare function useStoryblokRichText(options: StoryblokRichTextOptions<VNode>): {
|
|
4
|
+
render: (node: StoryblokRichTextNode<VNode<import("vue").RendererNode, import("vue").RendererElement, {
|
|
5
|
+
[key: string]: any;
|
|
6
|
+
}>>) => VNode<import("vue").RendererNode, import("vue").RendererElement, {
|
|
7
|
+
[key: string]: any;
|
|
8
|
+
}>;
|
|
9
|
+
};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,20 +1,12 @@
|
|
|
1
1
|
import type { Ref, Plugin } from "vue";
|
|
2
|
-
import type { StoryblokClient,
|
|
3
|
-
export
|
|
4
|
-
export { useStoryblokBridge, apiPlugin, renderRichText, RichTextSchema, RichTextResolver, } from "@storyblok/js";
|
|
2
|
+
import type { StoryblokClient, StoryblokBridgeConfigV2, ISbStoryData, ISbStoriesParams } from "./types";
|
|
3
|
+
export { useStoryblokBridge, apiPlugin, renderRichText, RichTextSchema, RichTextResolver, BlockTypes, MarkTypes, richTextResolver, TextTypes, type StoryblokRichTextOptions, type StoryblokRichTextDocumentNode, type StoryblokRichTextNodeTypes, type StoryblokRichTextNode, type StoryblokRichTextResolvers, type StoryblokRichTextNodeResolver, type StoryblokRichTextImageOptimizationOptions, } from "@storyblok/js";
|
|
5
4
|
export { default as StoryblokComponent } from "./StoryblokComponent.vue";
|
|
5
|
+
export { default as StoryblokRichText } from "./components/StoryblokRichText.vue";
|
|
6
|
+
export * from "./composables/useStoryblokRichText";
|
|
7
|
+
export declare const useStoryblokApi: () => StoryblokClient;
|
|
6
8
|
export declare const useStoryblok: (url: string, apiOptions?: ISbStoriesParams, bridgeOptions?: StoryblokBridgeConfigV2) => Promise<Ref<ISbStoryData<import("@storyblok/js").StoryblokComponentType<string> & {
|
|
7
9
|
[index: string]: any;
|
|
8
10
|
}>>>;
|
|
9
|
-
export interface SbVueSDKOptions extends SbSDKOptions {
|
|
10
|
-
/**
|
|
11
|
-
* Show a fallback component in your frontend if a component is not registered properly.
|
|
12
|
-
*/
|
|
13
|
-
enableFallbackComponent?: boolean;
|
|
14
|
-
/**
|
|
15
|
-
* Provide a custom fallback component, e.g. "CustomFallback".
|
|
16
|
-
*/
|
|
17
|
-
customFallbackComponent?: string;
|
|
18
|
-
}
|
|
19
11
|
export declare const StoryblokVue: Plugin;
|
|
20
12
|
export * from "./types";
|
package/dist/storyblok-vue.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(
|
|
1
|
+
(function(m,g){typeof exports=="object"&&typeof module<"u"?g(exports,require("vue")):typeof define=="function"&&define.amd?define(["exports","vue"],g):(m=typeof globalThis<"u"?globalThis:m||self,g(m.storyblokVue={},m.Vue))})(this,function(m,g){"use strict";let D=!1;const H=[],Q=s=>new Promise((e,t)=>{if(typeof window>"u"||(window.storyblokRegisterEvent=o=>{if(window.location===window.parent.location){console.warn("You are not in Draft Mode or in the Visual Editor.");return}D?o():H.push(o)},document.getElementById("storyblok-javascript-bridge")))return;const r=document.createElement("script");r.async=!0,r.src=s,r.id="storyblok-javascript-bridge",r.onerror=o=>t(o),r.onload=o=>{H.forEach(n=>n()),D=!0,e(o)},document.getElementsByTagName("head")[0].appendChild(r)});var Z=Object.defineProperty,ee=(s,e,t)=>e in s?Z(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,d=(s,e,t)=>ee(s,typeof e!="symbol"?e+"":e,t);function z(s){return!(s!==s||s===1/0||s===-1/0)}function te(s,e,t){if(!z(e))throw new TypeError("Expected `limit` to be a finite number");if(!z(t))throw new TypeError("Expected `interval` to be a finite number");const r=[];let o=[],n=0;const i=function(){n++;const a=setTimeout(function(){n--,r.length>0&&i(),o=o.filter(function(p){return p!==a})},t);o.indexOf(a)<0&&o.push(a);const u=r.shift();u.resolve(s.apply(u.self,u.args))},l=function(...a){const u=this;return new Promise(function(p,h){r.push({resolve:p,reject:h,args:a,self:u}),n<e&&i()})};return l.abort=function(){o.forEach(clearTimeout),o=[],r.forEach(function(a){a.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),r.length=0},l}class O{constructor(){d(this,"isCDNUrl",(e="")=>e.indexOf("/cdn/")>-1),d(this,"getOptionsPage",(e,t=25,r=1)=>({...e,per_page:t,page:r})),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 r=Math.abs(t-e)||0,o=e<t?1:-1;return this.arrayFrom(r,(n,i)=>i*o+e)}),d(this,"asyncMap",async(e,t)=>Promise.all(e.map(t))),d(this,"flatMap",(e=[],t)=>e.map(t).reduce((r,o)=>[...r,...o],[])),d(this,"escapeHTML",function(e){const t={"&":"&","<":"<",">":">",'"':""","'":"'"},r=/[&<>"']/g,o=RegExp(r.source);return e&&o.test(e)?e.replace(r,n=>t[n]):e})}stringify(e,t,r){const o=[];for(const n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;const i=e[n],l=r?"":encodeURIComponent(n);let a;typeof i=="object"?a=this.stringify(i,t?t+encodeURIComponent("["+l+"]"):l,Array.isArray(i)):a=(t?t+encodeURIComponent("["+l+"]"):l)+"="+encodeURIComponent(i),o.push(a)}return o.join("&")}getRegionURL(e){const t="api.storyblok.com",r="api-us.storyblok.com",o="app.storyblokchina.cn",n="api-ap.storyblok.com",i="api-ca.storyblok.com";switch(e){case"us":return r;case"cn":return o;case"ap":return n;case"ca":return i;default:return t}}}const re=function(s,e){const t={};for(const r in s){const o=s[r];e.indexOf(r)>-1&&o!==null&&(t[r]=o)}return t},se=s=>s==="email",oe=()=>({singleTag:"hr"}),ne=()=>({tag:"blockquote"}),ie=()=>({tag:"ul"}),ae=s=>({tag:["pre",{tag:"code",attrs:s.attrs}]}),le=()=>({singleTag:"br"}),ce=s=>({tag:`h${s.attrs.level}`}),he=s=>({singleTag:[{tag:"img",attrs:re(s.attrs,["src","alt","title"])}]}),ue=()=>({tag:"li"}),pe=()=>({tag:"ol"}),de=()=>({tag:"p"}),ge=s=>({tag:[{tag:"span",attrs:{"data-type":"emoji","data-name":s.attrs.name,emoji:s.attrs.emoji}}]}),fe=()=>({tag:"b"}),me=()=>({tag:"s"}),ye=()=>({tag:"u"}),be=()=>({tag:"strong"}),ke=()=>({tag:"code"}),ve=()=>({tag:"i"}),Te=s=>{if(!s.attrs)return{tag:""};const e=new O().escapeHTML,t={...s.attrs},{linktype:r="url"}=s.attrs;if(delete t.linktype,t.href&&(t.href=e(s.attrs.href||"")),se(r)&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),t.custom){for(const o in t.custom)t[o]=t.custom[o];delete t.custom}return{tag:[{tag:"a",attrs:t}]}},$e=s=>({tag:[{tag:"span",attrs:s.attrs}]}),_e=()=>({tag:"sub"}),Re=()=>({tag:"sup"}),we=s=>({tag:[{tag:"span",attrs:s.attrs}]}),Se=s=>{var e;return(e=s.attrs)!=null&&e.color?{tag:[{tag:"span",attrs:{style:`background-color:${s.attrs.color};`}}]}:{tag:""}},Ee=s=>{var e;return(e=s.attrs)!=null&&e.color?{tag:[{tag:"span",attrs:{style:`color:${s.attrs.color}`}}]}:{tag:""}},B={nodes:{horizontal_rule:oe,blockquote:ne,bullet_list:ie,code_block:ae,hard_break:le,heading:ce,image:he,list_item:ue,ordered_list:pe,paragraph:de,emoji:ge},marks:{bold:fe,strike:me,underline:ye,strong:be,code:ke,italic:ve,link:Te,styled:$e,subscript:_e,superscript:Re,anchor:we,highlight:Se,textStyle:Ee}},Ce=function(s){const e={"&":"&","<":"<",">":">",'"':""","'":"'"},t=/[&<>"']/g,r=RegExp(t.source);return s&&r.test(s)?s.replace(t,o=>e[o]):s};class Ie{constructor(e){d(this,"marks"),d(this,"nodes"),e||(e=B),this.marks=e.marks||[],this.nodes=e.nodes||[]}addNode(e,t){this.nodes[e]=t}addMark(e,t){this.marks[e]=t}render(e,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` package instead. https://github.com/storyblok/richtext/"),e&&e.content&&Array.isArray(e.content)){let r="";return e.content.forEach(o=>{r+=this.renderNode(o)}),t.optimizeImages?this.optimizeImages(r,t.optimizeImages):r}return console.warn(`The render method must receive an Object with a "content" field.
|
|
2
2
|
The "content" field must be an array of nodes as the type ISbRichtext.
|
|
3
3
|
ISbRichtext:
|
|
4
4
|
content?: ISbRichtext[]
|
|
@@ -21,5 +21,5 @@
|
|
|
21
21
|
}
|
|
22
22
|
],
|
|
23
23
|
type: 'doc'
|
|
24
|
-
}`),""}optimizeImages(e,t){let s=0,r=0,n="",i="";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&&(i+=`:blur(${t.filters.blur})`),typeof t.filters.brightness=="number"&&t.filters.brightness>=-100&&t.filters.brightness<=100&&(i+=`:brightness(${t.filters.brightness})`),t.filters.fill&&(t.filters.fill.match(/[0-9A-Fa-f]{6}/g)||t.filters.fill==="transparent")&&(i+=`:fill(${t.filters.fill})`),t.filters.format&&["webp","png","jpeg"].includes(t.filters.format)&&(i+=`:format(${t.filters.format})`),typeof t.filters.grayscale=="boolean"&&t.filters.grayscale&&(i+=":grayscale()"),typeof t.filters.quality=="number"&&t.filters.quality>=0&&t.filters.quality<=100&&(i+=`:quality(${t.filters.quality})`),t.filters.rotate&&[90,180,270].includes(t.filters.rotate)&&(i+=`:rotate(${t.filters.rotate})`),i.length>0&&(i="/filters"+i))),n.length>0&&(e=e.replace(/<img/g,`<img ${n.trim()}`));const l=s>0||r>0||i.length>0?`${s}x${r}${i}`:"";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/${l}`),typeof t!="boolean"&&(t.sizes||t.srcset)&&(e=e.replace(/<img.*?src=["|'](.*?)["|']/g,a=>{var c,p;const f=a.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);if(f&&f.length>0){const m={srcset:(c=t.srcset)==null?void 0:c.map(g=>{if(typeof g=="number")return`//${f}/m/${g}x0${i} ${g}w`;if(typeof g=="object"&&g.length===2){let T=0,L=0;return typeof g[0]=="number"&&(T=g[0]),typeof g[1]=="number"&&(L=g[1]),`//${f}/m/${T}x${L}${i} ${T}w`}}).join(", "),sizes:(p=t.sizes)==null?void 0:p.map(g=>g).join(", ")};let b="";return m.srcset&&(b+=`srcset="${m.srcset}" `),m.sizes&&(b+=`sizes="${m.sizes}" `),a.replace(/<img/g,`<img ${b.trim()}`)}return a})),e}renderNode(e){const t=[];e.marks&&e.marks.forEach(r=>{const 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(de(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 i=s.attrs[n];i!==null&&(r+=` ${n}="${i}"`)}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 fe{constructor(e){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=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 _;t=`${this.baseURL}${this.url}?${a.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const r=new URL(t),n=new AbortController,{signal:i}=n;let l;this.timeout&&(l=setTimeout(()=>n.abort(),this.timeout));try{const a=await this.fetch(`${r}`,{method:e,headers:this.headers,body:s,signal:i,...this.fetchOptions});this.timeout&&clearTimeout(l);const c=await this._responseHandler(a);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(c)):this._statusHandler(c)}catch(a){return{message:a}}}setFetchOptions(e={}){Object.keys(e).length>0&&"method"in e&&delete e.method,this.fetchOptions={...e}}eject(){this.ejectInterceptor=!0}_statusHandler(e){const t=/20[0-6]/g;return new Promise((s,r)=>{if(t.test(`${e.status}`))return s(e);const n={message:e.statusText,status:e.status,response:Array.isArray(e.data)?e.data[0]:e.data.error||e.data.slug};r(n)})}}const O="SB-Agent",$={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"6.0.0"};let w={};const y={};class ge{constructor(e,t){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=e.endpoint||t;if(!s){const i=new _().getRegionURL,l=e.https===!1?"http":"https";e.oauthToken?s=`${l}://${i(e.region)}/v1`:s=`${l}://${i(e.region)}/v2`}const r=new Headers;if(r.set("Content-Type","application/json"),r.set("Accept","application/json"),e.headers)for(const i in e.headers)r.set(i,e.headers[i]);r.has(O)||(r.set(O,$.defaultAgentName),r.set($.defaultAgentVersion,$.packageVersion));let n=5;e.oauthToken&&(r.set("Authorization",e.oauthToken),n=3),e.rateLimit&&(n=e.rateLimit),e.richTextSchema?this.richTextResolver=new k(e.richTextSchema):this.richTextResolver=new k,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||5,this.throttle=z(this.throttledRequest,n,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new _,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.stringifiedStoriesCache={},this.client=new fe({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=y[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,i=`/${e}`,l=i.split("/"),a=s||l[l.length-1],c=1,p=await this.makeRequest(i,t,n,c),f=p.total?Math.ceil(p.total/n):1;this.client.setFetchOptions(r);const m=await this.helpers.asyncMap(this.helpers.range(c,f),b=>this.makeRequest(i,t,n,b+1));return this.helpers.flatMap([p,...m],b=>Object.values(b.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 i=0;i<n.length;i++)r(n[i]);else if(n.constructor===Object){if(n._stopResolving)return;for(const i in n)(n.component&&n._uid||n.type==="link")&&(this._insertRelations(n,i,t,s),this._insertLinks(n,i,s)),r(n[i])}}};r(e.content)}async resolveLinks(e,t,s){let r=[];if(e.link_uuids){const n=e.link_uuids.length,i=[],l=50;for(let a=0;a<n;a+=l){const c=Math.min(n,a+l);i.push(e.link_uuids.slice(a,c))}for(let a=0;a<i.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:i[a].join(",")})).data.stories.forEach(c=>{r.push(c)})}else r=e.links;r.forEach(n=>{this.links[s][n.uuid]={...n,_stopResolving:!0}})}async resolveRelations(e,t,s){let r=[];if(e.rel_uuids){const n=e.rel_uuids.length,i=[],l=50;for(let a=0;a<n;a+=l){const c=Math.min(n,a+l);i.push(e.rel_uuids.slice(a,c))}for(let a=0;a<i.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:i[a].join(","),excluding_fields:t.excluding_fields})).data.stories.forEach(c=>{r.push(c)})}else r=e.rels;r&&r.length>0&&r.forEach(n=>{this.relations[s][n.uuid]={...n,_stopResolving:!0}})}async resolveStories(e,t,s){var r,n;let i=[];if(this.links[s]={},this.relations[s]={},typeof t.resolve_relations<"u"&&t.resolve_relations.length>0&&(typeof t.resolve_relations=="string"&&(i=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 l in this.relations[s])this.iterateTree(this.relations[s][l],i,s);e.story?this.iterateTree(e.story,i,s):e.stories.forEach(l=>{this.iterateTree(l,i,s)}),this.stringifiedStoriesCache={},delete this.links[s],delete this.relations[s]}async cacheResponse(e,t,s){(typeof s>"u"||!s)&&(s=0);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 i=await n.get(r);if(i)return Promise.resolve(i)}return new Promise(async(i,l)=>{var a;try{const c=await this.throttle("get",e,t);if(c.status!==200)return l(c);let p={data:c.data,headers:c.headers};if((a=c.headers)!=null&&a["per-page"]&&(p=Object.assign({},p,{perPage:c.headers["per-page"]?parseInt(c.headers["per-page"]):0,total:c.headers["per-page"]?parseInt(c.headers.total):0})),p.data.story||p.data.stories){const f=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(p.data,t,`${f}`)}return t.version==="published"&&e!="/cdn/spaces/me"&&await n.set(r,p),p.data.cv&&t.token&&(t.version==="draft"&&y[t.token]!=p.data.cv&&await this.flushCache(),y[t.token]=t.cv?t.cv:p.data.cv),i(p)}catch(c){if(c.response&&c.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(e,t,s).then(i).catch(l);l(c)}})}throttledRequest(e,t,s){return this.client[e](t,s)}cacheVersions(){return y}cacheVersion(){return y[this.accessToken]}setCacheVersion(e){this.accessToken&&(y[this.accessToken]=e)}clearCacheVersion(){this.accessToken&&(y[this.accessToken]=0)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(w[e])},getAll(){return Promise.resolve(w)},set(e,t){return w[e]=t,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 me=(o={})=>{const{apiOptions:e}=o;if(!e.accessToken){console.error("You need to provide an access token to interact with Storyblok API. Read https://www.storyblok.com/docs/api/content-delivery#topics/authentication");return}return{storyblokApi:new ge(e)}},ye=o=>{if(typeof o!="object"||typeof o._editable>"u")return{};try{const e=JSON.parse(o._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return e?{"data-blok-c":JSON.stringify(e),"data-blok-uid":e.id+"-"+e.uid}:{}}catch{return{}}};let R,P="https://app.storyblok.com/f/storyblok-v2-latest.js";const E=(o,e,t={})=>{var s;const r=!(typeof window>"u")&&typeof window.storyblokRegisterEvent<"u",n=+new URL((s=window.location)==null?void 0:s.href).searchParams.get("_storyblok")===o;if(!(!r||!n)){if(!o){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(t).on(["input","published","change"],i=>{i.action==="input"&&i.story.id===o?e(i.story):(i.action==="change"||i.action==="published")&&i.storyId===o&&window.location.reload()})})}},be=(o={})=>{var e,t;const{bridge:s,accessToken:r,use:n=[],apiOptions:i={},richText:l={},bridgeUrl:a}=o;i.accessToken=i.accessToken||r;const c={bridge:s,apiOptions:i};let p={};n.forEach(m=>{p={...p,...m(c)}}),a&&(P=a);const f=!(typeof window>"u")&&((t=(e=window.location)==null?void 0:e.search)==null?void 0:t.includes("_storyblok_tk"));return s!==!1&&f&&M(P),R=new k(l.schema),l.resolver&&I(R,l.resolver),p},I=(o,e)=>{o.addNode("blok",t=>{let s="";return t.attrs.body.forEach(r=>{s+=e(r.component,r)}),{html:s}})},ke=o=>!o||!(o!=null&&o.content.some(e=>e.content||e.type==="blok"||e.type==="horizontal_rule")),ve=(o,e,t)=>{let s=t||R;if(!s){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return ke(o)?"":(e&&(s=new k(e.schema),e.resolver&&I(s,e.resolver)),s.render(o))},A=u.defineComponent({__name:"StoryblokComponent",props:{blok:{}},setup(o,{expose:e}){const t=o,s=u.ref();e({value:s});const r=typeof u.resolveDynamicComponent(t.blok.component)!="string",n=u.inject("VueSDKOptions"),i=u.ref(t.blok.component);return r||(n.enableFallbackComponent?(i.value=n.customFallbackComponent??"FallbackComponent",typeof u.resolveDynamicComponent(i.value)=="string"&&console.error(`Is the Fallback component "${i.value}" registered properly?`)):console.error(`Component could not be found for blok "${t.blok.component}"! Is it defined in main.ts as "app.component("${t.blok.component}", ${t.blok.component});"?`)),(l,a)=>(u.openBlock(),u.createBlock(u.resolveDynamicComponent(i.value),u.mergeProps({ref_key:"blokRef",ref:s},{...l.$props,...l.$attrs}),null,16))}}),_e={beforeMount(o,e){if(e.value){const t=ye(e.value);Object.keys(t).length>0&&(o.setAttribute("data-blok-c",t["data-blok-c"]),o.setAttribute("data-blok-uid",t["data-blok-uid"]),o.classList.add("storyblok__outline"))}}},N=o=>{console.error(`You can't use ${o} if you're not loading apiPlugin. Please provide it on StoryblokVue initialization.
|
|
25
|
-
`)};let
|
|
24
|
+
}`),""}optimizeImages(e,t){let r=0,o=0,n="",i="";typeof t!="boolean"&&(typeof t.width=="number"&&t.width>0&&(n+=`width="${t.width}" `,r=t.width),typeof t.height=="number"&&t.height>0&&(n+=`height="${t.height}" `,o=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&&(i+=`:blur(${t.filters.blur})`),typeof t.filters.brightness=="number"&&t.filters.brightness>=-100&&t.filters.brightness<=100&&(i+=`:brightness(${t.filters.brightness})`),t.filters.fill&&(t.filters.fill.match(/[0-9A-Fa-f]{6}/g)||t.filters.fill==="transparent")&&(i+=`:fill(${t.filters.fill})`),t.filters.format&&["webp","png","jpeg"].includes(t.filters.format)&&(i+=`:format(${t.filters.format})`),typeof t.filters.grayscale=="boolean"&&t.filters.grayscale&&(i+=":grayscale()"),typeof t.filters.quality=="number"&&t.filters.quality>=0&&t.filters.quality<=100&&(i+=`:quality(${t.filters.quality})`),t.filters.rotate&&[90,180,270].includes(t.filters.rotate)&&(i+=`:rotate(${t.filters.rotate})`),i.length>0&&(i="/filters"+i))),n.length>0&&(e=e.replace(/<img/g,`<img ${n.trim()}`));const l=r>0||o>0||i.length>0?`${r}x${o}${i}`:"";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/${l}`),typeof t!="boolean"&&(t.sizes||t.srcset)&&(e=e.replace(/<img.*?src=["|'](.*?)["|']/g,a=>{var u,p;const h=a.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);if(h&&h.length>0){const b={srcset:(u=t.srcset)==null?void 0:u.map(k=>{if(typeof k=="number")return`//${h}/m/${k}x0${i} ${k}w`;if(typeof k=="object"&&k.length===2){let S=0,A=0;return typeof k[0]=="number"&&(S=k[0]),typeof k[1]=="number"&&(A=k[1]),`//${h}/m/${S}x${A}${i} ${S}w`}}).join(", "),sizes:(p=t.sizes)==null?void 0:p.map(k=>k).join(", ")};let _="";return b.srcset&&(_+=`srcset="${b.srcset}" `),b.sizes&&(_+=`sizes="${b.sizes}" `),a.replace(/<img/g,`<img ${_.trim()}`)}return a})),e}renderNode(e){const t=[];e.marks&&e.marks.forEach(o=>{const n=this.getMatchingMark(o);n&&n.tag!==""&&t.push(this.renderOpeningTag(n.tag))});const r=this.getMatchingNode(e);return r&&r.tag&&t.push(this.renderOpeningTag(r.tag)),e.content?e.content.forEach(o=>{t.push(this.renderNode(o))}):e.text?t.push(Ce(e.text)):r&&r.singleTag?t.push(this.renderTag(r.singleTag," /")):r&&r.html?t.push(r.html):e.type==="emoji"&&t.push(this.renderEmoji(e)),r&&r.tag&&t.push(this.renderClosingTag(r.tag)),e.marks&&e.marks.slice(0).reverse().forEach(o=>{const n=this.getMatchingMark(o);n&&n.tag!==""&&t.push(this.renderClosingTag(n.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(r=>{if(r.constructor===String)return`<${r}${t}>`;{let o=`<${r.tag}`;if(r.attrs){for(const n in r.attrs)if(Object.prototype.hasOwnProperty.call(r.attrs,n)){const i=r.attrs[n];i!==null&&(o+=` ${n}="${i}"`)}}return`${o}${t}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(t=>t.constructor===String?`</${t}>`:`</${t.tag}>`).join("")}getMatchingNode(e){const t=this.nodes[e.type];if(typeof t=="function")return t(e)}getMatchingMark(e){const t=this.marks[e.type];if(typeof t=="function")return t(e)}renderEmoji(e){if(e.attrs.emoji)return e.attrs.emoji;const t=[{tag:"img",attrs:{src:e.attrs.fallbackImage,draggable:"false",loading:"lazy",align:"absmiddle"}}];return this.renderTag(t," /")}}const C=Ie;class je{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=[],r={data:{},headers:{},status:0,statusText:""};e.status!==204&&await e.json().then(o=>{r.data=o});for(const o of e.headers.entries())t[o[0]]=o[1];return r.headers={...t},r.status=e.status,r.statusText=e.statusText,r}async _methodHandler(e){let t=`${this.baseURL}${this.url}`,r=null;if(e==="get"){const a=new O;t=`${this.baseURL}${this.url}?${a.stringify(this.parameters)}`}else r=JSON.stringify(this.parameters);const o=new URL(t),n=new AbortController,{signal:i}=n;let l;this.timeout&&(l=setTimeout(()=>n.abort(),this.timeout));try{const a=await this.fetch(`${o}`,{method:e,headers:this.headers,body:r,signal:i,...this.fetchOptions});this.timeout&&clearTimeout(l);const u=await this._responseHandler(a);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(u)):this._statusHandler(u)}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((r,o)=>{if(t.test(`${e.status}`))return r(e);const n={message:e.statusText,status:e.status,response:Array.isArray(e.data)?e.data[0]:e.data.error||e.data.slug};o(n)})}}const Oe=je,V="SB-Agent",P={defaultAgentName:"SB-JS-CLIENT",defaultAgentVersion:"SB-Agent-Version",packageVersion:"6.0.0"};let x={};const E={};class xe{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 r=e.endpoint||t;if(!r){const i=new O().getRegionURL,l=e.https===!1?"http":"https";e.oauthToken?r=`${l}://${i(e.region)}/v1`:r=`${l}://${i(e.region)}/v2`}const o=new Headers;o.set("Content-Type","application/json"),o.set("Accept","application/json"),e.headers&&e.headers.entries().toArray().forEach(([i,l])=>{o.set(i,l)}),o.has(V)||(o.set(V,P.defaultAgentName),o.set(P.defaultAgentVersion,P.packageVersion));let n=5;e.oauthToken&&(o.set("Authorization",e.oauthToken),n=3),e.rateLimit&&(n=e.rateLimit),e.richTextSchema?this.richTextResolver=new C(e.richTextSchema):this.richTextResolver=new C,e.componentResolver&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||10,this.retriesDelay=300,this.throttle=te(this.throttledRequest,n,1e3),this.accessToken=e.accessToken||"",this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.helpers=new O,this.resolveCounter=0,this.resolveNestedRelations=e.resolveNestedRelations||!0,this.stringifiedStoriesCache={},this.client=new Oe({baseURL:r,timeout:e.timeout||0,headers:o,responseInterceptor:e.responseInterceptor,fetch:e.fetch})}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let r="";return t.attrs.body&&t.attrs.body.forEach(o=>{r+=e(o.component,o)}),{html:r}})}parseParams(e){return e.token||(e.token=this.getToken()),e.cv||(e.cv=E[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),typeof e.resolve_relations<"u"&&(e.resolve_level=2),e}factoryParamOptions(e,t){return this.helpers.isCDNUrl(e)?this.parseParams(t):t}makeRequest(e,t,r,o,n){const i=this.factoryParamOptions(e,this.helpers.getOptionsPage(t,r,o));return this.cacheResponse(e,i,void 0,n)}get(e,t,r){t||(t={});const o=`/${e}`,n=this.factoryParamOptions(o,t);return this.cacheResponse(o,n,void 0,r)}async getAll(e,t,r,o){const n=(t==null?void 0:t.per_page)||25,i=`/${e}`,l=i.split("/"),a=r||l[l.length-1],u=1,p=await this.makeRequest(i,t,n,u,o),h=p.total?Math.ceil(p.total/n):1,b=await this.helpers.asyncMap(this.helpers.range(u,h),_=>this.makeRequest(i,t,n,_+1,o));return this.helpers.flatMap([p,...b],_=>Object.values(_.data[a]))}post(e,t,r){const o=`/${e}`;return Promise.resolve(this.throttle("post",o,t,r))}put(e,t,r){const o=`/${e}`;return Promise.resolve(this.throttle("put",o,t,r))}delete(e,t,r){const o=`/${e}`;return Promise.resolve(this.throttle("delete",o,t,r))}getStories(e,t){return this._addResolveLevel(e),this.get("cdn/stories",e,t)}getStory(e,t,r){return this._addResolveLevel(t),this.get(`cdn/stories/${e}`,t,r)}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,r){const o=e[t];o&&o.fieldtype=="multilink"&&o.linktype=="story"&&typeof o.id=="string"&&this.links[r][o.id]?o.story=this._cleanCopy(this.links[r][o.id]):o&&o.linktype==="story"&&typeof o.uuid=="string"&&this.links[r][o.uuid]&&(o.story=this._cleanCopy(this.links[r][o.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,r,o){r.indexOf(`${e.component}.${t}`)>-1&&(typeof e[t]=="string"?e[t]=this.getStoryReference(o,e[t]):Array.isArray(e[t])&&(e[t]=e[t].map(n=>this.getStoryReference(o,n)).filter(Boolean)))}iterateTree(e,t,r){const o=n=>{if(n!=null){if(n.constructor===Array)for(let i=0;i<n.length;i++)o(n[i]);else if(n.constructor===Object){if(n._stopResolving)return;for(const i in n)(n.component&&n._uid||n.type==="link")&&(this._insertRelations(n,i,t,r),this._insertLinks(n,i,r)),o(n[i])}}};o(e.content)}async resolveLinks(e,t,r){let o=[];if(e.link_uuids){const n=e.link_uuids.length,i=[],l=50;for(let a=0;a<n;a+=l){const u=Math.min(n,a+l);i.push(e.link_uuids.slice(a,u))}for(let a=0;a<i.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:i[a].join(",")})).data.stories.forEach(u=>{o.push(u)})}else o=e.links;o.forEach(n=>{this.links[r][n.uuid]={...n,_stopResolving:!0}})}async resolveRelations(e,t,r){let o=[];if(e.rel_uuids){const n=e.rel_uuids.length,i=[],l=50;for(let a=0;a<n;a+=l){const u=Math.min(n,a+l);i.push(e.rel_uuids.slice(a,u))}for(let a=0;a<i.length;a++)(await this.getStories({per_page:l,language:t.language,version:t.version,by_uuids:i[a].join(","),excluding_fields:t.excluding_fields})).data.stories.forEach(u=>{o.push(u)})}else o=e.rels;o&&o.length>0&&o.forEach(n=>{this.relations[r][n.uuid]={...n,_stopResolving:!0}})}async resolveStories(e,t,r){var o,n;let i=[];if(this.links[r]={},this.relations[r]={},typeof t.resolve_relations<"u"&&t.resolve_relations.length>0&&(typeof t.resolve_relations=="string"&&(i=t.resolve_relations.split(",")),await this.resolveRelations(e,t,r)),t.resolve_links&&["1","story","url","link"].indexOf(t.resolve_links)>-1&&((o=e.links)!=null&&o.length||(n=e.link_uuids)!=null&&n.length)&&await this.resolveLinks(e,t,r),this.resolveNestedRelations)for(const l in this.relations[r])this.iterateTree(this.relations[r][l],i,r);e.story?this.iterateTree(e.story,i,r):e.stories.forEach(l=>{this.iterateTree(l,i,r)}),this.stringifiedStoriesCache={},delete this.links[r],delete this.relations[r]}async cacheResponse(e,t,r,o){const n=this.helpers.stringify({url:e,params:t}),i=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&await this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const l=await i.get(n);if(l)return Promise.resolve(l)}return new Promise(async(l,a)=>{var u;try{const p=await this.throttle("get",e,t,o);if(p.status!==200)return a(p);let h={data:p.data,headers:p.headers};if((u=p.headers)!=null&&u["per-page"]&&(h=Object.assign({},h,{perPage:p.headers["per-page"]?parseInt(p.headers["per-page"]):0,total:p.headers["per-page"]?parseInt(p.headers.total):0})),h.data.story||h.data.stories){const b=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(h.data,t,`${b}`)}return t.version==="published"&&e!="/cdn/spaces/me"&&await i.set(n,h),h.data.cv&&t.token&&(t.version==="draft"&&E[t.token]!=h.data.cv&&await this.flushCache(),E[t.token]=t.cv?t.cv:h.data.cv),l(h)}catch(p){if(p.response&&p.status===429&&(r=typeof r>"u"?0:r+1,r<this.maxRetries))return console.log(`Hit rate limit. Retrying in ${this.retriesDelay/1e3} seconds.`),await this.helpers.delay(this.retriesDelay),this.cacheResponse(e,t,r).then(l).catch(a);a(p)}})}throttledRequest(e,t,r,o){return this.client.setFetchOptions(o),this.client[e](t,r)}cacheVersions(){return E}cacheVersion(){return E[this.accessToken]}setCacheVersion(e){this.accessToken&&(E[this.accessToken]=e)}clearCacheVersion(){this.accessToken&&(E[this.accessToken]=0)}cacheProvider(){switch(this.cache.type){case"memory":return{get(e){return Promise.resolve(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 Ae=(s={})=>{const{apiOptions:e}=s;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 xe(e)}},Pe=s=>{if(typeof s!="object"||typeof s._editable>"u")return{};try{const e=JSON.parse(s._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return e?{"data-blok-c":JSON.stringify(e),"data-blok-uid":e.id+"-"+e.uid}:{}}catch{return{}}};var v=(s=>(s.DOCUMENT="doc",s.HEADING="heading",s.PARAGRAPH="paragraph",s.QUOTE="blockquote",s.OL_LIST="ordered_list",s.UL_LIST="bullet_list",s.LIST_ITEM="list_item",s.CODE_BLOCK="code_block",s.HR="horizontal_rule",s.BR="hard_break",s.IMAGE="image",s.EMOJI="emoji",s.COMPONENT="blok",s))(v||{}),T=(s=>(s.BOLD="bold",s.STRONG="strong",s.STRIKE="strike",s.UNDERLINE="underline",s.ITALIC="italic",s.CODE="code",s.LINK="link",s.ANCHOR="anchor",s.STYLED="styled",s.SUPERSCRIPT="superscript",s.SUBSCRIPT="subscript",s.TEXT_STYLE="textStyle",s.HIGHLIGHT="highlight",s))(T||{}),L=(s=>(s.TEXT="text",s))(L||{}),I=(s=>(s.URL="url",s.STORY="story",s.ASSET="asset",s.EMAIL="email",s))(I||{});function Le(s,e){if(!e)return{src:s,attrs:{}};let t=0,r=0;const o={},n=[];function i(a,u,p,h,b){typeof a!="number"||a<=u||a>=p?console.warn(`[StoryblokRichText] - ${h.charAt(0).toUpperCase()+h.slice(1)} value must be a number between ${u} and ${p} (inclusive)`):b.push(`${h}(${a})`)}if(typeof e=="object"){if(typeof e.width=="number"&&e.width>0?(o.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?(o.height=e.height,r=e.height):console.warn("[StoryblokRichText] - Height value must be a number greater than 0"),e.loading&&["lazy","eager"].includes(e.loading)&&(o.loading=e.loading),e.class&&(o.class=e.class),e.filters){const{filters:a}=e||{},{blur:u,brightness:p,fill:h,format:b,grayscale:_,quality:k,rotate:S}=a||{};u&&i(u,0,100,"blur",n),k&&i(k,0,100,"quality",n),p&&i(p,0,100,"brightness",n),h&&n.push(`fill(${h})`),_&&n.push("grayscale()"),S&&[0,90,180,270].includes(e.filters.rotate||0)&&n.push(`rotate(${S})`),b&&["webp","png","jpeg"].includes(b)&&n.push(`format(${b})`)}e.srcset&&(o.srcset=e.srcset.map(a=>{if(typeof a=="number")return`${s}/m/${a}x0/${n.length>0?"filters:"+n.join(":"):""} ${a}w`;if(Array.isArray(a)&&a.length===2){const[u,p]=a;return`${s}/m/${u}x${p}/${n.length>0?"filters:"+n.join(":"):""} ${u}w`}}).join(", ")),e.sizes&&(o.sizes=e.sizes.join(", "))}let l=`${s}/m/`;return t>0&&r>0&&(l=`${l}${t}x${r}/`),n.length>0&&(l=`${l}filters:${n.join(":")}`),{src:l,attrs:o}}const Ne=(s={})=>Object.keys(s).map(e=>`${e}="${s[e]}"`).join(" "),Me=(s={})=>Object.keys(s).map(e=>`${e}: ${s[e]}`).join("; ");function Ue(s){return s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function De(s,e={},t){const r=Ne(e);return`<${r?`${s} ${r}`:s}>${Array.isArray(t)?t.join(""):t||""}</${s}>`}function F(s={}){let e=0;const{renderFn:t=De,textFn:r=Ue,resolvers:o={},optimizeImages:n=!1}=s,i=c=>f=>t(c,{...f.attrs,key:`${c}-${e}`},f.children||null),l=c=>{const{src:f,alt:y,...$}=c.attrs||{};let R=f,w={};if(n){const{src:Qe,attrs:Ze}=Le(f,n);R=Qe,w=Ze}const We={src:R,alt:y||"",key:`img-${e}`,...$,...w};return t("img",We,"")},a=c=>{const{level:f,...y}=c.attrs||{};return t(`h${f}`,{...y,key:`h${f}-${e}`},c.children)},u=c=>{var f,y,$,R;return t("span",{"data-type":"emoji","data-name":(f=c.attrs)==null?void 0:f.name,emoji:(y=c.attrs)==null?void 0:y.emoji,key:`emoji-${e}`},t("img",{src:($=c.attrs)==null?void 0:$.fallbackImage,alt:(R=c.attrs)==null?void 0:R.alt,style:"width: 1.25em; height: 1.25em; vertical-align: text-top",draggable:"false",loading:"lazy"},""))},p=c=>t("pre",{...c.attrs,key:`code-${e}`},t("code",{key:`code-${e}`},c.children||"")),h=(c,f=!1)=>({text:y,attrs:$})=>t(c,f?{style:Me($),key:`${c}-${e}`}:{...$,key:`${c}-${e}`},y),b=c=>U(c),_=c=>{const{marks:f,...y}=c;return"text"in c?f?f.reduce(($,R)=>b({...R,text:$}),b({...y,children:y.children})):r(y.text):""},k=c=>{const{linktype:f,href:y,anchor:$,...R}=c.attrs||{};let w="";switch(f){case I.ASSET:case I.URL:w=y;break;case I.EMAIL:w=`mailto:${y}`;break;case I.STORY:w=y;break}return $&&(w=`${w}#${$}`),t("a",{...R,href:w,key:`a-${e}`},c.text)},S=c=>{var f,y;return console.warn("[StoryblokRichtText] - BLOK resolver is not available for vanilla usage"),t("span",{blok:(f=c==null?void 0:c.attrs)==null?void 0:f.body[0],id:(y=c.attrs)==null?void 0:y.id,key:`component-${e}`,style:"display: none"},"")},A=new Map([[v.DOCUMENT,i("div")],[v.HEADING,a],[v.PARAGRAPH,i("p")],[v.UL_LIST,i("ul")],[v.OL_LIST,i("ol")],[v.LIST_ITEM,i("li")],[v.IMAGE,l],[v.EMOJI,u],[v.CODE_BLOCK,p],[v.HR,i("hr")],[v.BR,i("br")],[v.QUOTE,i("blockquote")],[v.COMPONENT,S],[L.TEXT,_],[T.LINK,k],[T.ANCHOR,k],[T.STYLED,h("span",!0)],[T.BOLD,h("strong")],[T.TEXT_STYLE,h("span",!0)],[T.ITALIC,h("em")],[T.UNDERLINE,h("u")],[T.STRIKE,h("s")],[T.CODE,h("code")],[T.SUPERSCRIPT,h("sup")],[T.SUBSCRIPT,h("sub")],[T.HIGHLIGHT,h("mark")],...Object.entries(o).map(([c,f])=>[c,f])]);function W(c){e+=1;const f=A.get(c.type);if(!f)return console.error("<Storyblok>",`No resolver found for node type ${c.type}`),"";if(c.type==="text")return f(c);const y=c.content?c.content.map(U):void 0;return f({...c,children:y})}function U(c){return Array.isArray(c)?c.map(W):W(c)}return{render:U}}let N,q="https://app.storyblok.com/f/storyblok-v2-latest.js";const G=(s,e,t={})=>{var r;const o=!(typeof window>"u")&&typeof window.storyblokRegisterEvent<"u",n=+new URL((r=window.location)==null?void 0:r.href).searchParams.get("_storyblok")===s;if(!(!o||!n)){if(!s){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(t).on(["input","published","change"],i=>{i.action==="input"&&i.story.id===s?e(i.story):(i.action==="change"||i.action==="published")&&i.storyId===s&&window.location.reload()})})}},He=(s={})=>{var e,t;const{bridge:r,accessToken:o,use:n=[],apiOptions:i={},richText:l={},bridgeUrl:a}=s;i.accessToken=i.accessToken||o;const u={bridge:r,apiOptions:i};let p={};n.forEach(b=>{p={...p,...b(u)}}),a&&(q=a);const h=!(typeof window>"u")&&((t=(e=window.location)==null?void 0:e.search)==null?void 0:t.includes("_storyblok_tk"));return r!==!1&&h&&Q(q),N=new C(l.schema),l.resolver&&K(N,l.resolver),p},K=(s,e)=>{s.addNode("blok",t=>{let r="";return t.attrs.body.forEach(o=>{r+=e(o.component,o)}),{html:r}})},ze=s=>!s||!(s!=null&&s.content.some(e=>e.content||e.type==="blok"||e.type==="horizontal_rule")),Be=(s,e,t)=>{let r=t||N;if(!r){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return ze(s)?"":(e&&(r=new C(e.schema),e.resolver&&K(r,e.resolver)),r.render(s))},M=g.defineComponent({__name:"StoryblokComponent",props:{blok:{}},setup(s,{expose:e}){const t=s,r=g.ref();e({value:r});const o=typeof g.resolveDynamicComponent(t.blok.component)!="string",n=g.inject("VueSDKOptions"),i=g.ref(t.blok.component);return o||(n.enableFallbackComponent?(i.value=n.customFallbackComponent??"FallbackComponent",typeof g.resolveDynamicComponent(i.value)=="string"&&console.error(`Is the Fallback component "${i.value}" registered properly?`)):console.error(`Component could not be found for blok "${t.blok.component}"! Is it defined in main.ts as "app.component("${t.blok.component}", ${t.blok.component});"?`)),(l,a)=>(g.openBlock(),g.createBlock(g.resolveDynamicComponent(i.value),g.mergeProps({ref_key:"blokRef",ref:r},{...l.$props,...l.$attrs}),null,16))}}),Ve=s=>{var e,t;return g.h(M,{blok:(e=s==null?void 0:s.attrs)==null?void 0:e.body[0],id:(t=s.attrs)==null?void 0:t.id},s.children)};function J(s){const e={renderFn:g.h,textFn:g.createTextVNode,resolvers:{[v.COMPONENT]:Ve,...s.resolvers}};return F(e)}const Y=g.defineComponent({__name:"StoryblokRichText",props:{doc:{},resolvers:{}},setup(s){const e=s,{render:t}=J({resolvers:e.resolvers??{}}),r=()=>t(e.doc);return(o,n)=>(g.openBlock(),g.createBlock(r))}}),Fe={beforeMount(s,e){if(e.value){const t=Pe(e.value);Object.keys(t).length>0&&(s.setAttribute("data-blok-c",t["data-blok-c"]),s.setAttribute("data-blok-uid",t["data-blok-uid"]),s.classList.add("storyblok__outline"))}}},X=s=>{console.error(`You can't use ${s} if you're not loading apiPlugin. Please provide it on StoryblokVue initialization.
|
|
25
|
+
`)};let j=null;const qe=()=>(j||X("useStoryblokApi"),j),Ge=async(s,e={},t={})=>{const r=g.ref(null);if(t.resolveRelations=t.resolveRelations??e.resolve_relations,t.resolveLinks=t.resolveLinks??e.resolve_links,g.onMounted(()=>{r.value&&r.value.id&&G(r.value.id,o=>r.value=o,t)}),j){const{data:o}=await j.get(`cdn/stories/${s}`,e);r.value=o.story}else X("useStoryblok");return r},Ke={install(s,e={}){s.directive("editable",Fe),s.component("StoryblokComponent",M),s.component("StoryblokRichText",Y),e.enableFallbackComponent&&!e.customFallbackComponent&&s.component("FallbackComponent",g.defineAsyncComponent(()=>Promise.resolve().then(()=>Xe)));const{storyblokApi:t}=He(e);j=t,s.provide("VueSDKOptions",e)}},Je={class:"fallback-component"},Ye={class:"component"},Xe=Object.freeze(Object.defineProperty({__proto__:null,default:((s,e)=>{const t=s.__vccOpts||s;for(const[r,o]of e)t[r]=o;return t})(g.defineComponent({__name:"FallbackComponent",props:{blok:{}},setup(s){return(e,t)=>(g.openBlock(),g.createElementBlock("div",Je,[g.createElementVNode("p",null,[g.createTextVNode(" Component could not be found for blok "),g.createElementVNode("span",Ye,g.toDisplayString(e.blok.component),1),g.createTextVNode("! Is it configured correctly? ")])]))}}),[["__scopeId","data-v-93c770c0"]])},Symbol.toStringTag,{value:"Module"}));m.BlockTypes=v,m.MarkTypes=T,m.RichTextResolver=C,m.RichTextSchema=B,m.StoryblokComponent=M,m.StoryblokRichText=Y,m.StoryblokVue=Ke,m.TextTypes=L,m.apiPlugin=Ae,m.renderRichText=Be,m.richTextResolver=F,m.useStoryblok=Ge,m.useStoryblokApi=qe,m.useStoryblokBridge=G,m.useStoryblokRichText=J,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})});
|