@tbs-fitness/contract 0.5.0 → 0.7.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/README.md +33 -9
- package/dist/cjs/auth/auth.dto.js +5 -0
- package/dist/cjs/enums/index.d.ts +80 -0
- package/dist/cjs/enums/index.js +97 -1
- package/dist/cjs/feature-flags/feature-flag.dto.d.ts +9 -0
- package/dist/cjs/feature-flags/feature-flag.dto.js +9 -1
- package/dist/cjs/food/client-food.dto.d.ts +49 -0
- package/dist/cjs/food/client-food.dto.js +26 -0
- package/dist/cjs/food/food-import.dto.d.ts +160 -0
- package/dist/cjs/food/food-import.dto.js +110 -0
- package/dist/cjs/food/food-suggestion.dto.d.ts +374 -0
- package/dist/cjs/food/food-suggestion.dto.js +170 -0
- package/dist/cjs/food/food.dto.d.ts +339 -0
- package/dist/cjs/food/food.dto.js +256 -0
- package/dist/cjs/food/index.d.ts +5 -0
- package/dist/cjs/food/index.js +21 -0
- package/dist/cjs/food/nutrition.d.ts +75 -0
- package/dist/cjs/food/nutrition.js +158 -0
- package/dist/esm/auth/auth.dto.js +5 -0
- package/dist/esm/enums/index.d.ts +80 -0
- package/dist/esm/enums/index.js +96 -0
- package/dist/esm/feature-flags/feature-flag.dto.d.ts +9 -0
- package/dist/esm/feature-flags/feature-flag.dto.js +8 -0
- package/dist/esm/food/client-food.dto.d.ts +49 -0
- package/dist/esm/food/client-food.dto.js +23 -0
- package/dist/esm/food/food-import.dto.d.ts +160 -0
- package/dist/esm/food/food-import.dto.js +107 -0
- package/dist/esm/food/food-suggestion.dto.d.ts +374 -0
- package/dist/esm/food/food-suggestion.dto.js +167 -0
- package/dist/esm/food/food.dto.d.ts +339 -0
- package/dist/esm/food/food.dto.js +253 -0
- package/dist/esm/food/index.d.ts +5 -0
- package/dist/esm/food/index.js +5 -0
- package/dist/esm/food/nutrition.d.ts +75 -0
- package/dist/esm/food/nutrition.js +144 -0
- package/package.json +11 -1
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { utcTimestampSchema } from '../common/date-time.schema.js';
|
|
3
|
+
import { paginationQuerySchema } from '../common/pagination.schema.js';
|
|
4
|
+
import { safeTextSchema } from '../common/safe-text.schema.js';
|
|
5
|
+
import { FOOD_METADATA_SELECTIONS, FOOD_SORT_FIELDS, FOOD_SOURCES, NUTRITION_BASES, SERVING_UNITS, SORT_ORDERS, } from '../enums/index.js';
|
|
6
|
+
import { nutrientAmountSchema, nutritionIssues, quantitySchema, toPer100, } from './nutrition.js';
|
|
7
|
+
// Each request has two types. `*Input` is what a client sends, where fields with
|
|
8
|
+
// a default are optional. `*Body` is what the API receives after validation.
|
|
9
|
+
export const MAX_FOOD_NAME_LENGTH = 120;
|
|
10
|
+
export const MAX_FOOD_NOTES_LENGTH = 1000;
|
|
11
|
+
export const MAX_FOOD_METADATA_VALUES = 50;
|
|
12
|
+
export const MAX_FOOD_SEARCH_LENGTH = 100;
|
|
13
|
+
export const foodIdParamSchema = z.uuid();
|
|
14
|
+
export const metadataTypeIdParamSchema = z.uuid();
|
|
15
|
+
export const metadataValueIdParamSchema = z.uuid();
|
|
16
|
+
const foodNameSchema = safeTextSchema(MAX_FOOD_NAME_LENGTH);
|
|
17
|
+
const optionalNameSchema = safeTextSchema(MAX_FOOD_NAME_LENGTH)
|
|
18
|
+
.nullable()
|
|
19
|
+
.optional();
|
|
20
|
+
export const servingSchema = z.strictObject({
|
|
21
|
+
/** As people say it, e.g. "1 cup (200g)". */
|
|
22
|
+
label: safeTextSchema(MAX_FOOD_NAME_LENGTH),
|
|
23
|
+
/** The weight or volume of one serving in `unit`, e.g. 200. */
|
|
24
|
+
quantity: quantitySchema(),
|
|
25
|
+
unit: z.enum(SERVING_UNITS),
|
|
26
|
+
});
|
|
27
|
+
/**
|
|
28
|
+
* Nutrient values as entered. `basis` says whether they are per 100 units of
|
|
29
|
+
* the serving unit or for one serving; the API stores them per 100.
|
|
30
|
+
*/
|
|
31
|
+
export const nutritionInputSchema = z.strictObject({
|
|
32
|
+
basis: z.enum(NUTRITION_BASES).default('PER_100'),
|
|
33
|
+
calories: nutrientAmountSchema(),
|
|
34
|
+
protein: nutrientAmountSchema(),
|
|
35
|
+
carbs: nutrientAmountSchema(),
|
|
36
|
+
fat: nutrientAmountSchema(),
|
|
37
|
+
sugar: nutrientAmountSchema().nullable().optional(),
|
|
38
|
+
fiber: nutrientAmountSchema().nullable().optional(),
|
|
39
|
+
solubleFiber: nutrientAmountSchema().nullable().optional(),
|
|
40
|
+
insolubleFiber: nutrientAmountSchema().nullable().optional(),
|
|
41
|
+
});
|
|
42
|
+
const uniqueIds = (ids) => new Set(ids).size === ids.length;
|
|
43
|
+
const metadataValueIdsSchema = z
|
|
44
|
+
.array(z.uuid())
|
|
45
|
+
.max(MAX_FOOD_METADATA_VALUES)
|
|
46
|
+
.refine(uniqueIds, { error: 'Each value may be listed once' });
|
|
47
|
+
/** Adds an issue for every nutrition rule the values break, measured per 100. */
|
|
48
|
+
function checkNutrition(nutrition, servingQuantity, ctx) {
|
|
49
|
+
if (nutrition.basis === 'PER_SERVING' && servingQuantity === undefined) {
|
|
50
|
+
// An update that changes values per serving without a serving uses the
|
|
51
|
+
// stored serving, so the API checks it.
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
const per100 = nutrition.basis === 'PER_SERVING' && servingQuantity !== undefined
|
|
55
|
+
? toPer100(nutrition, servingQuantity)
|
|
56
|
+
: nutrition;
|
|
57
|
+
for (const issue of nutritionIssues(per100)) {
|
|
58
|
+
ctx.addIssue({
|
|
59
|
+
code: 'custom',
|
|
60
|
+
message: issue.message,
|
|
61
|
+
path: ['nutrition', issue.path],
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
const foodFields = {
|
|
66
|
+
name: foodNameSchema,
|
|
67
|
+
nameHi: optionalNameSchema,
|
|
68
|
+
namePa: optionalNameSchema,
|
|
69
|
+
englishAlias: safeTextSchema(200).nullable().optional(),
|
|
70
|
+
serving: servingSchema,
|
|
71
|
+
nutrition: nutritionInputSchema,
|
|
72
|
+
/** Category, subcategory, tags and other labels, by value id. */
|
|
73
|
+
metadataValueIds: metadataValueIdsSchema.default([]),
|
|
74
|
+
notes: safeTextSchema(MAX_FOOD_NOTES_LENGTH).nullable().optional(),
|
|
75
|
+
};
|
|
76
|
+
// Strict objects reject unknown fields, so an attempt to set `source` or
|
|
77
|
+
// `createdBy` through the API fails loudly.
|
|
78
|
+
export const createFoodSchema = z
|
|
79
|
+
.strictObject(foodFields)
|
|
80
|
+
.superRefine((food, ctx) => checkNutrition(food.nutrition, food.serving.quantity, ctx));
|
|
81
|
+
export const updateFoodSchema = z
|
|
82
|
+
.strictObject({
|
|
83
|
+
// The version last read, so that a stale edit is refused rather than lost.
|
|
84
|
+
version: z.number().int().min(1),
|
|
85
|
+
name: foodNameSchema.optional(),
|
|
86
|
+
nameHi: optionalNameSchema,
|
|
87
|
+
namePa: optionalNameSchema,
|
|
88
|
+
englishAlias: safeTextSchema(200).nullable().optional(),
|
|
89
|
+
serving: servingSchema.optional(),
|
|
90
|
+
/** Replaces every nutrient value; omitted nutrients become unknown. */
|
|
91
|
+
nutrition: nutritionInputSchema.optional(),
|
|
92
|
+
/** Replaces every metadata value. */
|
|
93
|
+
metadataValueIds: metadataValueIdsSchema.optional(),
|
|
94
|
+
notes: safeTextSchema(MAX_FOOD_NOTES_LENGTH).nullable().optional(),
|
|
95
|
+
})
|
|
96
|
+
.superRefine((food, ctx) => {
|
|
97
|
+
if (food.nutrition) {
|
|
98
|
+
checkNutrition(food.nutrition, food.serving?.quantity, ctx);
|
|
99
|
+
}
|
|
100
|
+
})
|
|
101
|
+
.refine(({ version: _version, ...changes }) => Object.values(changes).some((value) => value !== undefined), { error: 'Provide at least one field to change' });
|
|
102
|
+
const MAX_FILTER_VALUES = 50;
|
|
103
|
+
/** Accepts `a,b` or a repeated parameter, as query strings carry either. */
|
|
104
|
+
const idListQuerySchema = z.preprocess((value) => {
|
|
105
|
+
if (typeof value === 'string') {
|
|
106
|
+
return value === ''
|
|
107
|
+
? undefined
|
|
108
|
+
: value
|
|
109
|
+
.split(',')
|
|
110
|
+
.map((part) => part.trim())
|
|
111
|
+
.filter(Boolean);
|
|
112
|
+
}
|
|
113
|
+
// Anything other than a string or a list of strings is left for the schema
|
|
114
|
+
// to reject.
|
|
115
|
+
return value;
|
|
116
|
+
}, z.array(z.uuid()).max(MAX_FILTER_VALUES).optional());
|
|
117
|
+
const searchQuerySchema = z
|
|
118
|
+
.string()
|
|
119
|
+
.trim()
|
|
120
|
+
.min(1)
|
|
121
|
+
.max(MAX_FOOD_SEARCH_LENGTH)
|
|
122
|
+
.optional();
|
|
123
|
+
/**
|
|
124
|
+
* `metadata` filters by value ids: a food matches when it has at least one of
|
|
125
|
+
* the listed values of each type that appears in the list.
|
|
126
|
+
*/
|
|
127
|
+
export const foodListQuerySchema = paginationQuerySchema.extend({
|
|
128
|
+
search: searchQuerySchema,
|
|
129
|
+
metadata: idListQuerySchema,
|
|
130
|
+
source: z.enum(FOOD_SOURCES).optional(),
|
|
131
|
+
sort: z.enum(FOOD_SORT_FIELDS).default('name'),
|
|
132
|
+
order: z.enum(SORT_ORDERS).default('asc'),
|
|
133
|
+
});
|
|
134
|
+
export const similarFoodQuerySchema = z.object({
|
|
135
|
+
name: safeTextSchema(MAX_FOOD_NAME_LENGTH),
|
|
136
|
+
});
|
|
137
|
+
// Responses
|
|
138
|
+
export const nutrientValuesResponseSchema = z.object({
|
|
139
|
+
calories: z.number(),
|
|
140
|
+
protein: z.number(),
|
|
141
|
+
carbs: z.number(),
|
|
142
|
+
fat: z.number(),
|
|
143
|
+
sugar: z.number().nullable(),
|
|
144
|
+
fiber: z.number().nullable(),
|
|
145
|
+
solubleFiber: z.number().nullable(),
|
|
146
|
+
insolubleFiber: z.number().nullable(),
|
|
147
|
+
});
|
|
148
|
+
export const servingResponseSchema = z.object({
|
|
149
|
+
label: z.string(),
|
|
150
|
+
quantity: z.number(),
|
|
151
|
+
unit: z.enum(SERVING_UNITS),
|
|
152
|
+
});
|
|
153
|
+
/** A metadata value as attached to a food. */
|
|
154
|
+
export const foodMetadataRefSchema = z.object({
|
|
155
|
+
id: z.uuid(),
|
|
156
|
+
typeKey: z.string(),
|
|
157
|
+
key: z.string(),
|
|
158
|
+
label: z.string(),
|
|
159
|
+
isActive: z.boolean(),
|
|
160
|
+
});
|
|
161
|
+
export const userRefSchema = z.object({
|
|
162
|
+
id: z.uuid(),
|
|
163
|
+
fullName: z.string().nullable(),
|
|
164
|
+
});
|
|
165
|
+
export const foodResponseSchema = z.object({
|
|
166
|
+
id: z.uuid(),
|
|
167
|
+
name: z.string(),
|
|
168
|
+
nameHi: z.string().nullable(),
|
|
169
|
+
namePa: z.string().nullable(),
|
|
170
|
+
englishAlias: z.string().nullable(),
|
|
171
|
+
serving: servingResponseSchema,
|
|
172
|
+
/** Per 100 g, or per 100 ml for a serving in ml. */
|
|
173
|
+
per100: nutrientValuesResponseSchema,
|
|
174
|
+
perServing: nutrientValuesResponseSchema,
|
|
175
|
+
/** Calories from the macros per 100 units: (protein + carbs) × 4 + fat × 9. */
|
|
176
|
+
formulaCalories: z.number(),
|
|
177
|
+
metadata: z.array(foodMetadataRefSchema),
|
|
178
|
+
notes: z.string().nullable(),
|
|
179
|
+
source: z.enum(FOOD_SOURCES),
|
|
180
|
+
createdBy: userRefSchema,
|
|
181
|
+
suggestionId: z.uuid().nullable(),
|
|
182
|
+
importBatchId: z.uuid().nullable(),
|
|
183
|
+
version: z.number().int(),
|
|
184
|
+
createdAt: utcTimestampSchema,
|
|
185
|
+
updatedAt: utcTimestampSchema,
|
|
186
|
+
});
|
|
187
|
+
export const similarFoodResponseSchema = z.object({
|
|
188
|
+
id: z.uuid(),
|
|
189
|
+
name: z.string(),
|
|
190
|
+
serving: servingResponseSchema,
|
|
191
|
+
per100: nutrientValuesResponseSchema,
|
|
192
|
+
/** 0 to 1; 1 is the same name. */
|
|
193
|
+
similarity: z.number(),
|
|
194
|
+
});
|
|
195
|
+
export const foodStatsResponseSchema = z.object({
|
|
196
|
+
totalFoods: z.number().int(),
|
|
197
|
+
categories: z.array(z.object({
|
|
198
|
+
valueId: z.uuid(),
|
|
199
|
+
key: z.string(),
|
|
200
|
+
label: z.string(),
|
|
201
|
+
count: z.number().int(),
|
|
202
|
+
})),
|
|
203
|
+
pendingSuggestions: z.number().int(),
|
|
204
|
+
});
|
|
205
|
+
// Metadata
|
|
206
|
+
export const MAX_METADATA_LABEL_LENGTH = 60;
|
|
207
|
+
export const metadataTypeResponseSchema = z.object({
|
|
208
|
+
id: z.uuid(),
|
|
209
|
+
key: z.string(),
|
|
210
|
+
label: z.string(),
|
|
211
|
+
selection: z.enum(FOOD_METADATA_SELECTIONS),
|
|
212
|
+
parentTypeId: z.uuid().nullable(),
|
|
213
|
+
isRequired: z.boolean(),
|
|
214
|
+
isSystem: z.boolean(),
|
|
215
|
+
isActive: z.boolean(),
|
|
216
|
+
sortOrder: z.number().int(),
|
|
217
|
+
});
|
|
218
|
+
export const metadataTypeListResponseSchema = z.array(metadataTypeResponseSchema);
|
|
219
|
+
export const metadataValueResponseSchema = z.object({
|
|
220
|
+
id: z.uuid(),
|
|
221
|
+
typeId: z.uuid(),
|
|
222
|
+
key: z.string(),
|
|
223
|
+
label: z.string(),
|
|
224
|
+
parentValueId: z.uuid().nullable(),
|
|
225
|
+
isActive: z.boolean(),
|
|
226
|
+
sortOrder: z.number().int(),
|
|
227
|
+
createdAt: utcTimestampSchema,
|
|
228
|
+
updatedAt: utcTimestampSchema,
|
|
229
|
+
});
|
|
230
|
+
export const metadataValueListResponseSchema = z.array(metadataValueResponseSchema);
|
|
231
|
+
export const metadataValueListQuerySchema = z.object({
|
|
232
|
+
includeInactive: z
|
|
233
|
+
.enum(['true', 'false'])
|
|
234
|
+
.transform((value) => value === 'true')
|
|
235
|
+
.optional(),
|
|
236
|
+
});
|
|
237
|
+
const sortOrderSchema = z.number().int().min(0).max(10000);
|
|
238
|
+
/** The key is made from the label, so "High Protein" is stored as `high-protein`. */
|
|
239
|
+
export const createMetadataValueSchema = z.strictObject({
|
|
240
|
+
label: safeTextSchema(MAX_METADATA_LABEL_LENGTH),
|
|
241
|
+
/** Required for a type with a parent, such as a subcategory's category. */
|
|
242
|
+
parentValueId: z.uuid().nullable().optional(),
|
|
243
|
+
sortOrder: sortOrderSchema.default(0),
|
|
244
|
+
});
|
|
245
|
+
/** The key never changes, so renaming a value keeps every link to it. */
|
|
246
|
+
export const updateMetadataValueSchema = z
|
|
247
|
+
.strictObject({
|
|
248
|
+
label: safeTextSchema(MAX_METADATA_LABEL_LENGTH).optional(),
|
|
249
|
+
parentValueId: z.uuid().nullable().optional(),
|
|
250
|
+
sortOrder: sortOrderSchema.optional(),
|
|
251
|
+
isActive: z.boolean().optional(),
|
|
252
|
+
})
|
|
253
|
+
.refine((changes) => Object.values(changes).some((value) => value !== undefined), { error: 'Provide at least one field to change' });
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { type ServingUnit } from '../enums/index.js';
|
|
3
|
+
/**
|
|
4
|
+
* Nutrition rules shared by the backend and the apps, so a value the web form
|
|
5
|
+
* accepts is a value the API accepts, and both calculate derived values the
|
|
6
|
+
* same way.
|
|
7
|
+
*
|
|
8
|
+
* Library nutrients are stored per 100 of the serving unit (per 100 g, or per
|
|
9
|
+
* 100 ml for a serving measured in ml). Per-serving values are always derived.
|
|
10
|
+
*/
|
|
11
|
+
/** The largest nutrient amount per 100 units. Pure fat is 100 g; pure fat calories are 900. */
|
|
12
|
+
export declare const MAX_NUTRIENT_PER_100 = 9999.99;
|
|
13
|
+
export declare const MAX_SERVING_QUANTITY = 10000;
|
|
14
|
+
export declare const NUTRIENT_DECIMALS = 2;
|
|
15
|
+
/** Rounds to two decimals, the precision every nutrient is stored at. */
|
|
16
|
+
export declare function roundNutrient(value: number): number;
|
|
17
|
+
export declare function hasAtMostTwoDecimals(value: number): boolean;
|
|
18
|
+
/** A non-negative amount with at most two decimals. */
|
|
19
|
+
export declare const nutrientAmountSchema: (max?: number) => z.ZodNumber;
|
|
20
|
+
/** A positive quantity with at most two decimals, such as 200 (g) or 1.5 (bowls). */
|
|
21
|
+
export declare const quantitySchema: (max?: number) => z.ZodNumber;
|
|
22
|
+
/** The nutrients a library food records. Calories and the three macros are required. */
|
|
23
|
+
export interface NutrientValues {
|
|
24
|
+
calories: number;
|
|
25
|
+
protein: number;
|
|
26
|
+
carbs: number;
|
|
27
|
+
fat: number;
|
|
28
|
+
sugar?: number | null;
|
|
29
|
+
fiber?: number | null;
|
|
30
|
+
solubleFiber?: number | null;
|
|
31
|
+
insolubleFiber?: number | null;
|
|
32
|
+
}
|
|
33
|
+
/** The same values with every optional nutrient present, `null` when unknown. */
|
|
34
|
+
export interface CompleteNutrientValues {
|
|
35
|
+
calories: number;
|
|
36
|
+
protein: number;
|
|
37
|
+
carbs: number;
|
|
38
|
+
fat: number;
|
|
39
|
+
sugar: number | null;
|
|
40
|
+
fiber: number | null;
|
|
41
|
+
solubleFiber: number | null;
|
|
42
|
+
insolubleFiber: number | null;
|
|
43
|
+
}
|
|
44
|
+
/** Converts values for one serving of `servingQuantity` units into values per 100 units. */
|
|
45
|
+
export declare function toPer100(perServing: NutrientValues, servingQuantity: number): CompleteNutrientValues;
|
|
46
|
+
/** Converts values per 100 units into values for one serving of `servingQuantity` units. */
|
|
47
|
+
export declare function perServing(per100: NutrientValues, servingQuantity: number): CompleteNutrientValues;
|
|
48
|
+
/** Calories from the macros, using Biki's formula: (protein + carbs) × 4 + fat × 9. */
|
|
49
|
+
export declare function formulaCalories(protein: number, carbs: number, fat: number): number;
|
|
50
|
+
export interface NutritionIssue {
|
|
51
|
+
path: string;
|
|
52
|
+
message: string;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* The checks that hold for any food's values per 100 units: the macros cannot
|
|
56
|
+
* weigh more than the food, and sugar, fibre and its parts cannot exceed what
|
|
57
|
+
* contains them. The database enforces the same rules.
|
|
58
|
+
*/
|
|
59
|
+
export declare function nutritionIssues(per100: NutrientValues): NutritionIssue[];
|
|
60
|
+
/**
|
|
61
|
+
* The form of a food name used to find duplicates: case, accents of width,
|
|
62
|
+
* punctuation and spacing are ignored, so "Paneer (Full-Fat)" and
|
|
63
|
+
* "paneer full fat" match. Letters in any script are kept.
|
|
64
|
+
*/
|
|
65
|
+
export declare function normalizeFoodName(name: string): string;
|
|
66
|
+
/** The stable key for a metadata value label: "High Protein" becomes "high-protein". */
|
|
67
|
+
export declare function slugifyMetadataKey(label: string): string;
|
|
68
|
+
/**
|
|
69
|
+
* Reads the weight or volume from a serving label such as "1 cup (200g)" or
|
|
70
|
+
* "1 glass (250ml)". Returns null when the label states neither.
|
|
71
|
+
*/
|
|
72
|
+
export declare function parseServingLabel(label: string): {
|
|
73
|
+
quantity: number;
|
|
74
|
+
unit: ServingUnit;
|
|
75
|
+
} | null;
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { SERVING_UNITS } from '../enums/index.js';
|
|
3
|
+
/**
|
|
4
|
+
* Nutrition rules shared by the backend and the apps, so a value the web form
|
|
5
|
+
* accepts is a value the API accepts, and both calculate derived values the
|
|
6
|
+
* same way.
|
|
7
|
+
*
|
|
8
|
+
* Library nutrients are stored per 100 of the serving unit (per 100 g, or per
|
|
9
|
+
* 100 ml for a serving measured in ml). Per-serving values are always derived.
|
|
10
|
+
*/
|
|
11
|
+
/** The largest nutrient amount per 100 units. Pure fat is 100 g; pure fat calories are 900. */
|
|
12
|
+
export const MAX_NUTRIENT_PER_100 = 9999.99;
|
|
13
|
+
export const MAX_SERVING_QUANTITY = 10000;
|
|
14
|
+
export const NUTRIENT_DECIMALS = 2;
|
|
15
|
+
const SCALE = 10 ** NUTRIENT_DECIMALS;
|
|
16
|
+
const DECIMAL_TOLERANCE = 1e-6;
|
|
17
|
+
/** Rounds to two decimals, the precision every nutrient is stored at. */
|
|
18
|
+
export function roundNutrient(value) {
|
|
19
|
+
return Math.round((value + Number.EPSILON) * SCALE) / SCALE;
|
|
20
|
+
}
|
|
21
|
+
export function hasAtMostTwoDecimals(value) {
|
|
22
|
+
const scaled = value * SCALE;
|
|
23
|
+
return Math.abs(scaled - Math.round(scaled)) < DECIMAL_TOLERANCE;
|
|
24
|
+
}
|
|
25
|
+
const TWO_DECIMALS_ERROR = { error: 'Use at most 2 decimal places' };
|
|
26
|
+
/** A non-negative amount with at most two decimals. */
|
|
27
|
+
export const nutrientAmountSchema = (max = MAX_NUTRIENT_PER_100) => z.number().min(0).max(max).refine(hasAtMostTwoDecimals, TWO_DECIMALS_ERROR);
|
|
28
|
+
/** A positive quantity with at most two decimals, such as 200 (g) or 1.5 (bowls). */
|
|
29
|
+
export const quantitySchema = (max = MAX_SERVING_QUANTITY) => z.number().gt(0).max(max).refine(hasAtMostTwoDecimals, TWO_DECIMALS_ERROR);
|
|
30
|
+
function scale(values, factor) {
|
|
31
|
+
const optional = (value) => value === null || value === undefined
|
|
32
|
+
? null
|
|
33
|
+
: roundNutrient(value * factor);
|
|
34
|
+
return {
|
|
35
|
+
calories: roundNutrient(values.calories * factor),
|
|
36
|
+
protein: roundNutrient(values.protein * factor),
|
|
37
|
+
carbs: roundNutrient(values.carbs * factor),
|
|
38
|
+
fat: roundNutrient(values.fat * factor),
|
|
39
|
+
sugar: optional(values.sugar),
|
|
40
|
+
fiber: optional(values.fiber),
|
|
41
|
+
solubleFiber: optional(values.solubleFiber),
|
|
42
|
+
insolubleFiber: optional(values.insolubleFiber),
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
/** Converts values for one serving of `servingQuantity` units into values per 100 units. */
|
|
46
|
+
export function toPer100(perServing, servingQuantity) {
|
|
47
|
+
return scale(perServing, 100 / servingQuantity);
|
|
48
|
+
}
|
|
49
|
+
/** Converts values per 100 units into values for one serving of `servingQuantity` units. */
|
|
50
|
+
export function perServing(per100, servingQuantity) {
|
|
51
|
+
return scale(per100, servingQuantity / 100);
|
|
52
|
+
}
|
|
53
|
+
/** Calories from the macros, using Biki's formula: (protein + carbs) × 4 + fat × 9. */
|
|
54
|
+
export function formulaCalories(protein, carbs, fat) {
|
|
55
|
+
return roundNutrient((protein + carbs) * 4 + fat * 9);
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* The checks that hold for any food's values per 100 units: the macros cannot
|
|
59
|
+
* weigh more than the food, and sugar, fibre and its parts cannot exceed what
|
|
60
|
+
* contains them. The database enforces the same rules.
|
|
61
|
+
*/
|
|
62
|
+
export function nutritionIssues(per100) {
|
|
63
|
+
const issues = [];
|
|
64
|
+
if (per100.protein + per100.carbs + per100.fat > 100 + DECIMAL_TOLERANCE) {
|
|
65
|
+
issues.push({
|
|
66
|
+
path: 'fat',
|
|
67
|
+
message: 'Protein, carbs and fat together cannot exceed 100 per 100',
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
if ((per100.sugar ?? 0) > per100.carbs + DECIMAL_TOLERANCE) {
|
|
71
|
+
issues.push({ path: 'sugar', message: 'Sugar cannot exceed carbs' });
|
|
72
|
+
}
|
|
73
|
+
if ((per100.fiber ?? 0) > per100.carbs + DECIMAL_TOLERANCE) {
|
|
74
|
+
issues.push({ path: 'fiber', message: 'Fibre cannot exceed carbs' });
|
|
75
|
+
}
|
|
76
|
+
const fiberParts = (per100.solubleFiber ?? 0) + (per100.insolubleFiber ?? 0);
|
|
77
|
+
const hasParts = isPresent(per100.solubleFiber) || isPresent(per100.insolubleFiber);
|
|
78
|
+
if (hasParts && !isPresent(per100.fiber)) {
|
|
79
|
+
issues.push({
|
|
80
|
+
path: 'fiber',
|
|
81
|
+
message: 'Enter total fibre when entering soluble or insoluble fibre',
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
else if (fiberParts > (per100.fiber ?? 0) + DECIMAL_TOLERANCE) {
|
|
85
|
+
issues.push({
|
|
86
|
+
path: 'insolubleFiber',
|
|
87
|
+
message: 'Soluble and insoluble fibre together cannot exceed total fibre',
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
return issues;
|
|
91
|
+
}
|
|
92
|
+
function isPresent(value) {
|
|
93
|
+
return value !== null && value !== undefined;
|
|
94
|
+
}
|
|
95
|
+
const NON_NAME_CHARACTERS = /[^\p{L}\p{M}\p{N}]+/gu;
|
|
96
|
+
/**
|
|
97
|
+
* The form of a food name used to find duplicates: case, accents of width,
|
|
98
|
+
* punctuation and spacing are ignored, so "Paneer (Full-Fat)" and
|
|
99
|
+
* "paneer full fat" match. Letters in any script are kept.
|
|
100
|
+
*/
|
|
101
|
+
export function normalizeFoodName(name) {
|
|
102
|
+
return name
|
|
103
|
+
.normalize('NFKC')
|
|
104
|
+
.toLowerCase()
|
|
105
|
+
.replace(NON_NAME_CHARACTERS, ' ')
|
|
106
|
+
.trim();
|
|
107
|
+
}
|
|
108
|
+
const METADATA_KEY_CHARACTERS = /[^a-z0-9]+/g;
|
|
109
|
+
const EDGE_HYPHENS = /^-+|-+$/g;
|
|
110
|
+
/** The stable key for a metadata value label: "High Protein" becomes "high-protein". */
|
|
111
|
+
export function slugifyMetadataKey(label) {
|
|
112
|
+
return label
|
|
113
|
+
.normalize('NFKD')
|
|
114
|
+
.toLowerCase()
|
|
115
|
+
.replace(METADATA_KEY_CHARACTERS, '-')
|
|
116
|
+
.replace(EDGE_HYPHENS, '');
|
|
117
|
+
}
|
|
118
|
+
// A serving label usually puts the weight in brackets after a household
|
|
119
|
+
// measure, "1 cup sliced (100g)", and may mention other amounts outside them,
|
|
120
|
+
// "1 scoop (33g) in 200ml water". An amount in brackets wins; otherwise the
|
|
121
|
+
// first amount in the label.
|
|
122
|
+
const SERVING_AMOUNT = /(\d+(?:[.,]\d+)?)\s*(g|ml)\b/i;
|
|
123
|
+
const BRACKETED = /\(([^)]*)\)/g;
|
|
124
|
+
/**
|
|
125
|
+
* Reads the weight or volume from a serving label such as "1 cup (200g)" or
|
|
126
|
+
* "1 glass (250ml)". Returns null when the label states neither.
|
|
127
|
+
*/
|
|
128
|
+
export function parseServingLabel(label) {
|
|
129
|
+
const bracketed = [...label.matchAll(BRACKETED)]
|
|
130
|
+
.map((group) => SERVING_AMOUNT.exec(group[1] ?? ''))
|
|
131
|
+
.find((match) => match !== null);
|
|
132
|
+
const [, amount, unitText] = bracketed ?? SERVING_AMOUNT.exec(label) ?? [];
|
|
133
|
+
if (amount === undefined || unitText === undefined) {
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
const quantity = Number(amount.replace(',', '.'));
|
|
137
|
+
const unit = unitText.toLowerCase();
|
|
138
|
+
if (!Number.isFinite(quantity) ||
|
|
139
|
+
quantity <= 0 ||
|
|
140
|
+
!SERVING_UNITS.includes(unit)) {
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
return { quantity: roundNutrient(quantity), unit };
|
|
144
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tbs-fitness/contract",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "TBS API contract: Zod schemas, DTO types and enums shared by the backend, web and mobile apps",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"type": "module",
|
|
@@ -103,6 +103,16 @@
|
|
|
103
103
|
"default": "./dist/cjs/feature-flags/index.js"
|
|
104
104
|
}
|
|
105
105
|
},
|
|
106
|
+
"./food": {
|
|
107
|
+
"import": {
|
|
108
|
+
"types": "./dist/esm/food/index.d.ts",
|
|
109
|
+
"default": "./dist/esm/food/index.js"
|
|
110
|
+
},
|
|
111
|
+
"require": {
|
|
112
|
+
"types": "./dist/cjs/food/index.d.ts",
|
|
113
|
+
"default": "./dist/cjs/food/index.js"
|
|
114
|
+
}
|
|
115
|
+
},
|
|
106
116
|
"./package.json": "./package.json"
|
|
107
117
|
},
|
|
108
118
|
"scripts": {
|