chore(release): v1.28.34 — nutrient intake lands as quiet context (server side)

Supplement-style intake written to Apple Health by nutrition apps —
vitamins, minerals, water, caffeine — can now sync as daily totals into a
dedicated NutrientIntakeDay store (migration 0241): composite (user, day,
nutrient) identity, re-post replaces, no soft delete, no rollup coupling.
A code-side catalog carries the 26 nutrient codes with canonical units,
plausibility caps, and EFSA dietary reference values (direction-aware;
chromium cites NIH ODS where EFSA declined a DRV).

Deliberately not a nutrition feature: no diary, no calories, no dashboard
surface. POST /api/nutrients/batch is gated behind the new opt-in
nutrients module (default off — with the module off the server refuses
ingest entirely), rate-limited, idempotency-wrapped, with per-entry
unit-mismatch and out-of-range skips. GET /api/nutrients serves a
catalog-ordered summary; the only visible surface is a read-only card
under Settings → Sources. Coach/correlation access is a later slice; the
iOS reading side is coordinated in the companion-app tracker.
This commit is contained in:
Marc-André Bombeck committed 2026-07-14 13:10:47 +02:00
1 parent 14a9a08a6e
commit 5445fc67ea
34 files changed
+2766 -12

No files matched your search

@@ -93,6 +93,7 @@ function moduleMap(
mcp: true,
inboundDocuments: true,
mentalHealth: true,
nutrients: true,
};
return { ...base, ...overrides };
}
+9 -1
View File
@@ -973,7 +973,15 @@ export const HK_QUANTITY_TYPE_DEFERRED = new Set<string>([
// `AppleSleepingBreathingDisturbances` (the per-night quantity) →
// BREATHING_DISTURBANCES, and `HKCategoryTypeIdentifierSleepApneaEvent`
// (the fired screening event) → BREATHING_DISTURBANCE_EVENT.
// Nutrition — the maintainer directive, indefinite hold
// Nutrition — the Measurement path stays PERMANENTLY closed to
// Dietary types. Energy / macros (and sodium): indefinite hold, the
// anti-goal against diet-app territory stands. Water + caffeine (and
// the 24 micro Dietary vitamin/mineral identifiers, which were never
// listed here because no sample ever mapped) ride the dedicated
// day-total endpoint `POST /api/nutrients/batch` (closed catalog in
// `src/lib/nutrients/catalog.ts`) — never Measurements, so the two
// entries below stay deferred and a stray sample-grain post keeps
// skipping as unmappable.
"HKQuantityTypeIdentifierDietaryWater",
"HKQuantityTypeIdentifierDietaryCaffeine",
"HKQuantityTypeIdentifierDietaryEnergyConsumed",
+6 -2
View File
@@ -357,14 +357,18 @@ describe("registry — opt-in marker", () => {
// are highly sensitive: `mcp` (remote external-assistant endpoint),
// `environment` (outbound weather fetch tied to a coarse location),
// `inboundDocuments` (sends an uploaded clinical document to the OCR/vision
// provider), and `mentalHealth` (a depression / anxiety self-assessment — at
// least as sensitive as mood, surfaced only on explicit opt-in). Every other
// provider), `mentalHealth` (a depression / anxiety self-assessment — at
// least as sensitive as mood, surfaced only on explicit opt-in), and
// `nutrients` (supplement-pattern intake synced from the phone's health
// store — the device-side HealthKit permission is not visible consent to
// server/AI-side storage, so ingest refuses while off). Every other
// module is the default-on disabled-allowlist.
const OPT_IN_KEYS = new Set([
"mcp",
"environment",
"inboundDocuments",
"mentalHealth",
"nutrients",
]);
it("marks only the egress-surface modules opt-in (every other is default-on)", () => {
+20
View File
@@ -147,6 +147,15 @@ export const MODULE_KEYS = [
// assessment routes refuse server-side. Item answers are always encrypted and
// always excluded from the AI Coach / MCP regardless of this toggle.
"mentalHealth",
// v1.28 — micronutrient-intake sync (vitamins, minerals, water,
// caffeine as day totals from Apple Health). OPT-IN (off by default):
// the HealthKit read permission is consent to read on the DEVICE, not
// visible consent to "a server — and later an AI assistant — holds my
// supplement pattern"; the project already answered this for less
// sensitive data (`environment`, weather, is opt-in). With it off the
// ingest route refuses (403 `module.disabled`) and the settings card
// does not render. The `optIn` marker inverts the per-user default.
"nutrients",
] as const;
export type ModuleKey = (typeof MODULE_KEYS)[number];
@@ -323,6 +332,17 @@ export const MODULE_REGISTRY: Readonly<Record<ModuleKey, ModuleDefinition>> =
// off the AI Coach / MCP regardless.
optIn: true,
},
nutrients: {
key: "nutrients",
labelKey: "modules.nutrients.label",
descriptionKey: "modules.nutrients.description",
category: "device",
// Off by default: supplement-pattern intake synced from the phone's
// health store is server/AI-consent-sensitive even though the
// HealthKit read permission was granted on the device. Ships dark;
// ingest refuses while off (refuse-ingest posture, not surface-only).
optIn: true,
},
});
const MODULE_KEY_SET: ReadonlySet<string> = new Set(MODULE_KEYS);
+153
View File
@@ -0,0 +1,153 @@
/**
* v1.28 — nutrient-catalog invariants.
*
* The catalog is the closed source of truth for the intake sync: codes,
* HK identifiers, canonical units (the µg/mg guard), plausibility caps,
* and the EFSA references a later Coach block reads. These tests pin
* the invariants the routes and the wire contract rely on.
*/
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import {
NUTRIENT_CATALOG,
NUTRIENT_CODES,
NUTRIENT_DEFINITIONS,
isNutrientCode,
} from "../catalog";
describe("nutrient catalog", () => {
it("carries exactly the 26 maintainer-scoped codes (no sodium, no potassium, no macros)", () => {
expect(NUTRIENT_CODES).toHaveLength(26);
expect(Object.keys(NUTRIENT_CATALOG).sort()).toEqual(
[...NUTRIENT_CODES].sort(),
);
// The maintainer exclusions stay excluded.
for (const banned of [
"sodium",
"potassium",
"energy",
"carbohydrates",
"protein",
"fat",
"sugar",
"fiber",
]) {
expect(isNutrientCode(banned), `banned code present: ${banned}`).toBe(
false,
);
}
});
it("codes and HealthKit identifiers are unique, and every HK id is a Dietary quantity type", () => {
const codes = new Set<string>();
const hkIds = new Set<string>();
for (const def of NUTRIENT_DEFINITIONS) {
expect(codes.has(def.code)).toBe(false);
expect(hkIds.has(def.hkIdentifier)).toBe(false);
codes.add(def.code);
hkIds.add(def.hkIdentifier);
expect(def.hkIdentifier).toMatch(
/^HKQuantityTypeIdentifierDietary[A-Za-z0-9]+$/,
);
}
});
it("every unit is canonical (mg | ug | ml) and water is the only ml type", () => {
for (const def of NUTRIENT_DEFINITIONS) {
expect(["mg", "ug", "ml"]).toContain(def.unit);
}
const mlCodes = NUTRIENT_DEFINITIONS.filter((d) => d.unit === "ml").map(
(d) => d.code,
);
expect(mlCodes).toEqual(["water"]);
// The known-µg micros stay µg — a silent switch to mg here would be
// the exact 1000× hazard the unit echo guards against.
for (const ugCode of [
"vitamin_a",
"biotin",
"folate",
"vitamin_b12",
"vitamin_d",
"vitamin_k",
"selenium",
"chromium",
"molybdenum",
"iodine",
] as const) {
expect(NUTRIENT_CATALOG[ugCode].unit).toBe("ug");
}
expect(NUTRIENT_CATALOG.caffeine.unit).toBe("mg");
});
it("every code carries a finite positive plausibility cap", () => {
for (const def of NUTRIENT_DEFINITIONS) {
expect(Number.isFinite(def.plausibleDailyMax)).toBe(true);
expect(def.plausibleDailyMax).toBeGreaterThan(0);
}
// The design-pinned guards.
expect(NUTRIENT_CATALOG.caffeine.plausibleDailyMax).toBe(2000);
expect(NUTRIENT_CATALOG.water.plausibleDailyMax).toBe(20000);
});
it("every code has a reference entry carrying kind, direction, a citation, and a resolvable value", () => {
for (const def of NUTRIENT_DEFINITIONS) {
const ref = def.reference;
expect(ref, `missing reference: ${def.code}`).toBeDefined();
expect(["PRI", "AI", "safeLevel"]).toContain(ref.kind);
expect(["target", "upperGuidance"]).toContain(ref.direction);
expect(ref.source.length).toBeGreaterThan(0);
// Value shape: a uniform adult value XOR a full sex split — never
// both, never a half split (profile resolution depends on this).
const hasAdult = ref.adult != null;
const hasMale = ref.male != null;
const hasFemale = ref.female != null;
expect(hasMale, `half sex-split: ${def.code}`).toBe(hasFemale);
expect(hasAdult !== hasMale, `value shape: ${def.code}`).toBe(true);
for (const v of [ref.adult, ref.male, ref.female]) {
if (v != null) expect(v).toBeGreaterThan(0);
}
}
});
it("caffeine is the one upperGuidance reference; everything else is a target", () => {
for (const def of NUTRIENT_DEFINITIONS) {
expect(def.reference.direction).toBe(
def.code === "caffeine" ? "upperGuidance" : "target",
);
}
expect(NUTRIENT_CATALOG.caffeine.reference.kind).toBe("safeLevel");
expect(NUTRIENT_CATALOG.caffeine.reference.adult).toBe(400);
});
it("every citation names EFSA, except the documented chromium exception (EFSA sets no DRV)", () => {
for (const def of NUTRIENT_DEFINITIONS) {
if (def.code === "chromium") {
expect(def.reference.source).toContain("NIH");
expect(def.reference.source).toContain("EFSA");
continue;
}
expect(def.reference.source, `citation: ${def.code}`).toContain("EFSA");
}
});
it("iron carries the EFSA sex split (11 male / 16 female)", () => {
expect(NUTRIENT_CATALOG.iron.reference.male).toBe(11);
expect(NUTRIENT_CATALOG.iron.reference.female).toBe(16);
});
it("every labelKey follows nutrients.names.<code> and resolves in the EN bundle", () => {
const en = JSON.parse(
readFileSync(join(__dirname, "../../../../messages/en.json"), "utf8"),
) as { nutrients?: { names?: Record<string, string> } };
for (const def of NUTRIENT_DEFINITIONS) {
expect(def.labelKey).toBe(`nutrients.names.${def.code}`);
expect(
en.nutrients?.names?.[def.code],
`EN name missing: ${def.code}`,
).toBeTruthy();
}
});
});
+307
View File
@@ -0,0 +1,307 @@
/**
* Nutrient catalog — the closed code set for the micronutrient-intake
* sync (v1.28).
*
* 26 codes: the 24 HealthKit `Dietary*` vitamin/mineral quantity types
* plus DietaryWater and DietaryCaffeine. Energy, carbohydrates,
* protein, fat, sugar, fiber AND sodium/potassium are deliberately NOT
* here — the anti-goal against diet-app territory stands, and
* sodium/potassium are food-composition signals, not "substances
* taken" (maintainer decision, out until explicit user demand).
*
* This catalog is the single source of truth for:
* - the closed `nutrient` code enum on the wire and in storage;
* - the canonical storage unit per code, which is ALSO the pinned
* HealthKit query unit for iOS (mass types in mg or µg as listed,
* water in mL — never IU). The batch route rejects any entry whose
* echoed `unit` differs, because a silent µg/mg confusion is a
* 1000× corruption and the one-string echo is the cheapest guard;
* - the generous per-day plausibility cap (ingest guard against
* unit-confused or corrupted writers, NOT a health judgement —
* values above high-dose supplement reality get skipped);
* - the EFSA dietary reference values a later Coach block compares
* against. Every reference names its EFSA value kind (PRI /
* AI / safeLevel) and a direction: `target` for reference intakes,
* `upperGuidance` for caffeine's safe-level ceiling. Sex-split
* values resolve against the user profile at consumption time —
* a profile without sex omits the reference, never guesses.
*
* Reference values are the EFSA DRV Finder adult values (Dietary
* Reference Values for the EU population); each entry cites its source
* verbatim in `reference.source`. Where EFSA expresses a vitamin per
* energy unit (thiamin, niacin), the entry carries the value at the
* 10 MJ/day reference energy intake and says so in the citation.
* Chromium is the one exception: EFSA concluded no DRV can be set, so
* the entry cites the NIH ODS adequate intake instead — spelled out in
* its source string.
*/
export const NUTRIENT_CODES = [
// 13 vitamins
"vitamin_a",
"thiamin",
"riboflavin",
"niacin",
"pantothenic_acid",
"vitamin_b6",
"biotin",
"folate",
"vitamin_b12",
"vitamin_c",
"vitamin_d",
"vitamin_e",
"vitamin_k",
// 11 minerals (sodium + potassium excluded by directive)
"calcium",
"iron",
"magnesium",
"phosphorus",
"zinc",
"copper",
"manganese",
"selenium",
"chromium",
"molybdenum",
"iodine",
// taken substances with correlation value
"water",
"caffeine",
] as const;
export type NutrientCode = (typeof NUTRIENT_CODES)[number];
/** Canonical storage units. `ug` is µg on the wire — ASCII on purpose. */
export type NutrientUnit = "mg" | "ug" | "ml";
export interface NutrientReference {
/** EFSA value type, named in Coach prose later (Slice B). */
kind: "PRI" | "AI" | "safeLevel";
/** `target` = reference intake; `upperGuidance` = do-not-exceed. */
direction: "target" | "upperGuidance";
/** Uniform adult value where the source is uniform. */
adult?: number;
/** Sex-split values where the source splits (e.g. iron 11 / 16). */
male?: number;
female?: number;
/** Citation, quoted verbatim wherever the reference surfaces. */
source: string;
}
export interface NutrientDefinition {
code: NutrientCode;
/** HealthKit quantity type identifier iOS reads this code from. */
hkIdentifier: string;
/** Canonical storage unit AND the pinned HK query unit. */
unit: NutrientUnit;
/** i18n key for the display name (settings card + exports). */
labelKey: string;
/**
* Generous per-day ingest cap in the canonical unit. Entries above it
* are skipped `value_out_of_range` — sized well above high-dose
* supplement reality so only unit confusion / corruption trips it.
*/
plausibleDailyMax: number;
reference: NutrientReference;
}
function def(
code: NutrientCode,
hkSuffix: string,
unit: NutrientUnit,
plausibleDailyMax: number,
reference: NutrientReference,
): NutrientDefinition {
return {
code,
hkIdentifier: `HKQuantityTypeIdentifierDietary${hkSuffix}`,
unit,
labelKey: `nutrients.names.${code}`,
plausibleDailyMax,
reference,
};
}
export const NUTRIENT_CATALOG: Readonly<
Record<NutrientCode, NutrientDefinition>
> = Object.freeze({
// ── Vitamins ─────────────────────────────────────────────────────
vitamin_a: def("vitamin_a", "VitaminA", "ug", 15000, {
kind: "PRI",
direction: "target",
male: 750,
female: 650,
source: "EFSA DRV 2015 (retinol equivalents, adults)",
}),
thiamin: def("thiamin", "Thiamin", "mg", 1000, {
kind: "PRI",
direction: "target",
adult: 1.0,
source: "EFSA DRV 2016 (PRI 0.1 mg/MJ ≈ 1.0 mg/d at 10 MJ/d)",
}),
riboflavin: def("riboflavin", "Riboflavin", "mg", 1000, {
kind: "PRI",
direction: "target",
adult: 1.6,
source: "EFSA DRV 2017 (adults)",
}),
niacin: def("niacin", "Niacin", "mg", 3000, {
kind: "PRI",
direction: "target",
adult: 16,
source: "EFSA DRV 2014 (PRI 1.6 mg NE/MJ ≈ 16 mg NE/d at 10 MJ/d)",
}),
pantothenic_acid: def("pantothenic_acid", "PantothenicAcid", "mg", 2000, {
kind: "AI",
direction: "target",
adult: 5,
source: "EFSA DRV 2014 (adults)",
}),
vitamin_b6: def("vitamin_b6", "VitaminB6", "mg", 1000, {
kind: "PRI",
direction: "target",
male: 1.7,
female: 1.6,
source: "EFSA DRV 2016 (adults)",
}),
biotin: def("biotin", "Biotin", "ug", 20000, {
kind: "AI",
direction: "target",
adult: 40,
source: "EFSA DRV 2014 (adults)",
}),
folate: def("folate", "Folate", "ug", 5000, {
kind: "PRI",
direction: "target",
adult: 330,
source: "EFSA DRV 2014 (dietary folate equivalents, adults)",
}),
vitamin_b12: def("vitamin_b12", "VitaminB12", "ug", 5000, {
kind: "AI",
direction: "target",
adult: 4,
source: "EFSA DRV 2015 (cobalamin, adults)",
}),
vitamin_c: def("vitamin_c", "VitaminC", "mg", 10000, {
kind: "PRI",
direction: "target",
male: 110,
female: 95,
source: "EFSA DRV 2013 (adults)",
}),
vitamin_d: def("vitamin_d", "VitaminD", "ug", 1000, {
kind: "AI",
direction: "target",
adult: 15,
source: "EFSA DRV 2016 (adults, assuming minimal cutaneous synthesis)",
}),
vitamin_e: def("vitamin_e", "VitaminE", "mg", 2000, {
kind: "AI",
direction: "target",
male: 13,
female: 11,
source: "EFSA DRV 2015 (alpha-tocopherol, adults)",
}),
vitamin_k: def("vitamin_k", "VitaminK", "ug", 10000, {
kind: "AI",
direction: "target",
adult: 70,
source: "EFSA DRV 2017 (phylloquinone, adults)",
}),
// ── Minerals ─────────────────────────────────────────────────────
calcium: def("calcium", "Calcium", "mg", 5000, {
kind: "PRI",
direction: "target",
adult: 950,
source: "EFSA DRV 2015 (adults ≥ 25 y)",
}),
iron: def("iron", "Iron", "mg", 500, {
kind: "PRI",
direction: "target",
male: 11,
female: 16,
source: "EFSA DRV 2015 (adults; 16 mg premenopausal women)",
}),
magnesium: def("magnesium", "Magnesium", "mg", 2000, {
kind: "AI",
direction: "target",
male: 350,
female: 300,
source: "EFSA DRV 2015 (adults)",
}),
phosphorus: def("phosphorus", "Phosphorus", "mg", 5000, {
kind: "AI",
direction: "target",
adult: 550,
source: "EFSA DRV 2015 (adults)",
}),
zinc: def("zinc", "Zinc", "mg", 200, {
kind: "PRI",
direction: "target",
male: 9.4,
female: 7.5,
source: "EFSA DRV 2014 (adults, at 300 mg/d phytate intake)",
}),
copper: def("copper", "Copper", "mg", 20, {
kind: "AI",
direction: "target",
male: 1.6,
female: 1.3,
source: "EFSA DRV 2015 (adults)",
}),
manganese: def("manganese", "Manganese", "mg", 50, {
kind: "AI",
direction: "target",
adult: 3,
source: "EFSA DRV 2013 (adults)",
}),
selenium: def("selenium", "Selenium", "ug", 1000, {
kind: "AI",
direction: "target",
adult: 70,
source: "EFSA DRV 2014 (adults)",
}),
chromium: def("chromium", "Chromium", "ug", 2000, {
kind: "AI",
direction: "target",
male: 35,
female: 25,
source: "NIH ODS 2018 (adults 19–50 y; EFSA 2014 sets no DRV for chromium)",
}),
molybdenum: def("molybdenum", "Molybdenum", "ug", 2000, {
kind: "AI",
direction: "target",
adult: 65,
source: "EFSA DRV 2013 (adults)",
}),
iodine: def("iodine", "Iodine", "ug", 2000, {
kind: "AI",
direction: "target",
adult: 150,
source: "EFSA DRV 2014 (adults)",
}),
// ── Taken substances with correlation value ──────────────────────
water: def("water", "Water", "ml", 20000, {
kind: "AI",
direction: "target",
male: 2500,
female: 2000,
source: "EFSA DRV 2010 (total water incl. food moisture, adults)",
}),
caffeine: def("caffeine", "Caffeine", "mg", 2000, {
kind: "safeLevel",
direction: "upperGuidance",
adult: 400,
source: "EFSA 2015 scientific opinion on the safety of caffeine (adults)",
}),
});
/** Catalog rows in canonical display order (the tuple order above). */
export const NUTRIENT_DEFINITIONS: ReadonlyArray<NutrientDefinition> =
NUTRIENT_CODES.map((code) => NUTRIENT_CATALOG[code]);
const NUTRIENT_CODE_SET: ReadonlySet<string> = new Set(NUTRIENT_CODES);
/** True when `code` is a known catalog code. */
export function isNutrientCode(code: string): code is NutrientCode {
return NUTRIENT_CODE_SET.has(code);
}
+3
View File
@@ -52,6 +52,7 @@ import { mentalHealthPaths } from "./mental-health";
import { medicationPaths, medicationResource } from "./medications";
import { metaPaths } from "./meta";
import { moodPaths } from "./mood";
import { nutrientPaths } from "./nutrients";
import { onboardingPaths } from "./onboarding";
import { profilePaths } from "./profile";
import { settingsPaths } from "./settings";
@@ -94,6 +95,8 @@ export const openApiPaths: NonNullable<ZodOpenApiObject["paths"]> = {
...inboundDocumentPaths,
...customMetricPaths,
...onboardingPaths,
// v1.28 — nutrient-intake sync (appended; spread order is load-bearing).
...nutrientPaths,
};
export const openApiComponents: NonNullable<ZodOpenApiObject["components"]> = {
+93
View File
@@ -0,0 +1,93 @@
/**
* OpenAPI route table — nutrient intake sync (v1.28).
*
* Part of the OpenAPI route table; aggregated in `./index.ts`. Request
* and response bodies come from `src/lib/validations/nutrients.ts` so
* the wire contract stays single-source. The batch description embeds
* the code ↔ HealthKit-identifier ↔ unit table generated from the
* code-side catalog — the iOS client reads the pinned HK query unit
* per type from here (this is the documented home of that table).
*/
import type { ZodOpenApiObject } from "zod-openapi";
import { NUTRIENT_DEFINITIONS } from "@/lib/nutrients/catalog";
import {
nutrientBatchSchema,
nutrientBatchResponseSchema,
nutrientOverviewQuerySchema,
nutrientOverviewSchema,
} from "@/lib/validations/nutrients";
import { dataEnvelope, errorEnvelope, stdResponses } from "./shared";
const moduleDisabled = {
"403": {
description:
"The opt-in `nutrients` module is off for this account (errorCode `module.disabled`). Stop syncing and do not retry; offer the enable-in-settings hint. Only run the HealthKit read-authorization flow while the module is on.",
content: { "application/json": { schema: errorEnvelope } },
},
} as const;
/**
* The catalog table, rendered into the endpoint description so the
* OpenAPI file is the one authoritative home of the code ↔ HK ↔ unit
* contract (µg is `ug` on the wire; water is mL; never IU).
*/
const catalogTable = NUTRIENT_DEFINITIONS.map(
(d) => `| ${d.code} | ${d.hkIdentifier} | ${d.unit} |`,
).join("\n");
export const nutrientPaths: NonNullable<ZodOpenApiObject["paths"]> = {
"/api/nutrients/batch": {
post: {
tags: ["Nutrients"],
summary: "Ingest micronutrient day totals (v1.28)",
description:
"Bulk upsert of supplement-style daily totals synced from HealthKit — vitamins, minerals, water, caffeine. Day totals only: compute HKStatisticsCollectionQuery cumulative sums day-anchored in the user's current IANA timezone; `day` is yyyy-MM-dd in that timezone (the same rule as the `stats:` day keys). Never post raw samples. Upsert key is (day, nutrient): a re-post replaces the stored total and reports `updated`. Post the current + previous local day per sync; backfill 30 days on first enable. Max 500 entries; Idempotency-Key supported; rate limit 60/min. Per-entry skips (`unit_mismatch` | `value_out_of_range` | `day_invalid`) are terminal — log and drop, do not retry the entry. Behind the opt-in `nutrients` module (403 `module.disabled` when off). Query HealthKit with exactly the listed unit per code (`ug` = microgram; do not convert to IU):\n\n| code | HealthKit identifier | unit |\n| --- | --- | --- |\n" +
catalogTable,
requestBody: {
required: true,
content: { "application/json": { schema: nutrientBatchSchema } },
},
responses: {
"200": {
description:
"Batch processed; per-entry statuses inserted | updated | skipped.",
content: {
"application/json": {
schema: dataEnvelope(
nutrientBatchResponseSchema,
"NutrientBatchEnvelope",
),
},
},
},
...moduleDisabled,
...stdResponses,
},
},
},
"/api/nutrients": {
get: {
tags: ["Nutrients"],
summary: "Synced-nutrient window summary (v1.28)",
description:
"Per-nutrient summary of the last `days` days (default 14): latest synced day + total and the days-with-data count, in catalog order. Read-only; feeds the settings card. Behind the opt-in `nutrients` module.",
requestParams: { query: nutrientOverviewQuerySchema },
responses: {
"200": {
description: "The window summary.",
content: {
"application/json": {
schema: dataEnvelope(
nutrientOverviewSchema,
"NutrientOverviewEnvelope",
),
},
},
},
...moduleDisabled,
...stdResponses,
},
},
},
};
+2
View File
@@ -33,6 +33,7 @@ import { measurementReminderKeys } from "./measurement-reminders";
import { medicationKeys } from "./medications";
import { mentalHealthKeys } from "./mental-health";
import { moodKeys } from "./mood";
import { nutrientKeys } from "./nutrients";
import { settingsKeys } from "./settings";
import { workoutKeys } from "./workouts";
@@ -58,6 +59,7 @@ export const queryKeys = {
...environmentKeys,
...documentKeys,
...customMetrics,
...nutrientKeys,
};
/**
+9
View File
@@ -0,0 +1,9 @@
/**
* Query keys — nutrient-intake sync (v1.28). One read: the window
* summary behind the read-only Settings → Sources card. Part of the
* centralized factory; aggregated in `./index.ts`.
*/
export const nutrientKeys = {
/** Per-nutrient window summary from `GET /api/nutrients?days=N`. */
nutrientIntake: (days: number) => ["nutrients", "intake", days] as const,
};
+108
View File
@@ -0,0 +1,108 @@
/**
* Zod schemas — nutrient intake sync (v1.28).
*
* Shared between the runtime request parsing
* (`src/app/api/nutrients/**`) and the OpenAPI route table
* (`src/lib/openapi/routes/nutrients.ts`) so the wire contract stays
* single-source. The closed `nutrient` code set comes from the
* code-side catalog (`src/lib/nutrients/catalog.ts`).
*/
import { z } from "zod/v4";
import { NUTRIENT_CODES } from "@/lib/nutrients/catalog";
export const MAX_NUTRIENT_ENTRIES_PER_BATCH = 500;
export const nutrientCodeEnum = z.enum(NUTRIENT_CODES).meta({
id: "NutrientCode",
description:
"Closed nutrient catalog code — 24 HealthKit Dietary vitamin/mineral types plus water and caffeine. Energy, macros and sodium/potassium are out of scope.",
});
/**
* One day-total entry. `day` is YYYY-MM-DD in the user's IANA timezone,
* computed client-side (the `stats:` day-key contract); the server
* trusts the string after regex + calendar sanity, no re-derivation.
* `unit` deliberately rides the wire even though the catalog pins it:
* a µg/mg confusion is a silent 1000× corruption and the one-string
* echo is the cheapest guard — a mismatch skips the entry.
*/
export const nutrientEntrySchema = z
.object({
day: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
nutrient: nutrientCodeEnum,
unit: z.string().min(1).max(10),
amount: z.number().finite().min(0),
externalSourceVersion: z.string().min(1).max(120).optional(),
})
.meta({
id: "NutrientIntakeEntry",
description:
"One nutrient day total. day = YYYY-MM-DD in the user's IANA timezone; unit must equal the catalog's canonical unit for the code (mg | ug | ml) or the entry is skipped unit_mismatch.",
});
export const nutrientBatchSchema = z
.object({
entries: z
.array(nutrientEntrySchema)
.min(1)
.max(MAX_NUTRIENT_ENTRIES_PER_BATCH),
})
.meta({
id: "NutrientBatchRequest",
description:
"Bulk day-total upsert, max 500 entries. Upsert key is (day, nutrient); a re-post replaces the stored total (last-writer-wins day-total contract).",
});
/** Per-entry outcome — a re-post is by definition an update, never a duplicate. */
export const nutrientEntryResultSchema = z
.object({
index: z.number().int().min(0),
status: z.enum(["inserted", "updated", "skipped"]),
reason: z.string().optional(),
})
.meta({
id: "NutrientEntryResult",
description:
"Per-entry ingest outcome. skipped reasons: unit_mismatch | value_out_of_range | day_invalid | upsert_failed. Log and drop a skipped entry — do not retry it.",
});
export const nutrientBatchResponseSchema = z
.object({
processed: z.number().int().min(0),
inserted: z.number().int().min(0),
updated: z.number().int().min(0),
skipped: z.array(
z.object({ index: z.number().int().min(0), reason: z.string() }),
),
entries: z.array(nutrientEntryResultSchema),
})
.meta({
id: "NutrientBatchResponse",
description:
"Always 200 when the envelope parses; per-entry failures surface as skipped entries, never a batch failure.",
});
/** `GET /api/nutrients` query — window size in days, default 14. */
export const nutrientOverviewQuerySchema = z.object({
days: z.coerce.number().int().min(1).max(365).default(14),
});
export const nutrientOverviewSchema = z
.object({
windowDays: z.number().int().min(1),
nutrients: z.array(
z.object({
nutrient: nutrientCodeEnum,
unit: z.string(),
latestDay: z.string(),
latestAmount: z.number(),
daysWithData: z.number().int().min(1),
}),
),
})
.meta({
id: "NutrientIntakeOverview",
description:
"Per-nutrient window summary in catalog order: latest synced day + total, and the count of days carrying data inside the window. Nutrients without data in the window are omitted.",
});