vilgain-mcp 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +135 -0
  3. package/dist/index.d.ts +2 -0
  4. package/dist/index.js +46 -0
  5. package/dist/index.js.map +1 -0
  6. package/dist/parsers/cart.d.ts +7 -0
  7. package/dist/parsers/cart.js +27 -0
  8. package/dist/parsers/cart.js.map +1 -0
  9. package/dist/parsers/common.d.ts +22 -0
  10. package/dist/parsers/common.js +98 -0
  11. package/dist/parsers/common.js.map +1 -0
  12. package/dist/parsers/orders.d.ts +7 -0
  13. package/dist/parsers/orders.js +91 -0
  14. package/dist/parsers/orders.js.map +1 -0
  15. package/dist/parsers/product.d.ts +5 -0
  16. package/dist/parsers/product.js +140 -0
  17. package/dist/parsers/product.js.map +1 -0
  18. package/dist/parsers/search.d.ts +3 -0
  19. package/dist/parsers/search.js +66 -0
  20. package/dist/parsers/search.js.map +1 -0
  21. package/dist/tools/cart.d.ts +99 -0
  22. package/dist/tools/cart.js +103 -0
  23. package/dist/tools/cart.js.map +1 -0
  24. package/dist/tools/helpers.d.ts +12 -0
  25. package/dist/tools/helpers.js +21 -0
  26. package/dist/tools/helpers.js.map +1 -0
  27. package/dist/tools/order-history.d.ts +46 -0
  28. package/dist/tools/order-history.js +93 -0
  29. package/dist/tools/order-history.js.map +1 -0
  30. package/dist/tools/product-detail.d.ts +27 -0
  31. package/dist/tools/product-detail.js +64 -0
  32. package/dist/tools/product-detail.js.map +1 -0
  33. package/dist/tools/product-variants.d.ts +25 -0
  34. package/dist/tools/product-variants.js +41 -0
  35. package/dist/tools/product-variants.js.map +1 -0
  36. package/dist/tools/search-products.d.ts +27 -0
  37. package/dist/tools/search-products.js +43 -0
  38. package/dist/tools/search-products.js.map +1 -0
  39. package/dist/types.d.ts +124 -0
  40. package/dist/types.js +2 -0
  41. package/dist/types.js.map +1 -0
  42. package/dist/validate-api.d.ts +9 -0
  43. package/dist/validate-api.js +97 -0
  44. package/dist/validate-api.js.map +1 -0
  45. package/dist/vilgain-api.d.ts +60 -0
  46. package/dist/vilgain-api.js +238 -0
  47. package/dist/vilgain-api.js.map +1 -0
  48. package/package.json +54 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tomas Pavlin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,135 @@
1
+ # <img src="https://vilgain.cz/favicon.ico" alt="Vilgain" width="30" height="30"> Vilgain MCP Server
2
+
3
+ **Let your favourite LLM shop for healthy food on [Vilgain.cz](https://vilgain.cz) (formerly Aktin).**
4
+
5
+ <img src="docs/cover.jpg" alt="A hand-drawn robot delivering a protein shaker to a guy at the gym, respecting his plant-based, nut-free preferences" width="700">
6
+
7
+ > [!WARNING]
8
+ > This is an unofficial MCP server for personal use only.
9
+
10
+ This is a [Model Context Protocol](https://modelcontextprotocol.io) server that lets AI assistants search products, inspect ingredients and nutrition facts, and manage the shopping cart on Vilgain.
11
+
12
+ Because Vilgain focuses on clean-label food, the product detail tool exposes what matters there: **ingredients, allergens and full nutrition facts** — so you can shop by what's actually in the food.
13
+
14
+ Example prompts:
15
+
16
+ **🛒 Shopping**
17
+
18
+ - *Add whey protein and a jar of peanut butter to my cart. Pick well-rated ones.*
19
+ - *I'm making protein pancakes — put the ingredients in my cart, high quality only.*
20
+ - *What's in my cart right now and how much will it cost?*
21
+ - *Swap the chocolate flavor in my cart for vanilla.*
22
+
23
+ **🥗 Ingredients & nutrition**
24
+
25
+ - *Find a protein bar without sucralose and with at least 25 % protein.*
26
+ - *Pick the omega-3 supplement with the best price per 1 g of EPA+DHA.*
27
+ - *Compare the ingredients of Vilgain peanut butter and almond butter — which has the shorter ingredient list?*
28
+ - *How much protein per 100 g does the vanilla flavor have compared to chocolate?*
29
+ - *Does the Double Trouble bar contain any allergens I should worry about? I'm allergic to nuts.*
30
+ - *Find me a breakfast granola with no added sugar and check its actual ingredient list.*
31
+
32
+ **🔁 Reordering**
33
+
34
+ - *What did I buy in my last order?*
35
+ - *Order the same things as last time, but skip the turkey breast.*
36
+ - *When did my last order arrive and where did I pick it up?*
37
+
38
+ ## Usage
39
+
40
+ ### Claude Desktop / Claude Code configuration
41
+
42
+ Add the MCP to the Claude Desktop configuration file:
43
+ - macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
44
+ - Windows: `%APPDATA%/Claude/claude_desktop_config.json`
45
+
46
+ ```json
47
+ {
48
+ "mcpServers": {
49
+ "vilgain": {
50
+ "command": "npx",
51
+ "args": ["-y", "vilgain-mcp"],
52
+ "env": {
53
+ "VILGAIN_EMAIL": "your-email@example.com",
54
+ "VILGAIN_PASSWORD": "your-password"
55
+ }
56
+ }
57
+ }
58
+ }
59
+ ```
60
+
61
+ For Claude Code: `claude mcp add vilgain -e VILGAIN_EMAIL=... -e VILGAIN_PASSWORD=... -- npx -y vilgain-mcp`
62
+
63
+ ### Configuration
64
+
65
+ | Variable | Required | Description |
66
+ |---|---|---|
67
+ | `VILGAIN_EMAIL` | yes | Vilgain account e-mail |
68
+ | `VILGAIN_PASSWORD` | yes | Vilgain account password |
69
+ | `VILGAIN_BASE_URL` | no | Store base URL, defaults to `https://vilgain.cz` |
70
+
71
+ ### Supported regions
72
+
73
+ Vilgain operates in several countries. The server is developed and tested against the Czech store; other regions can be selected with `VILGAIN_BASE_URL` and may work since they run the same platform, but are untested:
74
+
75
+ * **Czech Republic**: `https://vilgain.cz` (default)
76
+ * **Slovakia**: `https://vilgain.sk` (untested)
77
+ * **Other countries** (`vilgain.com`, `vilgain.de`, ...): untested
78
+
79
+ ## Tools
80
+
81
+ | Tool | Description |
82
+ |---|---|
83
+ | `search_products` | Full-text product search with prices, ratings and the displayed variant's ID |
84
+ | `get_product_variants` | All variants (flavors/sizes) of a product with prices and variant IDs |
85
+ | `get_product_detail` | What's inside: ingredients, allergens, nutrition facts, dosage, description |
86
+ | `get_cart_content` | Show cart items and total |
87
+ | `add_to_cart` | Add a product variant to the cart |
88
+ | `set_cart_item_quantity` | Change the quantity of a cart item |
89
+ | `remove_from_cart` | Remove an item from the cart |
90
+ | `get_order_history` | List past orders with dates, states, totals and product names |
91
+ | `get_order_detail` | One order's items, prices, delivery destination and shipment timeline |
92
+
93
+ `search_products` results can go straight to `add_to_cart` (the displayed variant); use `get_product_variants` to pick a different flavor or size. Checkout is intentionally not automated — finish the order yourself in the browser.
94
+
95
+ ## Development
96
+
97
+ ```bash
98
+ npm install
99
+ npm run build
100
+
101
+ npm test # parser unit tests (offline, against HTML fixtures)
102
+ npm run validate-api # live smoke test against vilgain.cz (needs credentials in .env)
103
+ npm run inspect # open MCP Inspector to try the tools manually
104
+ ```
105
+
106
+ Copy `.env.example` to `.env` and fill in your credentials for `validate-api` and `inspect`.
107
+
108
+ ### Testing with Claude Desktop
109
+
110
+ To run a local build instead of the published package, point the config at `dist/index.js`:
111
+
112
+ ```json
113
+ {
114
+ "mcpServers": {
115
+ "vilgain-local": {
116
+ "command": "node",
117
+ "args": ["/path/to/vilgain-mcp/dist/index.js"],
118
+ "env": {
119
+ "VILGAIN_EMAIL": "your-email@example.com",
120
+ "VILGAIN_PASSWORD": "your-password"
121
+ }
122
+ }
123
+ }
124
+ }
125
+ ```
126
+
127
+ The server has three layers:
128
+
129
+ - `src/vilgain-api.ts` – HTTP client for the reverse engineered website endpoints (see [docs/api.md](docs/api.md))
130
+ - `src/parsers/` – pure functions that extract data from Vilgain HTML pages, unit-tested against fixtures
131
+ - `src/tools/` – thin MCP tool wrappers around the API client
132
+
133
+ ## License
134
+
135
+ MIT
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,46 @@
1
+ #!/usr/bin/env node
2
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
+ import { VilgainAPI } from './vilgain-api.js';
5
+ import { createCartTools } from './tools/cart.js';
6
+ import { createOrderHistoryTools } from './tools/order-history.js';
7
+ import { createProductDetailTool } from './tools/product-detail.js';
8
+ import { createProductVariantsTool } from './tools/product-variants.js';
9
+ import { createSearchProductsTool } from './tools/search-products.js';
10
+ const email = process.env.VILGAIN_EMAIL;
11
+ const password = process.env.VILGAIN_PASSWORD;
12
+ const baseUrl = process.env.VILGAIN_BASE_URL || 'https://vilgain.cz';
13
+ if (!email || !password) {
14
+ console.error('VILGAIN_EMAIL and VILGAIN_PASSWORD environment variables are required');
15
+ process.exit(1);
16
+ }
17
+ // One shared API instance so the login session is reused across tool calls.
18
+ const api = new VilgainAPI({ email, password }, baseUrl);
19
+ const server = new McpServer({
20
+ name: 'vilgain-mcp',
21
+ version: '0.1.0',
22
+ });
23
+ const searchProducts = createSearchProductsTool(api);
24
+ const productVariants = createProductVariantsTool(api);
25
+ const productDetail = createProductDetailTool(api);
26
+ const cartTools = createCartTools(api);
27
+ const orderTools = createOrderHistoryTools(api);
28
+ server.registerTool(searchProducts.name, searchProducts.definition, searchProducts.handler);
29
+ server.registerTool(productVariants.name, productVariants.definition, productVariants.handler);
30
+ server.registerTool(productDetail.name, productDetail.definition, productDetail.handler);
31
+ server.registerTool(cartTools.getCartContent.name, cartTools.getCartContent.definition, cartTools.getCartContent.handler);
32
+ server.registerTool(cartTools.addToCart.name, cartTools.addToCart.definition, cartTools.addToCart.handler);
33
+ server.registerTool(cartTools.setCartItemQuantity.name, cartTools.setCartItemQuantity.definition, cartTools.setCartItemQuantity.handler);
34
+ server.registerTool(cartTools.removeFromCart.name, cartTools.removeFromCart.definition, cartTools.removeFromCart.handler);
35
+ server.registerTool(orderTools.getOrderHistory.name, orderTools.getOrderHistory.definition, orderTools.getOrderHistory.handler);
36
+ server.registerTool(orderTools.getOrderDetail.name, orderTools.getOrderDetail.definition, orderTools.getOrderDetail.handler);
37
+ async function main() {
38
+ const transport = new StdioServerTransport();
39
+ await server.connect(transport);
40
+ console.error('Vilgain MCP server running on stdio');
41
+ }
42
+ main().catch((error) => {
43
+ console.error('Server error:', error);
44
+ process.exit(1);
45
+ });
46
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAEA,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AACpE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AACjF,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AACnE,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AACxE,OAAO,EAAE,wBAAwB,E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AClB,CAAC,CAAC,CAAC"}
@@ -0,0 +1,7 @@
1
+ import { CartContent } from '../types.js';
2
+ /**
3
+ * Parse the cart page. The page embeds the cart as analytics data
4
+ * (items with variant ids, names, quantities and prices), which is more
5
+ * reliable than scraping the cart HTML.
6
+ */
7
+ export declare function parseCart(html: string): CartContent;
@@ -0,0 +1,27 @@
1
+ import { findDataLayerObject } from './common.js';
2
+ /**
3
+ * Parse the cart page. The page embeds the cart as analytics data
4
+ * (items with variant ids, names, quantities and prices), which is more
5
+ * reliable than scraping the cart HTML.
6
+ */
7
+ export function parseCart(html) {
8
+ const cartData = findDataLayerObject(html, (obj) => Array.isArray(obj.items) && 'total_value_with_vat' in obj);
9
+ if (!cartData) {
10
+ // A cart with no items has no cart analytics object.
11
+ return { items: [] };
12
+ }
13
+ const items = cartData.items.map((item) => ({
14
+ variantId: item.item_id,
15
+ productName: item.item_name,
16
+ variant: [item.variant, item.type].filter(Boolean).join(' ') || undefined,
17
+ quantity: item.quantity,
18
+ price: item.price,
19
+ currency: item.currency,
20
+ }));
21
+ return {
22
+ items,
23
+ totalWithVat: cartData.total_value_with_vat,
24
+ currency: cartData.currency,
25
+ };
26
+ }
27
+ //# sourceMappingURL=cart.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cart.js","sourceRoot":"","sources":["../../src/parsers/cart.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAkBlD;;;;GAIG;AACH,MAAM,UAAU,SAAS,CAAC,IAAY;IACpC,MAAM,QAAQ,GAAG,mBAAmB,CAClC,IAAI,EACJ,CAAC,GAAG,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,sBAAsB,IAAI,GAAG,CACnE,CAAC;IAEF,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,qDAAqD;QACrD,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC;IACvB,CAAC;IAED,MAAM,KAAK,GAAe,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;QACtD,SAAS,EAAE,IAAI,CAAC,OAAO;QACvB,WAAW,EAAE,IAAI,CAAC,SAAS;QAC3B,OAAO,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,SAAS;QACzE,QAAQ,EAAE,IAAI,CAAC,QAAQ;QACvB,KAAK,EAAE,IAAI,CAAC,KAAK;QACjB,QAAQ,EAAE,IAAI,CAAC,QAAQ;KACxB,CAAC,CAAC,CAAC;IAEJ,OAAO;QACL,KAAK;QACL,YAAY,EAAE,QAAQ,CAAC,oBAAoB;QAC3C,QAAQ,EAAE,QAAQ,CAAC,QAAQ;KAC5B,CAAC;AACJ,CAAC"}
@@ -0,0 +1,22 @@
1
+ /** Shared parsing helpers. */
2
+ /** Collapse whitespace (incl. non-breaking spaces) and strip word joiners common in Vilgain markup. */
3
+ export declare function cleanText(text: string): string;
4
+ /** Parse a price text like "999 Kč" or "1 234,50 Kč" into a number and ISO currency. */
5
+ export declare function parsePriceText(text: string): {
6
+ price: number;
7
+ currency: string;
8
+ } | undefined;
9
+ /** Parse rating from a screen-reader text like "Hodnocení 4.6/5, 425 recenzí". */
10
+ export declare function parseRatingText(text: string): {
11
+ rating: string;
12
+ reviewCount: number;
13
+ } | undefined;
14
+ /**
15
+ * Extract JSON arrays pushed to `dataLayer` / `dataLayerV2` in inline scripts.
16
+ * Vilgain pages embed analytics data as
17
+ * `([{...}]).forEach(function (data) { dataLayer.push(data); })`,
18
+ * which is the easiest machine-readable source of cart and product data.
19
+ */
20
+ export declare function extractDataLayerArrays(html: string): unknown[][];
21
+ /** Find the first object in dataLayer arrays that satisfies the predicate. */
22
+ export declare function findDataLayerObject<T = Record<string, unknown>>(html: string, predicate: (obj: Record<string, unknown>) => boolean): T | undefined;
@@ -0,0 +1,98 @@
1
+ /** Shared parsing helpers. */
2
+ const CURRENCY_MAP = {
3
+ 'Kč': 'CZK',
4
+ '€': 'EUR',
5
+ };
6
+ /** Collapse whitespace (incl. non-breaking spaces) and strip word joiners common in Vilgain markup. */
7
+ export function cleanText(text) {
8
+ return text
9
+ .replace(/\u2060/g, '')
10
+ .replace(/[\s\u00a0]+/g, ' ')
11
+ .trim();
12
+ }
13
+ /** Parse a price text like "999 Kč" or "1 234,50 Kč" into a number and ISO currency. */
14
+ export function parsePriceText(text) {
15
+ const cleaned = cleanText(text);
16
+ const match = cleaned.match(/(\d[\d ]*(?:[.,]\d+)?)\s*(Kč|€|[A-Z]{3})/);
17
+ if (!match)
18
+ return undefined;
19
+ const price = parseFloat(match[1].replace(/ /g, '').replace(',', '.'));
20
+ if (Number.isNaN(price))
21
+ return undefined;
22
+ return { price, currency: CURRENCY_MAP[match[2]] ?? match[2] };
23
+ }
24
+ /** Parse rating from a screen-reader text like "Hodnocení 4.6/5, 425 recenzí". */
25
+ export function parseRatingText(text) {
26
+ const match = cleanText(text).match(/(\d+(?:[.,]\d+)?\/5)\D*(\d+)/);
27
+ if (!match)
28
+ return undefined;
29
+ return { rating: match[1].replace(',', '.'), reviewCount: parseInt(match[2], 10) };
30
+ }
31
+ /**
32
+ * Extract JSON arrays pushed to `dataLayer` / `dataLayerV2` in inline scripts.
33
+ * Vilgain pages embed analytics data as
34
+ * `([{...}]).forEach(function (data) { dataLayer.push(data); })`,
35
+ * which is the easiest machine-readable source of cart and product data.
36
+ */
37
+ export function extractDataLayerArrays(html) {
38
+ const arrays = [];
39
+ let from = 0;
40
+ while (true) {
41
+ const start = html.indexOf('([', from);
42
+ if (start === -1)
43
+ break;
44
+ from = start + 2;
45
+ const end = findArrayEnd(html, start + 1);
46
+ if (end === -1)
47
+ continue;
48
+ if (!/^\)\.forEach\(function \(data\) \{ dataLayer(V2)?\.push/.test(html.slice(end + 1, end + 60)))
49
+ continue;
50
+ try {
51
+ const parsed = JSON.parse(html.slice(start + 1, end + 1));
52
+ if (Array.isArray(parsed))
53
+ arrays.push(parsed);
54
+ }
55
+ catch {
56
+ // Not valid JSON (e.g. contains JS expressions) - skip.
57
+ }
58
+ }
59
+ return arrays;
60
+ }
61
+ /** Given the index of a "[", return the index of its matching "]" (JSON-aware), or -1. */
62
+ function findArrayEnd(text, start) {
63
+ let depth = 0;
64
+ let inString = false;
65
+ for (let i = start; i < text.length; i++) {
66
+ const char = text[i];
67
+ if (inString) {
68
+ if (char === '\\')
69
+ i++;
70
+ else if (char === '"')
71
+ inString = false;
72
+ }
73
+ else if (char === '"') {
74
+ inString = true;
75
+ }
76
+ else if (char === '[' || char === '{') {
77
+ depth++;
78
+ }
79
+ else if (char === ']' || char === '}') {
80
+ depth--;
81
+ if (depth === 0)
82
+ return i;
83
+ }
84
+ }
85
+ return -1;
86
+ }
87
+ /** Find the first object in dataLayer arrays that satisfies the predicate. */
88
+ export function findDataLayerObject(html, predicate) {
89
+ for (const array of extractDataLayerArrays(html)) {
90
+ for (const item of array) {
91
+ if (item && typeof item === 'object' && predicate(item)) {
92
+ return item;
93
+ }
94
+ }
95
+ }
96
+ return undefined;
97
+ }
98
+ //# sourceMappingURL=common.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"common.js","sourceRoot":"","sources":["../../src/parsers/common.ts"],"names":[],"mappings":"AAAA,8BAA8B;AAE9B,MAAM,YAAY,GAA2B;IAC3C,IAAI,EAAE,KAAK;IACX,GAAG,EAAE,KAAK;CACX,CAAC;AAEF,uGAAuG;AACvG,MAAM,UAAU,SAAS,CAAC,IAAY;IACpC,OAAO,IAAI;SACR,OAAO,CAAC,SAAS,EAAE,EAAE,CAAC;SACtB,OAAO,CAAC,cAAc,EAAE,GAAG,CAAC;SAC5B,IAAI,EAAE,CAAC;AACZ,CAAC;AAED,wFAAwF;AACxF,MAAM,UAAU,cAAc,CAAC,IAAY;IACzC,MAAM,OAAO,GAAG,SAAS,CAAC,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M,IAAI,IAAI,KAAK,GAAG,IAAI,IAAI,KAAK,GAAG,EAAE,CAAC;YACxC,KAAK,EAAE,CAAC;YACR,IAAI,KAAK,KAAK,CAAC;gBAAE,OAAO,CAAC,CAAC;QAC5B,CAAC;IACH,CAAC;IACD,OAAO,CAAC,CAAC,CAAC;AACZ,CAAC;AAED,8EAA8E;AAC9E,MAAM,UAAU,mBAAmB,CACjC,IAAY,EACZ,SAAoD;IAEpD,KAAK,MAAM,KAAK,IAAI,sBAAsB,CAAC,IAAI,CAAC,EAAE,CAAC;QACjD,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;YACzB,IAAI,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,SAAS,CAAC,IAA+B,CAAC,EAAE,CAAC;gBACnF,OAAO,IAAS,CAAC;YACnB,CAAC;QACH,CAAC;IACH,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC"}
@@ -0,0 +1,7 @@
1
+ import { OrderDetail, OrderSummary } from '../types.js';
2
+ /** Parse the order history page (/muj-ucet/objednavky). */
3
+ export declare function parseOrderHistory(html: string, baseUrl: string): OrderSummary[];
4
+ /** True when the page shows the "no orders yet" empty state. */
5
+ export declare function isOrderHistoryEmpty(html: string): boolean;
6
+ /** Parse an order detail page (/muj-ucet/objednavka/<id>). */
7
+ export declare function parseOrderDetail(html: string, baseUrl: string): OrderDetail;
@@ -0,0 +1,91 @@
1
+ import * as cheerio from 'cheerio';
2
+ import { cleanText, parsePriceText } from './common.js';
3
+ import { variantIdFromUrl } from './product.js';
4
+ /** Parse the order history page (/muj-ucet/objednavky). */
5
+ export function parseOrderHistory(html, baseUrl) {
6
+ const $ = cheerio.load(html);
7
+ const orders = [];
8
+ $('li.p-order-list-item').each((_, el) => {
9
+ const row = $(el);
10
+ const href = row.find('a[href*="/muj-ucet/objednavka/"]').first().attr('href');
11
+ const idMatch = href?.match(/\/muj-ucet\/objednavka\/(\d+)/);
12
+ if (!href || !idMatch)
13
+ return;
14
+ const total = parsePriceText(row.find('.p-order-list-item__info--price').first().text());
15
+ const productNames = row
16
+ .find('.c-product-image-list__item')
17
+ .toArray()
18
+ .map((item) => cleanText($(item).attr('data-bs-original-title') ?? ''))
19
+ .filter((name) => name !== '');
20
+ orders.push({
21
+ id: idMatch[1],
22
+ url: new URL(href, baseUrl).href,
23
+ date: row.find('time').first().attr('datetime') ?? undefined,
24
+ state: cleanText(row.find('.p-order-list-item__info--state').first().text()) || undefined,
25
+ total: total?.price,
26
+ currency: total?.currency,
27
+ productNames,
28
+ });
29
+ });
30
+ return orders;
31
+ }
32
+ /** True when the page shows the "no orders yet" empty state. */
33
+ export function isOrderHistoryEmpty(html) {
34
+ return html.includes('Zatím nemáte žádné objednávky');
35
+ }
36
+ /** Parse an order detail page (/muj-ucet/objednavka/<id>). */
37
+ export function parseOrderDetail(html, baseUrl) {
38
+ const $ = cheerio.load(html);
39
+ const orderNumber = cleanText($('.p-order-detail-status__title strong').first().text());
40
+ const items = [];
41
+ const seenItems = new Set();
42
+ $('.p-order-detail-item__item').each((_, el) => {
43
+ const item = $(el);
44
+ const title = item.find('.p-order-detail-item__text--title').first();
45
+ const name = cleanText(title.text());
46
+ if (!name)
47
+ return;
48
+ const variant = cleanText(item.find('.p-order-detail-item__params').first().text()) || undefined;
49
+ // The page renders the item list twice (desktop and mobile layout).
50
+ const key = `${name}|${variant ?? ''}`;
51
+ if (seenItems.has(key))
52
+ return;
53
+ seenItems.add(key);
54
+ const quantityMatch = cleanText(item.find('.p-order-detail-item__column--count').first().text()).match(/(\d+)/);
55
+ const price = parsePriceText(item.find('.p-order-detail-item__column').not('.p-order-detail-item__column--count').first().text());
56
+ const href = title.attr('href');
57
+ items.push({
58
+ name,
59
+ variant,
60
+ // Item links point to the variant's product page; its URL suffix is the variant id.
61
+ variantId: href ? variantIdFromUrl(href) : undefined,
62
+ quantity: quantityMatch ? parseInt(quantityMatch[1], 10) : undefined,
63
+ price: price?.price,
64
+ currency: price?.currency,
65
+ url: href ? new URL(href, baseUrl).href : undefined,
66
+ });
67
+ });
68
+ const total = parsePriceText($('.p-order-detail-price__wrapper').first().text());
69
+ const timeline = [];
70
+ $('.order-detail-watch__item').each((_, el) => {
71
+ const text = cleanText($(el).text());
72
+ if (!text)
73
+ return;
74
+ const match = text.match(/^(.*?)\s*(\d{2}\.\s?\d{2}\.\s?\d{4}(?:\s\d{2}:\d{2})?)?$/);
75
+ const event = cleanText(match?.[1] ?? text);
76
+ // Skip non-timeline content blocks that share the class prefix (e.g. payment info).
77
+ if (!match?.[2])
78
+ return;
79
+ timeline.push({ event, date: match[2] });
80
+ });
81
+ const deliveryAddress = cleanText($('.p-order-detail-location__base').first().find('button, a').remove().end().text()) || undefined;
82
+ return {
83
+ orderNumber,
84
+ items,
85
+ totalWithVat: total?.price,
86
+ currency: total?.currency,
87
+ timeline,
88
+ deliveryAddress,
89
+ };
90
+ }
91
+ //# sourceMappingURL=orders.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"orders.js","sourceRoot":"","sources":["../../src/parsers/orders.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,OAAO,MAAM,SAAS,CAAC;AAEnC,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAEhD,2DAA2D;AAC3D,MAAM,UAAU,iBAAiB,CAAC,IAAY,EAAE,OAAe;IAC7D,MAAM,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC7B,MAAM,MAAM,GAAmB,EAAE,CAAC;IAElC,CAAC,CAAC,sBAAsB,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE;QACvC,MAAM,GAAG,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC;QAClB,MAAM,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC,kCAAkC,CAAC,CAAC,KAAK,EAAE,CAAC,IAAI,C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AE,CAAC,CAAC,CAAC;YAAE,OAAO;QACxB,QAAQ,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IAC3C,CAAC,CAAC,CAAC;IAEH,MAAM,eAAe,GAAG,SAAS,CAC/B,CAAC,CAAC,gCAAgC,CAAC,CAAC,KAAK,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,IAAI,EAAE,CACpF,IAAI,SAAS,CAAC;IAEf,OAAO;QACL,WAAW;QACX,KAAK;QACL,YAAY,EAAE,KAAK,EAAE,KAAK;QAC1B,QAAQ,EAAE,KAAK,EAAE,QAAQ;QACzB,QAAQ;QACR,eAAe;KAChB,CAAC;AACJ,CAAC"}
@@ -0,0 +1,5 @@
1
+ import { ProductDetail } from '../types.js';
2
+ /** Extract the numeric variant id from a variant URL like ".../cokolada-1-000-g-44471". */
3
+ export declare function variantIdFromUrl(url: string): number | undefined;
4
+ /** Parse a product detail page. `finalUrl` must be the URL after redirects (it identifies the selected variant). */
5
+ export declare function parseProductDetail(html: string, finalUrl: string): ProductDetail;
@@ -0,0 +1,140 @@
1
+ import * as cheerio from 'cheerio';
2
+ import { cleanText, findDataLayerObject, parseRatingText } from './common.js';
3
+ /** Extract the numeric variant id from a variant URL like ".../cokolada-1-000-g-44471". */
4
+ export function variantIdFromUrl(url) {
5
+ const match = url.match(/-(\d+)(?:[?#]|$)/);
6
+ return match ? parseInt(match[1], 10) : undefined;
7
+ }
8
+ function findProductJsonLd($) {
9
+ for (const el of $('script[type="application/ld+json"]').toArray()) {
10
+ try {
11
+ const data = JSON.parse($(el).text());
12
+ if (data['@type'] === 'Product')
13
+ return data;
14
+ }
15
+ catch {
16
+ // skip malformed JSON-LD
17
+ }
18
+ }
19
+ return undefined;
20
+ }
21
+ /** The product page embeds all variants (id, name, price, availability) as analytics data. */
22
+ function extractVariantsData(html) {
23
+ return findDataLayerObject(html, (obj) => typeof obj.productVariants === 'object' && obj.productVariants !== null && obj.pageType === 'product');
24
+ }
25
+ /** Id of the variant the page content (ingredients, nutrition) refers to. */
26
+ function extractSelectedVariantId(html) {
27
+ const viewItem = findDataLayerObject(html, (obj) => obj.event === 'view_item' && typeof obj.item_id === 'number');
28
+ return viewItem?.item_id;
29
+ }
30
+ /**
31
+ * Product pages contain content blocks (ingredients, nutrition tables, dosage)
32
+ * for every variant. The mapping of variant -> visible blocks is encoded in the
33
+ * variant radio buttons' `data-nette-rules` toggle maps, e.g.
34
+ * `"toggle":{"content-44471":true,"content-<uuid>":true,...}`.
35
+ * Returns the set of "content-<uuid>" toggle keys for the given variant.
36
+ */
37
+ function contentTogglesForVariant(html, variantId) {
38
+ const toggles = new Set();
39
+ const toggleRegex = /"toggle":\{([^{}]*)\}/g;
40
+ let match;
41
+ while ((match = toggleRegex.exec(html)) !== null) {
42
+ const body = match[1].replace(/&quot;/g, '"');
43
+ if (!body.includes(`"content-${variantId}"`))
44
+ continue;
45
+ for (const keyMatch of body.matchAll(/"(content-[0-9a-f-]{36})"/g)) {
46
+ toggles.add(keyMatch[1]);
47
+ }
48
+ }
49
+ return toggles;
50
+ }
51
+ function parseNutritionTable($, table) {
52
+ const rows = $(table).find('tr').toArray();
53
+ if (rows.length < 2)
54
+ return undefined;
55
+ const headerCells = $(rows[0]).find('td,th').toArray().map((c) => cleanText($(c).text()));
56
+ const columns = headerCells.slice(1).filter((c) => c !== '');
57
+ const dataRows = rows.slice(1).map((row) => {
58
+ const cells = $(row).find('td,th').toArray().map((c) => cleanText($(c).text()));
59
+ return { label: cells[0] ?? '', values: cells.slice(1) };
60
+ }).filter((row) => row.label !== '');
61
+ if (columns.length === 0 || dataRows.length === 0)
62
+ return undefined;
63
+ return { columns, rows: dataRows };
64
+ }
65
+ /**
66
+ * Select the content blocks within a tab that belong to the given variant
67
+ * (a variant typically has separate blocks for ingredients and nutrition tables).
68
+ * Falls back to the first content block when no toggle map matches
69
+ * (e.g. single-variant products have no toggles at all).
70
+ */
71
+ function variantBlocks($, tab, toggles) {
72
+ const toggled = tab.find('[data-toggle]');
73
+ if (toggled.length === 0)
74
+ return tab;
75
+ const matching = toggled.filter((_, el) => toggles.has($(el).attr('data-toggle') ?? ''));
76
+ return matching.length > 0 ? matching : toggled.first();
77
+ }
78
+ /** Parse a product detail page. `finalUrl` must be the URL after redirects (it identifies the selected variant). */
79
+ export function parseProductDetail(html, finalUrl) {
80
+ const $ = cheerio.load(html);
81
+ const jsonLd = findProductJsonLd($);
82
+ const name = jsonLd?.name ?? cleanText($('h1').first().text());
83
+ // <noscript> fallback images and inline styles/scripts would otherwise leak into extracted text.
84
+ $('noscript, style, script').remove();
85
+ // JSON-LD offers provide per-variant URLs and GTINs.
86
+ const offers = jsonLd?.offers?.offers ?? (jsonLd?.offers ? [jsonLd.offers] : []);
87
+ const offersByVariantId = new Map();
88
+ for (const offer of offers) {
89
+ const variantId = offer.url ? variantIdFromUrl(offer.url) : undefined;
90
+ if (variantId !== undefined)
91
+ offersByVariantId.set(variantId, offer);
92
+ }
93
+ const variantsData = extractVariantsData(html);
94
+ const currency = variantsData?.currencyCode ?? 'CZK';
95
+ const variants = Object.values(variantsData?.productVariants ?? {}).map((v) => {
96
+ const offer = offersByVariantId.get(v.id);
97
+ return {
98
+ variantId: v.id,
99
+ name: cleanText(v.variant),
100
+ url: offer?.url ?? finalUrl,
101
+ price: v.priceVat,
102
+ currency,
103
+ inStock: v.availability,
104
+ gtin: offer?.gtin,
105
+ };
106
+ });
107
+ const selectedVariantId = extractSelectedVariantId(html);
108
+ const toggles = selectedVariantId !== undefined ? contentTogglesForVariant(html, selectedVariantId) : new Set();
109
+ const ingredientsBlocks = variantBlocks($, $('#slozeni'), toggles);
110
+ const nutrition = [];
111
+ ingredientsBlocks.find('table').each((_, table) => {
112
+ const parsed = parseNutritionTable($, table);
113
+ if (parsed)
114
+ nutrition.push(parsed);
115
+ });
116
+ // Blocks without tables hold the ingredients text; table blocks hold nutrition facts.
117
+ const textBlocks = ingredientsBlocks.filter((_, el) => $(el).find('table').length === 0);
118
+ const ingredients = cleanText((textBlocks.length > 0 ? textBlocks : ingredientsBlocks.find('table').remove().end()).text()) || undefined;
119
+ const dosageBlock = variantBlocks($, $('#davkovani'), toggles);
120
+ const dosage = cleanText(dosageBlock.text()) || undefined;
121
+ const description = cleanText($('#popis').first().text()) || undefined;
122
+ const ratingText = $('.sr-only').toArray()
123
+ .map((el) => $(el).text())
124
+ .find((t) => /\/5,/.test(t));
125
+ const rating = ratingText ? parseRatingText(ratingText) : undefined;
126
+ return {
127
+ name,
128
+ url: finalUrl,
129
+ shortDescription: jsonLd?.description,
130
+ description,
131
+ ingredients,
132
+ dosage,
133
+ nutrition,
134
+ rating: rating?.rating,
135
+ reviewCount: rating?.reviewCount,
136
+ variants,
137
+ selectedVariantId,
138
+ };
139
+ }
140
+ //# sourceMappingURL=product.js.map