Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
22 changes: 16 additions & 6 deletions src/core/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -1246,20 +1256,20 @@ export class HalcClient implements Client {
}

/** Writes confirmed changes into the data of a record (for answers without content). */
private commitData(uri: string, changes: Record<string, unknown>): void {
private commitData(uri: string, patch: Record<string, unknown>): 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),
status: 'stale',
},
}
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])
Expand All @@ -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])
Expand Down
62 changes: 55 additions & 7 deletions src/core/mutations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ export interface PendingMutation {
optimistic: boolean
/** For PATCH: the local changes in record form (relations as refs). */
dirty?: Record<string, unknown>
/** For PATCH: the local merge-patch delta in record form, used to recompute `dirty`. */
patch?: Record<string, unknown>
/** For POST: the URI of the temporary record. */
tempUri?: string
}
Expand Down Expand Up @@ -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 : []
Expand Down Expand Up @@ -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<string, unknown>,
patch: Record<string, unknown>
): Record<string, unknown> {
const changes: Record<string, unknown> = {}
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
Expand All @@ -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<string, unknown> {
Expand All @@ -166,6 +196,24 @@ export interface PatchDiff {
dirty: Record<string, unknown>
}

/** Converts PATCH fields to record form using visible and confirmed relation references. */
export function recordPatchFor(
current: Record<string, unknown>,
data: Record<string, unknown>,
keys: Iterable<string>,
context: DiffContext,
confirmed: Record<string, unknown> = current
): Record<string, unknown> {
const patch: Record<string, unknown> = {}
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
Expand Down
194 changes: 194 additions & 0 deletions test/core/client.mutations.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading
Loading