@shopbite-de/storefront 2.4.0 → 2.6.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 (104) hide show
  1. package/.env.example +13 -1
  2. package/CLAUDE.md +7 -4
  3. package/api-types/storeApiSchema.json +62 -6
  4. package/api-types/storeApiTypes.d.ts +23 -4
  5. package/app/components/Checkout/DeliveryTimeSelect.vue +39 -18
  6. package/app/components/Checkout/Summary.vue +5 -1
  7. package/app/components/Home/Categories.vue +2 -2
  8. package/app/components/Home/Facts.vue +9 -4
  9. package/app/components/Home/Hero.vue +8 -2
  10. package/app/components/Navigation/MobileTop.vue +1 -1
  11. package/app/components/Order/Detail.vue +3 -4
  12. package/app/composables/useAddressAutocomplete.ts +3 -11
  13. package/app/composables/useCheckoutMethodGuard.ts +1 -1
  14. package/app/composables/useDeliveryTime.ts +8 -5
  15. package/app/composables/useShippingLeadTime.ts +17 -0
  16. package/app/composables/useShippingMethodChoice.ts +2 -2
  17. package/app/composables/useShopBiteConfig.ts +10 -1
  18. package/app/composables/useTrackEvent.ts +4 -3
  19. package/app/pages/account/recover/password/index.vue +10 -0
  20. package/app/pages/registrierung/bestaetigen.vue +4 -0
  21. package/app/utils/leadTime.ts +97 -0
  22. package/app/utils/openingHours.ts +1 -1
  23. package/app/utils/schema.ts +2 -2
  24. package/app/utils/trackingUrl.ts +39 -0
  25. package/content/index.yml +16 -16
  26. package/content/zahlung-und-versand.md +3 -3
  27. package/content.config.ts +2 -2
  28. package/docs/notes/2026-07-04-issue-239-hydration-mismatches.md +1 -1
  29. package/docs/notes/2026-09-08-issue-244-category-url-trailing-slash.md +2 -2
  30. package/docs/notes/2026-09-10-issue-251-shop-data-in-base-layer.md +4 -4
  31. package/docs/notes/2026-09-10-issue-272-restaurant-schema.md +3 -3
  32. package/docs/notes/2026-09-10-issue-273-performance-media.md +4 -4
  33. package/docs/notes/2026-09-10-issue-274-seo-basics.md +6 -6
  34. package/docs/notes/2026-09-10-issue-275-accessibility.md +3 -3
  35. package/docs/notes/2026-09-10-issue-290-footer-nap.md +5 -5
  36. package/docs/notes/2026-09-10-issue-294-matomo-without-config.md +1 -1
  37. package/docs/notes/2026-09-10-issue-296-track-direct-search.md +1 -1
  38. package/docs/notes/2026-09-10-issue-312-store-api-criteria-post.md +3 -3
  39. package/docs/notes/2026-09-10-issue-313-wishlist-scoped-tailwind.md +1 -1
  40. package/docs/notes/2026-09-10-issue-314-mobile-js-cost.md +1 -1
  41. package/docs/notes/2026-09-12-issue-319-stylesheet-cost.md +1 -1
  42. package/docs/notes/2026-09-12-issue-325-product-card.md +2 -2
  43. package/docs/notes/2026-09-12-issue-327-home-hero.md +2 -2
  44. package/docs/notes/2026-09-13-issue-332-home-info-cards.md +1 -1
  45. package/docs/notes/2026-09-13-quick-view-flicker.md +1 -1
  46. package/docs/notes/2026-09-14-demo-noindex.md +2 -2
  47. package/docs/notes/2026-09-17-quick-view-compact-options.md +1 -1
  48. package/docs/notes/2026-09-21-issue-273-cache-and-demo-video.md +1 -1
  49. package/docs/notes/2026-09-21-issue-363-non-fatal-404.md +2 -2
  50. package/docs/notes/2026-09-21-issue-366-wishlist-404.md +1 -1
  51. package/docs/notes/2026-09-21-issue-378-dev-modules.md +1 -1
  52. package/docs/notes/2026-10-05-issue-289-product-deep-links.md +1 -1
  53. package/docs/notes/2026-10-05-issue-400-menu-item-ingredients-diet.md +1 -1
  54. package/docs/notes/2026-10-05-issue-401-restaurant-schema-ordering.md +1 -1
  55. package/docs/notes/2026-10-05-issue-402-llms-txt.md +1 -1
  56. package/docs/notes/2026-10-05-issue-403-ai-crawlers.md +1 -1
  57. package/docs/notes/2026-10-05-issue-404-faq.md +1 -1
  58. package/docs/notes/2026-10-06-old-seo-url-redirect.md +5 -5
  59. package/docs/notes/2026-10-07-issue-434-property-group-projection.md +1 -1
  60. package/nuxt.config.ts +56 -8
  61. package/package.json +3 -2
  62. package/server/api/address/autocomplete.get.ts +79 -14
  63. package/server/api/listing/[categoryId].get.ts +5 -28
  64. package/server/api/search.get.ts +4 -18
  65. package/server/api/shopbite/config.get.ts +1 -1
  66. package/server/plugins/bounded-cache.ts +28 -0
  67. package/server/plugins/security-headers.ts +54 -0
  68. package/server/routes/llms.txt.ts +6 -5
  69. package/server/utils/addressAutocomplete.ts +181 -0
  70. package/server/utils/listingParams.ts +117 -0
  71. package/server/utils/llmsTxt.ts +7 -3
  72. package/server/utils/securityHeaders.ts +165 -0
  73. package/server/utils/shopBiteConfig.ts +1 -1
  74. package/test/layer/nuxt.config.ts +2 -2
  75. package/test/nuxt/AccountPagesPreset.test.ts +10 -10
  76. package/test/nuxt/AuthPagesPreset.test.ts +3 -0
  77. package/test/nuxt/CheckoutFormsPreset.test.ts +5 -5
  78. package/test/nuxt/CheckoutOnePage.test.ts +4 -1
  79. package/test/nuxt/CheckoutSummary.test.ts +42 -3
  80. package/test/nuxt/DeliveryTimeSelect.test.ts +181 -0
  81. package/test/nuxt/HeaderFooterPreset.test.ts +10 -10
  82. package/test/nuxt/HomeFaq.test.ts +1 -1
  83. package/test/nuxt/HomeLeadTimes.test.ts +78 -0
  84. package/test/nuxt/NavigationMobileTop.test.ts +1 -1
  85. package/test/nuxt/OrderPagesPreset.test.ts +22 -2
  86. package/test/nuxt/RegisterConfirmPage.test.ts +12 -0
  87. package/test/nuxt/useAddressAutocomplete.test.ts +7 -22
  88. package/test/nuxt/useCheckoutMethodGuard.test.ts +1 -1
  89. package/test/nuxt/useDeliveryTime.test.ts +30 -6
  90. package/test/nuxt/useShippingLeadTime.test.ts +66 -0
  91. package/test/nuxt/useShippingMethodChoice.test.ts +1 -1
  92. package/test/nuxt/useShopBiteConfig.test.ts +57 -3
  93. package/test/nuxt/useTrackEvent.test.ts +16 -0
  94. package/test/unit/addressAutocomplete.spec.ts +247 -0
  95. package/test/unit/boundedCache.spec.ts +231 -0
  96. package/test/unit/highlight.spec.ts +2 -2
  97. package/test/unit/leadTime.spec.ts +86 -0
  98. package/test/unit/llmsTxt.spec.ts +30 -29
  99. package/test/unit/openingHours.spec.ts +3 -3
  100. package/test/unit/schema.spec.ts +29 -32
  101. package/test/unit/securityHeaders.spec.ts +254 -0
  102. package/test/unit/seo.spec.ts +23 -29
  103. package/test/unit/sitemap.spec.ts +1 -1
  104. package/test/unit/trackingUrl.spec.ts +48 -0
@@ -0,0 +1,66 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest";
2
+ import { mockNuxtImport } from "@nuxt/test-utils/runtime";
3
+ import { ref } from "vue";
4
+ import { useShippingLeadTime } from "~/composables/useShippingLeadTime";
5
+
6
+ // The checkout's time choice follows the selected shipping method
7
+ // (shopbite#6).
8
+ const DELIVERY = "0190a3b0c1d27e0f8a9b0c1d2e3f4a5b";
9
+ const PICKUP = "0190a3b0c1d27e0f8a9b0c1d2e3f4a5c";
10
+
11
+ const { mockInvoke, selected } = vi.hoisted(() => ({
12
+ mockInvoke: vi.fn(),
13
+ selected: {
14
+ current: null as null | { value: unknown },
15
+ },
16
+ }));
17
+
18
+ mockNuxtImport("useShopwareContext", () => () => ({
19
+ apiClient: { invoke: mockInvoke },
20
+ }));
21
+
22
+ mockNuxtImport("useCheckout", () => () => ({
23
+ selectedShippingMethod: selected.current,
24
+ }));
25
+
26
+ const configData = ref<unknown>(null);
27
+ mockNuxtImport(
28
+ "useAsyncData",
29
+ () => (_key: string, fetcher: () => Promise<unknown>) => ({
30
+ data: configData,
31
+ refresh: async () => {
32
+ configData.value = await fetcher();
33
+ },
34
+ }),
35
+ );
36
+
37
+ describe("useShippingLeadTime", () => {
38
+ beforeEach(() => {
39
+ configData.value = null;
40
+ selected.current = ref({ id: DELIVERY, name: "Lieferung" });
41
+ });
42
+
43
+ it("switches between delivery and pickup with the shipping method", async () => {
44
+ configData.value = {
45
+ isCheckoutEnabled: true,
46
+ shippingMethods: [
47
+ { id: DELIVERY, fulfillment: "delivery", leadTimeMinutes: 45 },
48
+ { id: PICKUP, fulfillment: "pickup", leadTimeMinutes: 20 },
49
+ ],
50
+ };
51
+
52
+ const { fulfillment, leadTime } = useShippingLeadTime();
53
+ expect(fulfillment.value).toBe("delivery");
54
+ expect(leadTime.value).toBe(45);
55
+
56
+ selected.current!.value = { id: PICKUP, name: "Abholung" };
57
+ expect(fulfillment.value).toBe("pickup");
58
+ expect(leadTime.value).toBe(20);
59
+ });
60
+
61
+ it("defaults to delivery without a lead time before the config is loaded", () => {
62
+ const { fulfillment, leadTime } = useShippingLeadTime();
63
+ expect(fulfillment.value).toBe("delivery");
64
+ expect(leadTime.value).toBeNull();
65
+ });
66
+ });
@@ -21,7 +21,7 @@ describe("useShippingMethodChoice", () => {
21
21
  });
22
22
 
23
23
  it("loads all active methods, also those whose rule needs an address", async () => {
24
- // "Lieferung" at La Fattoria only matches with a shipping city in the
24
+ // "Lieferung" in a shop with a delivery-area rule only matches with a shipping city in the
25
25
  // delivery area; onlyAvailable hid it from guests without an address
26
26
  const { methods, load } = useShippingMethodChoice();
27
27
  await load({ forceReload: true });
@@ -31,15 +31,21 @@ describe("useShopBiteConfig", () => {
31
31
 
32
32
  it("should return default values when no data is loaded", () => {
33
33
  const { deliveryTime, isCheckoutEnabled } = useShopBiteConfig();
34
- expect(deliveryTime.value).toBe(30);
34
+ expect(deliveryTime.value).toBeNull();
35
35
  expect(isCheckoutEnabled.value).toBe(false);
36
36
  });
37
37
 
38
38
  it("should refresh values from API", async () => {
39
39
  mockInvoke.mockResolvedValue({
40
40
  data: {
41
- deliveryTime: 45,
42
41
  isCheckoutEnabled: true,
42
+ shippingMethods: [
43
+ {
44
+ id: "0190a3b0c1d27e0f8a9b0c1d2e3f4a5b",
45
+ fulfillment: "delivery",
46
+ leadTimeMinutes: 45,
47
+ },
48
+ ],
43
49
  },
44
50
  });
45
51
 
@@ -55,7 +61,7 @@ describe("useShopBiteConfig", () => {
55
61
 
56
62
  it("checks the checkout switch with Shopware before an order", async () => {
57
63
  mockInvoke.mockResolvedValue({
58
- data: { deliveryTime: 30, isCheckoutEnabled: false },
64
+ data: { isCheckoutEnabled: false, shippingMethods: [] },
59
65
  });
60
66
 
61
67
  const { checkCheckoutEnabled, isCheckoutEnabled } = useShopBiteConfig();
@@ -74,4 +80,52 @@ describe("useShopBiteConfig", () => {
74
80
 
75
81
  expect(await checkCheckoutEnabled([])).toBeNull();
76
82
  });
83
+
84
+ // shopbite#6: lead time per shipping method
85
+ const DELIVERY = "0190a3b0c1d27e0f8a9b0c1d2e3f4a5b";
86
+ const PICKUP = "0190a3b0c1d27e0f8a9b0c1d2e3f4a5c";
87
+
88
+ it("passes the lead times of the shipping methods through", async () => {
89
+ mockInvoke.mockResolvedValue({
90
+ data: {
91
+ isCheckoutEnabled: true,
92
+ shippingMethods: [
93
+ { id: DELIVERY, fulfillment: "delivery", leadTimeMinutes: 50 },
94
+ { id: PICKUP, fulfillment: "pickup", leadTimeMinutes: 15 },
95
+ ],
96
+ },
97
+ });
98
+
99
+ const { refresh, deliveryTime, pickupTime, leadTimeFor } =
100
+ useShopBiteConfig();
101
+ await refresh();
102
+
103
+ expect(deliveryTime.value).toBe(50);
104
+ expect(pickupTime.value).toBe(15);
105
+ expect(leadTimeFor({ id: PICKUP })).toEqual({
106
+ fulfillment: "pickup",
107
+ minutes: 15,
108
+ });
109
+ expect(leadTimeFor({ id: DELIVERY })).toEqual({
110
+ fulfillment: "delivery",
111
+ minutes: 50,
112
+ });
113
+ });
114
+
115
+ it("has no delivery time without a delivery method", async () => {
116
+ mockInvoke.mockResolvedValue({
117
+ data: {
118
+ isCheckoutEnabled: true,
119
+ shippingMethods: [
120
+ { id: PICKUP, fulfillment: "pickup", leadTimeMinutes: 15 },
121
+ ],
122
+ },
123
+ });
124
+
125
+ const { refresh, deliveryTime, pickupTime } = useShopBiteConfig();
126
+ await refresh();
127
+
128
+ expect(deliveryTime.value).toBeNull();
129
+ expect(pickupTime.value).toBe(15);
130
+ });
77
131
  });
@@ -96,6 +96,22 @@ describe("useTrackEvent", () => {
96
96
  ]);
97
97
  });
98
98
 
99
+ it("tracks no query parameters that may carry secrets", () => {
100
+ setMatomoConfig("https://analytics.example.com/", 3);
101
+ document.title = "Neues Passwort";
102
+
103
+ useTrackEvent().trackPageView("/account/recover/password?hash=abc#x");
104
+ useTrackEvent().trackShare("copy", "P1", "/?produkt=P1&em=x");
105
+
106
+ expect(matomoWindow._paq).toEqual([
107
+ ["setCustomUrl", "/account/recover/password"],
108
+ ["setDocumentTitle", "Neues Passwort"],
109
+ ["trackPageView"],
110
+ ["setCustomUrl", "/?produkt=P1"],
111
+ ["trackEvent", "Product", "CopyLink", "P1"],
112
+ ]);
113
+ });
114
+
99
115
  it("tracks an add from the cart suggestions as its own action", () => {
100
116
  setMatomoConfig("https://analytics.example.com/", 3);
101
117
 
@@ -0,0 +1,247 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
+ import { stubNitro, type TestEvent } from "./nitroStubs";
3
+
4
+ const API_KEY = "secret-geoapify-key";
5
+ const BOX = "8.822251,50.055026,8.899077,50.104327";
6
+
7
+ type Handler = (event: TestEvent & { ip?: string }) => Promise<unknown>;
8
+
9
+ const feature = {
10
+ type: "Feature",
11
+ geometry: { type: "Point", coordinates: [8.86, 50.07] },
12
+ properties: {
13
+ street: "Hauptstraße",
14
+ housenumber: "1",
15
+ city: "Musterstadt",
16
+ postcode: "12345",
17
+ formatted: "Hauptstraße 1, 12345 Musterstadt, Deutschland",
18
+ place_id: "abc",
19
+ datasource: { sourcename: "openstreetmap" },
20
+ },
21
+ };
22
+
23
+ let fetchMock: ReturnType<typeof vi.fn>;
24
+
25
+ async function loadHandler(
26
+ boundingBox = BOX,
27
+ apiKey = API_KEY,
28
+ ): Promise<Handler> {
29
+ vi.resetModules();
30
+ const utils = await import("../../server/utils/addressAutocomplete");
31
+ fetchMock = vi.fn().mockResolvedValue({ features: [feature] });
32
+ stubNitro({
33
+ ...utils,
34
+ $fetch: fetchMock,
35
+ getRequestIP: (event: { ip?: string }) => event.ip ?? "203.0.113.1",
36
+ setResponseHeader: vi.fn(),
37
+ useRuntimeConfig: () => ({
38
+ geoapifyApiKey: apiKey,
39
+ addressAutocomplete: {
40
+ rateLimit: { capacity: 3, refillPerMinute: 6 },
41
+ },
42
+ public: { shopBite: { addressAutocomplete: { boundingBox } } },
43
+ }),
44
+ });
45
+ return (await import("../../server/api/address/autocomplete.get"))
46
+ .default as unknown as Handler;
47
+ }
48
+
49
+ const requestedUrl = (call = 0) => new URL(fetchMock.mock.calls[call]![0]);
50
+
51
+ beforeEach(() => {
52
+ vi.useFakeTimers();
53
+ });
54
+
55
+ afterEach(() => {
56
+ vi.useRealTimers();
57
+ vi.unstubAllGlobals();
58
+ vi.restoreAllMocks();
59
+ });
60
+
61
+ describe("/api/address/autocomplete", () => {
62
+ it("asks Geoapify with the allowed parameters only", async () => {
63
+ const handler = await loadHandler();
64
+ await handler({
65
+ query: { text: "Hauptstraße 1", lang: "de", limit: "5", apiKey: "x" },
66
+ });
67
+
68
+ const url = requestedUrl();
69
+ expect(url.origin + url.pathname).toBe(
70
+ "https://api.geoapify.com/v1/geocode/autocomplete",
71
+ );
72
+ expect(Object.fromEntries(url.searchParams)).toEqual({
73
+ apiKey: API_KEY,
74
+ text: "Hauptstraße 1",
75
+ lang: "de",
76
+ limit: "5",
77
+ filter: `rect:${BOX}`,
78
+ });
79
+ });
80
+
81
+ it("takes the area from the runtime config, never from the query", async () => {
82
+ const handler = await loadHandler("");
83
+ await handler({
84
+ query: { text: "Hauptstraße 1", filter: "rect:0,0,180,90" },
85
+ });
86
+
87
+ expect(requestedUrl().searchParams.has("filter")).toBe(false);
88
+ });
89
+
90
+ it("ignores a malformed area in the runtime config", async () => {
91
+ const handler = await loadHandler("8.8,50.0,nope");
92
+ await handler({ query: { text: "Hauptstraße 1" } });
93
+
94
+ expect(requestedUrl().searchParams.has("filter")).toBe(false);
95
+ });
96
+
97
+ it("returns no suggestions for text shorter than three characters", async () => {
98
+ const handler = await loadHandler();
99
+
100
+ expect(await handler({ query: { text: "ab" } })).toEqual({ features: [] });
101
+ expect(await handler({ query: {} })).toEqual({ features: [] });
102
+ expect(fetchMock).not.toHaveBeenCalled();
103
+ });
104
+
105
+ it.each([
106
+ [{ text: "a".repeat(201) }],
107
+ [{ text: ["Hauptstraße", "Nebenstraße"] }],
108
+ [{ text: "Hauptstraße 1", limit: "0" }],
109
+ [{ text: "Hauptstraße 1", limit: "11" }],
110
+ [{ text: "Hauptstraße 1", limit: "2.5" }],
111
+ [{ text: "Hauptstraße 1", limit: "5abc" }],
112
+ [{ text: "Hauptstraße 1", lang: "deu" }],
113
+ [{ text: "Hauptstraße 1", lang: "de&apiKey=x" }],
114
+ ])("rejects %o with 400 without asking Geoapify", async (query) => {
115
+ const handler = await loadHandler();
116
+
117
+ await expect(handler({ query })).rejects.toMatchObject({
118
+ statusCode: 400,
119
+ });
120
+ expect(fetchMock).not.toHaveBeenCalled();
121
+ });
122
+
123
+ it("returns only the address fields of the suggestions", async () => {
124
+ const handler = await loadHandler();
125
+
126
+ expect(await handler({ query: { text: "Hauptstraße 1" } })).toEqual({
127
+ features: [
128
+ {
129
+ properties: {
130
+ street: "Hauptstraße",
131
+ housenumber: "1",
132
+ city: "Musterstadt",
133
+ postcode: "12345",
134
+ formatted: "Hauptstraße 1, 12345 Musterstadt, Deutschland",
135
+ },
136
+ },
137
+ ],
138
+ });
139
+ });
140
+
141
+ it("never passes the upstream error text on and logs the URL redacted", async () => {
142
+ const handler = await loadHandler();
143
+ const upstream = `[GET] "https://api.geoapify.com/v1/geocode/autocomplete?apiKey=${API_KEY}&text=x": 401 Unauthorized`;
144
+ fetchMock.mockRejectedValue(
145
+ Object.assign(new Error(upstream), { response: { status: 401 } }),
146
+ );
147
+ const log = vi.spyOn(console, "error").mockImplementation(() => {});
148
+
149
+ const error = await handler({ query: { text: "Hauptstraße 1" } }).catch(
150
+ (e: unknown) => e as Error & { statusCode: number },
151
+ );
152
+
153
+ expect(error).toMatchObject({ statusCode: 502 });
154
+ expect(JSON.stringify(error)).not.toContain(API_KEY);
155
+ expect((error as Error).message).not.toContain(API_KEY);
156
+ expect((error as Error).message).not.toContain("geoapify.com");
157
+ expect(log).toHaveBeenCalled();
158
+ const logged = JSON.stringify(log.mock.calls);
159
+ expect(logged).not.toContain(API_KEY);
160
+ expect(logged).toContain("apiKey=***");
161
+ });
162
+
163
+ it("answers an identical lookup from a short-lived cache", async () => {
164
+ const handler = await loadHandler();
165
+ await handler({ query: { text: "Hauptstraße 1" } });
166
+ await handler({ query: { text: "Hauptstraße 1" }, ip: "x" });
167
+
168
+ expect(fetchMock).toHaveBeenCalledTimes(1);
169
+
170
+ vi.advanceTimersByTime(10 * 60 * 1000);
171
+ await handler({ query: { text: "Hauptstraße 1" }, ip: "y" });
172
+ expect(fetchMock).toHaveBeenCalledTimes(2);
173
+ });
174
+
175
+ it("does not cache a failed lookup", async () => {
176
+ const handler = await loadHandler();
177
+ vi.spyOn(console, "error").mockImplementation(() => {});
178
+ fetchMock.mockRejectedValueOnce(new Error("fetch failed"));
179
+
180
+ await expect(
181
+ handler({ query: { text: "Hauptstraße 1" } }),
182
+ ).rejects.toBeTruthy();
183
+ await handler({ query: { text: "Hauptstraße 1" } });
184
+
185
+ expect(fetchMock).toHaveBeenCalledTimes(2);
186
+ });
187
+
188
+ it("limits the lookups per client IP", async () => {
189
+ const handler = await loadHandler();
190
+ for (const n of [1, 2, 3]) {
191
+ await handler({ query: { text: `Hauptstraße ${n}` }, ip: "a" });
192
+ }
193
+
194
+ await expect(
195
+ handler({ query: { text: "Hauptstraße 4" }, ip: "a" }),
196
+ ).rejects.toMatchObject({ statusCode: 429 });
197
+ // another client is not affected
198
+ await handler({ query: { text: "Hauptstraße 4" }, ip: "b" });
199
+ expect(fetchMock).toHaveBeenCalledTimes(4);
200
+
201
+ // capacity 3, 6 per minute: one token after 10 s
202
+ vi.advanceTimersByTime(10_000);
203
+ await handler({ query: { text: "Hauptstraße 5" }, ip: "a" });
204
+ expect(fetchMock).toHaveBeenCalledTimes(5);
205
+ });
206
+
207
+ it("returns no suggestions without an API key", async () => {
208
+ const handler = await loadHandler(BOX, "");
209
+
210
+ expect(await handler({ query: { text: "Hauptstraße 1" } })).toEqual({
211
+ features: [],
212
+ });
213
+ expect(fetchMock).not.toHaveBeenCalled();
214
+ });
215
+ });
216
+
217
+ describe("createTokenBucketLimiter", () => {
218
+ it("keeps at most maxKeys clients", async () => {
219
+ const { createTokenBucketLimiter } =
220
+ await import("../../server/utils/addressAutocomplete");
221
+ const limiter = createTokenBucketLimiter({
222
+ capacity: 1,
223
+ refillPerMinute: 1,
224
+ maxKeys: 2,
225
+ });
226
+
227
+ expect(limiter.take("a")).toBe(true);
228
+ expect(limiter.take("b")).toBe(true);
229
+ expect(limiter.take("c")).toBe(true);
230
+ expect(limiter.size()).toBeLessThanOrEqual(2);
231
+ });
232
+ });
233
+
234
+ describe("createTtlCache", () => {
235
+ it("keeps at most maxEntries entries", async () => {
236
+ const { createTtlCache } =
237
+ await import("../../server/utils/addressAutocomplete");
238
+ const cache = createTtlCache<number>({ ttlMs: 60_000, maxEntries: 2 });
239
+ cache.set("a", 1);
240
+ cache.set("b", 2);
241
+ cache.set("c", 3);
242
+
243
+ expect(cache.get("a")).toBeUndefined();
244
+ expect(cache.get("b")).toBe(2);
245
+ expect(cache.get("c")).toBe(3);
246
+ });
247
+ });
@@ -0,0 +1,231 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
+ import { createStorage } from "unstorage";
3
+ import { stubNitro, type CachedHandler } from "./nitroStubs";
4
+
5
+ const CATEGORY = "018dadb399837af3aa669c8fff4f4d6c";
6
+ const A = "0197baf0a6a971eaada59ed5c84138de";
7
+ const B = "018dbccef8257618b0b3a541f513aa9e";
8
+
9
+ const load = async <T>(path: string): Promise<T> =>
10
+ (await import(/* @vite-ignore */ path)).default as T;
11
+
12
+ async function route(path: string) {
13
+ const params = await import("../../server/utils/listingParams");
14
+ const stubs = stubNitro({ ...params, $fetch: vi.fn(), MEDIA_INCLUDES: {} });
15
+ return { stubs, ...(await load<CachedHandler>(path)) };
16
+ }
17
+
18
+ beforeEach(() => {
19
+ vi.resetModules();
20
+ });
21
+
22
+ afterEach(() => {
23
+ vi.unstubAllGlobals();
24
+ });
25
+
26
+ const listingEvent = (query: Record<string, unknown>) => ({
27
+ params: { categoryId: CATEGORY },
28
+ query,
29
+ });
30
+
31
+ describe("/api/listing/[categoryId] cache key", () => {
32
+ it("keys property and manufacturer filters as sorted lower-case ids", async () => {
33
+ const { opts, handler, stubs } = await route(
34
+ "../../server/api/listing/[categoryId].get",
35
+ );
36
+ const query = { properties: `${B.toUpperCase()}|${A}|${A}`, p: "2" };
37
+
38
+ expect(await opts.getKey(listingEvent(query))).toBe(
39
+ [CATEGORY, "", `${B}|${A}`, "", "", 2].join("|"),
40
+ );
41
+ await handler(listingEvent(query));
42
+ expect(stubs.storeApiPost).toHaveBeenCalledWith(
43
+ `/product-listing/${CATEGORY}`,
44
+ expect.objectContaining({ properties: `${B}|${A}`, p: 2 }),
45
+ expect.anything(),
46
+ );
47
+ });
48
+
49
+ it.each([
50
+ ["properties", "Käse"],
51
+ ["properties", `${A}|`],
52
+ ["properties", Array.from({ length: 51 }, () => A).join("|")],
53
+ ["manufacturer", "x".repeat(32)],
54
+ ["order", "random-key"],
55
+ ["p", "21"],
56
+ ["p", "0"],
57
+ ["p", "1.5"],
58
+ ["query", "x".repeat(101)],
59
+ ["properties", [A, B]],
60
+ ])("rejects %s=%s with 400 before it becomes a key", async (name, value) => {
61
+ const { opts, handler, stubs } = await route(
62
+ "../../server/api/listing/[categoryId].get",
63
+ );
64
+ const event = listingEvent({ [name]: value });
65
+
66
+ expect(() => opts.getKey(event)).toThrow(
67
+ expect.objectContaining({ statusCode: 400 }),
68
+ );
69
+ await expect(handler(event)).rejects.toMatchObject({ statusCode: 400 });
70
+ expect(stubs.storeApiPost).not.toHaveBeenCalled();
71
+ });
72
+
73
+ it("rejects a category id that is not 32 hex characters", async () => {
74
+ const { opts } = await route("../../server/api/listing/[categoryId].get");
75
+
76
+ expect(() =>
77
+ opts.getKey({ params: { categoryId: "pizza" }, query: {} }),
78
+ ).toThrow(expect.objectContaining({ statusCode: 400 }));
79
+ });
80
+
81
+ it("accepts Shopware's standard sortings", async () => {
82
+ const { opts } = await route("../../server/api/listing/[categoryId].get");
83
+
84
+ for (const order of ["name-asc", "name-desc", "price-asc", "topseller"]) {
85
+ expect(await opts.getKey(listingEvent({ order }))).toContain(order);
86
+ }
87
+ });
88
+
89
+ it("accepts the sortings configured for the shop", async () => {
90
+ const params = await import("../../server/utils/listingParams");
91
+ stubNitro({
92
+ ...params,
93
+ MEDIA_INCLUDES: {},
94
+ useRuntimeConfig: () => ({
95
+ listingSortings: "name-asc, menu-number",
96
+ public: { shopBite: { cacheTtl: { listing: 1 } } },
97
+ }),
98
+ });
99
+ const { opts } = await load<CachedHandler>(
100
+ "../../server/api/listing/[categoryId].get",
101
+ );
102
+
103
+ expect(await opts.getKey(listingEvent({ order: "menu-number" }))).toContain(
104
+ "menu-number",
105
+ );
106
+ expect(() => opts.getKey(listingEvent({ order: "price-asc" }))).toThrow();
107
+ });
108
+
109
+ it("normalises whitespace of the text query", async () => {
110
+ const { opts } = await route("../../server/api/listing/[categoryId].get");
111
+
112
+ expect(
113
+ await opts.getKey(listingEvent({ query: " Pizza Salami " })),
114
+ ).toBe([CATEGORY, "", "", "", "Pizza Salami", 1].join("|"));
115
+ });
116
+ });
117
+
118
+ describe("/api/search cache key", () => {
119
+ it.each([
120
+ [{ query: "x".repeat(101) }],
121
+ [{ query: "pizza", order: "x" }],
122
+ [{ query: "pizza", p: "99" }],
123
+ [{ query: ["pizza", "salami"] }],
124
+ ])("rejects %o with 400", async (query) => {
125
+ const { opts, handler, stubs } = await route("../../server/api/search.get");
126
+
127
+ expect(() => opts.getKey({ query })).toThrow(
128
+ expect.objectContaining({ statusCode: 400 }),
129
+ );
130
+ await expect(handler({ query })).rejects.toMatchObject({
131
+ statusCode: 400,
132
+ });
133
+ expect(stubs.$fetch).not.toHaveBeenCalled();
134
+ });
135
+
136
+ it("keys a valid search", async () => {
137
+ const { opts } = await route("../../server/api/search.get");
138
+
139
+ expect(
140
+ await opts.getKey({ query: { query: " pizza ", order: "score" } }),
141
+ ).toBe("pizza|score|1");
142
+ });
143
+ });
144
+
145
+ describe("bounded cache storage", () => {
146
+ async function mountWith(
147
+ config: Record<string, unknown>,
148
+ storage = createStorage(),
149
+ ) {
150
+ vi.stubGlobal("defineNitroPlugin", (plugin: unknown) => plugin);
151
+ vi.stubGlobal("useRuntimeConfig", () => ({ cacheStorage: config }));
152
+ vi.stubGlobal("useStorage", () => storage);
153
+ const plugin = await load<() => void>("../../server/plugins/bounded-cache");
154
+ plugin();
155
+ return storage;
156
+ }
157
+
158
+ it("keeps at most maxEntries cache entries", async () => {
159
+ const storage = await mountWith({ maxEntries: 3, maxSizeMb: 1 });
160
+
161
+ for (const n of [1, 2, 3, 4, 5]) {
162
+ await storage.setItem(`cache:nitro:handlers:search:q${n}.json`, {
163
+ value: n,
164
+ });
165
+ }
166
+
167
+ expect(await storage.getKeys("cache:nitro")).toHaveLength(3);
168
+ expect(await storage.getItem("cache:nitro:handlers:search:q1.json")).toBe(
169
+ null,
170
+ );
171
+ expect(
172
+ await storage.getItem("cache:nitro:handlers:search:q5.json"),
173
+ ).toEqual({ value: 5 });
174
+ // other mounts are not affected
175
+ await storage.setItem("data:x", 1);
176
+ expect(await storage.getItem("data:x")).toBe(1);
177
+ });
178
+
179
+ it("keeps at most maxSizeMb of cache data", async () => {
180
+ const storage = await mountWith({ maxEntries: 1000, maxSizeMb: 1 });
181
+ const big = "x".repeat(400_000);
182
+
183
+ for (const n of [1, 2, 3, 4]) {
184
+ await storage.setItem(`cache:nitro:handlers:listing:l${n}.json`, big);
185
+ }
186
+
187
+ expect((await storage.getKeys("cache:nitro")).length).toBeLessThanOrEqual(
188
+ 2,
189
+ );
190
+ });
191
+
192
+ it("leaves a cache storage the shop mounted itself", async () => {
193
+ const own = createStorage();
194
+ const { default: memory } = await import("unstorage/drivers/memory");
195
+ own.mount("cache", memory());
196
+ const driver = own.getMount("cache:").driver;
197
+
198
+ await mountWith({ maxEntries: 3, maxSizeMb: 1 }, own);
199
+
200
+ expect(own.getMount("cache:").driver).toBe(driver);
201
+ });
202
+
203
+ it("is off with maxEntries 0", async () => {
204
+ const storage = await mountWith({ maxEntries: 0, maxSizeMb: 1 });
205
+
206
+ expect(storage.getMount("cache:").base).toBe("");
207
+ });
208
+
209
+ it("still lets the purge find and remove the entries", async () => {
210
+ const storage = await mountWith({ maxEntries: 100, maxSizeMb: 1 });
211
+ const { keysToPurge } = await import("../../server/utils/cachePurge");
212
+ await storage.setItem(`cache:nitro:handlers:product:product${A}.json`, {
213
+ value: 1,
214
+ });
215
+ await storage.setItem(`cache:nitro:handlers:product:product${B}.json`, {
216
+ value: 2,
217
+ });
218
+ await storage.setItem(`cache:nitro:handlers:listing:${CATEGORY}1.json`, {
219
+ value: 3,
220
+ });
221
+
222
+ const keys = keysToPurge(await storage.getKeys("cache:nitro"), {
223
+ products: [A],
224
+ });
225
+ await Promise.all(keys.map((key) => storage.removeItem(key)));
226
+
227
+ expect(await storage.getKeys("cache:nitro")).toEqual([
228
+ `cache:nitro:handlers:product:product${B}.json`,
229
+ ]);
230
+ });
231
+ });
@@ -3,8 +3,8 @@ import { splitHighlight } from "../../app/utils/highlight";
3
3
 
4
4
  describe("splitHighlight", () => {
5
5
  it("keeps text without highlights as one part", () => {
6
- expect(splitHighlight("Pizzeria La Fattoria")).toEqual([
7
- { text: "Pizzeria La Fattoria", highlight: false },
6
+ expect(splitHighlight("Pizzeria Esempio")).toEqual([
7
+ { text: "Pizzeria Esempio", highlight: false },
8
8
  ]);
9
9
  });
10
10