diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c5901f..9e18b3d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,14 @@ All notable changes to this project are documented in this file. The format is b ## [Unreleased] +### Fixed + +- Reapply pending nested PATCH changes after rollback and on 204 responses without restoring + failed changes or overwriting confirmed server values. +- Keep recomputed optimistic objects read-only and relations callable across overlapping changes + and server-side clears. +- Apply nested merge patches to null, missing, array and scalar values using an empty object. + ## [1.0.0] - 2026-10-24 First release of halc, the successor of hal-json-vuex 3 and hal-json-normalizer 5 diff --git a/src/core/client.ts b/src/core/client.ts index e34d92d..194b831 100644 --- a/src/core/client.ts +++ b/src/core/client.ts @@ -10,9 +10,11 @@ import type { import { ApiError } from './errors.js' import { MemoryStore } from './memoryStore.js' import { + applyRecordPatch, bodyForPost, diffForPatch, MutationQueue, + recordPatchFor, type DiffContext, type PatchDiff, } from './mutations.js' @@ -634,12 +636,20 @@ export class HalcClient implements Client { if (loaded && Object.keys(diff.body).length === 0) return this.wrapperFor(uri) const optimistic = (options.optimistic ?? this.options.optimistic ?? true) && loaded + const patch = recordPatchFor( + record ? currentData(record) : {}, + data, + Object.keys(diff.body), + this.diffContext, + record?.data + ) const mutation: PendingMutation = { id: this.queue.nextId(), kind: 'patch', uri, body: diff.body, dirty: diff.dirty, + patch, optimistic, } this.queue.add(mutation) @@ -660,7 +670,7 @@ export class HalcClient implements Client { const storedUri = await this.storeMutationResponse(uri, response, 'PATCH') if (storedUri === undefined) { // No content: keep the change and fetch what the server made of it. - this.commitData(uri, diff.dirty) + this.commitData(uri, patch) void this.load(uri, false, true).catch(ignore) } return this.wrapperFor(uri) @@ -1192,7 +1202,7 @@ export class HalcClient implements Client { if (existing?.meta.deleting) meta.deleting = true deepFreeze(record.data) const dirty = this.queue.dirtyFor(record) - if (dirty) meta.dirty = dirty + if (dirty) meta.dirty = deepFreeze(dirty) uris.push(record.uri) } this.store.set(records) @@ -1246,12 +1256,12 @@ export class HalcClient implements Client { } /** Writes confirmed changes into the data of a record (for answers without content). */ - private commitData(uri: string, changes: Record): void { + private commitData(uri: string, patch: Record): void { const record = this.store.get(uri) if (!record) return const updated: EntityRecord = { uri, - data: deepFreeze({ ...record.data, ...changes }), + data: deepFreeze({ ...record.data, ...applyRecordPatch(record.data, patch) }), meta: { ...record.meta, version: this.nextVersion(record.meta.version), @@ -1259,7 +1269,7 @@ export class HalcClient implements Client { }, } const dirty = this.queue.dirtyFor(updated) - if (dirty) updated.meta.dirty = dirty + if (dirty) updated.meta.dirty = deepFreeze(dirty) else delete updated.meta.dirty this.touch(uri) this.store.set([updated]) @@ -1284,7 +1294,7 @@ export class HalcClient implements Client { meta: { ...record.meta, version: this.nextVersion(record.meta.version) }, } const dirty = this.queue.dirtyFor(updated) - if (dirty) updated.meta.dirty = dirty + if (dirty) updated.meta.dirty = deepFreeze(dirty) else delete updated.meta.dirty this.touch(collectionUri) this.store.set([updated]) diff --git a/src/core/mutations.ts b/src/core/mutations.ts index 693a157..2164f81 100644 --- a/src/core/mutations.ts +++ b/src/core/mutations.ts @@ -19,6 +19,8 @@ export interface PendingMutation { optimistic: boolean /** For PATCH: the local changes in record form (relations as refs). */ dirty?: Record + /** For PATCH: the local merge-patch delta in record form, used to recompute `dirty`. */ + patch?: Record /** For POST: the URI of the temporary record. */ tempUri?: string } @@ -80,7 +82,14 @@ export class MutationQueue { for (const mutation of this.mutations) { if (mutation.uri !== record.uri || !mutation.optimistic) continue if (mutation.kind === 'patch' && mutation.dirty) { - dirty = { ...dirty, ...mutation.dirty } + if (mutation.patch) { + dirty = { + ...dirty, + ...applyRecordPatch({ ...record.data, ...dirty }, mutation.patch), + } + } else { + dirty = { ...dirty, ...mutation.dirty } + } } else if (mutation.kind === 'post' && mutation.tempUri) { const base = (dirty?.items ?? record.data.items) as CollectionRef | undefined const hrefs = isCollectionRef(base) ? base.hrefs : [] @@ -126,6 +135,32 @@ function toHref(value: unknown, context: DiffContext): string | null | undefined * other objects compare the way they will be sent). */ function toRecordValue(current: unknown, value: unknown, context: DiffContext): unknown { + return applyRecordPatchValue(current, toRecordPatchValue(current, value, context)) +} + +function applyRecordPatchValue(current: unknown, patch: unknown): unknown { + return isRelationRef(current) || isRelationRef(patch) + ? patch + : mergePatch(current, patch) +} + +/** Applies a record-form merge patch, returning only the patched fields. */ +export function applyRecordPatch( + current: Record, + patch: Record +): Record { + const changes: Record = {} + for (const [key, value] of Object.entries(patch)) { + changes[key] = applyRecordPatchValue(current[key], value) + } + return changes +} + +function toRecordPatchValue( + current: unknown, + value: unknown, + context: DiffContext +): unknown { if (isLinkRef(current) || current === null) { const href = toHref(value, context) if (href === null) return null @@ -136,12 +171,7 @@ function toRecordValue(current: unknown, value: unknown, context: DiffContext): if (hrefs.every((href) => typeof href === 'string')) return { hrefs } } if (value === undefined) return undefined - const json = JSON.parse(JSON.stringify(value)) as unknown - // A PATCH is a JSON merge patch (RFC 7386): an object updates the current object field by - // field (null removes a field), so the optimistic value keeps the fields it doesn't mention. - return isJsonObject(current) && isJsonObject(json) && !isRelationRef(current) - ? mergePatch(current, json) - : json + return JSON.parse(JSON.stringify(value)) as unknown } function isJsonObject(value: unknown): value is Record { @@ -166,6 +196,24 @@ export interface PatchDiff { dirty: Record } +/** Converts PATCH fields to record form using visible and confirmed relation references. */ +export function recordPatchFor( + current: Record, + data: Record, + keys: Iterable, + context: DiffContext, + confirmed: Record = current +): Record { + const patch: Record = {} + for (const key of keys) { + const value = data[key] + if (key === '_meta' || typeof value === 'function' || value === undefined) continue + const reference = isRelationRef(current[key]) ? current[key] : confirmed[key] + patch[key] = toRecordPatchValue(reference, value, context) + } + return patch +} + /** * Computes what a PATCH has to send: every top-level field of `data` whose value differs from * the current value. Functions (relation accessors) and `_meta` are ignored, so a spread wrapper diff --git a/test/core/client.mutations.spec.ts b/test/core/client.mutations.spec.ts index 9016a4a..35f3543 100644 --- a/test/core/client.mutations.spec.ts +++ b/test/core/client.mutations.spec.ts @@ -131,6 +131,200 @@ describe('patch', () => { expect(api.get(camp._meta.self)._meta.dirty).toBeUndefined() }) + it.each([200, 204])( + 'rolls back a failed nested change before a %i response', + async (status) => { + const { api, camp, wrapper } = await loadedCamp(undefined, { + settings: { left: 'old', right: 'old' }, + }) + api.mock.patch(camp).reply(422).once() + api.mock + .patch(camp) + .delay(10) + .reply( + status, + status === 200 + ? { ...camp, settings: { left: 'old', right: 'pending' } } + : undefined + ) + api.mock + .get(camp) + .delay(10) + .reply(200, { + ...camp, + settings: { left: 'old', right: 'pending' }, + }) + + const first = wrapper.$patch({ settings: { left: 'failed' } }) + const second = wrapper.$patch({ settings: { right: 'pending' } }) + expect(api.get(camp._meta.self).settings).toEqual({ + left: 'failed', + right: 'pending', + }) + + await expect(first).rejects.toThrow('status 422') + expect(api.get(camp._meta.self).settings).toEqual({ + left: 'old', + right: 'pending', + }) + await second + expect(wrapper.settings).toEqual({ left: 'old', right: 'pending' }) + expect(wrapper._meta.dirty).toBeUndefined() + await wrapper._meta.load + expect(wrapper.settings).toEqual({ left: 'old', right: 'pending' }) + expect( + api.mock.requests + .filter((request) => request.method === 'PATCH') + .map((request) => request.body) + ).toEqual([{ settings: { left: 'failed' } }, { settings: { right: 'pending' } }]) + } + ) + + it.each([true, false])( + 'keeps confirmed server changes on 204 with optimistic=%s', + async (optimistic) => { + const { api, camp, wrapper } = await loadedCamp(undefined, { + settings: { left: 'old', right: 'old' }, + }) + api.mock + .patch(camp) + .once() + .reply(200, { + ...camp, + settings: { left: 'server', right: 'old' }, + }) + api.mock.patch(camp).delay(10).reply(204) + api.mock + .get(camp) + .delay(10) + .reply(200, { + ...camp, + settings: { left: 'server', right: 'pending' }, + }) + + const first = wrapper.$patch({ settings: { left: 'first' } }) + const second = wrapper.$patch({ settings: { right: 'pending' } }, { optimistic }) + await first + expect(wrapper.settings).toEqual({ + left: 'server', + right: optimistic ? 'pending' : 'old', + }) + expect(() => { + wrapper.settings.right = 'bypass' + }).toThrow(TypeError) + await second + expect(wrapper.settings).toEqual({ left: 'server', right: 'pending' }) + expect(wrapper._meta.dirty).toBeUndefined() + await wrapper._meta.load + } + ) + + it('keeps a later relation callable when an earlier patch clears it and fails', async () => { + const author = fixture('Author', { name: 'old' }) + const nextAuthor = fixture('Author', { name: 'new' }) + const book = fixture('Book', { author }) + const api = createApi() + api.mock.get(book) + api.mock.get(nextAuthor) + const wrapper = await api.get(book._meta.self)._meta.load + const replacement = await api.get(nextAuthor._meta.self)._meta.load + api.mock.patch(book).once().reply(422) + api.mock.patch(book).reply(204) + api.mock + .get(book) + .delay(10) + .reply(200, { + ...book, + _links: { ...book._links, author: { href: nextAuthor._meta.self } }, + }) + + const first = wrapper.$patch({ author: null }) + const second = wrapper.$patch({ author: replacement }) + expect(wrapper.author()._meta.self).toBe(replacement._meta.self) + await expect(first).rejects.toThrow('status 422') + expect(wrapper.author()._meta.self).toBe(replacement._meta.self) + await second + expect(wrapper.author()._meta.self).toBe(replacement._meta.self) + await wrapper._meta.load + }) + + it.each([ + [200, 'wrapper'], + [200, 'uri'], + [204, 'wrapper'], + [204, 'uri'], + ] as const)( + 'preserves an optimistic relation after a server clear with a %i response and %s input', + async (status, input) => { + const author = fixture('Author', { name: 'original' }) + const nextAuthor = fixture('Author', { name: 'pending' }) + const lastAuthor = fixture('Author', { name: 'last' }) + const book = fixture('Book', { title: 'old', author }) + const api = createApi() + api.mock.get(book) + api.mock.get(nextAuthor) + api.mock.get(lastAuthor) + const wrapper = await api.get(book._meta.self)._meta.load + const next = await api.get(nextAuthor._meta.self)._meta.load + const last = await api.get(lastAuthor._meta.self)._meta.load + api.mock + .patch(book) + .once() + .reply(200, { + title: 'new', + author: null, + _links: { self: { href: book._meta.self } }, + }) + api.mock + .patch(book) + .once() + .delay(10) + .reply(200, { + title: 'new', + _links: { + self: { href: book._meta.self }, + author: { href: nextAuthor._meta.self }, + }, + }) + const confirmed = { + title: 'new', + _links: { + self: { href: book._meta.self }, + author: { href: lastAuthor._meta.self }, + }, + } + api.mock.patch(book).reply(status, status === 200 ? confirmed : undefined) + api.mock.get(book).delay(10).reply(200, confirmed) + + const first = wrapper.$patch({ title: 'new' }) + const second = wrapper.$patch({ author: next }) + await first + expect(wrapper.author()._meta.self).toBe(next._meta.self) + + const third = wrapper.$patch({ + author: input === 'wrapper' ? last : lastAuthor._meta.self, + }) + expect(wrapper.author()._meta.self).toBe(last._meta.self) + expect(wrapper.$hrefSync('author')).toBe(last._meta.self) + await second + expect(wrapper.author()._meta.self).toBe(last._meta.self) + await third + expect(wrapper.author()._meta.self).toBe(last._meta.self) + expect(wrapper.$toData().author).toBe(last._meta.self) + expect(wrapper._meta.dirty).toBeUndefined() + await wrapper._meta.load + expect( + api.mock.requests + .filter((request) => request.method === 'PATCH') + .map((request) => request.body) + ).toEqual([ + { title: 'new' }, + { author: nextAuthor._meta.self }, + { author: lastAuthor._meta.self }, + ]) + } + ) + it('without optimistic, waits for the API before changing anything', async () => { const { api, camp, wrapper } = await loadedCamp(createApi({ optimistic: false })) api.mock.patch(camp).delay(5) diff --git a/test/core/mutations.spec.ts b/test/core/mutations.spec.ts index c137286..a6cf317 100644 --- a/test/core/mutations.spec.ts +++ b/test/core/mutations.spec.ts @@ -4,6 +4,7 @@ import { diffForPatch, mergePatch, MutationQueue, + recordPatchFor, } from '../../src/core/mutations.js' import type { EntityRecord } from '../../src/core/records.js' import { createUriNormalizer } from '../../src/core/uri.js' @@ -100,6 +101,38 @@ describe('bodyForPost', () => { }) }) +describe('recordPatchFor', () => { + it.each(['visible', 'confirmed'])( + 'normalizes to-one and to-many relations from the %s state', + (source) => { + const references = { + author: { href: '/authors/1' }, + chapters: { hrefs: ['/chapters/1'] }, + } + const cleared = { author: null, chapters: null } + const data = { + author: wrapper('/authors/2'), + chapters: [wrapper('/chapters/2')], + title: '/somewhere', + } + + expect( + recordPatchFor( + source === 'visible' ? references : cleared, + data, + Object.keys(data), + context, + source === 'confirmed' ? references : cleared + ) + ).toEqual({ + author: { href: '/authors/2' }, + chapters: { hrefs: ['/chapters/2'] }, + title: '/somewhere', + }) + } + ) +}) + describe('MutationQueue', () => { const record: EntityRecord = { uri: '/activities', @@ -170,6 +203,60 @@ describe('MutationQueue', () => { expect(log).toEqual(['b1', 'a1', 'a2']) await queue.settled('/a') }) + + it('reapplies remaining deltas after rollback, merging objects and replacing arrays and relations', () => { + const book: EntityRecord = { + uri: '/books/1', + data: { + settings: { left: 'old', nested: { kept: 1, removed: 2 } }, + tags: ['old'], + author: { href: '/authors/1' }, + chapters: { hrefs: ['/chapters/1'] }, + }, + meta: { version: 1, status: 'loaded' }, + } + const queue = new MutationQueue() + const first = { + id: '1', + kind: 'patch' as const, + uri: book.uri, + optimistic: true, + dirty: { settings: null }, + patch: { settings: null }, + } + const second = { + id: '2', + kind: 'patch' as const, + uri: book.uri, + optimistic: true, + dirty: { settings: { nested: { next: 3 } } }, + patch: { + settings: { nested: { removed: null, next: 3 } }, + tags: ['new'], + author: { href: '/authors/2' }, + chapters: { hrefs: ['/chapters/2'] }, + }, + } + queue.add(first) + queue.add(second) + expect(queue.dirtyFor(book)).toEqual({ + settings: { nested: { next: 3 } }, + tags: ['new'], + author: { href: '/authors/2' }, + chapters: { hrefs: ['/chapters/2'] }, + }) + + queue.remove(first) + expect(queue.dirtyFor(book)).toEqual({ + settings: { left: 'old', nested: { kept: 1, next: 3 } }, + tags: ['new'], + author: { href: '/authors/2' }, + chapters: { hrefs: ['/chapters/2'] }, + }) + queue.remove(second) + expect(queue.dirtyFor(book)).toBeUndefined() + expect(book.data.settings).toEqual({ left: 'old', nested: { kept: 1, removed: 2 } }) + }) }) describe('util', () => { @@ -212,6 +299,21 @@ describe('diffForPatch with nested objects', () => { ).toEqual({}) }) + it.each([ + { value: null }, + { value: 1 }, + { value: 'old' }, + { value: ['old'] }, + { value: undefined }, + ])('applies object patches to $value using an empty object', ({ value }) => { + expect( + diffForPatch({ data: value }, { data: { removed: null, kept: 'new' } }, context) + ).toEqual({ + body: { data: { removed: null, kept: 'new' } }, + dirty: { data: { kept: 'new' } }, + }) + }) + it('replaces arrays and primitives', () => { expect(mergePatch({ a: [1, 2], b: 1 }, { a: [3], b: { c: 1 } })).toEqual({ a: [3],