@chrischall/hellofresh-mcp 0.0.0 → 0.2.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.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +19 -9
- package/dist/bundle.js +1754 -713
- package/dist/client.js +123 -1
- package/dist/cooking.js +123 -0
- package/dist/index.js +5 -4
- package/dist/normalize.js +32 -0
- package/dist/planner.js +71 -16
- package/dist/session.js +47 -3
- package/dist/tools/cooking.js +150 -0
- package/dist/tools/favorites.js +164 -0
- package/dist/tools/index.js +7 -1
- package/dist/tools/planner.js +276 -83
- package/dist/tools/promo.js +108 -0
- package/dist/tools/reads.js +71 -40
- package/dist/tools/shared.js +210 -24
- package/dist/tools/writes/index.js +9 -0
- package/dist/tools/writes/plan.js +177 -0
- package/dist/tools/writes/shared.js +137 -0
- package/dist/tools/{writes.js → writes/week.js} +8 -290
- package/dist/transport.js +13 -1
- package/dist/version.js +1 -1
- package/manifest.json +43 -4
- package/mint.yaml +6 -0
- package/package.json +1 -1
- package/server.json +8 -2
- package/skills/hellofresh/SKILL.md +49 -12
- package/skills/hellofresh-fpx/SKILL.md +13 -5
- package/skills/hellofresh-fpx/references/requests.md +30 -10
package/dist/client.js
CHANGED
|
@@ -12,6 +12,11 @@
|
|
|
12
12
|
// - a READ that timed out / could not connect → McpToolError kind timeout / transport.
|
|
13
13
|
// Every request is bounded by a timeout and honours the tool call's
|
|
14
14
|
// cancellation (`currentCallSignal()`, folded in by withAmbientCancellation).
|
|
15
|
+
//
|
|
16
|
+
// One endpoint is the exception to "plain Node fetch": `POST /gw/calculate`
|
|
17
|
+
// (the real box price) is refused by Cloudflare's WAF from Node, so it runs as
|
|
18
|
+
// an in-tab fetch through the bridge (`tabFetch`) — same bearer, same 401
|
|
19
|
+
// replay, same error mapping. It changes nothing, so it is mapped as a READ.
|
|
15
20
|
import { EdgeBlockedError, McpToolError, UpstreamHttpError, WriteOutcomeUnknownError, apiPath, buildQueryString, currentCallSignal, describeTransportFailure, detectEdgeBlock, formatApiError, messageOf, parseJsonBody, truncateErrorMessage, withAmbientCancellation, } from '@chrischall/mcp-utils';
|
|
16
21
|
import { WEB_ORIGIN, signInHint } from './session.js';
|
|
17
22
|
export const API_BASE = `${WEB_ORIGIN}/gw`;
|
|
@@ -24,10 +29,12 @@ export const REQUEST_TIMEOUT_MS = 30_000;
|
|
|
24
29
|
export class HelloFreshClient {
|
|
25
30
|
session;
|
|
26
31
|
fetchImpl;
|
|
32
|
+
tabFetch;
|
|
27
33
|
timeoutMs;
|
|
28
34
|
constructor(opts) {
|
|
29
35
|
this.session = opts.session;
|
|
30
36
|
this.fetchImpl = opts.fetchImpl ?? globalThis.fetch.bind(globalThis);
|
|
37
|
+
this.tabFetch = opts.tabFetch;
|
|
31
38
|
this.timeoutMs = opts.timeoutMs ?? REQUEST_TIMEOUT_MS;
|
|
32
39
|
}
|
|
33
40
|
// ---- reads ---------------------------------------------------------------
|
|
@@ -72,6 +79,32 @@ export class HelloFreshClient {
|
|
|
72
79
|
},
|
|
73
80
|
});
|
|
74
81
|
}
|
|
82
|
+
/** The real box price (`POST /gw/calculate`, in-tab): money fields only. */
|
|
83
|
+
async calculatePrice(r) {
|
|
84
|
+
const raw = await this.request('POST', '/calculate', {
|
|
85
|
+
locale: false,
|
|
86
|
+
body: calculateBody(r),
|
|
87
|
+
viaTab: true,
|
|
88
|
+
sideEffectFree: true,
|
|
89
|
+
});
|
|
90
|
+
if (typeof raw?.grandTotal !== 'number') {
|
|
91
|
+
throw new McpToolError(`${SERVICE}'s price calculator answered without a grand total.`, { kind: 'http' });
|
|
92
|
+
}
|
|
93
|
+
return projectCalculation(raw);
|
|
94
|
+
}
|
|
95
|
+
/** Recipe detail by the menu meal's `recipe.id` (docs/HELLOFRESH-API.md "Recipe detail"). */
|
|
96
|
+
getRecipe(recipeId) {
|
|
97
|
+
return this.request('GET', apiPath `/recipes/recipes/${recipeId}`);
|
|
98
|
+
}
|
|
99
|
+
/** The customer's favourite recipes (items carry the customer uuid: project before returning). */
|
|
100
|
+
listFavorites() {
|
|
101
|
+
return this.request('GET', '/cfs/v2/favorites/recipe');
|
|
102
|
+
}
|
|
103
|
+
/** The customer's recipe ratings on one scale. The item shape is not yet observed: parse defensively. */
|
|
104
|
+
listRatings(scale) {
|
|
105
|
+
// The documented query uses a lowercase country here.
|
|
106
|
+
return this.request('GET', `/cfs/${scale}/ratings/recipe`, { locale: false, query: { country: 'us', locale: LOCALE } });
|
|
107
|
+
}
|
|
75
108
|
// ---- writes (docs/HELLOFRESH-API.md "Writes" 1–5, 3 split into 3a size / 3b day) -------------------------
|
|
76
109
|
// Each write is built by an exported pure builder (below), so the confirm
|
|
77
110
|
// preview of a write and the request actually sent are the same object.
|
|
@@ -99,6 +132,14 @@ export class HelloFreshClient {
|
|
|
99
132
|
async changePlanDeliveryDetails(customerPlanId, details) {
|
|
100
133
|
await this.send(planDeliveryDetailsRequest(customerPlanId, details));
|
|
101
134
|
}
|
|
135
|
+
/** Favourite a recipe (`recipe.id`). 204, no body. */
|
|
136
|
+
async addFavorite(recipeId, week) {
|
|
137
|
+
await this.send(addFavoriteRequest(recipeId, week), { discardBody: true });
|
|
138
|
+
}
|
|
139
|
+
/** Un-favourite a recipe (`recipe.id`). 204, no body. */
|
|
140
|
+
async removeFavorite(recipeId) {
|
|
141
|
+
await this.send(removeFavoriteRequest(recipeId), { discardBody: true });
|
|
142
|
+
}
|
|
102
143
|
send(w, opts = {}) {
|
|
103
144
|
return this.request(w.method, w.path, { locale: false, query: w.query, body: w.body, route: w.route, ...opts });
|
|
104
145
|
}
|
|
@@ -106,7 +147,7 @@ export class HelloFreshClient {
|
|
|
106
147
|
async request(method, path, opts = {}) {
|
|
107
148
|
const query = { ...(opts.locale === false ? {} : { country: COUNTRY, locale: LOCALE }), ...opts.query };
|
|
108
149
|
const url = `${API_BASE}${path}${buildQueryString(query)}`;
|
|
109
|
-
const isWrite = method !== 'GET';
|
|
150
|
+
const isWrite = method !== 'GET' && !opts.sideEffectFree;
|
|
110
151
|
// One timer per request, armed until the body is read (each 401 replay gets a fresh one).
|
|
111
152
|
let timer = AbortSignal.timeout(this.timeoutMs);
|
|
112
153
|
const fail = (err) => this.transportError(err, method, url, isWrite, timer.aborted);
|
|
@@ -116,6 +157,9 @@ export class HelloFreshClient {
|
|
|
116
157
|
if (opts.body !== undefined)
|
|
117
158
|
headers['content-type'] = 'application/json';
|
|
118
159
|
try {
|
|
160
|
+
// Given a signal, withAmbientCancellation always returns one.
|
|
161
|
+
if (opts.viaTab)
|
|
162
|
+
return await this.fetchInTab(url, method, headers, opts.body, withAmbientCancellation(timer));
|
|
119
163
|
return await this.fetchImpl(url, {
|
|
120
164
|
method,
|
|
121
165
|
headers,
|
|
@@ -158,6 +202,32 @@ export class HelloFreshClient {
|
|
|
158
202
|
}
|
|
159
203
|
return parseJsonBody(text, { ...where, status: res.status, headers: res.headers });
|
|
160
204
|
}
|
|
205
|
+
/** One request through the bridge's tab, answered as a Response (so the 401 replay and error mapping apply). */
|
|
206
|
+
async fetchInTab(url, method, headers, body, signal) {
|
|
207
|
+
const tabFetch = this.tabFetch;
|
|
208
|
+
if (!tabFetch) {
|
|
209
|
+
throw new McpToolError(`${SERVICE}'s price calculator needs the browser bridge, which this server was started without.`, {
|
|
210
|
+
kind: 'transport',
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
const pending = tabFetch({
|
|
214
|
+
method,
|
|
215
|
+
url,
|
|
216
|
+
headers,
|
|
217
|
+
body: JSON.stringify(body),
|
|
218
|
+
// Only side-effect-free requests come through here (see sideEffectFree).
|
|
219
|
+
retryOnTimeout: true,
|
|
220
|
+
});
|
|
221
|
+
// The bridge takes no signal: race it, so the timeout and the caller's cancellation still bound the call.
|
|
222
|
+
const aborted = new Promise((_, reject) => {
|
|
223
|
+
if (signal.aborted)
|
|
224
|
+
reject(signal.reason);
|
|
225
|
+
signal.addEventListener('abort', () => reject(signal.reason), { once: true });
|
|
226
|
+
});
|
|
227
|
+
const res = await Promise.race([pending, aborted]);
|
|
228
|
+
// A Response refuses a body on a null-body status.
|
|
229
|
+
return new Response([204, 205, 304].includes(res.status) ? null : res.body, { status: res.status });
|
|
230
|
+
}
|
|
161
231
|
transportError(err, method, url, isWrite, timedOut) {
|
|
162
232
|
if (isWrite) {
|
|
163
233
|
return new WriteOutcomeUnknownError(SERVICE, method, {
|
|
@@ -176,6 +246,40 @@ export class HelloFreshClient {
|
|
|
176
246
|
}
|
|
177
247
|
}
|
|
178
248
|
const LOCALE_QUERY = { country: COUNTRY, locale: LOCALE };
|
|
249
|
+
/** The `POST /gw/calculate` body, exactly as the site sends it. `recipeIndexes` MUST be strings. */
|
|
250
|
+
export function calculateBody(r) {
|
|
251
|
+
return {
|
|
252
|
+
customerID: r.customerId,
|
|
253
|
+
subscriptionID: Number(r.subscriptionId),
|
|
254
|
+
couponCode: r.couponCode,
|
|
255
|
+
shippingAddress: { postcode: r.postcode },
|
|
256
|
+
planID: r.customerPlanId,
|
|
257
|
+
locale: LOCALE,
|
|
258
|
+
country: COUNTRY,
|
|
259
|
+
products: [{ handle: r.sku, hfWeek: r.week, deliveryOption: r.deliveryOption, recipeIndexes: r.recipeIndexes.map(String) }],
|
|
260
|
+
weekId: r.week,
|
|
261
|
+
isFirstOrder: r.isFirstOrder,
|
|
262
|
+
isRecurring: !r.isFirstOrder,
|
|
263
|
+
isFutureWeek: r.isFutureWeek,
|
|
264
|
+
boxSize: r.boxSize,
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
/** The money fields of a calculator answer — an allowlist: ids and the address never pass. */
|
|
268
|
+
export function projectCalculation(raw) {
|
|
269
|
+
const product = raw.products?.[0];
|
|
270
|
+
const out = {
|
|
271
|
+
grandTotal: raw.grandTotal,
|
|
272
|
+
subTotal: raw.subTotal,
|
|
273
|
+
discount: raw.discountAmount,
|
|
274
|
+
shipping: raw.shippingAmount,
|
|
275
|
+
shippingDiscount: raw.shippingDiscountAmount,
|
|
276
|
+
tax: raw.taxAmount,
|
|
277
|
+
couponPercent: product?.couponPercent,
|
|
278
|
+
couponCode: raw.couponCode || product?.couponCode || undefined,
|
|
279
|
+
currency: raw.currency,
|
|
280
|
+
};
|
|
281
|
+
return Object.fromEntries(Object.entries(out).filter(([, v]) => v !== undefined && v !== null && v !== ''));
|
|
282
|
+
}
|
|
179
283
|
export function selectMealsRequest(r) {
|
|
180
284
|
return {
|
|
181
285
|
method: 'PUT',
|
|
@@ -246,3 +350,21 @@ export function planDeliveryDetailsRequest(customerPlanId, details) {
|
|
|
246
350
|
body: { deliveryOption: details.deliveryOption, deliveryInterval: details.deliveryInterval },
|
|
247
351
|
};
|
|
248
352
|
}
|
|
353
|
+
export function addFavoriteRequest(recipeId, week) {
|
|
354
|
+
return {
|
|
355
|
+
method: 'PUT',
|
|
356
|
+
path: apiPath `/cfs/v2/favorites/recipe/${recipeId}`,
|
|
357
|
+
route: `/cfs/v2/favorites/recipe/${recipeId}`,
|
|
358
|
+
query: { ...LOCALE_QUERY, ...(week ? { weekId: week } : {}) },
|
|
359
|
+
body: undefined,
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
export function removeFavoriteRequest(recipeId) {
|
|
363
|
+
return {
|
|
364
|
+
method: 'DELETE',
|
|
365
|
+
path: apiPath `/cfs/v2/favorites/recipe/${recipeId}`,
|
|
366
|
+
route: `/cfs/v2/favorites/recipe/${recipeId}`,
|
|
367
|
+
query: { ...LOCALE_QUERY },
|
|
368
|
+
body: undefined,
|
|
369
|
+
};
|
|
370
|
+
}
|
package/dist/cooking.js
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// Cooking day: the recipe-detail projection (hf_get_recipe) and the cook-order
|
|
2
|
+
// ranking (hf_cooking_plan). Pure — the tools in src/tools/cooking.ts do the
|
|
3
|
+
// reads. Recipe text is third-party content: the tools frame it as untrusted.
|
|
4
|
+
import { parseDurationMinutes } from './normalize.js';
|
|
5
|
+
// ---- text -------------------------------------------------------------------------
|
|
6
|
+
const ENTITIES = { amp: '&', nbsp: ' ', lt: '<', gt: '>', quot: '"', '#39': "'" };
|
|
7
|
+
/** HTML or multi-line text → one trimmed line (tags dropped, common entities decoded, whitespace collapsed). */
|
|
8
|
+
export function plainText(text) {
|
|
9
|
+
return text
|
|
10
|
+
.replace(/<[^>]*>/g, ' ')
|
|
11
|
+
.replace(/&(amp|nbsp|lt|gt|quot|#39);/g, (_, e) => ENTITIES[e])
|
|
12
|
+
.replace(/\s+/g, ' ')
|
|
13
|
+
.trim();
|
|
14
|
+
}
|
|
15
|
+
/** The longer of `prepTime` / `totalTime` in minutes (as the menu projection reads it), or undefined. */
|
|
16
|
+
export function recipeMinutes(r) {
|
|
17
|
+
const times = [parseDurationMinutes(r.prepTime), parseDurationMinutes(r.totalTime)].filter((n) => n !== undefined);
|
|
18
|
+
return times.length > 0 ? Math.max(...times) : undefined;
|
|
19
|
+
}
|
|
20
|
+
/** The yield for `servings`, else the nearest one (the larger on a tie). */
|
|
21
|
+
export function nearestYield(yields, servings) {
|
|
22
|
+
const numbered = (yields ?? []).filter((y) => typeof y.yields === 'number');
|
|
23
|
+
if (numbered.length === 0)
|
|
24
|
+
return undefined;
|
|
25
|
+
const best = [...numbered].sort((a, b) => Math.abs(a.yields - servings) - Math.abs(b.yields - servings) || b.yields - a.yields)[0];
|
|
26
|
+
return { yields: best.yields, exact: best.yields === servings, entry: best };
|
|
27
|
+
}
|
|
28
|
+
const trimmed = (s) => (s === undefined ? undefined : s.trim());
|
|
29
|
+
export function projectRecipe(detail, servings) {
|
|
30
|
+
const yieldFor = nearestYield(detail.yields, servings);
|
|
31
|
+
const amounts = new Map((yieldFor?.entry.ingredients ?? []).map((i) => [i.id, i]));
|
|
32
|
+
const ingredients = (detail.ingredients ?? []).filter((i) => !!i.name?.trim()).map((i) => {
|
|
33
|
+
const a = i.id !== undefined ? amounts.get(i.id) : undefined;
|
|
34
|
+
return {
|
|
35
|
+
name: i.name.trim(),
|
|
36
|
+
...(typeof a?.amount === 'number' ? { amount: a.amount } : {}),
|
|
37
|
+
...(a?.unit ? { unit: a.unit } : {}),
|
|
38
|
+
...(i.shipped === false ? { notInBox: true } : {}),
|
|
39
|
+
};
|
|
40
|
+
});
|
|
41
|
+
const yieldsNote = !yieldFor
|
|
42
|
+
? 'HelloFresh lists no ingredient amounts for this recipe: names only.'
|
|
43
|
+
: yieldFor.exact
|
|
44
|
+
? undefined
|
|
45
|
+
: `HelloFresh lists no ${servings}-serving amounts for this recipe; these are for ${yieldFor.yields} servings (the nearest) — scale them.`;
|
|
46
|
+
const totalMinutes = recipeMinutes(detail);
|
|
47
|
+
const steps = [...(detail.steps ?? [])]
|
|
48
|
+
.sort((a, b) => (a.index ?? Infinity) - (b.index ?? Infinity) || 0)
|
|
49
|
+
.map((s) => plainText(s.instructions ?? s.instructionsHTML ?? ''))
|
|
50
|
+
.filter((text) => text !== '')
|
|
51
|
+
.map((text, i) => ({ step: i + 1, text }));
|
|
52
|
+
return {
|
|
53
|
+
name: trimmed(detail.name),
|
|
54
|
+
headline: trimmed(detail.headline),
|
|
55
|
+
...(totalMinutes !== undefined ? { totalMinutes } : {}),
|
|
56
|
+
...(detail.difficulty !== undefined && detail.difficulty !== null ? { difficulty: detail.difficulty } : {}),
|
|
57
|
+
allergens: [...new Set((detail.allergens ?? []).map((a) => a.name).filter((n) => !!n))],
|
|
58
|
+
nutritionPerServing: (detail.nutrition ?? []).map((n) => ({
|
|
59
|
+
name: n.name,
|
|
60
|
+
...(typeof n.amount === 'number' ? { amount: n.amount } : {}),
|
|
61
|
+
unit: n.unit,
|
|
62
|
+
})),
|
|
63
|
+
...(yieldFor ? { amountsForServings: yieldFor.yields } : {}),
|
|
64
|
+
...(yieldsNote ? { yieldsNote } : {}),
|
|
65
|
+
ingredients,
|
|
66
|
+
steps,
|
|
67
|
+
utensils: (detail.utensils ?? [])
|
|
68
|
+
.map((u) => (typeof u === 'string' ? u : u.name))
|
|
69
|
+
.filter((n) => !!n),
|
|
70
|
+
...(detail.cardLink ? { cardLink: detail.cardLink } : {}),
|
|
71
|
+
...(detail.websiteUrl ? { websiteUrl: detail.websiteUrl } : {}),
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
const GROUPS = {
|
|
75
|
+
fish: { rank: 1, why: 'Fish is the most perishable protein: cook it first.' },
|
|
76
|
+
shellfish: { rank: 2, why: 'Shellfish keeps only a day or two: cook it early.' },
|
|
77
|
+
seafood: { rank: 3, why: 'Seafood keeps only a couple of days: cook it early in the week.' },
|
|
78
|
+
poultry: { rank: 4, why: 'Raw poultry keeps a few days: cook it before red meat.' },
|
|
79
|
+
'ground-meat': { rank: 5, why: 'Ground meat and sausage spoil sooner than whole cuts.' },
|
|
80
|
+
'other-meat': { rank: 5, why: 'No clear protein category: treated like ground or other meat, mid-week.' },
|
|
81
|
+
'red-meat': { rank: 6, why: 'Whole cuts of beef, pork or lamb keep longest of the proteins.' },
|
|
82
|
+
veggie: { rank: 7, why: 'Vegetarian: the most forgiving, so it goes last.' },
|
|
83
|
+
};
|
|
84
|
+
const SHELLFISH = /\b(scallops?|shrimps?|prawns?|mussels?|clams?)\b/i;
|
|
85
|
+
const POULTRY = /\b(chicken|turkey|duck)\b/i;
|
|
86
|
+
const GROUND = /\bground (beef|pork|lamb|meat|turkey|chicken)\b|\bsausages?\b|\bmeatballs?\b|\bburgers?\b|\bmeatloaf\b/i;
|
|
87
|
+
const RED = /\b(beef|steak|pork|lamb|brisket|ribs?)\b/i;
|
|
88
|
+
const VEGGIE = new Set(['veggie', 'vegetarian', 'vegan']);
|
|
89
|
+
const RED_CATEGORIES = new Set(['beef', 'pork', 'lamb']);
|
|
90
|
+
export function perishabilityOf(d) {
|
|
91
|
+
const category = d.category?.toLowerCase() ?? null;
|
|
92
|
+
const group = (() => {
|
|
93
|
+
if (category === 'seafood' || d.seafoodKind) {
|
|
94
|
+
if (d.seafoodKind === 'fish')
|
|
95
|
+
return 'fish';
|
|
96
|
+
if (d.seafoodKind === 'shrimp' || SHELLFISH.test(d.text))
|
|
97
|
+
return 'shellfish';
|
|
98
|
+
return 'seafood';
|
|
99
|
+
}
|
|
100
|
+
if (category === 'poultry' || (category === null && POULTRY.test(d.text)))
|
|
101
|
+
return 'poultry';
|
|
102
|
+
if (category !== null && VEGGIE.has(category))
|
|
103
|
+
return 'veggie';
|
|
104
|
+
if (GROUND.test(d.text))
|
|
105
|
+
return 'ground-meat';
|
|
106
|
+
if ((category !== null && RED_CATEGORIES.has(category)) || (category === null && RED.test(d.text)))
|
|
107
|
+
return 'red-meat';
|
|
108
|
+
return 'other-meat';
|
|
109
|
+
})();
|
|
110
|
+
return { group, ...GROUPS[group] };
|
|
111
|
+
}
|
|
112
|
+
/** Most perishable first; ties by shorter total time (an unknown time last). Stable. */
|
|
113
|
+
export function cookOrder(dishes) {
|
|
114
|
+
return dishes
|
|
115
|
+
.map((d) => ({ ...d, ...perishabilityOf(d) }))
|
|
116
|
+
.sort((a, b) => a.rank - b.rank || (a.totalMinutes ?? Infinity) - (b.totalMinutes ?? Infinity));
|
|
117
|
+
}
|
|
118
|
+
const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
|
|
119
|
+
/** The weekday and date `n` days after `date` (`YYYY-MM-DD`). */
|
|
120
|
+
export function dayFrom(date, n) {
|
|
121
|
+
const d = new Date(Date.parse(`${date}T00:00:00Z`) + n * 86_400_000);
|
|
122
|
+
return { day: DAYS[d.getUTCDay()], date: d.toISOString().slice(0, 10) };
|
|
123
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -7,9 +7,10 @@ import { createProfileStore } from './profiles.js';
|
|
|
7
7
|
import { HelloFreshSession } from './session.js';
|
|
8
8
|
import { createHelloFreshBridge } from './transport.js';
|
|
9
9
|
import { VERSION } from './version.js';
|
|
10
|
-
// The bridge
|
|
11
|
-
//
|
|
12
|
-
//
|
|
10
|
+
// The bridge bootstraps the session: it reads (and refreshes) the apiV2Auth
|
|
11
|
+
// cookie through the signed-in www.hellofresh.com tab. Every API call is a
|
|
12
|
+
// plain Node fetch with a Bearer token — except the price calculator, which
|
|
13
|
+
// Cloudflare refuses from Node, so it runs as an in-tab fetch (`tabFetch`).
|
|
13
14
|
const bridge = createHelloFreshBridge({ port: readWsPort(), version: VERSION });
|
|
14
15
|
// start() loads the fetchproxy identity (no port bind — that is lazy). A
|
|
15
16
|
// failure is NOT fatal: the next use retries the start (and throws its error
|
|
@@ -23,7 +24,7 @@ const deps = {
|
|
|
23
24
|
bridge,
|
|
24
25
|
session,
|
|
25
26
|
fetchImpl,
|
|
26
|
-
client: new HelloFreshClient({ session, fetchImpl }),
|
|
27
|
+
client: new HelloFreshClient({ session, fetchImpl, tabFetch: (req) => bridge.fetchInTab(req) }),
|
|
27
28
|
// Planner profiles load on first use: a malformed config is a tool error, never a boot failure.
|
|
28
29
|
profiles: createProfileStore(),
|
|
29
30
|
};
|
package/dist/normalize.js
CHANGED
|
@@ -114,6 +114,7 @@ function projectVariant(variation, meal) {
|
|
|
114
114
|
const charge = premium(meal);
|
|
115
115
|
return {
|
|
116
116
|
index: variation.index,
|
|
117
|
+
...(recipe.id ? { recipeId: recipe.id } : {}),
|
|
117
118
|
title: variation.title,
|
|
118
119
|
name: recipe.name,
|
|
119
120
|
category,
|
|
@@ -133,6 +134,7 @@ function projectMeal(meal, variants) {
|
|
|
133
134
|
const charge = premium(meal);
|
|
134
135
|
return {
|
|
135
136
|
index: meal.index,
|
|
137
|
+
...(recipe.id ? { recipeId: recipe.id } : {}),
|
|
136
138
|
name: recipe.name,
|
|
137
139
|
headline: recipe.headline,
|
|
138
140
|
category,
|
|
@@ -183,6 +185,36 @@ export function projectMenu(menu) {
|
|
|
183
185
|
}));
|
|
184
186
|
return { week: menu.week, mealsReady: menu.mealsReady, meals: projected, selected };
|
|
185
187
|
}
|
|
188
|
+
/** Recipe favourites as recipe id + date: the customer uuid each item carries is never kept. */
|
|
189
|
+
export function projectFavorites(raw) {
|
|
190
|
+
const favorites = (raw.items ?? []).flatMap((f) => (f.object_type === undefined || f.object_type === 'recipe') && typeof f.object_id === 'string' && f.object_id
|
|
191
|
+
? [{ recipeId: f.object_id, ...(f.created_at ? { favoritedAt: f.created_at } : {}) }]
|
|
192
|
+
: []);
|
|
193
|
+
return { ...(raw.total !== undefined ? { total: raw.total } : {}), favorites };
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Recipe ratings, read DEFENSIVELY: the list's item shape has not been observed
|
|
197
|
+
* (docs/HELLOFRESH-API.md "Ratings"). An item counts when it carries the recipe
|
|
198
|
+
* id as `object_id` (the shape of the same service's favourites) and a numeric
|
|
199
|
+
* `rating` (the rate call's body field), plus `hellofresh_week` when present;
|
|
200
|
+
* anything else is skipped and counted, never guessed at.
|
|
201
|
+
*/
|
|
202
|
+
export function projectRatings(raw, scale) {
|
|
203
|
+
let skipped = 0;
|
|
204
|
+
const ratings = [];
|
|
205
|
+
for (const item of raw.items ?? []) {
|
|
206
|
+
const r = typeof item === 'object' && item !== null ? item : {};
|
|
207
|
+
const recipeId = typeof r.object_id === 'string' && r.object_id ? r.object_id : undefined;
|
|
208
|
+
const rating = typeof r.rating === 'number' || typeof r.rating === 'string' ? Number(r.rating) : Number.NaN;
|
|
209
|
+
if (!recipeId || !Number.isFinite(rating)) {
|
|
210
|
+
skipped++;
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
const week = typeof r.hellofresh_week === 'string' ? r.hellofresh_week : undefined;
|
|
214
|
+
ratings.push({ recipeId, rating, scale, ...(week ? { week } : {}) });
|
|
215
|
+
}
|
|
216
|
+
return { ratings, skipped };
|
|
217
|
+
}
|
|
186
218
|
/**
|
|
187
219
|
* Estimate a box total (docs/HELLOFRESH-API.md "Pricing"): product + special
|
|
188
220
|
* fee + shipping + Σ premium upcharges, minus the voucher's percentage for this
|
package/dist/planner.js
CHANGED
|
@@ -10,6 +10,12 @@
|
|
|
10
10
|
// the cap only lightly penalised;
|
|
11
11
|
// - premiums over the profile's per-serving cap are excluded; under it they
|
|
12
12
|
// cost points in proportion to the upcharge × servings.
|
|
13
|
+
// - favourites: a recipe the user favourited (the dish's own recipe or, for
|
|
14
|
+
// a protein swap, its base recipe) is boosted;
|
|
15
|
+
// - ratings: a recipe the user rated 2 or lower (on either ratings scale) is
|
|
16
|
+
// NEVER suggested (it is listed in `excluded` with the rating).
|
|
17
|
+
// HelloFresh's own `averageRating` is not used: the weekly menu does not carry
|
|
18
|
+
// it, and reading it means one recipe-detail call per dish — not cheap.
|
|
13
19
|
// Picks then favour protein diversity (distinct categories, and within
|
|
14
20
|
// Seafood distinct kinds — e.g. one shrimp + one fish) and never repeat a
|
|
15
21
|
// recently picked recipe. Each recipe is ONE dish: a base course in the allowed
|
|
@@ -20,13 +26,31 @@ import { profileLabel } from './profiles.js';
|
|
|
20
26
|
/** The bonus for a pick whose protein is not yet in the box. */
|
|
21
27
|
const DIVERSITY_BONUS = 15;
|
|
22
28
|
const QUICK_MINUTES = 30;
|
|
29
|
+
/** The bonus for a recipe the user favourited. */
|
|
30
|
+
const FAVORITE_BONUS = 25;
|
|
31
|
+
/** A user rating at or below this (either scale) means never suggest the recipe. */
|
|
32
|
+
export const LOW_RATING = 2;
|
|
23
33
|
/** Cuisines that do not count as adventurous. */
|
|
24
34
|
const FAMILIAR_CUISINES = new Set(['American', 'Italian', 'Irish', 'British']);
|
|
25
35
|
export const dollars = (cents) => `$${(cents / 100).toFixed(2)}`;
|
|
26
36
|
const normalName = (name) => name.trim().toLowerCase().replace(/\s+/g, ' ');
|
|
27
37
|
const courseOf = (c) => c.baseIndex ?? c.index;
|
|
28
|
-
|
|
29
|
-
const
|
|
38
|
+
const proteinOf = (d) => d.seafoodKind ?? d.category ?? 'unknown';
|
|
39
|
+
const titledDouble = (v) => /\b2x\b/i.test(`${v.title ?? ''} ${v.name ?? ''}`);
|
|
40
|
+
/**
|
|
41
|
+
* A double-protein swap — an upgrade, not a swap: "2x" in its title or name
|
|
42
|
+
* ("2x Shrimp", "… with 2x Tilapia"), OR a premium above the cheapest
|
|
43
|
+
* single-protein swap of the SAME protein on the same base course (e.g.
|
|
44
|
+
* "Extra Shrimp" at +$3.99 next to "Shrimp" at +$0). A different protein at a
|
|
45
|
+
* premium (Salmon next to Shrimp) is an ordinary swap.
|
|
46
|
+
*/
|
|
47
|
+
export function isDoubleProtein(variant, siblings) {
|
|
48
|
+
if (titledDouble(variant))
|
|
49
|
+
return true;
|
|
50
|
+
const protein = proteinOf(variant);
|
|
51
|
+
const singles = siblings.filter((s) => !titledDouble(s) && proteinOf(s) === protein).map((s) => s.premiumPerServingCents);
|
|
52
|
+
return singles.length > 0 && variant.premiumPerServingCents > Math.min(...singles);
|
|
53
|
+
}
|
|
30
54
|
/**
|
|
31
55
|
* One dish per recipe (a base course and its protein swaps are ONE recipe):
|
|
32
56
|
* the base course itself when it is in the allowed categories (or there is no
|
|
@@ -41,6 +65,7 @@ function dishes(menu, allowed) {
|
|
|
41
65
|
{
|
|
42
66
|
dish: {
|
|
43
67
|
index: course.index,
|
|
68
|
+
recipeId: course.recipeId,
|
|
44
69
|
name: course.name,
|
|
45
70
|
category: course.category,
|
|
46
71
|
seafoodKind: course.seafoodKind,
|
|
@@ -51,9 +76,10 @@ function dishes(menu, allowed) {
|
|
|
51
76
|
},
|
|
52
77
|
];
|
|
53
78
|
}
|
|
79
|
+
const double = (v) => isDoubleProtein(v, course.variants);
|
|
54
80
|
const [swap] = course.variants
|
|
55
81
|
.filter((v) => allowed(v.category))
|
|
56
|
-
.sort((a, b) => Number(
|
|
82
|
+
.sort((a, b) => Number(double(a)) - Number(double(b)) || a.premiumPerServingCents - b.premiumPerServingCents || a.index - b.index);
|
|
57
83
|
if (!swap)
|
|
58
84
|
return [];
|
|
59
85
|
return [
|
|
@@ -61,6 +87,8 @@ function dishes(menu, allowed) {
|
|
|
61
87
|
dish: {
|
|
62
88
|
index: swap.index,
|
|
63
89
|
baseIndex: course.index,
|
|
90
|
+
recipeId: swap.recipeId ?? course.recipeId,
|
|
91
|
+
...(double(swap) ? { double: true } : {}),
|
|
64
92
|
name: swap.name ?? swap.title,
|
|
65
93
|
category: swap.category,
|
|
66
94
|
seafoodKind: swap.seafoodKind,
|
|
@@ -72,8 +100,9 @@ function dishes(menu, allowed) {
|
|
|
72
100
|
];
|
|
73
101
|
});
|
|
74
102
|
}
|
|
75
|
-
|
|
76
|
-
|
|
103
|
+
/** The recipe ids a dish stands for: its own and, for a swap, its base course's. */
|
|
104
|
+
const recipeIdsOf = (dish, course) => [dish.recipeId, course.recipeId].filter((id) => !!id);
|
|
105
|
+
function score(dish, course, profile, people, favorite) {
|
|
77
106
|
const reasons = [];
|
|
78
107
|
let points = 0;
|
|
79
108
|
const add = (n, why) => {
|
|
@@ -82,6 +111,10 @@ function score(dish, course, profile, people) {
|
|
|
82
111
|
};
|
|
83
112
|
const minutes = course.totalMinutes;
|
|
84
113
|
const premiumBoxCents = dish.premiumPerServingCents * people;
|
|
114
|
+
if (dish.double)
|
|
115
|
+
reasons.push('double-protein upgrade (no single-protein swap fits)');
|
|
116
|
+
if (favorite)
|
|
117
|
+
add(FAVORITE_BONUS, 'one of your favorites');
|
|
85
118
|
if (profile.kidFriendly) {
|
|
86
119
|
if (course.kidFriendly)
|
|
87
120
|
add(30, 'kid friendly');
|
|
@@ -102,8 +135,10 @@ function score(dish, course, profile, people) {
|
|
|
102
135
|
const why = `premium +${dollars(dish.premiumPerServingCents)}/serving (+${dollars(premiumBoxCents)} for ${people} servings)`;
|
|
103
136
|
add(profile.adventurous ? 5 - Math.round(premiumBoxCents / 200) : -Math.round(premiumBoxCents / 100), why);
|
|
104
137
|
}
|
|
138
|
+
const { double: _double, ...rest } = dish;
|
|
105
139
|
return {
|
|
106
|
-
...
|
|
140
|
+
...rest,
|
|
141
|
+
...(favorite ? { favorite: true } : {}),
|
|
107
142
|
protein: proteinOf(dish),
|
|
108
143
|
kidFriendly: course.kidFriendly,
|
|
109
144
|
quick: course.quick,
|
|
@@ -143,20 +178,29 @@ export function suggestMeals(menu, opts) {
|
|
|
143
178
|
const avoidIndexes = new Set(opts.avoidIndexes ?? []);
|
|
144
179
|
const avoidNames = new Set((opts.avoidNames ?? []).map(normalName));
|
|
145
180
|
const allowed = (category) => !categories || categories.has((category ?? '').toLowerCase());
|
|
181
|
+
const favorites = new Set(opts.favoriteRecipeIds ?? []);
|
|
182
|
+
const lowRated = new Map();
|
|
183
|
+
for (const r of opts.ratings ?? [])
|
|
184
|
+
if (r.rating <= LOW_RATING && !lowRated.has(r.recipeId))
|
|
185
|
+
lowRated.set(r.recipeId, r);
|
|
146
186
|
const excluded = [];
|
|
147
187
|
const eligible = [];
|
|
148
188
|
for (const { dish, course } of dishes(menu, allowed)) {
|
|
149
|
-
const
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
189
|
+
const ids = recipeIdsOf(dish, course);
|
|
190
|
+
const low = ids.map((id) => lowRated.get(id)).find((r) => r !== undefined);
|
|
191
|
+
const reason = low
|
|
192
|
+
? `you rated it ${low.rating} (${low.scale} scale): low-rated recipes are never suggested`
|
|
193
|
+
: avoidIndexes.has(dish.index)
|
|
194
|
+
? 'avoided by request'
|
|
195
|
+
: dish.name && avoidNames.has(normalName(dish.name))
|
|
196
|
+
? 'picked in a recent week'
|
|
197
|
+
: dish.premiumPerServingCents > cap
|
|
198
|
+
? `premium ${dollars(dish.premiumPerServingCents)}/serving over the ${dollars(cap)} cap`
|
|
199
|
+
: undefined;
|
|
156
200
|
if (reason)
|
|
157
201
|
excluded.push({ index: dish.index, name: dish.name, reason });
|
|
158
202
|
else
|
|
159
|
-
eligible.push(score(dish, course, profile, people));
|
|
203
|
+
eligible.push(score(dish, course, profile, people, ids.some((id) => favorites.has(id))));
|
|
160
204
|
}
|
|
161
205
|
const ranked = eligible.sort((a, b) => b.score - a.score || a.index - b.index);
|
|
162
206
|
const picks = choose(ranked, profile.meals);
|
|
@@ -200,14 +244,25 @@ export function dayLabel(iso) {
|
|
|
200
244
|
const [year, month, day] = [Number(m[1]), Number(m[2]), Number(m[3])];
|
|
201
245
|
return `${WEEKDAYS[new Date(Date.UTC(year, month - 1, day)).getUTCDay()]} ${month}/${day}`;
|
|
202
246
|
}
|
|
247
|
+
const usd = (amount) => `$${amount.toFixed(2)}`;
|
|
248
|
+
function priceLine(p) {
|
|
249
|
+
const discount = p.discount ? `−${usd(p.discount)}${p.couponCode ? ` ${p.couponCode}` : ''}` : 'no discount';
|
|
250
|
+
if (p.totalWithPremiums === undefined)
|
|
251
|
+
return `Box total ${usd(p.grandTotal)} (HelloFresh price, premiums not included; ${discount}).`;
|
|
252
|
+
const source = p.premiumUpcharge ? `HelloFresh price ${usd(p.grandTotal)} + ${usd(p.premiumUpcharge)} premiums` : 'HelloFresh price';
|
|
253
|
+
return `Box total ${usd(p.totalWithPremiums)} (${source}; ${discount}).`;
|
|
254
|
+
}
|
|
203
255
|
/**
|
|
204
256
|
* The approval line:
|
|
205
257
|
* `Family week (4 servings) — delivering Mon 11/30: <A> + <B>. Est. box total $X (−$Y CODE).`
|
|
206
258
|
*/
|
|
207
|
-
export function summaryText({ profile, people, deliveryDate, picks, estimate }) {
|
|
259
|
+
export function summaryText({ profile, people, deliveryDate, picks, estimate, price }) {
|
|
208
260
|
const meals = picks.length > 0 ? picks.map((p) => p.name?.trim() || '(unnamed meal)').join(' + ') : 'no picks fit';
|
|
209
261
|
let total = 'Box total not estimated.';
|
|
210
|
-
if (
|
|
262
|
+
if (price) {
|
|
263
|
+
total = priceLine(price);
|
|
264
|
+
}
|
|
265
|
+
else if (estimate) {
|
|
211
266
|
const discount = estimate.discountCents > 0
|
|
212
267
|
? `−${dollars(estimate.discountCents)}${estimate.voucher?.code ? ` ${estimate.voucher.code}` : ''}`
|
|
213
268
|
: 'no voucher discount';
|
package/dist/session.js
CHANGED
|
@@ -14,6 +14,20 @@
|
|
|
14
14
|
// surfaces WRITE_BACK_WARNING.
|
|
15
15
|
// 4. A 401 from any call invalidates the token, re-runs the lifecycle once
|
|
16
16
|
// (never trusting the rejected token again) and retries the call once.
|
|
17
|
+
// 5. When the browser cookie read FAILS (bridge down, tab closed, pairing
|
|
18
|
+
// pending) but the newest set this process knows is one it refreshed
|
|
19
|
+
// itself, it may stand in — how far depends on its write-back:
|
|
20
|
+
// - the write-back FAILED: the browser never received that refresh token,
|
|
21
|
+
// so only this process can have spent it. While it has not expired it
|
|
22
|
+
// is used, refreshed (and written back) as in 3 when stale.
|
|
23
|
+
// - the write-back SUCCEEDED: the browser holds that refresh token and
|
|
24
|
+
// may already have rotated it (POSTing a spent one can sign the browser
|
|
25
|
+
// out). Only its ACCESS token is used, while still valid (and not
|
|
26
|
+
// rejected); otherwise the original bridge error is rethrown, its
|
|
27
|
+
// pairing hint intact. /gw/refresh is never called.
|
|
28
|
+
// A set read from the browser is never a fallback: its refresh token may
|
|
29
|
+
// already be spent by the browser. A missing cookie (signed out) is NOT a
|
|
30
|
+
// read failure and still fails.
|
|
17
31
|
//
|
|
18
32
|
// No token value is ever logged, put in an error message or returned.
|
|
19
33
|
import { EdgeBlockedError, McpToolError, SessionNotAuthenticatedError, createCachedTokenSource, decodeJwtClaim, detectEdgeBlock, messageOf, parseJsonBody, redactValues, truncateErrorMessage, } from '@chrischall/mcp-utils';
|
|
@@ -139,6 +153,10 @@ export class HelloFreshSession {
|
|
|
139
153
|
/** An access token the API rejected: never trusted again, even if the cookie still holds it. */
|
|
140
154
|
rejected;
|
|
141
155
|
writeBackWarning;
|
|
156
|
+
/** The refresh token of this process's own latest refresh (the fallback when the cookie read fails). */
|
|
157
|
+
ownRefreshToken;
|
|
158
|
+
/** Whether that refresh was written back to the browser (which may then rotate it on its own). */
|
|
159
|
+
ownWrittenBack = false;
|
|
142
160
|
seen = [];
|
|
143
161
|
constructor(opts) {
|
|
144
162
|
this.opts = opts;
|
|
@@ -204,8 +222,28 @@ export class HelloFreshSession {
|
|
|
204
222
|
fresh(set) {
|
|
205
223
|
return set.access_token !== this.rejected && tokenExpiresAtMs(set) - this.now() > EXPIRY_SKEW_MS;
|
|
206
224
|
}
|
|
207
|
-
|
|
208
|
-
|
|
225
|
+
/** Whether `set`'s refresh token is still usable: its stated lifetime has not run out (unstated = try it). */
|
|
226
|
+
refreshable(set) {
|
|
227
|
+
if (typeof set.refresh_expires_in !== 'number')
|
|
228
|
+
return true;
|
|
229
|
+
return (set.issued_at + set.refresh_expires_in) * 1000 > this.now();
|
|
230
|
+
}
|
|
231
|
+
/** The newest token set: the browser cookie's or our own (lifecycle steps 2 and 5). */
|
|
232
|
+
async newestSet() {
|
|
233
|
+
let raw;
|
|
234
|
+
try {
|
|
235
|
+
raw = await this.bridged(() => this.opts.bridge.readAuthCookie());
|
|
236
|
+
}
|
|
237
|
+
catch (err) {
|
|
238
|
+
const ours = this.latest;
|
|
239
|
+
if (!ours || ours.refresh_token !== this.ownRefreshToken)
|
|
240
|
+
throw err;
|
|
241
|
+
// Written back: the browser may have rotated (spent) its refresh token — use the access token only.
|
|
242
|
+
if (this.ownWrittenBack ? !this.fresh(ours) : !this.refreshable(ours))
|
|
243
|
+
throw err;
|
|
244
|
+
console.error(`[hellofresh-mcp] could not read the browser session (${truncateErrorMessage(this.redact(messageOf(err)), 200)}); using this process's own refreshed session`);
|
|
245
|
+
return ours;
|
|
246
|
+
}
|
|
209
247
|
if (!raw)
|
|
210
248
|
throw new HelloFreshSessionError(`no ${AUTH_COOKIE} cookie was found on www.hellofresh.com`);
|
|
211
249
|
const browser = decodeAuthCookie(raw);
|
|
@@ -214,18 +252,24 @@ export class HelloFreshSession {
|
|
|
214
252
|
// then the cookie's refresh token is already spent and ours must be used.
|
|
215
253
|
const ours = this.latest;
|
|
216
254
|
const browserIsNewest = !ours || browser.issued_at >= ours.issued_at;
|
|
217
|
-
const newest = browserIsNewest ? browser : ours;
|
|
218
255
|
if (browserIsNewest)
|
|
219
256
|
this.writeBackWarning = undefined;
|
|
257
|
+
return browserIsNewest ? browser : ours;
|
|
258
|
+
}
|
|
259
|
+
async lifecycle() {
|
|
260
|
+
const newest = await this.newestSet();
|
|
220
261
|
if (this.fresh(newest)) {
|
|
221
262
|
this.latest = newest;
|
|
222
263
|
return newest;
|
|
223
264
|
}
|
|
224
265
|
const next = await this.refresh(newest);
|
|
225
266
|
this.latest = next;
|
|
267
|
+
this.ownRefreshToken = next.refresh_token;
|
|
268
|
+
this.ownWrittenBack = false;
|
|
226
269
|
this.remember(next);
|
|
227
270
|
try {
|
|
228
271
|
await this.opts.bridge.writeAuthCookie(encodeAuthCookie(next));
|
|
272
|
+
this.ownWrittenBack = true;
|
|
229
273
|
this.writeBackWarning = undefined;
|
|
230
274
|
}
|
|
231
275
|
catch (err) {
|