@shopbite-de/storefront 2.2.1 → 2.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 (69) hide show
  1. package/.github/workflows/build.yaml +2 -2
  2. package/.github/workflows/ci.yaml +11 -11
  3. package/.nuxtrc +1 -1
  4. package/CLAUDE.md +13 -7
  5. package/app/app.vue +10 -7
  6. package/app/components/Address/Fields.vue +1 -2
  7. package/app/components/Category/Breadcrumb.vue +9 -10
  8. package/app/components/Checkout/Summary.vue +27 -2
  9. package/app/components/Header.vue +6 -2
  10. package/app/components/Menu/BonCard.vue +1 -2
  11. package/app/components/Order/Confirmation.vue +1 -2
  12. package/app/components/Product/QuickView.vue +1 -2
  13. package/app/composables/useBusinessHours.ts +35 -14
  14. package/app/composables/useHolidays.ts +31 -11
  15. package/app/composables/useHomeMenuCategories.ts +6 -34
  16. package/app/composables/useLiveShopData.ts +17 -0
  17. package/app/composables/useNavigation.ts +14 -66
  18. package/app/composables/useNavigationSearch.ts +8 -31
  19. package/app/composables/useRestaurantSchema.ts +2 -13
  20. package/app/composables/useSeoUrlRoute.ts +21 -0
  21. package/app/composables/useShopBiteConfig.ts +50 -6
  22. package/app/composables/useTopSellers.ts +2 -43
  23. package/app/error.vue +4 -0
  24. package/docs/notes/2026-09-10-issue-275-accessibility.md +2 -2
  25. package/docs/notes/2026-09-12-issue-327-home-hero.md +1 -1
  26. package/docs/notes/2026-09-13-issue-332-home-info-cards.md +1 -3
  27. package/docs/notes/2026-09-21-issue-273-cache-and-demo-video.md +1 -1
  28. package/docs/notes/2026-09-21-issue-363-non-fatal-404.md +1 -1
  29. package/docs/notes/2026-09-23-issue-388-home-sections.md +2 -2
  30. package/docs/notes/2026-10-05-issue-401-restaurant-schema-ordering.md +1 -1
  31. package/docs/notes/2026-11-18-dependency-update.md +118 -0
  32. package/modules/theme.ts +1 -1
  33. package/node.dockerfile +7 -7
  34. package/nuxt.config.ts +22 -1
  35. package/package.json +40 -40
  36. package/pnpm-workspace.yaml +0 -2
  37. package/server/api/_cache/purge.post.ts +6 -3
  38. package/server/api/breadcrumb/[categoryId].get.ts +31 -0
  39. package/server/api/navigation/[type].get.ts +97 -0
  40. package/server/api/payment-methods.get.ts +29 -0
  41. package/server/api/seo-url/index.get.ts +17 -0
  42. package/server/api/seo-url/known.get.ts +33 -0
  43. package/server/api/shopbite/business-hours.get.ts +22 -0
  44. package/server/api/shopbite/config.get.ts +6 -0
  45. package/server/api/shopbite/holidays.get.ts +20 -0
  46. package/server/api/top-sellers.get.ts +59 -0
  47. package/server/plugins/ai-crawlers.ts +1 -1
  48. package/server/plugins/site-url.ts +2 -2
  49. package/server/routes/llms.txt.ts +6 -2
  50. package/server/utils/backoff.ts +67 -0
  51. package/server/utils/cachePurge.ts +45 -12
  52. package/server/utils/menuRoot.ts +24 -18
  53. package/server/utils/seoPaths.ts +130 -0
  54. package/server/utils/seoUrlCache.ts +98 -0
  55. package/server/utils/shopBiteConfig.ts +30 -0
  56. package/server/utils/storeApi.ts +25 -1
  57. package/test/a11y/presets.test.ts +3 -1
  58. package/test/layer/nuxt.config.ts +1 -1
  59. package/test/nuxt/CheckoutOnePage.test.ts +2 -0
  60. package/test/nuxt/CheckoutSummary.test.ts +38 -2
  61. package/test/nuxt/HeaderFooterPreset.test.ts +13 -4
  62. package/test/nuxt/liveShopData.test.ts +114 -0
  63. package/test/nuxt/useShopBiteConfig.test.ts +22 -0
  64. package/test/nuxt/useTopSellers.test.ts +10 -27
  65. package/test/unit/cachePurge.spec.ts +41 -0
  66. package/test/unit/layoutCacheRoutes.spec.ts +566 -0
  67. package/test/unit/nitroStubs.ts +99 -0
  68. package/test/unit/seoPaths.spec.ts +117 -0
  69. package/patches/@shopware__nuxt-module@1.5.2.patch +0 -13
@@ -52,4 +52,26 @@ describe("useShopBiteConfig", () => {
52
52
  expect(deliveryTime.value).toBe(45);
53
53
  expect(isCheckoutEnabled.value).toBe(true);
54
54
  });
55
+
56
+ it("checks the checkout switch with Shopware before an order", async () => {
57
+ mockInvoke.mockResolvedValue({
58
+ data: { deliveryTime: 30, isCheckoutEnabled: false },
59
+ });
60
+
61
+ const { checkCheckoutEnabled, isCheckoutEnabled } = useShopBiteConfig();
62
+
63
+ expect(await checkCheckoutEnabled()).toBe(false);
64
+ expect(isCheckoutEnabled.value).toBe(false);
65
+ expect(mockInvoke).toHaveBeenCalledWith(
66
+ "shopbite.config.get get /shopbite/config",
67
+ );
68
+ });
69
+
70
+ it("reports an unknown checkout switch when Shopware fails", async () => {
71
+ mockInvoke.mockRejectedValue(new Error("offline"));
72
+
73
+ const { checkCheckoutEnabled } = useShopBiteConfig();
74
+
75
+ expect(await checkCheckoutEnabled([])).toBeNull();
76
+ });
55
77
  });
@@ -1,44 +1,27 @@
1
- import { describe, it, expect, vi, beforeEach } from "vitest";
2
- import { mockNuxtImport } from "@nuxt/test-utils/runtime";
1
+ import { describe, it, expect, vi } from "vitest";
2
+ import { registerEndpoint } from "@nuxt/test-utils/runtime";
3
3
  import { useTopSellers } from "~/composables/useTopSellers";
4
4
 
5
- const { mockInvoke } = vi.hoisted(() => ({
6
- mockInvoke: vi.fn(),
7
- }));
5
+ const { topSellers } = vi.hoisted(() => ({ topSellers: vi.fn() }));
8
6
 
9
- mockNuxtImport("useShopwareContext", () => {
10
- return () => ({
11
- apiClient: {
12
- invoke: mockInvoke,
13
- },
14
- });
15
- });
7
+ registerEndpoint("/api/top-sellers", () => topSellers());
16
8
 
17
9
  describe("useTopSellers", () => {
18
- beforeEach(() => {
19
- vi.clearAllMocks();
20
- });
21
-
22
- it("should load top sellers successfully", async () => {
10
+ it("should load top sellers from the server cache", async () => {
23
11
  const mockElements = [{ id: "1", name: "Top Product" }];
24
- mockInvoke.mockResolvedValue({
25
- data: {
26
- elements: mockElements,
27
- },
28
- });
12
+ topSellers.mockReturnValue(mockElements);
29
13
 
30
14
  const { loadTopSellers } = useTopSellers();
31
15
  const result = await loadTopSellers();
32
16
 
33
- expect(mockInvoke).toHaveBeenCalledWith(
34
- "readProduct post /product",
35
- expect.any(Object),
36
- );
17
+ expect(topSellers).toHaveBeenCalled();
37
18
  expect(result).toEqual(mockElements);
38
19
  });
39
20
 
40
21
  it("should return empty array on error", async () => {
41
- mockInvoke.mockRejectedValue(new Error("Network error"));
22
+ topSellers.mockImplementation(() => {
23
+ throw new Error("Network error");
24
+ });
42
25
 
43
26
  // Silence console.error for this test
44
27
  const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
@@ -16,6 +16,20 @@ const KEYS = [
16
16
  `cache:nitro:handlers:sitemap:urls.json`,
17
17
  `cache:nitro:routes:_:llmstxt.json`,
18
18
  ];
19
+ // layout data of every page, purged with any target
20
+ const LAYOUT_KEYS = [
21
+ `cache:nitro:handlers:navigation:navigationmenu${PIZZA}.json`,
22
+ `cache:nitro:handlers:navigation:navigationmainmainnavigation.json`,
23
+ `cache:nitro:handlers:breadcrumb:breadcrumb${PIZZA}.json`,
24
+ `cache:nitro:handlers:business-hours:businesshours.json`,
25
+ `cache:nitro:handlers:holidays:holidays.json`,
26
+ `cache:nitro:handlers:payment-methods:paymentmethods.json`,
27
+ `cache:nitro:handlers:top-sellers:topsellers.json`,
28
+ `cache:nitro:functions:seo-url:3f786850e387550fdab836ed7e6dc881de23001b.json`,
29
+ `cache:nitro:functions:seo-paths:seo-paths.json`,
30
+ `cache:nitro:functions:shopbite-config:shopbite-config.json`,
31
+ ];
32
+ const OTHER_FUNCTION = `cache:nitro:functions:_:abc.json`;
19
33
 
20
34
  describe("keysToPurge", () => {
21
35
  it("purges every Store API cache without a target", () => {
@@ -45,6 +59,33 @@ describe("keysToPurge", () => {
45
59
  ]);
46
60
  });
47
61
 
62
+ it("purges the layout data with every target", () => {
63
+ const keys = [...KEYS, ...LAYOUT_KEYS, OTHER_FUNCTION];
64
+ for (const target of [
65
+ {},
66
+ { products: [MARGHERITA] },
67
+ { categories: [PIZZA] },
68
+ ]) {
69
+ const purged = keysToPurge(keys, target);
70
+ expect(purged).toEqual(expect.arrayContaining(LAYOUT_KEYS));
71
+ expect(purged).not.toContain(OTHER_FUNCTION);
72
+ }
73
+ });
74
+
75
+ it("purges only the layout data and llms.txt for a layout target", () => {
76
+ const keys = [...KEYS, ...LAYOUT_KEYS, OTHER_FUNCTION];
77
+ const layout = LAYOUT_KEYS.filter((k) => !k.includes("top-sellers"));
78
+ expect(keysToPurge(keys, { layout: true })).toEqual([KEYS[8], ...layout]);
79
+ });
80
+
81
+ it("adds the layout data to a menu target, not other products", () => {
82
+ const keys = [...KEYS, ...LAYOUT_KEYS];
83
+ const purged = keysToPurge(keys, { products: [SCHNITZEL], layout: true });
84
+ expect(purged).toEqual(expect.arrayContaining(LAYOUT_KEYS));
85
+ expect(purged).toContain(KEYS[1]);
86
+ expect(purged).not.toContain(KEYS[0]);
87
+ });
88
+
48
89
  it("finds ids written with dashes or upper case", () => {
49
90
  const dashed = `0197BAF0-A6A9-71EA-ADA5-9ED5C84138DE`;
50
91
  expect(keysToPurge(KEYS, { products: [dashed] })).toContain(KEYS[0]);
@@ -0,0 +1,566 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
+ import {
3
+ stubNitro,
4
+ type CachedFunction,
5
+ type CachedHandler,
6
+ } from "./nitroStubs";
7
+
8
+ const ROOT = "018dadb399837af3aa669c8fff4f4d6c";
9
+ const SECTION = "0197baf0a6a971eaada59ed5c84138de";
10
+
11
+ beforeEach(() => {
12
+ vi.resetModules();
13
+ });
14
+
15
+ afterEach(() => {
16
+ vi.unstubAllGlobals();
17
+ });
18
+
19
+ /** What ofetch throws when Shopware cannot be reached. */
20
+ const fetchFailed = () =>
21
+ Object.assign(new Error("[GET] fetch failed"), { name: "FetchError" });
22
+
23
+ const load = async <T>(path: string): Promise<T> =>
24
+ (await import(/* @vite-ignore */ path)).default as T;
25
+
26
+ describe("/api/navigation/[type]", () => {
27
+ it("keys and fetches the menu navigations by the menu root", async () => {
28
+ const stubs = stubNitro({
29
+ menuRootIdStrict: vi.fn().mockResolvedValue(ROOT),
30
+ });
31
+ stubs.storeApiPost!.mockResolvedValue([]);
32
+ const { handler, opts } = await load<CachedHandler>(
33
+ "../../server/api/navigation/[type].get",
34
+ );
35
+
36
+ expect(await opts.getKey({ params: { type: "menu" } })).toBe(
37
+ `navigation-menu-${ROOT}`,
38
+ );
39
+ expect(await opts.getKey({ params: { type: "main" } })).toBe(
40
+ "navigation-main-main-navigation",
41
+ );
42
+ await handler({ params: { type: "home" } });
43
+ expect(stubs.storeApiPost).toHaveBeenCalledWith(
44
+ `/navigation/main-navigation/${ROOT}`,
45
+ expect.objectContaining({ depth: 1 }),
46
+ );
47
+ });
48
+
49
+ it("resolves the menu root once for key and request", async () => {
50
+ const strict = vi
51
+ .fn()
52
+ .mockResolvedValueOnce(ROOT)
53
+ .mockResolvedValue("0".repeat(32));
54
+ const stubs = stubNitro({ menuRootIdStrict: strict });
55
+ stubs.storeApiPost!.mockResolvedValue([]);
56
+ const { handler, opts } = await load<CachedHandler>(
57
+ "../../server/api/navigation/[type].get",
58
+ );
59
+ const event = { params: { type: "menu" }, context: {} };
60
+
61
+ expect(await opts.getKey(event)).toBe(`navigation-menu-${ROOT}`);
62
+ await handler(event);
63
+ expect(stubs.storeApiPost).toHaveBeenCalledWith(
64
+ `/navigation/main-navigation/${ROOT}`,
65
+ expect.anything(),
66
+ );
67
+ });
68
+
69
+ it("caches nothing when the menu root cannot be resolved", async () => {
70
+ stubNitro({
71
+ menuRootIdStrict: vi.fn().mockRejectedValue(new Error("down")),
72
+ });
73
+ const { opts } = await load<CachedHandler>(
74
+ "../../server/api/navigation/[type].get",
75
+ );
76
+
77
+ // a rejected key fails the request instead of caching the fallback root
78
+ await expect(opts.getKey({ params: { type: "menu" } })).rejects.toThrow();
79
+ });
80
+ });
81
+
82
+ describe("/api/breadcrumb/[categoryId]", () => {
83
+ it("answers an unknown category with 404, so it is not cached", async () => {
84
+ const stubs = stubNitro();
85
+ stubs.storeApiGet!.mockResolvedValue([]);
86
+ const { handler } = await load<CachedHandler>(
87
+ "../../server/api/breadcrumb/[categoryId].get",
88
+ );
89
+
90
+ await expect(
91
+ handler({ params: { categoryId: SECTION } }),
92
+ ).rejects.toMatchObject({ statusCode: 404 });
93
+ });
94
+
95
+ it("returns the breadcrumb of a known category", async () => {
96
+ const stubs = stubNitro();
97
+ const crumbs = [{ name: "Pizza", path: "Speisekarte/Pizza/" }];
98
+ stubs.storeApiGet!.mockResolvedValue(crumbs);
99
+ const { handler } = await load<CachedHandler>(
100
+ "../../server/api/breadcrumb/[categoryId].get",
101
+ );
102
+
103
+ expect(await handler({ params: { categoryId: SECTION } })).toEqual(crumbs);
104
+ });
105
+ });
106
+
107
+ describe("time-critical layout data", () => {
108
+ it("never serves business hours or holidays older than their TTL", async () => {
109
+ stubNitro();
110
+ for (const name of ["business-hours", "holidays"]) {
111
+ vi.resetModules();
112
+ const { opts } = await load<CachedHandler>(
113
+ `../../server/api/shopbite/${name}.get`,
114
+ );
115
+ expect(opts.swr).toBe(false);
116
+ }
117
+ });
118
+
119
+ it("keeps the plugin config for the config TTL, without stale answers", async () => {
120
+ const stubs = stubNitro();
121
+ stubs.storeApiGet!.mockResolvedValue({ isCheckoutEnabled: true });
122
+ const { shopBiteConfig } =
123
+ await import("../../server/utils/shopBiteConfig");
124
+
125
+ expect(stubs.defineCachedFunction!.mock.calls[0]![1]).toMatchObject({
126
+ name: "shopbite-config",
127
+ maxAge: 60,
128
+ swr: false,
129
+ });
130
+ expect(await shopBiteConfig()).toEqual({ isCheckoutEnabled: true });
131
+ expect(await shopBiteConfig()).toEqual({ isCheckoutEnabled: true });
132
+ expect(stubs.storeApiGet).toHaveBeenCalledOnce();
133
+ expect(stubs.storeApiGet).toHaveBeenCalledWith("/shopbite/config");
134
+ });
135
+ });
136
+
137
+ describe("menuRootId", () => {
138
+ it("falls back to the navigation root without caching the failure", async () => {
139
+ const stubs = stubNitro();
140
+ stubs.storeApiGet!.mockRejectedValueOnce(fetchFailed());
141
+ stubs.storeApiGet!.mockResolvedValueOnce({ menuCategoryId: ROOT });
142
+ const { menuRootId, menuRootIdStrict } =
143
+ await import("../../server/utils/menuRoot");
144
+
145
+ vi.useFakeTimers();
146
+ try {
147
+ expect(await menuRootId()).toBe("main-navigation");
148
+ // asked again after the pause, not answered with the fallback
149
+ vi.advanceTimersByTime(31_000);
150
+ expect(await menuRootIdStrict()).toBe(ROOT);
151
+ } finally {
152
+ vi.useRealTimers();
153
+ }
154
+ });
155
+
156
+ it("rejects in the strict variant when the config fails", async () => {
157
+ const stubs = stubNitro();
158
+ stubs.storeApiGet!.mockRejectedValue(fetchFailed());
159
+ const { menuRootIdStrict } = await import("../../server/utils/menuRoot");
160
+
161
+ await expect(menuRootIdStrict()).rejects.toMatchObject({
162
+ statusCode: 503,
163
+ });
164
+ });
165
+ });
166
+
167
+ describe("SEO URL caches", () => {
168
+ const loadCaches = async () =>
169
+ (await import("../../server/utils/seoUrlCache")) as unknown as {
170
+ findSeoUrl: CachedFunction<[string], unknown>;
171
+ knownSeoPaths: CachedFunction<[], { paths: string[] | null }>;
172
+ };
173
+
174
+ const PIZZA = {
175
+ seoPathInfo: "Speisekarte/Pizza/",
176
+ foreignKey: SECTION,
177
+ routeName: "frontend.navigation.page",
178
+ };
179
+ const NAVIGATION = {
180
+ pathInfo: `/navigation/${SECTION}`,
181
+ seoPathInfo: "Speisekarte/Pizza/",
182
+ foreignKey: SECTION,
183
+ };
184
+
185
+ /** Shopware's lookup: case-, accent- and trailing-space-insensitive. */
186
+ function stubShopwareSeoUrls() {
187
+ const stubs = stubNitro();
188
+ const loose = (value: string) =>
189
+ value
190
+ .normalize("NFD")
191
+ .replace(/\p{Diacritic}/gu, "")
192
+ .toLowerCase()
193
+ .replace(/ +$/, "");
194
+ stubs.storeApiPost!.mockImplementation(
195
+ async (
196
+ _path: string,
197
+ criteria: { filter: { field: string; value: string }[] },
198
+ ) => {
199
+ const { field, value } = criteria.filter[0]!;
200
+ if (
201
+ field === "seoPathInfo" &&
202
+ loose(value) === loose(PIZZA.seoPathInfo)
203
+ )
204
+ return { elements: [PIZZA] };
205
+ if (field === "pathInfo" && loose(value) === loose(NAVIGATION.pathInfo))
206
+ return { elements: [NAVIGATION] };
207
+ return { elements: [] };
208
+ },
209
+ );
210
+ return stubs;
211
+ }
212
+
213
+ it("keeps SEO URL matches, one entry for all casings of a path", async () => {
214
+ const stubs = stubShopwareSeoUrls();
215
+ const { findSeoUrl } = await loadCaches();
216
+
217
+ expect(await findSeoUrl("/Speisekarte/Pizza/")).toEqual(PIZZA);
218
+ expect(await findSeoUrl("/speisekarte/pizza/")).toEqual(PIZZA);
219
+ expect(await findSeoUrl("/Speisekarte/Pizza/")).toEqual(PIZZA);
220
+ expect(stubs.storeApiPost).toHaveBeenCalledTimes(1);
221
+ });
222
+
223
+ it("caches neither misses nor loose matches (accents, trailing spaces)", async () => {
224
+ const stubs = stubShopwareSeoUrls();
225
+ const { findSeoUrl } = await loadCaches();
226
+ const variants = [
227
+ "/Speisekarte/Pizza/ ",
228
+ "/Speisekarte/Pizza/ ",
229
+ "/Spéisekarte/Pizza/",
230
+ "/Spêisekárte/Pizzà/",
231
+ ];
232
+
233
+ for (const round of [1, 2]) {
234
+ for (const path of variants) {
235
+ expect(await findSeoUrl(path), `${path} round ${round}`).toEqual(PIZZA);
236
+ }
237
+ expect(await findSeoUrl("/wp-admin/")).toBeNull();
238
+ }
239
+ expect(stubs.storeApiPost).toHaveBeenCalledTimes(2 * (variants.length + 1));
240
+ });
241
+
242
+ it("keys technical URLs apart from SEO paths of the same spelling", async () => {
243
+ stubShopwareSeoUrls();
244
+ const { findSeoUrl } = await loadCaches();
245
+
246
+ expect(await findSeoUrl(`/navigation/${SECTION}`)).toEqual(NAVIGATION);
247
+ // not a technical URL (case-sensitive prefix): a SEO path lookup
248
+ expect(await findSeoUrl(`/Navigation/${SECTION}`)).toBeNull();
249
+ });
250
+
251
+ it("asks Shopware page by page with `page` for the known paths", async () => {
252
+ const stubs = stubNitro();
253
+ const page = (n: number, prefix: string) =>
254
+ Array.from({ length: n }, (_, i) => ({ seoPathInfo: `${prefix}${i}/` }));
255
+ stubs.storeApiPost!.mockImplementation(
256
+ async (_path: string, criteria: { page: number; filter: unknown[] }) => {
257
+ const canonical = JSON.stringify(criteria.filter).includes("true");
258
+ if (!canonical) return { elements: [] };
259
+ return {
260
+ elements: page(criteria.page < 3 ? 100 : 5, `p${criteria.page}-`),
261
+ };
262
+ },
263
+ );
264
+ const { knownSeoPaths } = await loadCaches();
265
+
266
+ const { paths } = await knownSeoPaths();
267
+ expect(paths).toHaveLength(205);
268
+ // stable order, so pages neither skip nor repeat rows
269
+ for (const [, criteria] of stubs.storeApiPost!.mock.calls) {
270
+ expect(criteria.sort).toEqual([{ field: "id", order: "ASC" }]);
271
+ }
272
+ expect(paths).toContain("p2-7");
273
+ expect(knownSeoPaths.opts.swr).toBe(false);
274
+ });
275
+
276
+ it("keeps an answer for a list too long to filter by", async () => {
277
+ const stubs = stubNitro();
278
+ stubs.storeApiPost!.mockImplementation(async () => ({
279
+ elements: Array.from({ length: 100 }, (_, i) => ({
280
+ seoPathInfo: `${i}`,
281
+ })),
282
+ }));
283
+ const { knownSeoPaths } = await loadCaches();
284
+
285
+ // stored (a value, not undefined), so the next request does not page again
286
+ expect(await knownSeoPaths()).toMatchObject({ paths: null });
287
+ const calls = stubs.storeApiPost!.mock.calls.length;
288
+ await knownSeoPaths();
289
+ expect(stubs.storeApiPost!.mock.calls.length).toBe(calls);
290
+ });
291
+ });
292
+
293
+ describe("/api/seo-url/known", () => {
294
+ const ask = async (
295
+ knownSeoPaths: ReturnType<typeof vi.fn>,
296
+ paths: string[],
297
+ ) => {
298
+ stubNitro({ knownSeoPaths });
299
+ const handler = await load<(event: unknown) => Promise<unknown>>(
300
+ "../../server/api/seo-url/known.get",
301
+ );
302
+ const results = [];
303
+ for (const path of paths) results.push(await handler({ query: { path } }));
304
+ return results;
305
+ };
306
+
307
+ const HOSTILE = ["/navigation/zzz", "/%ff", "/%252e%252e/etc/passwd"];
308
+
309
+ it("rejects hostile paths while the list is too long to filter by", async () => {
310
+ const known = vi.fn().mockResolvedValue({ paths: null, loadedAt: 1 });
311
+ expect(await ask(known, HOSTILE)).toEqual(
312
+ HOSTILE.map(() => ({ known: false })),
313
+ );
314
+ });
315
+
316
+ it("rejects hostile paths while backing off after a failed load", async () => {
317
+ vi.spyOn(console, "error").mockImplementation(() => {});
318
+ const known = vi.fn().mockRejectedValue(new Error("down"));
319
+ // the first request trips the backoff, the others are answered during it
320
+ expect(await ask(known, ["/wp-admin/", ...HOSTILE])).toEqual([
321
+ { known: true },
322
+ ...HOSTILE.map(() => ({ known: false })),
323
+ ]);
324
+ expect(known).toHaveBeenCalledTimes(1);
325
+ });
326
+
327
+ it("rejects paths no category had and lets known ones through", async () => {
328
+ const known = vi
329
+ .fn()
330
+ .mockResolvedValue({ paths: ["speisekarte/pizza"], loadedAt: 1 });
331
+ expect(await ask(known, ["/wp-admin/", "/Speisekarte/Pizza"])).toEqual([
332
+ { known: false },
333
+ { known: true },
334
+ ]);
335
+ });
336
+
337
+ it("lets everything through for a list too long to filter by", async () => {
338
+ const known = vi.fn().mockResolvedValue({ paths: null, loadedAt: 1 });
339
+ expect(await ask(known, ["/wp-admin/"])).toEqual([{ known: true }]);
340
+ });
341
+
342
+ it("backs off after a failed load instead of asking on every request", async () => {
343
+ vi.spyOn(console, "error").mockImplementation(() => {});
344
+ const known = vi.fn().mockRejectedValue(new Error("down"));
345
+ expect(await ask(known, ["/wp-admin/", "/.git/HEAD"])).toEqual([
346
+ { known: true },
347
+ { known: true },
348
+ ]);
349
+ expect(known).toHaveBeenCalledTimes(1);
350
+ });
351
+ });
352
+
353
+ describe("plugin config during an outage", () => {
354
+ const CONFIG = { menuCategoryId: ROOT, isCheckoutEnabled: true };
355
+
356
+ beforeEach(() => {
357
+ vi.useFakeTimers();
358
+ vi.setSystemTime(0);
359
+ });
360
+
361
+ afterEach(() => {
362
+ vi.useRealTimers();
363
+ });
364
+
365
+ it("keeps the last good config and asks again only after a pause", async () => {
366
+ const stubs = stubNitro();
367
+ stubs.storeApiGet!.mockResolvedValueOnce(CONFIG);
368
+ stubs.storeApiGet!.mockRejectedValue(fetchFailed());
369
+ const { shopBiteConfig } =
370
+ await import("../../server/utils/shopBiteConfig");
371
+
372
+ expect(await shopBiteConfig()).toEqual(CONFIG);
373
+ vi.setSystemTime(61_000); // cache entry expired
374
+ expect(await shopBiteConfig()).toEqual(CONFIG);
375
+ expect(await shopBiteConfig()).toEqual(CONFIG);
376
+ expect(stubs.storeApiGet).toHaveBeenCalledTimes(2);
377
+
378
+ vi.setSystemTime(92_000); // after the pause
379
+ await shopBiteConfig();
380
+ expect(stubs.storeApiGet).toHaveBeenCalledTimes(3);
381
+ });
382
+
383
+ it("without a good config fails fast during the pause", async () => {
384
+ const stubs = stubNitro();
385
+ stubs.storeApiGet!.mockRejectedValue(fetchFailed());
386
+ const { menuRootIdStrict } = await import("../../server/utils/menuRoot");
387
+
388
+ await expect(menuRootIdStrict()).rejects.toThrow();
389
+ await expect(menuRootIdStrict()).rejects.toThrow();
390
+ expect(stubs.storeApiGet).toHaveBeenCalledTimes(1);
391
+ });
392
+
393
+ it("keeps the menu on the last good root", async () => {
394
+ const stubs = stubNitro();
395
+ stubs.storeApiGet!.mockResolvedValueOnce(CONFIG);
396
+ stubs.storeApiGet!.mockRejectedValue(fetchFailed());
397
+ const { menuRootIdStrict } = await import("../../server/utils/menuRoot");
398
+
399
+ expect(await menuRootIdStrict()).toBe(ROOT);
400
+ vi.setSystemTime(61_000);
401
+ expect(await menuRootIdStrict()).toBe(ROOT);
402
+ });
403
+ });
404
+
405
+ describe("/api/_cache/purge", () => {
406
+ async function purge(body: unknown) {
407
+ const { keysToPurge, hasPurgeSecret } =
408
+ await import("../../server/utils/cachePurge");
409
+ const removeItem = vi.fn();
410
+ stubNitro({
411
+ useRuntimeConfig: () => ({ cachePurgeSecret: "s" }),
412
+ getHeader: () => "Bearer s",
413
+ readBody: async () => body,
414
+ useStorage: () => ({
415
+ getKeys: async () => [
416
+ "cache:nitro:handlers:holidays:holidays.json",
417
+ "cache:nitro:handlers:listing:x1.json",
418
+ ],
419
+ removeItem,
420
+ }),
421
+ keysToPurge,
422
+ hasPurgeSecret,
423
+ });
424
+ const handler = await load<(event: unknown) => Promise<unknown>>(
425
+ "../../server/api/_cache/purge.post",
426
+ );
427
+ return { result: handler({}), removeItem };
428
+ }
429
+
430
+ it("accepts a layout target", async () => {
431
+ const { result, removeItem } = await purge({ layout: true });
432
+ expect(await result).toEqual({ purged: 1 });
433
+ expect(removeItem).toHaveBeenCalledWith(
434
+ "cache:nitro:handlers:holidays:holidays.json",
435
+ );
436
+ });
437
+
438
+ it("rejects a layout target that is not a boolean", async () => {
439
+ const { result } = await purge({ layout: "yes" });
440
+ await expect(result).rejects.toMatchObject({ statusCode: 400 });
441
+ });
442
+ });
443
+
444
+ describe("cold caches during a Shopware outage", () => {
445
+ const DOWN = Object.assign(new Error("503 Service Unavailable"), {
446
+ statusCode: 503,
447
+ });
448
+
449
+ beforeEach(() => {
450
+ vi.useFakeTimers();
451
+ vi.setSystemTime(0);
452
+ });
453
+
454
+ afterEach(() => {
455
+ vi.useRealTimers();
456
+ });
457
+
458
+ const HANDLERS: { path: string; params: Record<string, string> }[] = [
459
+ {
460
+ path: "../../server/api/navigation/[type].get",
461
+ params: { type: "main" },
462
+ },
463
+ {
464
+ path: "../../server/api/navigation/[type].get",
465
+ params: { type: "menu" },
466
+ },
467
+ { path: "../../server/api/shopbite/business-hours.get", params: {} },
468
+ { path: "../../server/api/shopbite/holidays.get", params: {} },
469
+ { path: "../../server/api/payment-methods.get", params: {} },
470
+ { path: "../../server/api/top-sellers.get", params: {} },
471
+ {
472
+ path: "../../server/api/breadcrumb/[categoryId].get",
473
+ params: { categoryId: SECTION },
474
+ },
475
+ ];
476
+
477
+ for (const { path, params } of HANDLERS) {
478
+ it(`asks Shopware once per pause: ${path.split("/api/")[1]} ${JSON.stringify(params)}`, async () => {
479
+ const stubs = stubNitro({
480
+ menuRootIdStrict: vi.fn().mockResolvedValue(ROOT),
481
+ });
482
+ stubs.storeApiGet!.mockRejectedValue(DOWN);
483
+ stubs.storeApiPost!.mockRejectedValue(DOWN);
484
+ const { handler } = await load<CachedHandler>(path);
485
+ const calls = () =>
486
+ stubs.storeApiGet!.mock.calls.length +
487
+ stubs.storeApiPost!.mock.calls.length;
488
+
489
+ for (let i = 0; i < 3; i++) {
490
+ await expect(handler({ params, context: {} })).rejects.toMatchObject({
491
+ statusCode: 503,
492
+ });
493
+ }
494
+ expect(calls()).toBe(1);
495
+
496
+ vi.setSystemTime(31_000);
497
+ await expect(handler({ params, context: {} })).rejects.toThrow();
498
+ expect(calls()).toBe(2);
499
+ });
500
+ }
501
+
502
+ it("serves the last good answer per key during an outage", async () => {
503
+ const stubs = stubNitro();
504
+ const hours = { businessHours: [{ dayOfWeek: 1 }] };
505
+ stubs.storeApiGet!.mockResolvedValueOnce(hours).mockRejectedValue(DOWN);
506
+ const { handler } = await load<CachedHandler>(
507
+ "../../server/api/shopbite/business-hours.get",
508
+ );
509
+
510
+ expect(await handler({})).toEqual(hours);
511
+ expect(await handler({})).toEqual(hours);
512
+ expect(await handler({})).toEqual(hours);
513
+ expect(stubs.storeApiGet).toHaveBeenCalledTimes(2);
514
+ });
515
+
516
+ it("does not take a client error for an outage", async () => {
517
+ const stubs = stubNitro();
518
+ stubs.storeApiGet!.mockRejectedValue(
519
+ Object.assign(new Error("400"), { statusCode: 400 }),
520
+ );
521
+ const { handler } = await load<CachedHandler>(
522
+ "../../server/api/breadcrumb/[categoryId].get",
523
+ );
524
+
525
+ await expect(
526
+ handler({ params: { categoryId: SECTION } }),
527
+ ).rejects.toThrow();
528
+ await expect(
529
+ handler({ params: { categoryId: SECTION } }),
530
+ ).rejects.toThrow();
531
+ expect(stubs.storeApiGet).toHaveBeenCalledTimes(2);
532
+ });
533
+ });
534
+
535
+ describe("storeApi", () => {
536
+ it("does not retry: a failing request reaches Shopware once", async () => {
537
+ const fetch = vi.fn().mockResolvedValue({});
538
+ stubNitro({ $fetch: fetch });
539
+ const { storeApiGet, storeApiPost } =
540
+ await import("../../server/utils/storeApi");
541
+
542
+ await storeApiGet("/shopbite/holiday");
543
+ await storeApiPost("/seo-url", {});
544
+ for (const [, options] of fetch.mock.calls) {
545
+ expect(options.retry).toBe(0);
546
+ }
547
+ });
548
+ });
549
+
550
+ describe("/api/seo-url with hostile paths", () => {
551
+ it("answers without a lookup", async () => {
552
+ const findSeoUrl = vi.fn().mockResolvedValue(null);
553
+ stubNitro({ findSeoUrl });
554
+ const handler = await load<(event: unknown) => Promise<unknown>>(
555
+ "../../server/api/seo-url/index.get",
556
+ );
557
+
558
+ expect(
559
+ await handler({ query: { path: "/%c0%ae%c0%ae/etc/passwd" } }),
560
+ ).toEqual({ seoUrl: null });
561
+ expect(await handler({ query: { path: "/navigation/zzz" } })).toEqual({
562
+ seoUrl: null,
563
+ });
564
+ expect(findSeoUrl).not.toHaveBeenCalled();
565
+ });
566
+ });