From 7c8edb9b9231421c59c5894cc901e358f126e342 Mon Sep 17 00:00:00 2001 From: hsiegeln <37154749+hsiegeln@users.noreply.github.com> Date: Sat, 18 Apr 2026 16:34:39 +0200 Subject: [PATCH] feat(pwa): Cache-Manifest-Diff-Funktion + Tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pure Funktion diffManifest(current, cached) → {toAdd, toRemove}. Vom SW beim Update-Sync genutzt: neue Rezept-IDs nachladen, gelöschte aus dem Cache räumen. 5 Tests decken add/remove/ beides/unchanged/empty-cache ab. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/lib/sw/diff-manifest.ts | 14 +++++++++++++ tests/unit/diff-manifest.test.ts | 34 ++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 src/lib/sw/diff-manifest.ts create mode 100644 tests/unit/diff-manifest.test.ts diff --git a/src/lib/sw/diff-manifest.ts b/src/lib/sw/diff-manifest.ts new file mode 100644 index 0000000..28a53b2 --- /dev/null +++ b/src/lib/sw/diff-manifest.ts @@ -0,0 +1,14 @@ +// Vergleicht die aktuelle Rezept-ID-Liste (vom Server) mit dem, was +// der Cache schon hat. Der SW nutzt das Delta, um nur Neue zu laden +// und Gelöschte abzuräumen. +export type ManifestDiff = { toAdd: number[]; toRemove: number[] }; + +export function diffManifest(currentIds: number[], cachedIds: number[]): ManifestDiff { + const current = new Set(currentIds); + const cached = new Set(cachedIds); + const toAdd: number[] = []; + const toRemove: number[] = []; + for (const id of current) if (!cached.has(id)) toAdd.push(id); + for (const id of cached) if (!current.has(id)) toRemove.push(id); + return { toAdd, toRemove }; +} diff --git a/tests/unit/diff-manifest.test.ts b/tests/unit/diff-manifest.test.ts new file mode 100644 index 0000000..55bf183 --- /dev/null +++ b/tests/unit/diff-manifest.test.ts @@ -0,0 +1,34 @@ +import { describe, it, expect } from 'vitest'; +import { diffManifest } from '../../src/lib/sw/diff-manifest'; + +describe('diffManifest', () => { + it('detects new IDs to add', () => { + const result = diffManifest([1, 2, 3, 4], [1, 2]); + expect(result.toAdd.sort()).toEqual([3, 4]); + expect(result.toRemove).toEqual([]); + }); + + it('detects removed IDs', () => { + const result = diffManifest([1, 2], [1, 2, 3, 4]); + expect(result.toAdd).toEqual([]); + expect(result.toRemove.sort()).toEqual([3, 4]); + }); + + it('detects both add and remove in one diff', () => { + const result = diffManifest([1, 3, 5], [1, 2, 3]); + expect(result.toAdd).toEqual([5]); + expect(result.toRemove).toEqual([2]); + }); + + it('returns empty arrays when identical', () => { + const result = diffManifest([1, 2, 3], [3, 2, 1]); + expect(result.toAdd).toEqual([]); + expect(result.toRemove).toEqual([]); + }); + + it('handles empty caches (first sync)', () => { + const result = diffManifest([1, 2], []); + expect(result.toAdd.sort()).toEqual([1, 2]); + expect(result.toRemove).toEqual([]); + }); +});