@storyblok/nuxt 3.0.0 → 3.0.3

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
@@ -2,8 +2,8 @@
2
2
  <a href="https://www.storyblok.com?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-nuxt" align="center">
3
3
  <img src="https://a.storyblok.com/f/88751/1776x360/b8979e5c96/sb-nuxt.png" alt="Storyblok Logo">
4
4
  </a>
5
- <h1 align="center">storyblok-nuxt</h1>
6
- <p align="center">Nuxt module for the <a href="http://www.storyblok.com?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-nuxt" target="_blank">Storyblok</a>, Headless CMS.</p> <br />
5
+ <h1 align="center">@storyblok/nuxt</h1>
6
+ <p align="center">Nuxt 2 module for the <a href="http://www.storyblok.com?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-nuxt" target="_blank">Storyblok</a>, Headless CMS.</p> <br />
7
7
  </div>
8
8
 
9
9
  <p align="center">
@@ -27,10 +27,12 @@
27
27
  </a>
28
28
  </p>
29
29
 
30
- **Note**: This module is for Nuxt 2. [Check out `@storyblok/nuxt-beta` for Nuxt 3](https://github.com/storyblok/storyblok-nuxt-beta)
30
+ > Try out the **[LIVE DEMO](https://stackblitz.com/edit/nuxt-2-sdk-demo?file=pages%2Findex.vue&terminal=dev)** on Stackblitz and play with code yourself!
31
31
 
32
32
  ## 🚀 Usage
33
33
 
34
+ _Note: This module is for Nuxt 2. [Check out `@storyblok/nuxt-beta` for Nuxt 3](https://github.com/storyblok/storyblok-nuxt-beta)_.
35
+
34
36
  > If you are first-time user of the Storyblok, read the [Getting Started](https://www.storyblok.com/docs/guide/getting-started?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-nuxt) guide to get a project ready in less than 5 minutes.
35
37
 
36
38
  ### Installation
@@ -62,7 +64,7 @@ When you initialize the module, you can pass all [_@storyblok/vue_ options](http
62
64
  ["@storyblok/nuxt/module", {
63
65
  {
64
66
  accessToken: "<your-access-token>",
65
- bridge: process.env.NODE_ENV !== "production", // bridge is disabled in production by default
67
+ bridge: true,
66
68
  apiOptions: {}, // storyblok-js-client options
67
69
  useApiClient: true
68
70
  }
@@ -97,12 +99,12 @@ To link your Vue components to their equivalent you created in Storyblok:
97
99
 
98
100
  > To use Nuxt 2 with Composition API, make sure you installed the [@nuxtjs/composition-api](https://composition-api.nuxtjs.org/) plugin.
99
101
 
100
- The simplest way is by using the `useStoryblok` one-liner composable:
102
+ The simplest way is by using the `useStoryblok` one-liner composable, which uses the [useFetch from @nuxtjs/composition-api](https://composition-api.nuxtjs.org/lifecycle/useFetch) under the hood:
101
103
 
102
104
  ```html
103
105
  <script setup>
104
106
  import { useStoryblok } from "@storyblok/nuxt";
105
- const story = useStoryblok("vue/test", { version: "draft" });
107
+ const { story, fetchState } = useStoryblok("vue", { version: "draft" });
106
108
  </script>
107
109
 
108
110
  <template>
@@ -114,19 +116,23 @@ Which is the short-hand equivalent to using `useStoryblokApi` and `useStoryblokB
114
116
 
115
117
  ```html
116
118
  <script setup>
117
- import { onMounted, ref } from "@nuxtjs/composition-api";
119
+ import { onMounted, ref, useFetch } from "@nuxtjs/composition-api";
118
120
  import { useStoryblokBridge, useStoryblokApi } from "@storyblok/nuxt";
119
121
 
120
122
  const story = ref(null);
121
123
 
122
- onMounted(async () => {
124
+ const { fetch } = useFetch(async () => {
123
125
  const storyblokApi = useStoryblokApi();
124
- const { data } = await storyblokApi.get("cdn/stories/vue/test", {
126
+ const { data } = await storyblokApi.get(`cdn/stories/vue/test`, {
125
127
  version: "draft",
126
128
  });
127
129
  story.value = data.story;
130
+ });
131
+ fetch();
128
132
 
129
- useStoryblokBridge(story.value.id, (evStory) => (story.value = evStory));
133
+ onMounted(async () => {
134
+ if (story.value && story.value.id)
135
+ useStoryblokBridge(story.value.id, (evStory) => (story.value = evStory));
130
136
  });
131
137
  </script>
132
138
 
@@ -186,8 +192,9 @@ Equivalent to the client that `useStoryblokApi` returns, but accessible in the N
186
192
 
187
193
  ## 🔗 Related Links
188
194
 
189
- - **[Nuxt.js Hub](https://www.storyblok.com/tc/nuxtjs?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-nuxt)**: Learn how to develop your own Nuxt.js applications that use Storyblok APIs to retrieve and manage content;
190
- - **[Storyblok & Nuxt.js on GitHub](https://github.com/search?q=org%3Astoryblok+topic%3Anuxt)**: Check all of our Nuxt.js open source repos;
195
+ - **[Live Demo on Stackblitz](https://stackblitz.com/edit/nuxt-2-sdk-demo?file=pages%2Findex.vue&terminal=dev)**
196
+ - **[Nuxt.js Hub](https://www.storyblok.com/tc/nuxtjs?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-nuxt)**: Learn how to develop your own Nuxt.js applications that use Storyblok APIs to retrieve and manage content.
197
+ - **[Storyblok & Nuxt.js on GitHub](https://github.com/search?q=org%3Astoryblok+topic%3Anuxt)**: Check all of our Nuxt.js open source repos.
191
198
  - **[Storyblok CLI](https://github.com/storyblok/storyblok)**: A simple CLI for scaffolding Storyblok projects and fieldtypes.
192
199
 
193
200
  ## â„šī¸ More Resources
@@ -1,6 +1,6 @@
1
- (function(h,y){typeof exports=="object"&&typeof module!="undefined"?y(exports,require("axios"),require("@vue/composition-api")):typeof define=="function"&&define.amd?define(["exports","axios","@vue/composition-api"],y):(h=typeof globalThis!="undefined"?globalThis:h||self,y(h.storyblokNuxt={},h.t,h.VueCompositionAPI))})(this,function(h,y,_){"use strict";function N(s){return s&&typeof s=="object"&&"default"in s?s:{default:s}}var V=N(y),q=Object.defineProperty,x=Object.defineProperties,B=Object.getOwnPropertyDescriptors,w=Object.getOwnPropertySymbols,L=Object.prototype.hasOwnProperty,U=Object.prototype.propertyIsEnumerable,T=(s,e,t)=>e in s?q(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,f=(s,e)=>{for(var t in e||(e={}))L.call(e,t)&&T(s,t,e[t]);if(w)for(var t of w(e))U.call(e,t)&&T(s,t,e[t]);return s},k=(s,e)=>x(s,B(e));let R=!1;const S=[],z=s=>new Promise((e,t)=>{if(typeof window=="undefined"||(window.storyblokRegisterEvent=o=>{if(window.location===window.parent.location){console.warn("You are not in Draft Mode or in the Visual Editor.");return}R?o():S.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=>{S.forEach(n=>n()),R=!0,e(o)},document.getElementsByTagName("head")[0].appendChild(r)});/*!
1
+ (function(h,y){typeof exports=="object"&&typeof module!="undefined"?y(exports,require("axios"),require("@vue/composition-api"),require("@nuxtjs/composition-api")):typeof define=="function"&&define.amd?define(["exports","axios","@vue/composition-api","@nuxtjs/composition-api"],y):(h=typeof globalThis!="undefined"?globalThis:h||self,y(h.storyblokNuxt={},h.t,h.VueCompositionAPI,h.NuxtCompositionAPI))})(this,function(h,y,ie,k){"use strict";function M(s){return s&&typeof s=="object"&&"default"in s?s:{default:s}}var N=M(y),x=Object.defineProperty,I=Object.defineProperties,V=Object.getOwnPropertyDescriptors,w=Object.getOwnPropertySymbols,q=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable,T=(s,e,t)=>e in s?x(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,f=(s,e)=>{for(var t in e||(e={}))q.call(e,t)&&T(s,t,e[t]);if(w)for(var t of w(e))B.call(e,t)&&T(s,t,e[t]);return s},v=(s,e)=>I(s,V(e));let R=!1;const S=[],L=s=>new Promise((e,t)=>{if(typeof window=="undefined"||(window.storyblokRegisterEvent=o=>{if(window.location===window.parent.location){console.warn("You are not in Draft Mode or in the Visual Editor.");return}R?o():S.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=>{S.forEach(n=>n()),R=!0,e(o)},document.getElementsByTagName("head")[0].appendChild(r)});/*!
2
2
  * storyblok-js-client v0.0.0-development
3
3
  * Universal JavaScript SDK for Storyblok's API
4
4
  * (c) 2020-2022 Stobylok Team
5
- */function O(s){return typeof s=="number"&&s==s&&s!==1/0&&s!==-1/0}function E(s,e,t){if(!O(e))throw new TypeError("Expected `limit` to be a finite number");if(!O(t))throw new TypeError("Expected `interval` to be a finite number");var r=[],o=[],n=0,i=function(){n++;var a=setTimeout(function(){n--,r.length>0&&i(),o=o.filter(function(u){return u!==a})},t);o.indexOf(a)<0&&o.push(a);var c=r.shift();c.resolve(s.apply(c.self,c.args))},l=function(){var a=arguments,c=this;return new Promise(function(u,p){r.push({resolve:u,reject:p,args:a,self:c}),n<e&&i()})};return l.abort=function(){o.forEach(clearTimeout),o=[],r.forEach(function(a){a.reject(new throttle.AbortError)}),r.length=0},l}E.AbortError=function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"};const D=function(s,e){if(!s)return null;let t={};for(let r in s){let o=s[r];e.indexOf(r)>-1&&o!==null&&(t[r]=o)}return t};var J={nodes:{horizontal_rule:s=>({singleTag:"hr"}),blockquote:s=>({tag:"blockquote"}),bullet_list:s=>({tag:"ul"}),code_block:s=>({tag:["pre",{tag:"code",attrs:s.attrs}]}),hard_break:s=>({singleTag:"br"}),heading:s=>({tag:"h"+s.attrs.level}),image:s=>({singleTag:[{tag:"img",attrs:D(s.attrs,["src","alt","title"])}]}),list_item:s=>({tag:"li"}),ordered_list:s=>({tag:"ol"}),paragraph:s=>({tag:"p"})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link(s){const e=f({},s.attrs),{linktype:t="url"}=s.attrs;return t==="email"&&(e.href="mailto:"+e.href),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),{tag:[{tag:"a",attrs:e}]}},styled:s=>({tag:[{tag:"span",attrs:s.attrs}]})}};class Y{constructor(e){e||(e=J),this.marks=e.marks||[],this.nodes=e.nodes||[]}addNode(e,t){this.nodes[e]=t}addMark(e,t){this.marks[e]=t}render(e={}){if(e.content&&Array.isArray(e.content)){let t="";return e.content.forEach(r=>{t+=this.renderNode(r)}),t}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(e){let t=[];e.marks&&e.marks.forEach(o=>{const n=this.getMatchingMark(o);n&&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(function(o){const n={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},i=/[&<>"']/g,l=RegExp(i.source);return o&&l.test(o)?o.replace(i,a=>n[a]):o}(e.text)):r&&r.singleTag?t.push(this.renderTag(r.singleTag," /")):r&&r.html&&t.push(r.html),r&&r.tag&&t.push(this.renderClosingTag(r.tag)),e.marks&&e.marks.slice(0).reverse().forEach(o=>{const n=this.getMatchingMark(o);n&&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(let n in r.attrs){let 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){if(typeof this.nodes[e.type]=="function")return this.nodes[e.type](e)}getMatchingMark(e){if(typeof this.marks[e.type]=="function")return this.marks[e.type](e)}}const F=(s=0,e=s)=>{const t=Math.abs(e-s)||0,r=s<e?1:-1;return((o=0,n)=>[...Array(o)].map(n))(t,(o,n)=>n*r+s)},v=(s,e,t)=>{const r=[];for(const o in s){if(!Object.prototype.hasOwnProperty.call(s,o))continue;const n=s[o],i=t?"":encodeURIComponent(o);let l;l=typeof n=="object"?v(n,e?e+encodeURIComponent("["+i+"]"):i,Array.isArray(n)):(e?e+encodeURIComponent("["+i+"]"):i)+"="+encodeURIComponent(n),r.push(l)}return r.join("&")};let m={},g={};class X{constructor(e,t){if(!t){let n=e.region?"-"+e.region:"",i=e.https===!1?"http":"https";t=e.oauthToken===void 0?`${i}://api${n}.storyblok.com/v2`:`${i}://api${n}.storyblok.com/v1`}let r=Object.assign({},e.headers),o=5;e.oauthToken!==void 0&&(r.Authorization=e.oauthToken,o=3),e.rateLimit!==void 0&&(o=e.rateLimit),this.richTextResolver=new Y(e.richTextSchema),typeof e.componentResolver=="function"&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||5,this.throttle=E(this.throttledRequest,o,1e3),this.accessToken=e.accessToken,this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.client=V.default.create({baseURL:t,timeout:e.timeout||0,headers:r,proxy:e.proxy||!1}),e.responseInterceptor&&this.client.interceptors.response.use(n=>e.responseInterceptor(n))}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let r="";return t.attrs.body.forEach(o=>{r+=e(o.component,o)}),{html:r}})}parseParams(e={}){return e.version||(e.version="published"),e.token||(e.token=this.getToken()),e.cv||(e.cv=g[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),e}factoryParamOptions(e,t={}){return((r="")=>r.indexOf("/cdn/")>-1)(e)?this.parseParams(t):t}makeRequest(e,t,r,o){const n=this.factoryParamOptions(e,((i={},l=25,a=1)=>k(f({},i),{per_page:l,page:a}))(t,r,o));return this.cacheResponse(e,n)}get(e,t){let r="/"+e;const o=this.factoryParamOptions(r,t);return this.cacheResponse(r,o)}async getAll(e,t={},r){const o=t.per_page||25,n="/"+e,i=n.split("/");r=r||i[i.length-1];const l=await this.makeRequest(n,t,o,1),a=Math.ceil(l.total/o);return((c=[],u)=>c.map(u).reduce((p,d)=>[...p,...d],[]))([l,...await(async(c=[],u)=>Promise.all(c.map(u)))(F(1,a),async c=>this.makeRequest(n,t,o,c+1))],c=>Object.values(c.data[r]))}post(e,t){let r="/"+e;return this.throttle("post",r,t)}put(e,t){let r="/"+e;return this.throttle("put",r,t)}delete(e,t){let r="/"+e;return this.throttle("delete",r,t)}getStories(e){return this.get("cdn/stories",e)}getStory(e,t){return this.get("cdn/stories/"+e,t)}setToken(e){this.accessToken=e}getToken(){return this.accessToken}_cleanCopy(e){return JSON.parse(JSON.stringify(e))}_insertLinks(e,t){const r=e[t];r&&r.fieldtype=="multilink"&&r.linktype=="story"&&typeof r.id=="string"&&this.links[r.id]?r.story=this._cleanCopy(this.links[r.id]):r&&r.linktype==="story"&&typeof r.uuid=="string"&&this.links[r.uuid]&&(r.story=this._cleanCopy(this.links[r.uuid]))}_insertRelations(e,t,r){if(r.indexOf(e.component+"."+t)>-1){if(typeof e[t]=="string")this.relations[e[t]]&&(e[t]=this._cleanCopy(this.relations[e[t]]));else if(e[t].constructor===Array){let o=[];e[t].forEach(n=>{this.relations[n]&&o.push(this._cleanCopy(this.relations[n]))}),e[t]=o}}}iterateTree(e,t){let r=o=>{if(o!=null){if(o.constructor===Array)for(let n=0;n<o.length;n++)r(o[n]);else if(o.constructor===Object){if(o._stopResolving)return;for(let n in o)(o.component&&o._uid||o.type==="link")&&(this._insertRelations(o,n,t),this._insertLinks(o,n)),r(o[n])}}};r(e.content)}async resolveLinks(e,t){let r=[];if(e.link_uuids){const o=e.link_uuids.length;let n=[];const i=50;for(let l=0;l<o;l+=i){const a=Math.min(o,l+i);n.push(e.link_uuids.slice(l,a))}for(let l=0;l<n.length;l++)(await this.getStories({per_page:i,language:t.language,version:t.version,by_uuids:n[l].join(",")})).data.stories.forEach(a=>{r.push(a)})}else r=e.links;r.forEach(o=>{this.links[o.uuid]=k(f({},o),{_stopResolving:!0})})}async resolveRelations(e,t){let r=[];if(e.rel_uuids){const o=e.rel_uuids.length;let n=[];const i=50;for(let l=0;l<o;l+=i){const a=Math.min(o,l+i);n.push(e.rel_uuids.slice(l,a))}for(let l=0;l<n.length;l++)(await this.getStories({per_page:i,language:t.language,version:t.version,by_uuids:n[l].join(",")})).data.stories.forEach(a=>{r.push(a)})}else r=e.rels;r.forEach(o=>{this.relations[o.uuid]=k(f({},o),{_stopResolving:!0})})}async resolveStories(e,t){let r=[];t.resolve_relations!==void 0&&t.resolve_relations.length>0&&(r=t.resolve_relations.split(","),await this.resolveRelations(e,t)),["1","story","url"].indexOf(t.resolve_links)>-1&&await this.resolveLinks(e,t);for(const o in this.relations)this.iterateTree(this.relations[o],r);e.story?this.iterateTree(e.story,r):e.stories.forEach(o=>{this.iterateTree(o,r)})}cacheResponse(e,t,r){return r===void 0&&(r=0),new Promise(async(o,n)=>{let i=v({url:e,params:t}),l=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&await this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const c=await l.get(i);if(c)return o(c)}try{let c=await this.throttle("get",e,{params:t,paramsSerializer:p=>v(p)}),u={data:c.data,headers:c.headers};if(c.headers["per-page"]&&(u=Object.assign({},u,{perPage:parseInt(c.headers["per-page"]),total:parseInt(c.headers.total)})),c.status!=200)return n(c);(u.data.story||u.data.stories)&&await this.resolveStories(u.data,t),t.version==="published"&&e!="/cdn/spaces/me"&&l.set(i,u),u.data.cv&&(t.version=="draft"&&g[t.token]!=u.data.cv&&this.flushCache(),g[t.token]=u.data.cv),o(u)}catch(c){if(c.response&&c.response.status===429&&(r+=1)<this.maxRetries)return console.log(`Hit rate limit. Retrying in ${r} seconds.`),await(a=1e3*r,new Promise(u=>setTimeout(u,a))),this.cacheResponse(e,t,r).then(o).catch(n);n(c)}var a})}throttledRequest(e,t,r){return this.client[e](t,r)}cacheVersions(){return g}cacheVersion(){return g[this.accessToken]}setCacheVersion(e){this.accessToken&&(g[this.accessToken]=e)}cacheProvider(){switch(this.cache.type){case"memory":return{get:e=>m[e],getAll:()=>m,set(e,t){m[e]=t},flush(){m={}}};default:return{get(){},getAll(){},set(){},flush(){}}}}async flushCache(){return await this.cacheProvider().flush(),this}}var H=(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 X(e)}},W=s=>{if(typeof s!="object"||typeof s._editable=="undefined")return{};const e=JSON.parse(s._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(e),"data-blok-uid":e.id+"-"+e.uid}};const P=(s,e,t={})=>{if(typeof window!="undefined"){if(typeof window.storyblokRegisterEvent=="undefined"){console.error("Storyblok Bridge is disabled. Please enable it to use it. Read https://github.com/storyblok/storyblok-js");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(t).on(["input","published","change"],o=>{o.action=="input"&&o.story.id===s?e(o.story):window.location.reload()})})}},G=(s={})=>{const{bridge:e,accessToken:t,use:r=[],apiOptions:o={}}=s;o.accessToken=o.accessToken||t;const n={bridge:e,apiOptions:o};let i={};return r.forEach(l=>{i=f(f({},i),l(n))}),e!==!1&&z("https://app.storyblok.com/f/storyblok-v2-latest.js"),i};var K=function(){var s=this,e=s.$createElement,t=s._self._c||e;return t(s.blok.component,s._g(s._b({tag:"component"},"component",Object.assign({},s.$props,s.$attrs),!1),s.$listeners))},Q=[];function Z(s,e,t,r,o,n,i,l){var a=typeof s=="function"?s.options:s;e&&(a.render=e,a.staticRenderFns=t,a._compiled=!0),r&&(a.functional=!0),n&&(a._scopeId="data-v-"+n);var c;if(i?(c=function(d){d=d||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext,!d&&typeof __VUE_SSR_CONTEXT__!="undefined"&&(d=__VUE_SSR_CONTEXT__),o&&o.call(this,d),d&&d._registeredComponents&&d._registeredComponents.add(i)},a._ssrRegister=c):o&&(c=l?function(){o.call(this,(a.functional?this.parent:this).$root.$options.shadowRoot)}:o),c)if(a.functional){a._injectStyles=c;var u=a.render;a.render=function(ne,I){return c.call(I),u(ne,I)}}else{var p=a.beforeCreate;a.beforeCreate=p?[].concat(p,c):[c]}return{exports:s,options:a}}const ee={props:{blok:{type:Object}}},C={};var te=Z(ee,K,Q,!1,re,null,null,null);function re(s){for(let e in C)this[e]=C[e]}var $=function(){return te.exports}();const j=s=>{console.error(`You can't use ${s} if you're not loading apiPlugin. Please provide it on StoryblokVue initialization.
6
- `)};var oe=(s,e={},t={})=>{const r=_.ref(null),o=A();return _.onMounted(async()=>{if(o){const{data:n}=await o.get(`cdn/stories/${s}`,e);r.value=n.story}else j("useStoryblok");r.value&&r.value.id&&P(r.value.id,n=>r.value=n,t)}),r};const se={bind(s,e){if(e.value){const t=W(e.value);s.setAttribute("data-blok-c",t["data-blok-c"]),s.setAttribute("data-blok-uid",t["data-blok-uid"]),s.classList.add("storyblok__outline")}}};let b=null;const A=()=>(b||j("useStoryblokApi"),b),M={install(s,e={}){s.directive("editable",se),s.component("StoryblokComponent",$);const{storyblokApi:t}=G(e);b=t,s.prototype.$storyblokApi=t}};typeof window!="undefined"&&window.Vue&&window.Vue.use(M),h.StoryblokComponent=$,h.StoryblokVue=M,h.apiPlugin=H,h.useStoryblok=oe,h.useStoryblokApi=A,h.useStoryblokBridge=P,Object.defineProperty(h,"__esModule",{value:!0}),h[Symbol.toStringTag]="Module"});
5
+ */function O(s){return typeof s=="number"&&s==s&&s!==1/0&&s!==-1/0}function E(s,e,t){if(!O(e))throw new TypeError("Expected `limit` to be a finite number");if(!O(t))throw new TypeError("Expected `interval` to be a finite number");var r=[],o=[],n=0,i=function(){n++;var l=setTimeout(function(){n--,r.length>0&&i(),o=o.filter(function(u){return u!==l})},t);o.indexOf(l)<0&&o.push(l);var c=r.shift();c.resolve(s.apply(c.self,c.args))},a=function(){var l=arguments,c=this;return new Promise(function(u,p){r.push({resolve:u,reject:p,args:l,self:c}),n<e&&i()})};return a.abort=function(){o.forEach(clearTimeout),o=[],r.forEach(function(l){l.reject(new throttle.AbortError)}),r.length=0},a}E.AbortError=function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"};const U=function(s,e){if(!s)return null;let t={};for(let r in s){let o=s[r];e.indexOf(r)>-1&&o!==null&&(t[r]=o)}return t};var z={nodes:{horizontal_rule:s=>({singleTag:"hr"}),blockquote:s=>({tag:"blockquote"}),bullet_list:s=>({tag:"ul"}),code_block:s=>({tag:["pre",{tag:"code",attrs:s.attrs}]}),hard_break:s=>({singleTag:"br"}),heading:s=>({tag:"h"+s.attrs.level}),image:s=>({singleTag:[{tag:"img",attrs:U(s.attrs,["src","alt","title"])}]}),list_item:s=>({tag:"li"}),ordered_list:s=>({tag:"ol"}),paragraph:s=>({tag:"p"})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link(s){const e=f({},s.attrs),{linktype:t="url"}=s.attrs;return t==="email"&&(e.href="mailto:"+e.href),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),{tag:[{tag:"a",attrs:e}]}},styled:s=>({tag:[{tag:"span",attrs:s.attrs}]})}};class D{constructor(e){e||(e=z),this.marks=e.marks||[],this.nodes=e.nodes||[]}addNode(e,t){this.nodes[e]=t}addMark(e,t){this.marks[e]=t}render(e={}){if(e.content&&Array.isArray(e.content)){let t="";return e.content.forEach(r=>{t+=this.renderNode(r)}),t}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(e){let t=[];e.marks&&e.marks.forEach(o=>{const n=this.getMatchingMark(o);n&&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(function(o){const n={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},i=/[&<>"']/g,a=RegExp(i.source);return o&&a.test(o)?o.replace(i,l=>n[l]):o}(e.text)):r&&r.singleTag?t.push(this.renderTag(r.singleTag," /")):r&&r.html&&t.push(r.html),r&&r.tag&&t.push(this.renderClosingTag(r.tag)),e.marks&&e.marks.slice(0).reverse().forEach(o=>{const n=this.getMatchingMark(o);n&&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(let n in r.attrs){let 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){if(typeof this.nodes[e.type]=="function")return this.nodes[e.type](e)}getMatchingMark(e){if(typeof this.marks[e.type]=="function")return this.marks[e.type](e)}}const J=(s=0,e=s)=>{const t=Math.abs(e-s)||0,r=s<e?1:-1;return((o=0,n)=>[...Array(o)].map(n))(t,(o,n)=>n*r+s)},b=(s,e,t)=>{const r=[];for(const o in s){if(!Object.prototype.hasOwnProperty.call(s,o))continue;const n=s[o],i=t?"":encodeURIComponent(o);let a;a=typeof n=="object"?b(n,e?e+encodeURIComponent("["+i+"]"):i,Array.isArray(n)):(e?e+encodeURIComponent("["+i+"]"):i)+"="+encodeURIComponent(n),r.push(a)}return r.join("&")};let m={},g={};class F{constructor(e,t){if(!t){let n=e.region?"-"+e.region:"",i=e.https===!1?"http":"https";t=e.oauthToken===void 0?`${i}://api${n}.storyblok.com/v2`:`${i}://api${n}.storyblok.com/v1`}let r=Object.assign({},e.headers),o=5;e.oauthToken!==void 0&&(r.Authorization=e.oauthToken,o=3),e.rateLimit!==void 0&&(o=e.rateLimit),this.richTextResolver=new D(e.richTextSchema),typeof e.componentResolver=="function"&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||5,this.throttle=E(this.throttledRequest,o,1e3),this.accessToken=e.accessToken,this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.client=N.default.create({baseURL:t,timeout:e.timeout||0,headers:r,proxy:e.proxy||!1}),e.responseInterceptor&&this.client.interceptors.response.use(n=>e.responseInterceptor(n))}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let r="";return t.attrs.body.forEach(o=>{r+=e(o.component,o)}),{html:r}})}parseParams(e={}){return e.version||(e.version="published"),e.token||(e.token=this.getToken()),e.cv||(e.cv=g[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),e}factoryParamOptions(e,t={}){return((r="")=>r.indexOf("/cdn/")>-1)(e)?this.parseParams(t):t}makeRequest(e,t,r,o){const n=this.factoryParamOptions(e,((i={},a=25,l=1)=>v(f({},i),{per_page:a,page:l}))(t,r,o));return this.cacheResponse(e,n)}get(e,t){let r="/"+e;const o=this.factoryParamOptions(r,t);return this.cacheResponse(r,o)}async getAll(e,t={},r){const o=t.per_page||25,n="/"+e,i=n.split("/");r=r||i[i.length-1];const a=await this.makeRequest(n,t,o,1),l=Math.ceil(a.total/o);return((c=[],u)=>c.map(u).reduce((p,d)=>[...p,...d],[]))([a,...await(async(c=[],u)=>Promise.all(c.map(u)))(J(1,l),async c=>this.makeRequest(n,t,o,c+1))],c=>Object.values(c.data[r]))}post(e,t){let r="/"+e;return this.throttle("post",r,t)}put(e,t){let r="/"+e;return this.throttle("put",r,t)}delete(e,t){let r="/"+e;return this.throttle("delete",r,t)}getStories(e){return this.get("cdn/stories",e)}getStory(e,t){return this.get("cdn/stories/"+e,t)}setToken(e){this.accessToken=e}getToken(){return this.accessToken}_cleanCopy(e){return JSON.parse(JSON.stringify(e))}_insertLinks(e,t){const r=e[t];r&&r.fieldtype=="multilink"&&r.linktype=="story"&&typeof r.id=="string"&&this.links[r.id]?r.story=this._cleanCopy(this.links[r.id]):r&&r.linktype==="story"&&typeof r.uuid=="string"&&this.links[r.uuid]&&(r.story=this._cleanCopy(this.links[r.uuid]))}_insertRelations(e,t,r){if(r.indexOf(e.component+"."+t)>-1){if(typeof e[t]=="string")this.relations[e[t]]&&(e[t]=this._cleanCopy(this.relations[e[t]]));else if(e[t].constructor===Array){let o=[];e[t].forEach(n=>{this.relations[n]&&o.push(this._cleanCopy(this.relations[n]))}),e[t]=o}}}iterateTree(e,t){let r=o=>{if(o!=null){if(o.constructor===Array)for(let n=0;n<o.length;n++)r(o[n]);else if(o.constructor===Object){if(o._stopResolving)return;for(let n in o)(o.component&&o._uid||o.type==="link")&&(this._insertRelations(o,n,t),this._insertLinks(o,n)),r(o[n])}}};r(e.content)}async resolveLinks(e,t){let r=[];if(e.link_uuids){const o=e.link_uuids.length;let n=[];const i=50;for(let a=0;a<o;a+=i){const l=Math.min(o,a+i);n.push(e.link_uuids.slice(a,l))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:i,language:t.language,version:t.version,by_uuids:n[a].join(",")})).data.stories.forEach(l=>{r.push(l)})}else r=e.links;r.forEach(o=>{this.links[o.uuid]=v(f({},o),{_stopResolving:!0})})}async resolveRelations(e,t){let r=[];if(e.rel_uuids){const o=e.rel_uuids.length;let n=[];const i=50;for(let a=0;a<o;a+=i){const l=Math.min(o,a+i);n.push(e.rel_uuids.slice(a,l))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:i,language:t.language,version:t.version,by_uuids:n[a].join(",")})).data.stories.forEach(l=>{r.push(l)})}else r=e.rels;r.forEach(o=>{this.relations[o.uuid]=v(f({},o),{_stopResolving:!0})})}async resolveStories(e,t){let r=[];t.resolve_relations!==void 0&&t.resolve_relations.length>0&&(r=t.resolve_relations.split(","),await this.resolveRelations(e,t)),["1","story","url"].indexOf(t.resolve_links)>-1&&await this.resolveLinks(e,t);for(const o in this.relations)this.iterateTree(this.relations[o],r);e.story?this.iterateTree(e.story,r):e.stories.forEach(o=>{this.iterateTree(o,r)})}cacheResponse(e,t,r){return r===void 0&&(r=0),new Promise(async(o,n)=>{let i=b({url:e,params:t}),a=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&await this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const c=await a.get(i);if(c)return o(c)}try{let c=await this.throttle("get",e,{params:t,paramsSerializer:p=>b(p)}),u={data:c.data,headers:c.headers};if(c.headers["per-page"]&&(u=Object.assign({},u,{perPage:parseInt(c.headers["per-page"]),total:parseInt(c.headers.total)})),c.status!=200)return n(c);(u.data.story||u.data.stories)&&await this.resolveStories(u.data,t),t.version==="published"&&e!="/cdn/spaces/me"&&a.set(i,u),u.data.cv&&(t.version=="draft"&&g[t.token]!=u.data.cv&&this.flushCache(),g[t.token]=u.data.cv),o(u)}catch(c){if(c.response&&c.response.status===429&&(r+=1)<this.maxRetries)return console.log(`Hit rate limit. Retrying in ${r} seconds.`),await(l=1e3*r,new Promise(u=>setTimeout(u,l))),this.cacheResponse(e,t,r).then(o).catch(n);n(c)}var l})}throttledRequest(e,t,r){return this.client[e](t,r)}cacheVersions(){return g}cacheVersion(){return g[this.accessToken]}setCacheVersion(e){this.accessToken&&(g[this.accessToken]=e)}cacheProvider(){switch(this.cache.type){case"memory":return{get:e=>m[e],getAll:()=>m,set(e,t){m[e]=t},flush(){m={}}};default:return{get(){},getAll(){},set(){},flush(){}}}}async flushCache(){return await this.cacheProvider().flush(),this}}var Y=(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 F(e)}},X=s=>{if(typeof s!="object"||typeof s._editable=="undefined")return{};const e=JSON.parse(s._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(e),"data-blok-uid":e.id+"-"+e.uid}};const P=(s,e,t={})=>{if(typeof window!="undefined"){if(typeof window.storyblokRegisterEvent=="undefined"){console.error("Storyblok Bridge is disabled. Please enable it to use it. Read https://github.com/storyblok/storyblok-js");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(t).on(["input","published","change"],o=>{o.action=="input"&&o.story.id===s?e(o.story):window.location.reload()})})}},H=(s={})=>{const{bridge:e,accessToken:t,use:r=[],apiOptions:o={}}=s;o.accessToken=o.accessToken||t;const n={bridge:e,apiOptions:o};let i={};return r.forEach(a=>{i=f(f({},i),a(n))}),e!==!1&&L("https://app.storyblok.com/f/storyblok-v2-latest.js"),i};var W=function(){var s=this,e=s.$createElement,t=s._self._c||e;return t(s.blok.component,s._g(s._b({tag:"component"},"component",Object.assign({},s.$props,s.$attrs),!1),s.$listeners))},G=[];function K(s,e,t,r,o,n,i,a){var l=typeof s=="function"?s.options:s;e&&(l.render=e,l.staticRenderFns=t,l._compiled=!0),r&&(l.functional=!0),n&&(l._scopeId="data-v-"+n);var c;if(i?(c=function(d){d=d||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext,!d&&typeof __VUE_SSR_CONTEXT__!="undefined"&&(d=__VUE_SSR_CONTEXT__),o&&o.call(this,d),d&&d._registeredComponents&&d._registeredComponents.add(i)},l._ssrRegister=c):o&&(c=a?function(){o.call(this,(l.functional?this.parent:this).$root.$options.shadowRoot)}:o),c)if(l.functional){l._injectStyles=c;var u=l.render;l.render=function(ne,A){return c.call(A),u(ne,A)}}else{var p=l.beforeCreate;l.beforeCreate=p?[].concat(p,c):[c]}return{exports:s,options:l}}const Q={props:{blok:{type:Object}}},C={};var Z=K(Q,W,G,!1,ee,null,null,null);function ee(s){for(let e in C)this[e]=C[e]}var te=function(){return Z.exports}();const re=s=>{console.error(`You can't use ${s} if you're not loading apiPlugin. Please provide it on StoryblokVue initialization.
6
+ `)},oe={bind(s,e){if(e.value){const t=X(e.value);s.setAttribute("data-blok-c",t["data-blok-c"]),s.setAttribute("data-blok-uid",t["data-blok-uid"]),s.classList.add("storyblok__outline")}}};let _=null;const $=()=>(_||re("useStoryblokApi"),_),j={install(s,e={}){s.directive("editable",oe),s.component("StoryblokComponent",te);const{storyblokApi:t}=H(e);_=t,s.prototype.$storyblokApi=t}};typeof window!="undefined"&&window.Vue&&window.Vue.use(j);const se=(s,e={},t={})=>{const r=$();if(!r)return console.error("useStoryblok cannot be used if you disabled useApiClient when adding @storyblok/nuxt-beta to your nuxt.config.js");const o=k.ref(null);k.onMounted(()=>{o.value&&o.value.id&&P(o.value.id,a=>o.value=a,t)});const{fetch:n,fetchState:i}=k.useFetch(async()=>{const{data:a}=await r.get(`cdn/stories/${s}`,e);o.value=a.story},s);return n(),{story:o,fetchState:i}};h.StoryblokVue=j,h.apiPlugin=Y,h.useStoryblok=se,h.useStoryblokApi=$,h.useStoryblokBridge=P,Object.defineProperty(h,"__esModule",{value:!0}),h[Symbol.toStringTag]="Module"});
@@ -1,5 +1,6 @@
1
1
  import t from "axios";
2
- import { ref, onMounted } from "@vue/composition-api";
2
+ import "@vue/composition-api";
3
+ import { ref, onMounted, useFetch } from "@nuxtjs/composition-api";
3
4
  var __defProp = Object.defineProperty;
4
5
  var __defProps = Object.defineProperties;
5
6
  var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
@@ -518,21 +519,6 @@ const printError = (fnName) => {
518
519
  console.error(`You can't use ${fnName} if you're not loading apiPlugin. Please provide it on StoryblokVue initialization.
519
520
  `);
520
521
  };
521
- var useStoryblok = (url, apiOptions = {}, bridgeOptions = {}) => {
522
- const story = ref(null);
523
- const storyblokApiInstance2 = useStoryblokApi();
524
- onMounted(async () => {
525
- if (storyblokApiInstance2) {
526
- const { data } = await storyblokApiInstance2.get(`cdn/stories/${url}`, apiOptions);
527
- story.value = data.story;
528
- } else
529
- printError("useStoryblok");
530
- if (story.value && story.value.id) {
531
- useStoryblokBridge(story.value.id, (evStory) => story.value = evStory, bridgeOptions);
532
- }
533
- });
534
- return story;
535
- };
536
522
  const vEditableDirective = {
537
523
  bind(el, binding) {
538
524
  if (binding.value) {
@@ -561,4 +547,21 @@ const StoryblokVue = {
561
547
  if (typeof window !== "undefined" && window.Vue) {
562
548
  window.Vue.use(StoryblokVue);
563
549
  }
564
- export { StoryblokComponent, StoryblokVue, api as apiPlugin, useStoryblok, useStoryblokApi, useStoryblokBridge };
550
+ const useStoryblok = (slug, apiOptions = {}, bridgeOptions = {}) => {
551
+ const storyblokApi = useStoryblokApi();
552
+ if (!storyblokApi)
553
+ return console.error("useStoryblok cannot be used if you disabled useApiClient when adding @storyblok/nuxt-beta to your nuxt.config.js");
554
+ const story = ref(null);
555
+ onMounted(() => {
556
+ if (story.value && story.value.id) {
557
+ useStoryblokBridge(story.value.id, (evStory) => story.value = evStory, bridgeOptions);
558
+ }
559
+ });
560
+ const { fetch, fetchState } = useFetch(async () => {
561
+ const { data } = await storyblokApi.get(`cdn/stories/${slug}`, apiOptions);
562
+ story.value = data.story;
563
+ }, slug);
564
+ fetch();
565
+ return { story, fetchState };
566
+ };
567
+ export { StoryblokVue, api as apiPlugin, useStoryblok, useStoryblokApi, useStoryblokBridge };
package/module/plugin.js CHANGED
@@ -11,7 +11,7 @@ export default (ctx) => {
11
11
 
12
12
  Vue.use(StoryblokVue, {
13
13
  accessToken: "<%= options.accessToken %>",
14
- bridge: <%= 'process.env.NODE_ENV !== "production"' %>,
14
+ bridge: <%= typeof options.bridge === "undefined" ? true : options.bridge %>,
15
15
  apiOptions: <%- JSON.stringify(options.apiOptions || {}) %>,
16
16
  <% if (options.useApiClient !== false) { %>
17
17
  use: [apiPlugin]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storyblok/nuxt",
3
- "version": "3.0.0",
3
+ "version": "3.0.3",
4
4
  "description": "Storyblok Nuxt.js module",
5
5
  "exports": {
6
6
  ".": {