@storyblok/react 5.3.0 → 5.4.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.
Files changed (84) hide show
  1. package/README.md +192 -64
  2. package/dist/core/init.js +1 -0
  3. package/dist/core/init.mjs +17 -0
  4. package/dist/core/richtext-hoc.js +1 -0
  5. package/dist/core/richtext-hoc.mjs +38 -0
  6. package/dist/core/state.js +1 -0
  7. package/dist/core/state.mjs +23 -0
  8. package/dist/core/storyblok-component.js +1 -0
  9. package/dist/{storyblok-component.mjs → core/storyblok-component.mjs} +4 -3
  10. package/dist/core/use-storyblok-api.js +1 -0
  11. package/dist/core/use-storyblok-api.mjs +11 -0
  12. package/dist/core/use-storyblok-state.js +2 -0
  13. package/dist/{client.mjs → core/use-storyblok-state.mjs} +6 -6
  14. package/dist/index.d.ts +209 -13
  15. package/dist/index.js +1 -1
  16. package/dist/index.mjs +33 -32
  17. package/dist/richtext.js +1 -1
  18. package/dist/richtext.mjs +6 -27
  19. package/dist/rsc/live-editing.js +2 -0
  20. package/dist/rsc/live-editing.mjs +30 -0
  21. package/dist/rsc/story.js +1 -0
  22. package/dist/{story.mjs → rsc/story.mjs} +6 -7
  23. package/dist/rsc.d.ts +194 -0
  24. package/dist/rsc.js +1 -1
  25. package/dist/rsc.mjs +32 -29
  26. package/dist/server/richtext.js +1 -0
  27. package/dist/server/richtext.mjs +8 -0
  28. package/dist/server/server-component.js +1 -0
  29. package/dist/{server-component.mjs → server/server-component.mjs} +3 -5
  30. package/dist/server/server-story.js +1 -0
  31. package/dist/server/server-story.mjs +25 -0
  32. package/dist/{server-storyblok-richtext-component.js → server/server-storyblok-richtext-component.js} +1 -1
  33. package/dist/{server-storyblok-richtext-component.mjs → server/server-storyblok-richtext-component.mjs} +2 -2
  34. package/dist/ssr.d.ts +192 -0
  35. package/dist/ssr.js +1 -0
  36. package/dist/ssr.mjs +35 -0
  37. package/package.json +7 -2
  38. package/dist/client.js +0 -2
  39. package/dist/common/client.d.ts +0 -3
  40. package/dist/common/client.d.ts.map +0 -1
  41. package/dist/common/index.d.ts +0 -12
  42. package/dist/common/index.d.ts.map +0 -1
  43. package/dist/common/storyblok-component.d.ts +0 -7
  44. package/dist/common/storyblok-component.d.ts.map +0 -1
  45. package/dist/common.js +0 -1
  46. package/dist/common.mjs +0 -33
  47. package/dist/index.d.ts.map +0 -1
  48. package/dist/index2.js +0 -1
  49. package/dist/index2.mjs +0 -30
  50. package/dist/live-editing.js +0 -2
  51. package/dist/live-editing.mjs +0 -24
  52. package/dist/richtext.d.ts +0 -7
  53. package/dist/richtext.d.ts.map +0 -1
  54. package/dist/richtext2.js +0 -1
  55. package/dist/richtext2.mjs +0 -32
  56. package/dist/rsc/common.d.ts +0 -15
  57. package/dist/rsc/common.d.ts.map +0 -1
  58. package/dist/rsc/index.d.ts +0 -7
  59. package/dist/rsc/index.d.ts.map +0 -1
  60. package/dist/rsc/live-edit-update-action.d.ts +0 -6
  61. package/dist/rsc/live-edit-update-action.d.ts.map +0 -1
  62. package/dist/rsc/live-editing.d.ts +0 -7
  63. package/dist/rsc/live-editing.d.ts.map +0 -1
  64. package/dist/rsc/richtext.d.ts +0 -11
  65. package/dist/rsc/richtext.d.ts.map +0 -1
  66. package/dist/rsc/server-component.d.ts +0 -7
  67. package/dist/rsc/server-component.d.ts.map +0 -1
  68. package/dist/rsc/server-storyblok-richtext-component.d.ts +0 -5
  69. package/dist/rsc/server-storyblok-richtext-component.d.ts.map +0 -1
  70. package/dist/rsc/story.d.ts +0 -8
  71. package/dist/rsc/story.d.ts.map +0 -1
  72. package/dist/server-component.js +0 -1
  73. package/dist/story.js +0 -1
  74. package/dist/storyblok-component.js +0 -1
  75. package/dist/storyblok-js.js +0 -1
  76. package/dist/storyblok-js.mjs +0 -898
  77. package/dist/storyblok-rich-text.d.ts +0 -5
  78. package/dist/storyblok-rich-text.d.ts.map +0 -1
  79. package/dist/types.d.ts +0 -17
  80. package/dist/types.d.ts.map +0 -1
  81. package/dist/utils.d.ts +0 -19
  82. package/dist/utils.d.ts.map +0 -1
  83. /package/dist/{live-edit-update-action.js → rsc/live-edit-update-action.js} +0 -0
  84. /package/dist/{live-edit-update-action.mjs → rsc/live-edit-update-action.mjs} +0 -0
@@ -1,898 +0,0 @@
1
- function re(n, e) {
2
- if (!e)
3
- return { src: n, attrs: {} };
4
- let t = 0, r = 0;
5
- const s = {}, o = [];
6
- function c(i, h, f, y, $) {
7
- typeof i != "number" || i <= h || i >= f ? console.warn(`[StoryblokRichText] - ${y.charAt(0).toUpperCase() + y.slice(1)} value must be a number between ${h} and ${f} (inclusive)`) : $.push(`${y}(${i})`);
8
- }
9
- if (typeof e == "object") {
10
- 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, r = 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) {
11
- const { filters: i } = e || {}, { blur: h, brightness: f, fill: y, format: $, grayscale: T, quality: A, rotate: S } = i || {};
12
- h && c(h, 0, 100, "blur", o), A && c(A, 0, 100, "quality", o), f && c(f, 0, 100, "brightness", o), y && o.push(`fill(${y})`), T && o.push("grayscale()"), S && [0, 90, 180, 270].includes(e.filters.rotate || 0) && o.push(`rotate(${S})`), $ && ["webp", "png", "jpeg"].includes($) && o.push(`format(${$})`);
13
- }
14
- e.srcset && (s.srcset = e.srcset.map((i) => {
15
- if (typeof i == "number")
16
- return `${n}/m/${i}x0/${o.length > 0 ? `filters:${o.join(":")}` : ""} ${i}w`;
17
- if (Array.isArray(i) && i.length === 2) {
18
- const [h, f] = i;
19
- return `${n}/m/${h}x${f}/${o.length > 0 ? `filters:${o.join(":")}` : ""} ${h}w`;
20
- } else {
21
- console.warn("[StoryblokRichText] - srcset entry must be a number or a tuple of two numbers");
22
- return;
23
- }
24
- }).join(", ")), e.sizes && (s.sizes = e.sizes.join(", "));
25
- }
26
- let l = `${n}/m/`;
27
- return t > 0 && r > 0 && (l = `${l}${t}x${r}/`), o.length > 0 && (l = `${l}filters:${o.join(":")}`), {
28
- src: l,
29
- attrs: s
30
- };
31
- }
32
- var v = /* @__PURE__ */ ((n) => (n.DOCUMENT = "doc", n.HEADING = "heading", n.PARAGRAPH = "paragraph", n.QUOTE = "blockquote", n.OL_LIST = "ordered_list", n.UL_LIST = "bullet_list", n.LIST_ITEM = "list_item", n.CODE_BLOCK = "code_block", n.HR = "horizontal_rule", n.BR = "hard_break", n.IMAGE = "image", n.EMOJI = "emoji", n.COMPONENT = "blok", n.TABLE = "table", n.TABLE_ROW = "tableRow", n.TABLE_CELL = "tableCell", n.TABLE_HEADER = "tableHeader", n))(v || {}), R = /* @__PURE__ */ ((n) => (n.BOLD = "bold", n.STRONG = "strong", n.STRIKE = "strike", n.UNDERLINE = "underline", n.ITALIC = "italic", n.CODE = "code", n.LINK = "link", n.ANCHOR = "anchor", n.STYLED = "styled", n.SUPERSCRIPT = "superscript", n.SUBSCRIPT = "subscript", n.TEXT_STYLE = "textStyle", n.HIGHLIGHT = "highlight", n))(R || {}), J = /* @__PURE__ */ ((n) => (n.TEXT = "text", n))(J || {}), I = /* @__PURE__ */ ((n) => (n.URL = "url", n.STORY = "story", n.ASSET = "asset", n.EMAIL = "email", n))(I || {});
33
- const ne = [
34
- "area",
35
- "base",
36
- "br",
37
- "col",
38
- "embed",
39
- "hr",
40
- "img",
41
- "input",
42
- "link",
43
- "meta",
44
- "param",
45
- "source",
46
- "track",
47
- "wbr"
48
- ], oe = (n = {}) => Object.keys(n).map((e) => `${e}="${n[e]}"`).join(" "), ie = (n = {}) => Object.keys(n).map((e) => `${e}: ${n[e]}`).join("; ");
49
- function ae(n) {
50
- return n.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
51
- }
52
- const O = (n) => Object.fromEntries(Object.entries(n).filter(([e, t]) => t !== void 0));
53
- function D(n, e = {}, t) {
54
- const r = oe(e), s = r ? `${n} ${r}` : n, o = Array.isArray(t) ? t.join("") : t || "";
55
- if (n) {
56
- if (ne.includes(n))
57
- return `<${s}>`;
58
- } else return o;
59
- return `<${s}>${o}</${n}>`;
60
- }
61
- function le(n = {}) {
62
- const e = /* @__PURE__ */ new Map(), {
63
- renderFn: t = D,
64
- textFn: r = ae,
65
- resolvers: s = {},
66
- optimizeImages: o = !1,
67
- keyedResolvers: c = !1
68
- } = n, l = t !== D, i = (a) => (u, d) => {
69
- const p = u.attrs || {};
70
- return d.render(a, p, u.children || null);
71
- }, h = (a, u) => {
72
- const { src: d, alt: p, title: m, srcset: w, sizes: b } = a.attrs || {};
73
- let k = d, _ = {};
74
- if (o) {
75
- const { src: te, attrs: se } = re(d, o);
76
- k = te, _ = se;
77
- }
78
- const ee = {
79
- src: k,
80
- alt: p,
81
- title: m,
82
- srcset: w,
83
- sizes: b,
84
- ..._
85
- };
86
- return u.render("img", O(ee));
87
- }, f = (a, u) => {
88
- const { level: d, ...p } = a.attrs || {};
89
- return u.render(`h${d}`, p, a.children);
90
- }, y = (a, u) => {
91
- var d, p, m, w;
92
- const b = u.render("img", {
93
- src: (d = a.attrs) == null ? void 0 : d.fallbackImage,
94
- alt: (p = a.attrs) == null ? void 0 : p.alt,
95
- style: "width: 1.25em; height: 1.25em; vertical-align: text-top",
96
- draggable: "false",
97
- loading: "lazy"
98
- });
99
- return u.render("span", {
100
- "data-type": "emoji",
101
- "data-name": (m = a.attrs) == null ? void 0 : m.name,
102
- "data-emoji": (w = a.attrs) == null ? void 0 : w.emoji
103
- }, b);
104
- }, $ = (a, u) => u.render(
105
- "pre",
106
- a.attrs || {},
107
- u.render("code", {}, a.children || "")
108
- ), T = (a, u = !1) => ({ text: d, attrs: p }, m) => {
109
- const { class: w, id: b, ...k } = p || {}, _ = u ? {
110
- class: w,
111
- id: b,
112
- style: ie(k) || void 0
113
- } : p || {};
114
- return m.render(a, O(_), d);
115
- }, A = (a) => C(a), S = (a) => {
116
- const { marks: u, ...d } = a;
117
- if ("text" in a) {
118
- if (u)
119
- return u.reduce(
120
- (m, w) => A({ ...w, text: m }),
121
- A({ ...d, children: d.children })
122
- );
123
- const p = a.attrs || {};
124
- if (c) {
125
- const m = e.get("txt") || 0;
126
- e.set("txt", m + 1), p.key = `txt-${m}`;
127
- }
128
- return r(d.text, p);
129
- }
130
- return "";
131
- }, H = (a, u) => {
132
- const { linktype: d, href: p, anchor: m, ...w } = a.attrs || {};
133
- let b = "";
134
- switch (d) {
135
- case I.ASSET:
136
- case I.URL:
137
- b = p;
138
- break;
139
- case I.EMAIL:
140
- b = `mailto:${p}`;
141
- break;
142
- case I.STORY:
143
- b = p, m && (b = `${b}#${m}`);
144
- break;
145
- default:
146
- b = p;
147
- break;
148
- }
149
- const k = { ...w };
150
- return b && (k.href = b), u.render("a", k, a.text);
151
- }, Y = (a, u) => {
152
- var d, p;
153
- return console.warn("[StoryblokRichtText] - BLOK resolver is not available for vanilla usage"), u.render("span", {
154
- blok: (d = a == null ? void 0 : a.attrs) == null ? void 0 : d.body[0],
155
- id: (p = a.attrs) == null ? void 0 : p.id,
156
- style: "display: none"
157
- });
158
- }, K = (a, u) => {
159
- const d = {}, p = u.render("tbody", {}, a.children);
160
- return u.render("table", d, p);
161
- }, W = (a, u) => {
162
- const d = {};
163
- return u.render("tr", d, a.children);
164
- }, X = (a, u) => {
165
- const { colspan: d, rowspan: p, colwidth: m, backgroundColor: w, ...b } = a.attrs || {}, k = {
166
- ...b
167
- };
168
- d > 1 && (k.colspan = d), p > 1 && (k.rowspan = p);
169
- const _ = [];
170
- return m && _.push(`width: ${m}px;`), w && _.push(`background-color: ${w};`), _.length > 0 && (k.style = _.join(" ")), u.render("td", O(k), a.children);
171
- }, Q = (a, u) => {
172
- const { colspan: d, rowspan: p, colwidth: m, backgroundColor: w, ...b } = a.attrs || {}, k = {
173
- ...b
174
- };
175
- d > 1 && (k.colspan = d), p > 1 && (k.rowspan = p);
176
- const _ = [];
177
- return m && _.push(`width: ${m}px;`), w && _.push(`background-color: ${w};`), _.length > 0 && (k.style = _.join(" ")), u.render("th", O(k), a.children);
178
- }, U = /* @__PURE__ */ new Map([
179
- [v.DOCUMENT, i("")],
180
- [v.HEADING, f],
181
- [v.PARAGRAPH, i("p")],
182
- [v.UL_LIST, i("ul")],
183
- [v.OL_LIST, i("ol")],
184
- [v.LIST_ITEM, i("li")],
185
- [v.IMAGE, h],
186
- [v.EMOJI, y],
187
- [v.CODE_BLOCK, $],
188
- [v.HR, i("hr")],
189
- [v.BR, i("br")],
190
- [v.QUOTE, i("blockquote")],
191
- [v.COMPONENT, Y],
192
- [J.TEXT, S],
193
- [R.LINK, H],
194
- [R.ANCHOR, H],
195
- [R.STYLED, T("span", !0)],
196
- [R.BOLD, T("strong")],
197
- [R.TEXT_STYLE, T("span", !0)],
198
- [R.ITALIC, T("em")],
199
- [R.UNDERLINE, T("u")],
200
- [R.STRIKE, T("s")],
201
- [R.CODE, T("code")],
202
- [R.SUPERSCRIPT, T("sup")],
203
- [R.SUBSCRIPT, T("sub")],
204
- [R.HIGHLIGHT, T("mark")],
205
- [v.TABLE, K],
206
- [v.TABLE_ROW, W],
207
- [v.TABLE_CELL, X],
208
- [v.TABLE_HEADER, Q]
209
- ]), B = new Map([
210
- ...U,
211
- ...Object.entries(s).map(([a, u]) => [a, u])
212
- ]), Z = () => ({
213
- render: (a, u = {}, d) => {
214
- if (c && a) {
215
- const p = e.get(a) || 0;
216
- e.set(a, p + 1), u.key = `${a}-${p}`;
217
- }
218
- return t(a, u, d);
219
- },
220
- originalResolvers: U,
221
- mergedResolvers: B
222
- });
223
- function L(a) {
224
- const u = B.get(a.type);
225
- if (!u)
226
- return console.error("<Storyblok>", `No resolver found for node type ${a.type}`), "";
227
- const d = Z();
228
- if (a.type === "text")
229
- return u(a, d);
230
- const p = a.content ? a.content.map(C) : void 0;
231
- return u({
232
- ...a,
233
- children: p
234
- }, d);
235
- }
236
- function C(a) {
237
- return a.type === "doc" ? l ? a.content.map(L) : a.content.map(L).join("") : Array.isArray(a) ? a.map(L) : L(a);
238
- }
239
- return {
240
- render: C
241
- };
242
- }
243
- let M = !1;
244
- const z = [], F = (n) => new Promise((e, t) => {
245
- if (typeof window > "u") {
246
- t(new Error("Cannot load Storyblok bridge: window is undefined (server-side environment)"));
247
- return;
248
- }
249
- if (window.storyblokRegisterEvent = (s) => {
250
- if (!window.location.search.includes("_storyblok")) {
251
- console.warn("You are not in Draft Mode or in the Visual Editor.");
252
- return;
253
- }
254
- M ? s() : z.push(s);
255
- }, document.getElementById("storyblok-javascript-bridge")) {
256
- e(void 0);
257
- return;
258
- }
259
- const r = document.createElement("script");
260
- r.async = !0, r.src = n, r.id = "storyblok-javascript-bridge", r.onerror = (s) => t(s), r.onload = (s) => {
261
- z.forEach((o) => o()), M = !0, e(s);
262
- }, document.getElementsByTagName("head")[0].appendChild(r);
263
- });
264
- var ce = Object.defineProperty, he = (n, e, t) => e in n ? ce(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t, g = (n, e, t) => he(n, typeof e != "symbol" ? e + "" : e, t);
265
- class ue extends Error {
266
- constructor(e) {
267
- super(e), this.name = "AbortError";
268
- }
269
- }
270
- function de(n, e, t) {
271
- if (!Number.isFinite(e))
272
- throw new TypeError("Expected `limit` to be a finite number");
273
- if (!Number.isFinite(t))
274
- throw new TypeError("Expected `interval` to be a finite number");
275
- const r = [];
276
- let s = [], o = 0, c = !1;
277
- const l = async () => {
278
- o++;
279
- const h = r.shift();
280
- if (h)
281
- try {
282
- const y = await n(...h.args);
283
- h.resolve(y);
284
- } catch (y) {
285
- h.reject(y);
286
- }
287
- const f = setTimeout(() => {
288
- o--, r.length > 0 && l(), s = s.filter((y) => y !== f);
289
- }, t);
290
- s.includes(f) || s.push(f);
291
- }, i = (...h) => c ? Promise.reject(
292
- new Error(
293
- "Throttled function is already aborted and not accepting new promises"
294
- )
295
- ) : new Promise((f, y) => {
296
- r.push({
297
- resolve: f,
298
- reject: y,
299
- args: h
300
- }), o < e && l();
301
- });
302
- return i.abort = () => {
303
- c = !0, s.forEach(clearTimeout), s = [], r.forEach(
304
- (h) => h.reject(() => new ue("Throttle function aborted"))
305
- ), r.length = 0;
306
- }, i;
307
- }
308
- const G = (n = "") => n.includes("/cdn/"), pe = (n, e = 25, t = 1) => ({
309
- ...n,
310
- per_page: e,
311
- page: t
312
- }), fe = (n) => new Promise((e) => setTimeout(e, n)), ye = (n = 0, e) => Array.from({ length: n }, e), ge = (n = 0, e = n) => {
313
- const t = Math.abs(e - n) || 0, r = n < e ? 1 : -1;
314
- return ye(t, (s, o) => o * r + n);
315
- }, me = async (n, e) => Promise.all(n.map(e)), be = (n = [], e) => n.map(e).reduce((t, r) => [...t, ...r], []), N = (n, e, t) => {
316
- const r = [];
317
- for (const s in n) {
318
- if (!Object.prototype.hasOwnProperty.call(n, s))
319
- continue;
320
- const o = n[s];
321
- if (o == null)
322
- continue;
323
- const c = t ? "" : encodeURIComponent(s);
324
- let l;
325
- typeof o == "object" ? l = N(
326
- o,
327
- e ? e + encodeURIComponent(`[${c}]`) : c,
328
- Array.isArray(o)
329
- ) : l = `${e ? e + encodeURIComponent(`[${c}]`) : c}=${encodeURIComponent(o)}`, r.push(l);
330
- }
331
- return r.join("&");
332
- }, V = (n) => {
333
- const e = {
334
- eu: "api.storyblok.com",
335
- us: "api-us.storyblok.com",
336
- cn: "app.storyblokchina.cn",
337
- ap: "api-ap.storyblok.com",
338
- ca: "api-ca.storyblok.com"
339
- };
340
- return e[n] ?? e.eu;
341
- };
342
- class ve {
343
- constructor(e) {
344
- 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 = {};
345
- }
346
- /**
347
- *
348
- * @param url string
349
- * @param params ISbStoriesParams
350
- * @returns Promise<ISbResponse | Error>
351
- */
352
- get(e, t) {
353
- return this.url = e, this.parameters = t, this._methodHandler("get");
354
- }
355
- post(e, t) {
356
- return this.url = e, this.parameters = t, this._methodHandler("post");
357
- }
358
- put(e, t) {
359
- return this.url = e, this.parameters = t, this._methodHandler("put");
360
- }
361
- delete(e, t) {
362
- return this.url = e, this.parameters = t ?? {}, this._methodHandler("delete");
363
- }
364
- async _responseHandler(e) {
365
- const t = [], r = {
366
- data: {},
367
- headers: {},
368
- status: 0,
369
- statusText: ""
370
- };
371
- e.status !== 204 && await e.json().then((s) => {
372
- r.data = s;
373
- });
374
- for (const s of e.headers.entries())
375
- t[s[0]] = s[1];
376
- return r.headers = { ...t }, r.status = e.status, r.statusText = e.statusText, r;
377
- }
378
- async _methodHandler(e) {
379
- let t = `${this.baseURL}${this.url}`, r = null;
380
- e === "get" ? t = `${this.baseURL}${this.url}?${N(this.parameters)}` : r = JSON.stringify(this.parameters);
381
- const s = new URL(t), o = new AbortController(), { signal: c } = o;
382
- let l;
383
- this.timeout && (l = setTimeout(() => o.abort(), this.timeout));
384
- try {
385
- const i = await this.fetch(`${s}`, {
386
- method: e,
387
- headers: this.headers,
388
- body: r,
389
- signal: c,
390
- ...this.fetchOptions
391
- });
392
- this.timeout && clearTimeout(l);
393
- const h = await this._responseHandler(
394
- i
395
- );
396
- return this.responseInterceptor && !this.ejectInterceptor ? this._statusHandler(this.responseInterceptor(h)) : this._statusHandler(h);
397
- } catch (i) {
398
- return {
399
- message: i
400
- };
401
- }
402
- }
403
- setFetchOptions(e = {}) {
404
- Object.keys(e).length > 0 && "method" in e && delete e.method, this.fetchOptions = { ...e };
405
- }
406
- eject() {
407
- this.ejectInterceptor = !0;
408
- }
409
- /**
410
- * Normalizes error messages from different response structures
411
- * @param data The response data that might contain error information
412
- * @returns A normalized error message string
413
- */
414
- _normalizeErrorMessage(e) {
415
- if (Array.isArray(e))
416
- return e[0] || "Unknown error";
417
- if (e && typeof e == "object") {
418
- if (e.error)
419
- return e.error;
420
- for (const t in e) {
421
- if (Array.isArray(e[t]))
422
- return `${t}: ${e[t][0]}`;
423
- if (typeof e[t] == "string")
424
- return `${t}: ${e[t]}`;
425
- }
426
- if (e.slug)
427
- return e.slug;
428
- }
429
- return "Unknown error";
430
- }
431
- _statusHandler(e) {
432
- const t = /20[0-6]/g;
433
- return new Promise((r, s) => {
434
- if (t.test(`${e.status}`))
435
- return r(e);
436
- const o = {
437
- message: this._normalizeErrorMessage(e.data),
438
- status: e.status,
439
- response: e
440
- };
441
- s(o);
442
- });
443
- }
444
- }
445
- const q = "SB-Agent", P = {
446
- defaultAgentName: "SB-JS-CLIENT",
447
- defaultAgentVersion: "SB-Agent-Version",
448
- packageVersion: "7.0.0"
449
- }, ke = {
450
- PUBLISHED: "published"
451
- };
452
- let j = {};
453
- const E = {};
454
- class we {
455
- /**
456
- *
457
- * @param config ISbConfig interface
458
- * @param pEndpoint string, optional
459
- */
460
- constructor(e, t) {
461
- 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");
462
- let r = e.endpoint || t;
463
- if (!r) {
464
- const c = e.https === !1 ? "http" : "https";
465
- e.oauthToken ? r = `${c}://${V(e.region)}/v1` : r = `${c}://${V(e.region)}/v2`;
466
- }
467
- const s = new Headers();
468
- 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(([c, l]) => {
469
- s.set(c, l);
470
- }), s.has(q) || (s.set(q, P.defaultAgentName), s.set(
471
- P.defaultAgentVersion,
472
- P.packageVersion
473
- ));
474
- let o = 5;
475
- e.oauthToken && (s.set("Authorization", e.oauthToken), o = 3), e.rateLimit && (o = e.rateLimit), this.maxRetries = e.maxRetries || 10, this.retriesDelay = 300, this.throttle = de(
476
- this.throttledRequest.bind(this),
477
- o,
478
- 1e3
479
- ), 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 || ke.PUBLISHED, this.inlineAssets = e.inlineAssets || !1, this.client = new ve({
480
- baseURL: r,
481
- timeout: e.timeout || 0,
482
- headers: s,
483
- responseInterceptor: e.responseInterceptor,
484
- fetch: e.fetch
485
- });
486
- }
487
- parseParams(e) {
488
- 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;
489
- }
490
- factoryParamOptions(e, t) {
491
- return G(e) ? this.parseParams(t) : t;
492
- }
493
- makeRequest(e, t, r, s, o) {
494
- const c = this.factoryParamOptions(
495
- e,
496
- pe(t, r, s)
497
- );
498
- return this.cacheResponse(e, c, void 0, o);
499
- }
500
- get(e, t = {}, r) {
501
- t || (t = {});
502
- const s = `/${e}`;
503
- G(s) && (t.version = t.version || this.version);
504
- const o = this.factoryParamOptions(s, t);
505
- return this.cacheResponse(s, o, void 0, r);
506
- }
507
- async getAll(e, t = {}, r, s) {
508
- const o = (t == null ? void 0 : t.per_page) || 25, c = `/${e}`.replace(/\/$/, ""), l = r ?? c.substring(c.lastIndexOf("/") + 1);
509
- t.version = t.version || this.version;
510
- const i = 1, h = await this.makeRequest(
511
- c,
512
- t,
513
- o,
514
- i,
515
- s
516
- ), f = h.total ? Math.ceil(h.total / o) : 1, y = await me(
517
- ge(i, f),
518
- ($) => this.makeRequest(c, t, o, $ + 1, s)
519
- );
520
- return be([h, ...y], ($) => Object.values($.data[l]));
521
- }
522
- post(e, t = {}, r) {
523
- const s = `/${e}`;
524
- return this.throttle("post", s, t, r);
525
- }
526
- put(e, t = {}, r) {
527
- const s = `/${e}`;
528
- return this.throttle("put", s, t, r);
529
- }
530
- delete(e, t = {}, r) {
531
- t || (t = {});
532
- const s = `/${e}`;
533
- return this.throttle("delete", s, t, r);
534
- }
535
- getStories(e = {}, t) {
536
- return this._addResolveLevel(e), this.get("cdn/stories", e, t);
537
- }
538
- getStory(e, t = {}, r) {
539
- return this._addResolveLevel(t), this.get(`cdn/stories/${e}`, t, r);
540
- }
541
- getToken() {
542
- return this.accessToken;
543
- }
544
- ejectInterceptor() {
545
- this.client.eject();
546
- }
547
- _addResolveLevel(e) {
548
- typeof e.resolve_relations < "u" && (e.resolve_level = 2);
549
- }
550
- _cleanCopy(e) {
551
- return JSON.parse(JSON.stringify(e));
552
- }
553
- _insertLinks(e, t, r) {
554
- const s = e[t];
555
- s && s.fieldtype === "multilink" && s.linktype === "story" && typeof s.id == "string" && this.links[r][s.id] ? s.story = this._cleanCopy(this.links[r][s.id]) : s && s.linktype === "story" && typeof s.uuid == "string" && this.links[r][s.uuid] && (s.story = this._cleanCopy(this.links[r][s.uuid]));
556
- }
557
- /**
558
- *
559
- * @param resolveId A counter number as a string
560
- * @param uuid The uuid of the story
561
- * @returns string | object
562
- */
563
- getStoryReference(e, t) {
564
- return this.relations[e][t] ? JSON.parse(this.stringifiedStoriesCache[t] || JSON.stringify(this.relations[e][t])) : t;
565
- }
566
- /**
567
- * Resolves a field's value by replacing UUIDs with their corresponding story references
568
- * @param jtree - The JSON tree object containing the field to resolve
569
- * @param treeItem - The key of the field to resolve
570
- * @param resolveId - The unique identifier for the current resolution context
571
- *
572
- * This method handles both single string UUIDs and arrays of UUIDs:
573
- * - For single strings: directly replaces the UUID with the story reference
574
- * - For arrays: maps through each UUID and replaces with corresponding story references
575
- */
576
- _resolveField(e, t, r) {
577
- const s = e[t];
578
- typeof s == "string" ? e[t] = this.getStoryReference(r, s) : Array.isArray(s) && (e[t] = s.map(
579
- (o) => this.getStoryReference(r, o)
580
- ).filter(Boolean));
581
- }
582
- /**
583
- * Inserts relations into the JSON tree by resolving references
584
- * @param jtree - The JSON tree object to process
585
- * @param treeItem - The current field being processed
586
- * @param fields - The relation patterns to resolve (string or array of strings)
587
- * @param resolveId - The unique identifier for the current resolution context
588
- *
589
- * This method handles two types of relation patterns:
590
- * 1. Nested relations: matches fields that end with the current field name
591
- * Example: If treeItem is "event_type", it matches patterns like "*.event_type"
592
- *
593
- * 2. Direct component relations: matches exact component.field patterns
594
- * Example: "event.event_type" for component "event" and field "event_type"
595
- *
596
- * The method supports both string and array formats for the fields parameter,
597
- * allowing flexible specification of relation patterns.
598
- */
599
- _insertRelations(e, t, r, s) {
600
- if (Array.isArray(r) ? r.find((c) => c.endsWith(`.${t}`)) : r.endsWith(`.${t}`)) {
601
- this._resolveField(e, t, s);
602
- return;
603
- }
604
- const o = e.component ? `${e.component}.${t}` : t;
605
- (Array.isArray(r) ? r.includes(o) : r === o) && this._resolveField(e, t, s);
606
- }
607
- /**
608
- * Recursively traverses and resolves relations in the story content tree
609
- * @param story - The story object containing the content to process
610
- * @param fields - The relation patterns to resolve
611
- * @param resolveId - The unique identifier for the current resolution context
612
- */
613
- iterateTree(e, t, r) {
614
- const s = (o, c = "") => {
615
- if (!(!o || o._stopResolving)) {
616
- if (Array.isArray(o))
617
- o.forEach((l, i) => s(l, `${c}[${i}]`));
618
- else if (typeof o == "object")
619
- for (const l in o) {
620
- const i = c ? `${c}.${l}` : l;
621
- (o.component && o._uid || o.type === "link") && (this._insertRelations(o, l, t, r), this._insertLinks(o, l, r)), s(o[l], i);
622
- }
623
- }
624
- };
625
- s(e.content);
626
- }
627
- async resolveLinks(e, t, r) {
628
- let s = [];
629
- if (e.link_uuids) {
630
- const o = e.link_uuids.length, c = [], l = 50;
631
- for (let i = 0; i < o; i += l) {
632
- const h = Math.min(o, i + l);
633
- c.push(e.link_uuids.slice(i, h));
634
- }
635
- for (let i = 0; i < c.length; i++)
636
- (await this.getStories({
637
- per_page: l,
638
- language: t.language,
639
- version: t.version,
640
- starts_with: t.starts_with,
641
- by_uuids: c[i].join(",")
642
- })).data.stories.forEach(
643
- (h) => {
644
- s.push(h);
645
- }
646
- );
647
- } else
648
- s = e.links;
649
- s.forEach((o) => {
650
- this.links[r][o.uuid] = {
651
- ...o,
652
- _stopResolving: !0
653
- };
654
- });
655
- }
656
- async resolveRelations(e, t, r) {
657
- let s = [];
658
- if (e.rel_uuids) {
659
- const o = e.rel_uuids.length, c = [], l = 50;
660
- for (let i = 0; i < o; i += l) {
661
- const h = Math.min(o, i + l);
662
- c.push(e.rel_uuids.slice(i, h));
663
- }
664
- for (let i = 0; i < c.length; i++)
665
- (await this.getStories({
666
- per_page: l,
667
- language: t.language,
668
- version: t.version,
669
- starts_with: t.starts_with,
670
- by_uuids: c[i].join(","),
671
- excluding_fields: t.excluding_fields
672
- })).data.stories.forEach((h) => {
673
- s.push(h);
674
- });
675
- s.length > 0 && (e.rels = s, delete e.rel_uuids);
676
- } else
677
- s = e.rels;
678
- s && s.length > 0 && s.forEach((o) => {
679
- this.relations[r][o.uuid] = {
680
- ...o,
681
- _stopResolving: !0
682
- };
683
- });
684
- }
685
- /**
686
- *
687
- * @param responseData
688
- * @param params
689
- * @param resolveId
690
- * @description Resolves the relations and links of the stories
691
- * @returns Promise<void>
692
- *
693
- */
694
- async resolveStories(e, t, r) {
695
- var s, o;
696
- let c = [];
697
- if (this.links[r] = {}, this.relations[r] = {}, typeof t.resolve_relations < "u" && t.resolve_relations.length > 0 && (typeof t.resolve_relations == "string" && (c = t.resolve_relations.split(",")), await this.resolveRelations(e, t, r)), t.resolve_links && ["1", "story", "url", "link"].includes(t.resolve_links) && ((s = e.links) != null && s.length || (o = e.link_uuids) != null && o.length) && await this.resolveLinks(e, t, r), this.resolveNestedRelations)
698
- for (const l in this.relations[r])
699
- this.iterateTree(
700
- this.relations[r][l],
701
- c,
702
- r
703
- );
704
- e.story ? this.iterateTree(e.story, c, r) : e.stories.forEach((l) => {
705
- this.iterateTree(l, c, r);
706
- }), this.stringifiedStoriesCache = {}, delete this.links[r], delete this.relations[r];
707
- }
708
- async cacheResponse(e, t, r, s) {
709
- const o = N({ url: e, params: t }), c = this.cacheProvider();
710
- if (t.version === "published" && e !== "/cdn/spaces/me") {
711
- const l = await c.get(o);
712
- if (l)
713
- return Promise.resolve(l);
714
- }
715
- return new Promise(async (l, i) => {
716
- var h;
717
- try {
718
- const f = await this.throttle(
719
- "get",
720
- e,
721
- t,
722
- s
723
- );
724
- if (f.status !== 200)
725
- return i(f);
726
- let y = { data: f.data, headers: f.headers };
727
- if ((h = f.headers) != null && h["per-page"] && (y = Object.assign({}, y, {
728
- perPage: f.headers["per-page"] ? Number.parseInt(f.headers["per-page"]) : 0,
729
- total: f.headers["per-page"] ? Number.parseInt(f.headers.total) : 0
730
- })), y.data.story || y.data.stories) {
731
- const T = this.resolveCounter = ++this.resolveCounter % 1e3;
732
- await this.resolveStories(y.data, t, `${T}`), y = await this.processInlineAssets(y);
733
- }
734
- t.version === "published" && e !== "/cdn/spaces/me" && await c.set(o, y);
735
- const $ = this.cache.clear === "onpreview" && t.version === "draft" || this.cache.clear === "auto";
736
- return t.token && y.data.cv && ($ && E[t.token] && E[t.token] !== y.data.cv && await this.flushCache(), E[t.token] = y.data.cv), l(y);
737
- } catch (f) {
738
- if (f.response && f.status === 429 && (r = typeof r > "u" ? 0 : r + 1, r < this.maxRetries))
739
- return console.log(
740
- `Hit rate limit. Retrying in ${this.retriesDelay / 1e3} seconds.`
741
- ), await fe(this.retriesDelay), this.cacheResponse(e, t, r).then(l).catch(i);
742
- i(f);
743
- }
744
- });
745
- }
746
- throttledRequest(e, t, r, s) {
747
- return this.client.setFetchOptions(s), this.client[e](t, r);
748
- }
749
- cacheVersions() {
750
- return E;
751
- }
752
- cacheVersion() {
753
- return E[this.accessToken];
754
- }
755
- setCacheVersion(e) {
756
- this.accessToken && (E[this.accessToken] = e);
757
- }
758
- clearCacheVersion() {
759
- this.accessToken && (E[this.accessToken] = 0);
760
- }
761
- cacheProvider() {
762
- switch (this.cache.type) {
763
- case "memory":
764
- return {
765
- get(e) {
766
- return Promise.resolve(j[e]);
767
- },
768
- getAll() {
769
- return Promise.resolve(j);
770
- },
771
- set(e, t) {
772
- return j[e] = t, Promise.resolve(void 0);
773
- },
774
- flush() {
775
- return j = {}, Promise.resolve(void 0);
776
- }
777
- };
778
- case "custom":
779
- if (this.cache.custom)
780
- return this.cache.custom;
781
- // eslint-disable-next-line no-fallthrough
782
- default:
783
- return {
784
- get() {
785
- return Promise.resolve();
786
- },
787
- getAll() {
788
- return Promise.resolve(void 0);
789
- },
790
- set() {
791
- return Promise.resolve(void 0);
792
- },
793
- flush() {
794
- return Promise.resolve(void 0);
795
- }
796
- };
797
- }
798
- }
799
- async flushCache() {
800
- return await this.cacheProvider().flush(), this.clearCacheVersion(), this;
801
- }
802
- async processInlineAssets(e) {
803
- if (!this.inlineAssets)
804
- return e;
805
- const t = (r) => {
806
- if (!r || typeof r != "object")
807
- return r;
808
- if (Array.isArray(r))
809
- return r.map((o) => t(o));
810
- let s = { ...r };
811
- s.fieldtype === "asset" && Array.isArray(e.data.assets) && (s = {
812
- ...s,
813
- ...e.data.assets.find((o) => o.id === s.id)
814
- });
815
- for (const o in s)
816
- typeof s[o] == "object" && (s[o] = t(s[o]));
817
- return s;
818
- };
819
- return e.data.story && (e.data.story.content = t(e.data.story.content)), e.data.stories && (e.data.stories = e.data.stories.map((r) => (r.content = t(r.content), r))), e;
820
- }
821
- }
822
- const Te = (n = {}) => {
823
- const { apiOptions: e } = n;
824
- if (!e || !e.accessToken) {
825
- console.error(
826
- "You need to provide an access token to interact with Storyblok API. Read https://www.storyblok.com/docs/api/content-delivery#topics/authentication"
827
- );
828
- return;
829
- }
830
- return { storyblokApi: new we(e) };
831
- }, _e = (n) => {
832
- if (typeof n != "object" || typeof n._editable > "u")
833
- return {};
834
- try {
835
- const e = JSON.parse(
836
- n._editable.replace(/^<!--#storyblok#/, "").replace(/-->$/, "")
837
- );
838
- return e ? {
839
- "data-blok-c": JSON.stringify(e),
840
- "data-blok-uid": `${e.id}-${e.uid}`
841
- } : {};
842
- } catch {
843
- return {};
844
- }
845
- };
846
- let x = "https://app.storyblok.com/f/storyblok-v2-latest.js";
847
- const $e = (n, e, t = {}) => {
848
- var r;
849
- const s = !(typeof window > "u") && typeof window.storyblokRegisterEvent < "u", o = new URL((r = window.location) == null ? void 0 : r.href).searchParams.get(
850
- "_storyblok"
851
- ), c = o !== null && +o === n;
852
- if (!(!s || !c)) {
853
- if (!n) {
854
- console.warn("Story ID is not defined. Please provide a valid ID.");
855
- return;
856
- }
857
- window.storyblokRegisterEvent(() => {
858
- new window.StoryblokBridge(t).on(["input", "published", "change"], (l) => {
859
- var i;
860
- l && (l.action === "input" && ((i = l.story) == null ? void 0 : i.id) === n ? e(l.story) : (l.action === "change" || l.action === "published") && l.storyId === n && window.location.reload());
861
- });
862
- });
863
- }
864
- }, Re = (n = {}) => {
865
- var e, t;
866
- const {
867
- bridge: r,
868
- accessToken: s,
869
- use: o = [],
870
- apiOptions: c = {},
871
- bridgeUrl: l
872
- } = n;
873
- c.accessToken = c.accessToken || s;
874
- const i = { bridge: r, apiOptions: c };
875
- let h = {};
876
- o.forEach((y) => {
877
- h = { ...h, ...y(i) };
878
- }), l && (x = l);
879
- const f = !(typeof window > "u") && ((t = (e = window.location) == null ? void 0 : e.search) == null ? void 0 : t.includes("_storyblok_tk"));
880
- return r !== !1 && f && F(x), h;
881
- };
882
- function Ee(n, e) {
883
- return le(e).render(n);
884
- }
885
- const Ae = () => F(x);
886
- export {
887
- v as BlockTypes,
888
- R as MarkTypes,
889
- J as TextTypes,
890
- Te as apiPlugin,
891
- Ae as loadStoryblokBridge,
892
- $e as registerStoryblokBridge,
893
- Ee as renderRichText,
894
- le as richTextResolver,
895
- _e as storyblokEditable,
896
- Re as storyblokInit,
897
- $e as useStoryblokBridge
898
- };