/*-------------------------------------------------------------------------- @sinclair/typebox/value The MIT License (MIT) Copyright (c) 2017-2025 Haydn Paterson (sinclair) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ---------------------------------------------------------------------------*/ import { computeArrayDiff, getArrayDiffMapping, } from "@noya-app/noya-array-diff"; import { Array, Literal, Number, Static, String, TArray, TLiteral, TNumber, TObject, TString, TUnion, TUnknown, TypeBoxError, Union, Unknown, } from "@sinclair/typebox"; import { Equal, HasPropertyKey, IsArray, IsStandardObject, IsTypedArray, IsValueType, } from "@sinclair/typebox/value"; // ------------------------------------------------------------------ // Types // ------------------------------------------------------------------ export type ObjectType = Record; export type ArrayType = unknown[]; export type ValueType = | null | undefined | symbol | bigint | number | boolean | string; // prettier-ignore export type TypedArrayType = | Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array // ------------------------------------------------------------------ // Commands // ------------------------------------------------------------------ // Note: A TypeScript 5.4.2 compiler regression resulted in the type // import paths being generated incorrectly. We can resolve this by // explicitly importing the correct TSchema types above. Note also // that the left-side annotations are optional, but since the types // are imported we might as well use them. We should check this // regression in future. The regression occured between TypeScript // versions 5.3.3 -> 5.4.2. export const Path: TArray> = Array( Union([String(), Number()]) ); export type Path = Static; export type Insert = Static; export const Insert: TObject<{ op: TLiteral<"add">; path: typeof Path; value: TUnknown; }> = Object({ op: Literal("add"), path: Path, value: Unknown(), }); export type Update = Static; export const Update: TObject<{ op: TLiteral<"replace">; path: typeof Path; value: TUnknown; }> = Object({ op: Literal("replace"), path: Path, value: Unknown(), }); export type Delete = Static; export const Delete: TObject<{ op: TLiteral<"remove">; path: typeof Path; }> = Object({ op: Literal("remove"), path: Path, }); export type Move = Static; export const Move: TObject<{ op: TLiteral<"move">; from: typeof Path; path: typeof Path; }> = Object({ op: Literal("move"), from: Path, path: Path, }); export type Edit = Static; export const Edit: TUnion< [typeof Insert, typeof Update, typeof Delete, typeof Move] > = Union([Insert, Update, Delete, Move]); // ------------------------------------------------------------------ // Errors // ------------------------------------------------------------------ export class ValueDiffError extends TypeBoxError { constructor( public readonly value: unknown, message: string ) { super(message); } } // ------------------------------------------------------------------ // Command Factory // ------------------------------------------------------------------ function CreateUpdate(path: Path, value: unknown): Edit { return { op: "replace", path, value }; } function CreateInsert(path: Path, value: unknown): Edit { return { op: "add", path, value }; } function CreateDelete(path: Path): Edit { return { op: "remove", path }; } function CreateMove(from: Path, to: Path): Edit { return { op: "move", from, path: to }; } // ------------------------------------------------------------------ // Diffing Generators // ------------------------------------------------------------------ function* ObjectType( path: Path, current: ObjectType, next: unknown ): IterableIterator { if (!IsStandardObject(next)) return yield CreateUpdate(path, next); const currentKeys = globalThis.Object.getOwnPropertyNames(current); const nextKeys = globalThis.Object.getOwnPropertyNames(next); // ---------------------------------------------------------------- // inserts // ---------------------------------------------------------------- for (const key of nextKeys) { if (HasPropertyKey(current, key)) continue; yield CreateInsert([...path, key], next[key]); } // ---------------------------------------------------------------- // updates // ---------------------------------------------------------------- for (const key of currentKeys) { if (!HasPropertyKey(next, key)) continue; if (Equal(current, next)) continue; yield* Visit([...path, key], current[key], next[key]); } // ---------------------------------------------------------------- // deletes // ---------------------------------------------------------------- for (const key of currentKeys) { if (HasPropertyKey(next, key)) continue; yield CreateDelete([...path, key]); } } function identity(item: T): string { // return item as string; return typeof item === "object" && item !== null && "id" in item ? (item.id as string) : (item as string); } function* ArrayType( path: Path, current: ArrayType, next: unknown ): IterableIterator { if (!IsArray(next)) return yield CreateUpdate(path, next); const arrayDiff = computeArrayDiff(current, next, identity); for (const item of arrayDiff) { switch (item[0]) { case "a": { yield CreateInsert([...path, item[2]!], item[1]); break; } case "r": { yield CreateDelete([...path, item[1]]); break; } case "m": { yield CreateMove([...path, item[1]], [...path, item[2]]); break; } } } const mapping = getArrayDiffMapping(current.length, arrayDiff); for (let i = 0; i < mapping.length; i++) { const originalIndex = mapping[i]; if (originalIndex !== null) { yield* Visit([...path, i], current[originalIndex], next[i]); } } } function* TypedArrayType( path: Path, current: TypedArrayType, next: unknown ): IterableIterator { if ( !IsTypedArray(next) || current.length !== next.length || globalThis.Object.getPrototypeOf(current).constructor.name !== globalThis.Object.getPrototypeOf(next).constructor.name ) return yield CreateUpdate(path, next); for (let i = 0; i < Math.min(current.length, next.length); i++) { yield* Visit([...path, i], current[i], next[i]); } } function* ValueType( path: Path, current: ValueType, next: unknown ): IterableIterator { if (current === next) return; yield CreateUpdate(path, next); } function* Visit( path: Path, current: unknown, next: unknown ): IterableIterator { if (IsStandardObject(current)) return yield* ObjectType(path, current, next); if (IsArray(current)) return yield* ArrayType(path, current, next); if (IsTypedArray(current)) return yield* TypedArrayType(path, current, next); if (IsValueType(current)) return yield* ValueType(path, current, next); // throw new ValueDiffError(current, "Unable to diff value"); // Fallback: for unsupported types (e.g., Date, Map, Set, Function), // treat as a simple replacement to avoid throwing during diff. return yield CreateUpdate(path, next); } // ------------------------------------------------------------------ // Diff // ------------------------------------------------------------------ export function Diff(current: unknown, next: unknown): Edit[] { return [...Visit([], current, next)]; } // ------------------------------------------------------------------ // Patch // ------------------------------------------------------------------ // function IsRootUpdate(edits: Edit[]): edits is [Update] { // return ( // edits.length > 0 && // edits[0].type === "replace" && // edits[0].path.length === 0 // ); // } // function IsIdentity(edits: Edit[]) { // return edits.length === 0; // } // export function Patch(current: unknown, edits: Edit[]): T { // if (IsRootUpdate(edits)) { // return Clone(edits[0].value) as T; // } // if (IsIdentity(edits)) { // return Clone(current) as T; // } // const clone = Clone(current); // for (const edit of edits) { // switch (edit.type) { // case "add": { // ValuePointer.Set(clone, edit.path, edit.value); // break; // } // case "replace": { // ValuePointer.Set(clone, edit.path, edit.value); // break; // } // case "remove": { // ValuePointer.Delete(clone, edit.path); // break; // } // } // } // return clone as T; // }