chore(release): v1.4.42 — Knip enforcing, queryKey factory closed, iOS Workouts dedup, Withings off-response classification

Six touch-disjoint waves landed on develop before this release:

- W1-KNIP — exports/types tiers flipped to enforcing-mode on main;
  35 unused exports + 52 unused types triaged to 0/0; shadcn surface
  + zod-infer contract types scoped via knip.json ignore-block.
- W2-ZOD-MULTI-ISSUE — `returnAllZodIssues` shared helper +
  `/api/dashboard/widgets` 422 now returns every Zod issue + worker
  audit-ledger breadcrumb. 41 sibling routes documented for v1.4.43.
- W3-QUERYKEY-LONGTAIL — 40 settings/medications/admin/hooks files
  migrated to the queryKeys factory; 9 new factory entries; ESLint
  rule + test-guard scope extended in lockstep.
- W4-ARCH-HYGIENE — BERLIN_DAY_FORMATTER consolidated across nine
  sites (seven status helpers + bucket-series + bp-in-target);
  Suspense double-comment consolidated; doctor-report sanitiser regex
  rewritten to escape-form so diffs are reviewable; pr-detection-
  worker soft-delete filter; offhost-backup DR-intent comment.
- W5-IOS-WORKOUTS — `dedupeWorkoutBatch` write-time cross-source
  dedup helper for the v1.5 iOS HealthKit observer ingest; dashboard
  tile-strip placeholder parity with the live TrendCard chrome.
- W6-WITHINGS-OFF + ENV-CHECK — Withings off-response classifier
  (transient/reauth/persistent) + WithingsApiError typed throw + the
  `pnpm check-env` CLI. APNs `allOrNone: true` closes the AP-2
  silent-disable gap the wave was conceived to close.

No migration, no env-var change, no API contract break for iOS v0.5.4.
The new `/api/dashboard/widgets` 422 envelope is additively extended.

pnpm test --run green at 4815 passing / 1 skipped.
pnpm typecheck, pnpm lint, pnpm knip (no --include flag) green.
This commit is contained in:
Marc-André Bombeck authored and GitHub committed 2026-05-21 19:33:07 +02:00
1 parent 67207d725e
commit 9b6e237f5f
121 files changed
+6481 -590

No files matched your search

@@ -0,0 +1,160 @@
/**
* v1.4.42 W2 — multi-issue 422 envelope on PUT.
*
* Until v1.4.41 this route returned `parsed.error.issues[0].message`,
* which dropped every issue past the first. iOS contract debugging
* needed one round-trip per wrong field. The route now returns every
* issue under `details.issues` AND writes a
* `dashboard.widgets.validation-failed` audit-ledger row so the
* operator can grep `/api/admin/audit` for the same trail.
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
vi.mock("@/lib/db", () => ({
prisma: {
user: {
findUnique: vi.fn(),
update: vi.fn(),
},
auditLog: {
create: vi.fn(),
},
},
toJson: (v: unknown) => v,
}));
vi.mock("@/lib/auth/session", () => ({
getSession: vi.fn(),
}));
vi.mock("@/lib/logging/transports", () => ({
emitIfSampled: vi.fn(),
}));
vi.mock("@/lib/db-compat", () => ({
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("next/headers", () => ({
headers: vi.fn(async () => ({ get: () => null })),
cookies: vi.fn(async () => ({
get: () => undefined,
set: () => {},
delete: () => {},
})),
}));
import { PUT } from "../route";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth/session";
import { __resetAllCachesForTests } from "@/lib/cache/server-cache";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: {
id: "user-1",
username: "tester",
role: "USER" as const,
displayName: null,
},
};
const callPut = PUT as unknown as (req: NextRequest) => Promise<Response>;
function makeReq(body: unknown): NextRequest {
return new NextRequest("http://localhost/api/dashboard/widgets", {
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
}
beforeEach(() => {
vi.resetAllMocks();
__resetAllCachesForTests();
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.auditLog.create).mockResolvedValue({} as never);
});
describe("PUT /api/dashboard/widgets — 422 multi-issue envelope (v1.4.42 W2)", () => {
it("surfaces TWO simultaneous validation errors under details.issues", async () => {
// version=2 (literal mismatch) + widgets=[] (min(1) violation).
const res = await callPut(makeReq({ version: 2, widgets: [] }));
expect(res.status).toBe(422);
const body = (await res.json()) as {
data: null;
error: string;
details: {
issues: Array<{ path: string; code: string; message: string }>;
};
};
expect(body.data).toBeNull();
expect(body.error).toBe("Validation failed");
expect(body.details.issues.length).toBe(2);
const paths = body.details.issues.map((i) => i.path).sort();
expect(paths).toEqual(["version", "widgets"]);
// Every issue carries exactly path / code / message — issue.params
// never leaks (it may echo the offending user input for some codes).
for (const issue of body.details.issues) {
expect(Object.keys(issue).sort()).toEqual(["code", "message", "path"]);
}
});
it("surfaces THREE simultaneous validation errors", async () => {
const res = await callPut(
makeReq({
version: 99,
widgets: [],
comparisonBaseline: "tomorrow",
}),
);
expect(res.status).toBe(422);
const body = (await res.json()) as {
details: { issues: Array<{ path: string; code: string }> };
};
expect(body.details.issues.length).toBe(3);
const paths = body.details.issues.map((i) => i.path).sort();
expect(paths).toEqual(["comparisonBaseline", "version", "widgets"]);
});
it("writes one audit-ledger row keyed dashboard.widgets.validation-failed", async () => {
const res = await callPut(makeReq({ version: 2, widgets: [] }));
expect(res.status).toBe(422);
// The audit row is fire-and-forget — let the microtask queue drain.
await new Promise((r) => setTimeout(r, 5));
expect(prisma.auditLog.create).toHaveBeenCalledTimes(1);
const call = vi.mocked(prisma.auditLog.create).mock.calls[0]?.[0] as {
data: { userId: string; action: string; details: string };
};
expect(call.data.userId).toBe("user-1");
expect(call.data.action).toBe("dashboard.widgets.validation-failed");
const details = JSON.parse(call.data.details) as {
issues: Array<{ path: string; code: string; message: string }>;
};
expect(details.issues.length).toBe(2);
for (const issue of details.issues) {
// Audit row carries the same sanitised shape — issue.params never
// hits the ledger either.
expect(Object.keys(issue).sort()).toEqual(["code", "message", "path"]);
}
});
it("does not block the 422 response when the audit-row write rejects", async () => {
vi.mocked(prisma.auditLog.create).mockRejectedValueOnce(
new Error("db down"),
);
const res = await callPut(makeReq({ version: 2, widgets: [] }));
// The response is the contract — the audit row is best-effort.
expect(res.status).toBe(422);
const body = (await res.json()) as {
details: { issues: Array<unknown> };
};
expect(body.details.issues.length).toBe(2);
});
});
+31 -2
View File
@@ -6,7 +6,12 @@
* to default.
*/
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { apiSuccess, apiError, safeJson } from "@/lib/api-response";
import {
apiSuccess,
safeJson,
returnAllZodIssues,
sanitiseZodIssues,
} from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { prisma, toJson } from "@/lib/db";
import {
@@ -126,7 +131,31 @@ export const PUT = apiHandler(async (request: NextRequest) => {
const parsed = layoutSchema.safeParse(body);
if (!parsed.success) {
return apiError(parsed.error.issues[0].message, 422);
// v1.4.42 W2 — the legacy `issues[0].message` envelope dropped
// every issue past the first. iOS contract debugging hit one
// round-trip per wrong field; the new helper surfaces every
// issue under `details.issues`. We additionally emit an
// append-only audit-ledger row so the operator can grep
// `/api/admin/audit` for these without combing the iOS dev
// console.
const issues = sanitiseZodIssues(parsed.error.issues);
annotate({
action: { name: "dashboard.widgets.validation-failed" },
meta: { issue_count: issues.length },
});
// Best-effort breadcrumb — never block the 422 on a write miss.
prisma.auditLog
.create({
data: {
userId: user.id,
action: "dashboard.widgets.validation-failed",
details: JSON.stringify({ issues }),
},
})
.catch(() => {
/* swallow — validation response is the contract, audit row is best-effort */
});
return returnAllZodIssues(parsed.error, 422);
}
// v1.4.18 — preserve any per-chart overlay prefs that the client
@@ -225,8 +225,17 @@ describe("POST /api/workouts/batch — per-entry status envelope", () => {
const res = await POST(
makeRequest({
workouts: [
// Two distinct runs separated by 2 h so the v1.4.42 W5
// write-time canonical-row picker treats them as separate
// workouts. Without the spacing the picker would collapse
// them to one survivor (same userId + sportType + startedAt
// inside the 90 s dedup window) and the envelope-count
// assertion would mask the per-entry status pin.
validWorkout("uuid-fresh-1"),
validWorkout("uuid-fresh-2"),
validWorkout("uuid-fresh-2", {
startedAt: "2026-05-14T08:30:00.000Z",
endedAt: "2026-05-14T09:15:00.000Z",
}),
],
}),
);
@@ -253,8 +262,14 @@ describe("POST /api/workouts/batch — per-entry status envelope", () => {
const res = await POST(
makeRequest({
workouts: [
// Same spacing rationale as the prior test — keep the two
// entries' `startedAt` outside the W5 dedup window so the
// pre-`createMany` pass doesn't collapse them.
validWorkout("uuid-existing"),
validWorkout("uuid-fresh"),
validWorkout("uuid-fresh", {
startedAt: "2026-05-14T08:30:00.000Z",
endedAt: "2026-05-14T09:15:00.000Z",
}),
],
}),
);
@@ -284,8 +299,15 @@ describe("POST /api/workouts/batch — per-entry status envelope", () => {
const res = await POST(
makeRequest({
workouts: [
// Same spacing rationale as the per-entry tests — keep both
// entries outside the W5 dedup window so the race-reconcile
// contract is exercised directly without the write-time
// canonical-picker absorbing one of the rows first.
validWorkout("uuid-race-1"),
validWorkout("uuid-race-2"),
validWorkout("uuid-race-2", {
startedAt: "2026-05-14T08:30:00.000Z",
endedAt: "2026-05-14T09:15:00.000Z",
}),
],
}),
);
+55 -6
View File
@@ -68,7 +68,8 @@ import {
createBatchWorkoutSchema,
MAX_WORKOUTS_PER_BATCH,
} from "@/lib/validations/workout";
import { Prisma } from "@/generated/prisma/client";
import { dedupeWorkoutBatch } from "@/lib/workouts/canonical-rows";
import { Prisma, type MeasurementSource } from "@/generated/prisma/client";
// v1.4.25 W16c — push-suppression threshold for workout PRs. A batch
// larger than this fires the detection job with `silent: true` so a
@@ -254,11 +255,56 @@ async function postBatch(request: NextRequest): Promise<Response> {
};
});
// v1.4.42 W5 — write-time cross-source dedup. The v1.5 iOS app
// drains a HealthKit observer queue that frequently carries the
// SAME logical workout from two paired sensors (Apple Watch +
// Withings ScanWatch). Without this pass, both rows persist (their
// `externalId`s differ → the `(userId, source, externalId)` unique
// index never fires) and the read-time canonical-picker has to
// carry the duplicate forward on every dashboard render.
//
// The helper is pure (no Prisma, no user lookups). It groups by
// `(userId, activityType, startedAt ± 90 s)`, prefers the canonical
// source ladder (APPLE_HEALTH > WITHINGS > MANUAL > IMPORT), and
// breaks ties on calories > earliest createdAt > input order. Rows
// dropped here surface to the iOS client as `duplicate` so the
// sync cursor advances past them identically to the externalId
// case below.
const canonicalPrepared = dedupeWorkoutBatch(
prepared.map((p) => ({
userId: p.row.userId,
activityType: p.row.sportType,
startedAt: p.row.startedAt as Date,
// Zod's `measurementSourceEnum.optional().default("MANUAL")`
// guarantees `source` is set post-parse, but Prisma's
// `WorkoutCreateManyInput` types it optional. Default through
// the same fallback the validator uses so the picker's source
// ladder still resolves on the rare row where TypeScript
// can't prove the union.
source: (p.row.source ?? "MANUAL") as MeasurementSource,
caloriesKcal: p.row.totalEnergyKcal ?? null,
// No createdAt yet — the row is pre-insert; the tie-breaker
// falls through to input order via the `index` field below.
index: p.index,
})),
);
const survivingIndices = new Set(canonicalPrepared.map((r) => r.index ?? -1));
const droppedByWriteDedup: number[] = [];
for (const p of prepared) {
if (!survivingIndices.has(p.index)) {
results[p.index] = { index: p.index, status: "duplicate" };
droppedByWriteDedup.push(p.index);
}
}
const survivors = prepared.filter((p) => survivingIndices.has(p.index));
let duplicateCount = droppedByWriteDedup.length;
let insertedCount = 0;
let duplicateCount = 0;
if (prepared.length > 0) {
const dedupCandidates = prepared
if (survivors.length > 0) {
// v1.4.42 W5 — only the write-time dedup survivors are probed
// against existing rows; the dropped twins already carry a
// `duplicate` status and never reach the DB.
const dedupCandidates = survivors
.map((p) => p.dedupKey)
.filter((k): k is { source: string; externalId: string } => k !== null);
@@ -280,7 +326,7 @@ async function postBatch(request: NextRequest): Promise<Response> {
);
const toInsert: Prepared[] = [];
for (const p of prepared) {
for (const p of survivors) {
const keyTuple = p.dedupKey
? `${p.dedupKey.source}::${p.dedupKey.externalId}`
: null;
@@ -461,7 +507,10 @@ async function postBatch(request: NextRequest): Promise<Response> {
const racedDuplicates = toInsert.length - insertedCount;
if (racedDuplicates > 0) {
let downgraded = 0;
for (const p of prepared) {
// v1.4.42 W5 — walk `survivors` (not `prepared`) so the
// already-downgraded-by-write-dedup losers don't get
// double-counted toward the race-reconcile budget.
for (const p of survivors) {
if (downgraded >= racedDuplicates) break;
if (results[p.index]?.status === "inserted") {
results[p.index] = { index: p.index, status: "duplicate" };