1import type { Differ } from "../../Differ.ts"
2import * as JsonPatch from "../../JsonPatch.ts"
3import type * as Schema from "../../Schema.ts"
4import * as SchemaParser from "../../SchemaParser.ts"
5import * as InternalToCodec from "./toCodec.ts"
6
7/** @internal */
8export function toDifferJsonPatch<T>(
9 schema: Schema.ConstraintCodec<T, unknown>
10): Differ<T, JsonPatch.JsonPatch> {
11 const serializer = InternalToCodec.toCodecJson(schema)
12 const get = SchemaParser.encodeSync(serializer)
13 const set = SchemaParser.decodeSync(serializer)
14 return {
15 empty: [],
16 diff: (oldValue, newValue) => JsonPatch.get(get(oldValue), get(newValue)),
17 combine: (first, second) => [...first, ...second],
18 patch: (oldValue, patch) => {
19 const value = get(oldValue)
20 const patched = JsonPatch.apply(patch, value)
21 return Object.is(patched, value) ? oldValue : set(patched)
22 }
23 }
24}