{"version":3,"file":"index.mjs","sources":["../src/document/debug.ts","../src/patch/ImmutableAccessor.ts","../src/util.ts","../src/jsonpath/arrayToJSONMatchPath.ts","../src/jsonpath/descend.ts","../src/jsonpath/tokenize.ts","../src/jsonpath/parse.ts","../src/jsonpath/toPath.ts","../src/jsonpath/Expression.ts","../src/jsonpath/Descender.ts","../src/jsonpath/Matcher.ts","../src/jsonpath/PlainProbe.ts","../src/jsonpath/extractAccessors.ts","../src/jsonpath/extract.ts","../src/jsonpath/extractWithPath.ts","../src/patch/DiffMatchPatch.ts","../src/patch/IncPatch.ts","../src/patch/util.ts","../src/patch/InsertPatch.ts","../src/patch/SetIfMissingPatch.ts","../src/patch/SetPatch.ts","../src/patch/UnsetPatch.ts","../src/patch/parse.ts","../src/patch/Patcher.ts","../src/document/luid.ts","../src/document/Mutation.ts","../src/document/Document.ts","../src/document/SquashingBuffer.ts","../src/document/BufferedDocument.ts"],"sourcesContent":["import debugIt from 'debug'\n\nexport const debug = debugIt('mutator-document')\n","import {type Probe} from '../jsonpath/Probe'\n\n/**\n * An immutable probe/writer for plain JS objects that will never mutate\n * the provided _value in place. Each setter returns a new (wrapped) version\n * of the value.\n */\nexport class ImmutableAccessor implements Probe {\n  _value: unknown\n  path: (string | number)[]\n\n  constructor(value: unknown, path?: (string | number)[]) {\n    this._value = value\n    this.path = path || []\n  }\n\n  containerType(): 'array' | 'object' | 'primitive' {\n    if (Array.isArray(this._value)) {\n      return 'array'\n    } else if (this._value !== null && typeof this._value === 'object') {\n      return 'object'\n    }\n    return 'primitive'\n  }\n\n  // Common reader, supported by all containers\n  get(): unknown {\n    return this._value\n  }\n\n  // Array reader\n  length(): number {\n    if (!Array.isArray(this._value)) {\n      throw new Error(\"Won't return length of non-indexable _value\")\n    }\n\n    return this._value.length\n  }\n\n  getIndex(i: number): ImmutableAccessor | false | null {\n    if (!Array.isArray(this._value)) {\n      return false\n    }\n\n    if (i >= this.length()) {\n      return null\n    }\n\n    return new ImmutableAccessor(this._value[i], this.path.concat(i))\n  }\n\n  // Object reader\n  hasAttribute(key: string): boolean {\n    return isRecord(this._value) ? this._value.hasOwnProperty(key) : false\n  }\n\n  attributeKeys(): string[] {\n    return isRecord(this._value) ? Object.keys(this._value) : []\n  }\n\n  getAttribute(key: string): ImmutableAccessor | null {\n    if (!isRecord(this._value)) {\n      throw new Error('getAttribute only applies to plain objects')\n    }\n\n    if (!this.hasAttribute(key)) {\n      return null\n    }\n\n    return new ImmutableAccessor(this._value[key], this.path.concat(key))\n  }\n\n  // Common writer, supported by all containers\n  set(value: unknown): ImmutableAccessor {\n    return value === this._value ? this : new ImmutableAccessor(value, this.path)\n  }\n\n  // array writer interface\n  setIndex(i: number, value: unknown): ImmutableAccessor {\n    if (!Array.isArray(this._value)) {\n      throw new Error('setIndex only applies to arrays')\n    }\n\n    if (Object.is(value, this._value[i])) {\n      return this\n    }\n\n    const nextValue = this._value.slice()\n    nextValue[i] = value\n    return new ImmutableAccessor(nextValue, this.path)\n  }\n\n  setIndexAccessor(i: number, accessor: ImmutableAccessor): ImmutableAccessor {\n    return this.setIndex(i, accessor.get())\n  }\n\n  unsetIndices(indices: number[]): ImmutableAccessor {\n    if (!Array.isArray(this._value)) {\n      throw new Error('unsetIndices only applies to arrays')\n    }\n\n    const length = this._value.length\n    const nextValue = []\n    // Copy every _value _not_ in the indices array over to the newValue\n    for (let i = 0; i < length; i++) {\n      if (indices.indexOf(i) === -1) {\n        nextValue.push(this._value[i])\n      }\n    }\n    return new ImmutableAccessor(nextValue, this.path)\n  }\n\n  insertItemsAt(pos: number, items: unknown[]): ImmutableAccessor {\n    if (!Array.isArray(this._value)) {\n      throw new Error('insertItemsAt only applies to arrays')\n    }\n\n    let nextValue\n    if (this._value.length === 0 && pos === 0) {\n      nextValue = items\n    } else {\n      nextValue = this._value.slice(0, pos).concat(items).concat(this._value.slice(pos))\n    }\n\n    return new ImmutableAccessor(nextValue, this.path)\n  }\n\n  // Object writer interface\n  setAttribute(key: string, value: unknown): ImmutableAccessor {\n    if (!isRecord(this._value)) {\n      throw new Error('Unable to set attribute of non-object container')\n    }\n\n    if (Object.is(value, this._value[key])) {\n      return this\n    }\n\n    const nextValue = Object.assign({}, this._value, {[key]: value})\n    return new ImmutableAccessor(nextValue, this.path)\n  }\n\n  setAttributeAccessor(key: string, accessor: ImmutableAccessor): ImmutableAccessor {\n    return this.setAttribute(key, accessor.get())\n  }\n\n  unsetAttribute(key: string): ImmutableAccessor {\n    if (!isRecord(this._value)) {\n      throw new Error('Unable to unset attribute of non-object container')\n    }\n\n    const nextValue = Object.assign({}, this._value)\n    delete nextValue[key]\n    return new ImmutableAccessor(nextValue, this.path)\n  }\n}\n\nfunction isRecord(value: unknown): value is {[key: string]: unknown} {\n  return value !== null && typeof value === 'object'\n}\n","export function isRecord(value: unknown): value is {[key: string]: unknown} {\n  return value !== null && typeof value === 'object'\n}\n","import {type Path, type PathSegment} from '@sanity/types'\n\nimport {isRecord} from '../util'\n\nconst IS_DOTTABLE = /^[a-z_$]+/\n\n/**\n * Converts a path in array form to a JSONPath string\n *\n * @param pathArray - Array of path segments\n * @returns String representation of the path\n * @internal\n */\nexport function arrayToJSONMatchPath(pathArray: Path): string {\n  let path = ''\n  pathArray.forEach((segment, index) => {\n    path += stringifySegment(segment, index === 0)\n  })\n  return path\n}\n\n// Converts an array of simple values (strings, numbers only) to a jsonmatch path string.\nfunction stringifySegment(\n  segment: PathSegment | Record<string, unknown>,\n  hasLeading: boolean,\n): string {\n  if (typeof segment === 'number') {\n    return `[${segment}]`\n  }\n\n  if (isRecord(segment)) {\n    const seg = segment as Record<string, unknown>\n    return Object.keys(segment)\n      .map((key) => (isPrimitiveValue(seg[key]) ? `[${key}==\"${seg[key]}\"]` : ''))\n      .join('')\n  }\n\n  if (typeof segment === 'string' && IS_DOTTABLE.test(segment)) {\n    return hasLeading ? segment : `.${segment}`\n  }\n\n  return `['${segment}']`\n}\n\nfunction isPrimitiveValue(val: unknown): val is string | number | boolean {\n  switch (typeof val) {\n    case 'number':\n    case 'string':\n    case 'boolean':\n      return true\n    default:\n      return false\n  }\n}\n","import {type Expr, type PathExpr} from './types'\n\n/**\n * Splits an expression into a set of heads, tails. A head is the next leaf node to\n * check for matches, and a tail is everything that follows it. Matching is done by\n * matching heads, then proceedint to the matching value, splitting the tail into\n * heads and tails and checking the heads against the new value, and so on.\n */\nexport function descend(tail: Expr): [Expr | null, PathExpr | null][] {\n  const [head, newTail] = splitIfPath(tail)\n  if (!head) {\n    throw new Error('Head cannot be null')\n  }\n\n  return spreadIfUnionHead(head, newTail)\n}\n\n// Split path in [head, tail]\nfunction splitIfPath(tail: Expr): [Expr | null, PathExpr | null] {\n  if (tail.type !== 'path') {\n    return [tail, null]\n  }\n\n  const nodes = tail.nodes\n  if (nodes.length === 0) {\n    return [null, null]\n  }\n\n  if (nodes.length === 1) {\n    return [nodes[0], null]\n  }\n\n  return [nodes[0], {type: 'path', nodes: nodes.slice(1)}]\n}\n\nfunction concatPaths(path1: PathExpr | null, path2: PathExpr | null): PathExpr | null {\n  if (!path1 && !path2) {\n    return null\n  }\n\n  const nodes1 = path1 ? path1.nodes : []\n  const nodes2 = path2 ? path2.nodes : []\n  return {\n    type: 'path',\n    nodes: nodes1.concat(nodes2),\n  }\n}\n\n// Spreads a union head into several heads/tails\nfunction spreadIfUnionHead(head: Expr, tail: PathExpr | null): [Expr | null, PathExpr | null][] {\n  if (head.type !== 'union') {\n    return [[head, tail]]\n  }\n\n  return head.nodes.map((node) => {\n    if (node.type === 'path') {\n      const [subHead, subTail] = splitIfPath(node)\n      return [subHead, concatPaths(subTail, tail)]\n    }\n\n    return [node, tail]\n  })\n}\n","import {\n  type IdentifierToken,\n  type NumberToken,\n  type QuotedToken,\n  type SymbolClass,\n  type SymbolToken,\n  type Token,\n} from './types'\n\n// TODO: Support '*'\n\nconst digitChar = /[0-9]/\nconst attributeCharMatcher = /^[a-zA-Z0-9_]$/\nconst attributeFirstCharMatcher = /^[a-zA-Z_]$/\n\nconst symbols: Record<SymbolClass, string[]> = {\n  // NOTE: These are compared against in order of definition,\n  // thus '==' must come before '=', '>=' before '>', etc.\n  operator: ['..', '.', ',', ':', '?'],\n  comparator: ['>=', '<=', '<', '>', '==', '!='],\n  keyword: ['$', '@'],\n  boolean: ['true', 'false'],\n  paren: ['[', ']'],\n}\n\nconst symbolClasses = Object.keys(symbols) as SymbolClass[]\n\ntype TokenizerFn = () => Token | null\n\n/**\n * Tokenizes a jsonpath2 expression\n */\nclass Tokenizer {\n  source: string\n  i: number\n  length: number\n  tokenizers: TokenizerFn[]\n\n  constructor(path: string) {\n    this.source = path\n    this.length = path.length\n    this.i = 0\n    this.tokenizers = [\n      this.tokenizeSymbol,\n      this.tokenizeIdentifier,\n      this.tokenizeNumber,\n      this.tokenizeQuoted,\n    ].map((fn) => fn.bind(this))\n  }\n\n  tokenize(): Token[] {\n    const result: Token[] = []\n    while (!this.EOF()) {\n      this.chompWhitespace()\n      let token: Token | null = null\n      // @todo refactor into a simpler `.find()`?\n      const found = this.tokenizers.some((tokenizer) => {\n        token = tokenizer()\n        return Boolean(token)\n      })\n      if (!found || !token) {\n        throw new Error(`Invalid tokens in jsonpath '${this.source}' @ ${this.i}`)\n      }\n      result.push(token)\n    }\n    return result\n  }\n\n  takeWhile(fn: (character: string) => string | null): string | null {\n    const start = this.i\n    let result = ''\n    while (!this.EOF()) {\n      const nextChar = fn(this.source[this.i])\n      if (nextChar === null) {\n        break\n      }\n      result += nextChar\n      this.i++\n    }\n    if (this.i === start) {\n      return null\n    }\n    return result\n  }\n\n  EOF(): boolean {\n    return this.i >= this.length\n  }\n\n  peek(): string | null {\n    if (this.EOF()) {\n      return null\n    }\n    return this.source[this.i]\n  }\n\n  consume(str: string) {\n    if (this.i + str.length > this.length) {\n      throw new Error(`Expected ${str} at end of jsonpath`)\n    }\n    if (str === this.source.slice(this.i, this.i + str.length)) {\n      this.i += str.length\n    } else {\n      throw new Error(`Expected \"${str}\", but source contained \"${this.source.slice()}`)\n    }\n  }\n\n  // Tries to match the upcoming bit of string with the provided string. If it matches, returns\n  // the string, then advances the read pointer to the next bit. If not, returns null and nothing\n  // happens.\n  tryConsume(str: string) {\n    if (this.i + str.length > this.length) {\n      return null\n    }\n    if (str === this.source.slice(this.i, this.i + str.length)) {\n      // When checking symbols that consist of valid attribute characters, we\n      // need to make sure we don't inadvertently treat an attribute as a\n      // symbol. For example, an attribute 'trueCustomerField' should not be\n      // scanned as the boolean symbol \"true\".\n      if (str[0].match(attributeCharMatcher)) {\n        // check that char following the symbol match is not also an attribute char\n        if (this.length > this.i + str.length) {\n          const nextChar = this.source[this.i + str.length]\n          if (nextChar && nextChar.match(attributeCharMatcher)) {\n            return null\n          }\n        }\n      }\n      this.i += str.length\n      return str\n    }\n    return null\n  }\n\n  chompWhitespace(): void {\n    this.takeWhile((char): string | null => {\n      return char === ' ' ? '' : null\n    })\n  }\n\n  tokenizeQuoted(): QuotedToken | null {\n    const quote = this.peek()\n    if (quote === \"'\" || quote === '\"') {\n      this.consume(quote)\n      let escape = false\n      const inner = this.takeWhile((char) => {\n        if (escape) {\n          escape = false\n          return char\n        }\n        if (char === '\\\\') {\n          escape = true\n          return ''\n        }\n        if (char != quote) {\n          return char\n        }\n        return null\n      })\n      this.consume(quote)\n      return {\n        type: 'quoted',\n        value: inner,\n        quote: quote === '\"' ? 'double' : 'single',\n      }\n    }\n    return null\n  }\n\n  tokenizeIdentifier(): IdentifierToken | null {\n    let first = true\n    const identifier = this.takeWhile((char) => {\n      if (first) {\n        first = false\n        return char.match(attributeFirstCharMatcher) ? char : null\n      }\n      return char.match(attributeCharMatcher) ? char : null\n    })\n    if (identifier !== null) {\n      return {\n        type: 'identifier',\n        name: identifier,\n      }\n    }\n    return null\n  }\n\n  tokenizeNumber(): NumberToken | null {\n    const start = this.i\n    let dotSeen = false\n    let digitSeen = false\n    let negative = false\n    if (this.peek() === '-') {\n      negative = true\n      this.consume('-')\n    }\n    const number = this.takeWhile((char) => {\n      if (char === '.' && !dotSeen && digitSeen) {\n        dotSeen = true\n        return char\n      }\n      digitSeen = true\n      return char.match(digitChar) ? char : null\n    })\n    if (number !== null) {\n      return {\n        type: 'number',\n        value: negative ? -number : +number,\n        raw: negative ? `-${number}` : number,\n      }\n    }\n    // No number, rewind\n    this.i = start\n    return null\n  }\n\n  tokenizeSymbol(): SymbolToken | null {\n    for (const symbolClass of symbolClasses) {\n      const patterns = symbols[symbolClass]\n      const symbol = patterns.find((pattern) => this.tryConsume(pattern))\n      if (symbol) {\n        return {\n          type: symbolClass,\n          symbol,\n        }\n      }\n    }\n\n    return null\n  }\n}\n\nexport function tokenize(jsonpath: string): Token[] {\n  return new Tokenizer(jsonpath).tokenize()\n}\n","// Converts a string into an abstract syntax tree representation\n\nimport {tokenize} from './tokenize'\nimport {\n  type AliasExpr,\n  type AttributeExpr,\n  type BooleanExpr,\n  type ConstraintExpr,\n  type IndexExpr,\n  type NumberExpr,\n  type PathExpr,\n  type RangeExpr,\n  type RecursiveExpr,\n  type StringExpr,\n  type Token,\n  type UnionExpr,\n} from './types'\n\n// TODO: Support '*'\n\nclass Parser {\n  tokens: Token[]\n  length: number\n  i: number\n\n  constructor(path: string) {\n    this.tokens = tokenize(path)\n    this.length = this.tokens.length\n    this.i = 0\n  }\n\n  parse() {\n    return this.parsePath()\n  }\n\n  EOF() {\n    return this.i >= this.length\n  }\n\n  // Look at upcoming token\n  peek() {\n    if (this.EOF()) {\n      return null\n    }\n    return this.tokens[this.i]\n  }\n\n  consume() {\n    const result = this.peek()\n    this.i += 1\n    return result\n  }\n\n  // Return next token if it matches the pattern\n  probe(pattern: Record<string, unknown>): Token | null {\n    const token = this.peek()\n    if (!token) {\n      return null\n    }\n\n    const record = token as unknown as Record<string, unknown>\n    const match = Object.keys(pattern).every((key) => {\n      return key in token && pattern[key] === record[key]\n    })\n\n    return match ? token : null\n  }\n\n  // Return and consume next token if it matches the pattern\n  match(pattern: Partial<Token>): Token | null {\n    return this.probe(pattern) ? this.consume() : null\n  }\n\n  parseAttribute(): AttributeExpr | null {\n    const token = this.match({type: 'identifier'})\n    if (token && token.type === 'identifier') {\n      return {\n        type: 'attribute',\n        name: token.name,\n      }\n    }\n    const quoted = this.match({type: 'quoted', quote: 'single'})\n    if (quoted && quoted.type === 'quoted') {\n      return {\n        type: 'attribute',\n        name: quoted.value || '',\n      }\n    }\n    return null\n  }\n\n  parseAlias(): AliasExpr | null {\n    if (this.match({type: 'keyword', symbol: '@'}) || this.match({type: 'keyword', symbol: '$'})) {\n      return {\n        type: 'alias',\n        target: 'self',\n      }\n    }\n    return null\n  }\n\n  parseNumber(): NumberExpr | null {\n    const token = this.match({type: 'number'})\n    if (token && token.type === 'number') {\n      return {\n        type: 'number',\n        value: token.value,\n      }\n    }\n    return null\n  }\n\n  parseNumberValue(): number | null {\n    const expr = this.parseNumber()\n    if (expr) {\n      return expr.value\n    }\n    return null\n  }\n\n  parseSliceSelector(): RangeExpr | IndexExpr | null {\n    const start = this.i\n    const rangeStart = this.parseNumberValue()\n\n    const colon1 = this.match({type: 'operator', symbol: ':'})\n    if (!colon1) {\n      if (rangeStart === null) {\n        // Rewind, this was actually nothing\n        this.i = start\n        return null\n      }\n\n      // Unwrap, this was just a single index not followed by colon\n      return {type: 'index', value: rangeStart}\n    }\n\n    const result: RangeExpr = {\n      type: 'range',\n      start: rangeStart,\n      end: this.parseNumberValue(),\n    }\n\n    const colon2 = this.match({type: 'operator', symbol: ':'})\n    if (colon2) {\n      result.step = this.parseNumberValue()\n    }\n\n    if (result.start === null && result.end === null) {\n      // rewind, this wasnt' a slice selector\n      this.i = start\n      return null\n    }\n\n    return result\n  }\n\n  parseValueReference(): AttributeExpr | RangeExpr | IndexExpr | null {\n    return this.parseAttribute() || this.parseSliceSelector()\n  }\n\n  parseLiteralValue(): StringExpr | BooleanExpr | NumberExpr | null {\n    const literalString = this.match({type: 'quoted', quote: 'double'})\n    if (literalString && literalString.type === 'quoted') {\n      return {\n        type: 'string',\n        value: literalString.value || '',\n      }\n    }\n    const literalBoolean = this.match({type: 'boolean'})\n    if (literalBoolean && literalBoolean.type === 'boolean') {\n      return {\n        type: 'boolean',\n        value: literalBoolean.symbol === 'true',\n      }\n    }\n    return this.parseNumber()\n  }\n\n  // TODO: Reorder constraints so that literal value is always on rhs, and variable is always\n  // on lhs.\n  parseFilterExpression(): ConstraintExpr | null {\n    const start = this.i\n    const expr = this.parseAttribute() || this.parseAlias()\n    if (!expr) {\n      return null\n    }\n\n    if (this.match({type: 'operator', symbol: '?'})) {\n      return {\n        type: 'constraint',\n        operator: '?',\n        lhs: expr,\n      }\n    }\n\n    const binOp = this.match({type: 'comparator'})\n    if (!binOp || binOp.type !== 'comparator') {\n      // No expression, rewind!\n      this.i = start\n      return null\n    }\n\n    const lhs = expr\n    const rhs = this.parseLiteralValue()\n    if (!rhs) {\n      throw new Error(`Operator ${binOp.symbol} needs a literal value at the right hand side`)\n    }\n\n    return {\n      type: 'constraint',\n      operator: binOp.symbol,\n      lhs: lhs,\n      rhs: rhs,\n    }\n  }\n\n  parseExpression(): ConstraintExpr | AttributeExpr | RangeExpr | IndexExpr | null {\n    return this.parseFilterExpression() || this.parseValueReference()\n  }\n\n  parseUnion(): UnionExpr | null {\n    if (!this.match({type: 'paren', symbol: '['})) {\n      return null\n    }\n\n    const terms = []\n    let expr = this.parseFilterExpression() || this.parsePath() || this.parseValueReference()\n    while (expr) {\n      terms.push(expr)\n      // End of union?\n      if (this.match({type: 'paren', symbol: ']'})) {\n        break\n      }\n\n      if (!this.match({type: 'operator', symbol: ','})) {\n        throw new Error('Expected ]')\n      }\n\n      expr = this.parseFilterExpression() || this.parsePath() || this.parseValueReference()\n      if (!expr) {\n        throw new Error(\"Expected expression following ','\")\n      }\n    }\n\n    return {\n      type: 'union',\n      nodes: terms,\n    }\n  }\n\n  parseRecursive(): RecursiveExpr | null {\n    if (!this.match({type: 'operator', symbol: '..'})) {\n      return null\n    }\n\n    const subpath = this.parsePath()\n    if (!subpath) {\n      throw new Error(\"Expected path following '..' operator\")\n    }\n\n    return {\n      type: 'recursive',\n      term: subpath,\n    }\n  }\n\n  parsePath(): PathExpr | AttributeExpr | UnionExpr | RecursiveExpr | null {\n    const nodes: (AttributeExpr | UnionExpr | RecursiveExpr)[] = []\n    const expr = this.parseAttribute() || this.parseUnion() || this.parseRecursive()\n    if (!expr) {\n      return null\n    }\n\n    nodes.push(expr)\n    while (!this.EOF()) {\n      if (this.match({type: 'operator', symbol: '.'})) {\n        const attr = this.parseAttribute()\n        if (!attr) {\n          throw new Error(\"Expected attribute name following '.\")\n        }\n        nodes.push(attr)\n        continue\n      } else if (this.probe({type: 'paren', symbol: '['})) {\n        const union = this.parseUnion()\n        if (!union) {\n          throw new Error(\"Expected union following '['\")\n        }\n        nodes.push(union)\n      } else {\n        const recursive = this.parseRecursive()\n        if (recursive) {\n          nodes.push(recursive)\n        }\n        break\n      }\n    }\n\n    if (nodes.length === 1) {\n      return nodes[0]\n    }\n\n    return {\n      type: 'path',\n      nodes: nodes,\n    }\n  }\n}\n\nexport function parseJsonPath(path: string): PathExpr | AttributeExpr | UnionExpr | RecursiveExpr {\n  const parsed = new Parser(path).parse()\n  if (!parsed) {\n    throw new Error(`Failed to parse JSON path \"${path}\"`)\n  }\n  return parsed\n}\n","import {type Expr} from './types'\n\n/**\n * Converts a parsed expression back into jsonpath2, roughly -\n * mostly for use with tests.\n *\n * @param expr - Expression to convert to path\n * @returns a string representation of the path\n * @internal\n */\nexport function toPath(expr: Expr): string {\n  return toPathInner(expr, false)\n}\n\nfunction toPathInner(expr: Expr, inUnion: boolean): string {\n  switch (expr.type) {\n    case 'attribute':\n      return expr.name\n    case 'alias':\n      return expr.target === 'self' ? '@' : '$'\n    case 'number':\n      return `${expr.value}`\n    case 'range': {\n      const result = []\n      if (!inUnion) {\n        result.push('[')\n      }\n      if (expr.start) {\n        result.push(`${expr.start}`)\n      }\n      result.push(':')\n      if (expr.end) {\n        result.push(`${expr.end}`)\n      }\n      if (expr.step) {\n        result.push(`:${expr.step}`)\n      }\n      if (!inUnion) {\n        result.push(']')\n      }\n      return result.join('')\n    }\n    case 'index':\n      if (inUnion) {\n        return `${expr.value}`\n      }\n\n      return `[${expr.value}]`\n    case 'constraint': {\n      const rhs = expr.rhs ? ` ${toPathInner(expr.rhs, false)}` : ''\n      const inner = `${toPathInner(expr.lhs, false)} ${expr.operator}${rhs}`\n\n      if (inUnion) {\n        return inner\n      }\n\n      return `[${inner}]`\n    }\n    case 'string':\n      return JSON.stringify(expr.value)\n    case 'path': {\n      const result = []\n      const nodes = expr.nodes.slice()\n      while (nodes.length > 0) {\n        const node = nodes.shift()\n        if (node) {\n          result.push(toPath(node))\n        }\n\n        const upcoming = nodes[0]\n        if (upcoming && toPathInner(upcoming, false)[0] !== '[') {\n          result.push('.')\n        }\n      }\n      return result.join('')\n    }\n    case 'union':\n      return `[${expr.nodes.map((e) => toPathInner(e, true)).join(',')}]`\n    default:\n      throw new Error(`Unknown node type ${expr.type}`)\n    case 'recursive':\n      return `..${toPathInner(expr.term, false)}`\n  }\n}\n","// A utility wrapper class to process parsed jsonpath expressions\n\nimport {descend} from './descend'\nimport {parseJsonPath} from './parse'\nimport {type Probe} from './Probe'\nimport {toPath} from './toPath'\nimport {type Expr, type HeadTail} from './types'\n\nexport interface Range {\n  start: number\n  end: number\n  step: number\n}\n\nexport class Expression {\n  expr: Expr\n\n  constructor(expr: Expr | Expression | null) {\n    if (!expr) {\n      throw new Error('Attempted to create Expression from null-value')\n    }\n\n    // This is a wrapped expr\n    if ('expr' in expr) {\n      this.expr = expr.expr\n    } else {\n      this.expr = expr\n    }\n\n    if (!('type' in this.expr)) {\n      throw new Error('Attempt to create Expression for expression with no type')\n    }\n  }\n\n  isPath(): boolean {\n    return this.expr.type === 'path'\n  }\n\n  isUnion(): boolean {\n    return this.expr.type === 'union'\n  }\n\n  isCollection(): boolean {\n    return this.isPath() || this.isUnion()\n  }\n\n  isConstraint(): boolean {\n    return this.expr.type === 'constraint'\n  }\n\n  isRecursive(): boolean {\n    return this.expr.type === 'recursive'\n  }\n\n  isExistenceConstraint(): boolean {\n    return this.expr.type === 'constraint' && this.expr.operator === '?'\n  }\n\n  isIndex(): boolean {\n    return this.expr.type === 'index'\n  }\n\n  isRange(): boolean {\n    return this.expr.type === 'range'\n  }\n\n  expandRange(probe?: Probe): Range {\n    const probeLength = () => {\n      if (!probe) {\n        throw new Error('expandRange() required a probe that was not passed')\n      }\n\n      return probe.length()\n    }\n\n    let start = 'start' in this.expr ? this.expr.start || 0 : 0\n    start = interpretNegativeIndex(start, probe)\n    let end = 'end' in this.expr ? this.expr.end || probeLength() : probeLength()\n    end = interpretNegativeIndex(end, probe)\n    const step = 'step' in this.expr ? this.expr.step || 1 : 1\n    return {start, end, step}\n  }\n\n  isAttributeReference(): boolean {\n    return this.expr.type === 'attribute'\n  }\n\n  // Is a range or index -> something referencing indexes\n  isIndexReference(): boolean {\n    return this.isIndex() || this.isRange()\n  }\n\n  name(): string {\n    return 'name' in this.expr ? this.expr.name : ''\n  }\n\n  isSelfReference(): boolean {\n    return this.expr.type === 'alias' && this.expr.target === 'self'\n  }\n\n  constraintTargetIsSelf(): boolean {\n    return (\n      this.expr.type === 'constraint' &&\n      this.expr.lhs.type === 'alias' &&\n      this.expr.lhs.target === 'self'\n    )\n  }\n\n  constraintTargetIsAttribute(): boolean {\n    return this.expr.type === 'constraint' && this.expr.lhs.type === 'attribute'\n  }\n\n  testConstraint(probe: Probe): boolean {\n    const expr = this.expr\n\n    if (expr.type === 'constraint' && expr.lhs.type === 'alias' && expr.lhs.target === 'self') {\n      if (probe.containerType() !== 'primitive') {\n        return false\n      }\n\n      if (expr.type === 'constraint' && expr.operator === '?') {\n        return true\n      }\n\n      const lhs = probe.get()\n      const rhs = expr.rhs && 'value' in expr.rhs ? expr.rhs.value : undefined\n      return testBinaryOperator(lhs, expr.operator, rhs)\n    }\n\n    if (expr.type !== 'constraint') {\n      return false\n    }\n\n    const lhs = expr.lhs\n    if (!lhs) {\n      throw new Error('No LHS of expression')\n    }\n\n    if (lhs.type !== 'attribute') {\n      throw new Error(`Constraint target ${lhs.type} not supported`)\n    }\n\n    if (probe.containerType() !== 'object') {\n      return false\n    }\n\n    const lhsValue = probe.getAttribute(lhs.name)\n    if (lhsValue === undefined || lhsValue === null || lhsValue.containerType() !== 'primitive') {\n      // LHS is void and empty, or it is a collection\n      return false\n    }\n\n    if (this.isExistenceConstraint()) {\n      // There is no rhs, and if we're here the key did exist\n      return true\n    }\n\n    const rhs = expr.rhs && 'value' in expr.rhs ? expr.rhs.value : undefined\n    return testBinaryOperator(lhsValue.get(), expr.operator, rhs)\n  }\n\n  pathNodes(): Expr[] {\n    return this.expr.type === 'path' ? this.expr.nodes : [this.expr]\n  }\n\n  prepend(node: Expression): Expression {\n    if (!node) {\n      return this\n    }\n\n    return new Expression({\n      type: 'path',\n      nodes: node.pathNodes().concat(this.pathNodes()),\n    })\n  }\n\n  concat(other: Expression | null): Expression {\n    return other ? other.prepend(this) : this\n  }\n\n  descend(): HeadTail[] {\n    return descend(this.expr).map((headTail) => {\n      const [head, tail] = headTail\n      return {\n        head: head ? new Expression(head) : null,\n        tail: tail ? new Expression(tail) : null,\n      }\n    })\n  }\n\n  unwrapRecursive(): Expression {\n    if (this.expr.type !== 'recursive') {\n      throw new Error(`Attempt to unwrap recursive on type ${this.expr.type}`)\n    }\n\n    return new Expression(this.expr.term)\n  }\n\n  toIndicies(probe?: Probe): number[] {\n    if (this.expr.type !== 'index' && this.expr.type !== 'range') {\n      throw new Error('Node cannot be converted to indexes')\n    }\n\n    if (this.expr.type === 'index') {\n      return [interpretNegativeIndex(this.expr.value, probe)]\n    }\n\n    const result: number[] = []\n    const range = this.expandRange(probe)\n    let {start, end} = range\n    if (range.step < 0) {\n      ;[start, end] = [end, start]\n    }\n\n    for (let i = start; i < end; i++) {\n      result.push(i)\n    }\n\n    return result\n  }\n\n  toFieldReferences(): number[] | string[] {\n    if (this.isIndexReference()) {\n      return this.toIndicies()\n    }\n    if (this.expr.type === 'attribute') {\n      return [this.expr.name]\n    }\n    throw new Error(`Can't convert ${this.expr.type} to field references`)\n  }\n\n  toString(): string {\n    return toPath(this.expr)\n  }\n\n  static fromPath(path: string): Expression {\n    const parsed = parseJsonPath(path)\n    if (!parsed) {\n      throw new Error(`Failed to parse path \"${path}\"`)\n    }\n\n    return new Expression(parsed)\n  }\n\n  static attributeReference(name: string): Expression {\n    return new Expression({\n      type: 'attribute',\n      name: name,\n    })\n  }\n\n  static indexReference(i: number): Expression {\n    return new Expression({\n      type: 'index',\n      value: i,\n    })\n  }\n}\n\n// Tests an operator on two given primitive values\nfunction testBinaryOperator(lhsValue: any, operator: string, rhsValue: any) {\n  switch (operator) {\n    case '>':\n      return lhsValue > rhsValue\n    case '>=':\n      return lhsValue >= rhsValue\n    case '<':\n      return lhsValue < rhsValue\n    case '<=':\n      return lhsValue <= rhsValue\n    case '==':\n      return lhsValue === rhsValue\n    case '!=':\n      return lhsValue !== rhsValue\n    default:\n      throw new Error(`Unsupported binary operator ${operator}`)\n  }\n}\n\nfunction interpretNegativeIndex(index: number, probe?: Probe): number {\n  if (index >= 0) {\n    return index\n  }\n\n  if (!probe) {\n    throw new Error('interpretNegativeIndex() must have a probe when < 0')\n  }\n\n  return index + probe.length()\n}\n","import {flatten} from 'lodash'\n\nimport {Expression} from './Expression'\nimport {type Probe} from './Probe'\n\n/**\n * Descender models the state of one partial jsonpath evaluation. Head is the\n * next thing to match, tail is the upcoming things once the head is matched.\n */\nexport class Descender {\n  head: Expression | null\n  tail: Expression | null\n\n  constructor(head: Expression | null, tail: Expression | null) {\n    this.head = head\n    this.tail = tail\n  }\n\n  // Iterate this descender once processing any constraints that are\n  // resolvable on the current value. Returns an array of new descenders\n  // that are guaranteed to be without constraints in the head\n  iterate(probe: Probe): Descender[] {\n    let result: Descender[] = [this]\n    if (this.head && this.head.isConstraint()) {\n      let anyConstraints = true\n      // Keep rewriting constraints until there are none left\n      while (anyConstraints) {\n        result = flatten(\n          result.map((descender) => {\n            return descender.iterateConstraints(probe)\n          }),\n        )\n        anyConstraints = result.some((descender) => {\n          return descender.head && descender.head.isConstraint()\n        })\n      }\n    }\n    return result\n  }\n\n  isRecursive(): boolean {\n    return Boolean(this.head && this.head.isRecursive())\n  }\n\n  hasArrived(): boolean {\n    return this.head === null && this.tail === null\n  }\n\n  extractRecursives(): Descender[] {\n    if (this.head && this.head.isRecursive()) {\n      const term = this.head.unwrapRecursive()\n      return new Descender(null, term.concat(this.tail)).descend()\n    }\n    return []\n  }\n\n  iterateConstraints(probe: Probe): Descender[] {\n    const head = this.head\n    if (head === null || !head.isConstraint()) {\n      // Not a constraint, no rewrite\n      return [this]\n    }\n\n    const result: Descender[] = []\n\n    if (probe.containerType() === 'primitive' && head.constraintTargetIsSelf()) {\n      if (head.testConstraint(probe)) {\n        result.push(...this.descend())\n      }\n      return result\n    }\n\n    // The value is an array\n    if (probe.containerType() === 'array') {\n      const length = probe.length()\n      for (let i = 0; i < length; i++) {\n        // Push new descenders with constraint translated to literal indices\n        // where they match\n        const constraint = probe.getIndex(i)\n        if (constraint && head.testConstraint(constraint)) {\n          result.push(new Descender(new Expression({type: 'index', value: i}), this.tail))\n        }\n      }\n      return result\n    }\n\n    // The value is an object\n    if (probe.containerType() === 'object') {\n      if (head.constraintTargetIsSelf()) {\n        // There are no matches for target self ('@') on a plain object\n        return []\n      }\n\n      if (head.testConstraint(probe)) {\n        return this.descend()\n      }\n\n      return result\n    }\n\n    return result\n  }\n\n  descend(): Descender[] {\n    if (!this.tail) {\n      return [new Descender(null, null)]\n    }\n\n    return this.tail.descend().map((ht) => {\n      return new Descender(ht.head, ht.tail)\n    })\n  }\n\n  toString(): string {\n    const result = ['<']\n    if (this.head) {\n      result.push(this.head.toString())\n    }\n    result.push('|')\n    if (this.tail) {\n      result.push(this.tail.toString())\n    }\n    result.push('>')\n    return result.join('')\n  }\n}\n","import {Descender} from './Descender'\nimport {Expression} from './Expression'\nimport {parseJsonPath} from './parse'\nimport {type Probe} from './Probe'\n\ninterface Result<P = unknown> {\n  leads: {\n    target: Expression\n    matcher: Matcher\n  }[]\n\n  delivery?: {\n    targets: Expression[]\n    payload: P\n  }\n}\n\n/**\n * @internal\n */\nexport class Matcher {\n  active: Descender[]\n  recursives: Descender[]\n  payload: unknown\n\n  constructor(active: Descender[], parent?: Matcher) {\n    this.active = active || []\n    if (parent) {\n      this.recursives = parent.recursives\n      this.payload = parent.payload\n    } else {\n      this.recursives = []\n    }\n    this.extractRecursives()\n  }\n\n  setPayload(payload: unknown): this {\n    this.payload = payload\n    return this\n  }\n\n  // Moves any recursive descenders onto the recursive track, removing them from\n  // the active set\n  extractRecursives(): void {\n    this.active = this.active.filter((descender) => {\n      if (descender.isRecursive()) {\n        this.recursives.push(...descender.extractRecursives())\n        return false\n      }\n      return true\n    })\n  }\n\n  // Find recursives that are relevant now and should be considered part of the active set\n  activeRecursives(probe: Probe): Descender[] {\n    return this.recursives.filter((descender) => {\n      const head = descender.head\n      if (!head) {\n        return false\n      }\n\n      // Constraints are always relevant\n      if (head.isConstraint()) {\n        return true\n      }\n\n      // Index references are only relevant for indexable values\n      if (probe.containerType() === 'array' && head.isIndexReference()) {\n        return true\n      }\n\n      // Attribute references are relevant for plain objects\n      if (probe.containerType() === 'object') {\n        return head.isAttributeReference() && probe.hasAttribute(head.name())\n      }\n\n      return false\n    })\n  }\n\n  match(probe: Probe): Result {\n    return this.iterate(probe).extractMatches(probe)\n  }\n\n  iterate(probe: Probe): Matcher {\n    const newActiveSet: Descender[] = []\n    this.active.concat(this.activeRecursives(probe)).forEach((descender) => {\n      newActiveSet.push(...descender.iterate(probe))\n    })\n    return new Matcher(newActiveSet, this)\n  }\n\n  // Returns true if any of the descenders in the active or recursive set\n  // consider the current state a final destination\n  isDestination(): boolean {\n    return this.active.some((descender) => descender.hasArrived())\n  }\n\n  hasRecursives(): boolean {\n    return this.recursives.length > 0\n  }\n\n  // Returns any payload delivieries and leads that needs to be followed to complete\n  // the process.\n  extractMatches(probe: Probe): Result {\n    const leads: {target: Expression; matcher: Matcher}[] = []\n    const targets: Expression[] = []\n    this.active.forEach((descender) => {\n      if (descender.hasArrived()) {\n        // This was already arrived, so matches this value, not descenders\n        targets.push(\n          new Expression({\n            type: 'alias',\n            target: 'self',\n          }),\n        )\n        return\n      }\n\n      const descenderHead = descender.head\n      if (!descenderHead) {\n        return\n      }\n\n      if (probe.containerType() === 'array' && !descenderHead.isIndexReference()) {\n        // This descender does not match an indexable value\n        return\n      }\n\n      if (probe.containerType() === 'object' && !descenderHead.isAttributeReference()) {\n        // This descender never match a plain object\n        return\n      }\n\n      if (descender.tail) {\n        // Not arrived yet\n        const matcher = new Matcher(descender.descend(), this)\n        descenderHead.toFieldReferences().forEach(() => {\n          leads.push({\n            target: descenderHead,\n            matcher: matcher,\n          })\n        })\n      } else {\n        // arrived\n        targets.push(descenderHead)\n      }\n    })\n\n    // If there are recursive terms, we need to add a lead for every descendant ...\n    if (this.hasRecursives()) {\n      // The recustives matcher will have no active set, only inherit recursives from this\n      const recursivesMatcher = new Matcher([], this)\n      if (probe.containerType() === 'array') {\n        const length = probe.length()\n        for (let i = 0; i < length; i++) {\n          leads.push({\n            target: Expression.indexReference(i),\n            matcher: recursivesMatcher,\n          })\n        }\n      } else if (probe.containerType() === 'object') {\n        probe.attributeKeys().forEach((name) => {\n          leads.push({\n            target: Expression.attributeReference(name),\n            matcher: recursivesMatcher,\n          })\n        })\n      }\n    }\n\n    return targets.length > 0\n      ? {leads: leads, delivery: {targets, payload: this.payload}}\n      : {leads: leads}\n  }\n\n  static fromPath(jsonpath: string): Matcher {\n    const path = parseJsonPath(jsonpath)\n    if (!path) {\n      throw new Error(`Failed to parse path from \"${jsonpath}\"`)\n    }\n\n    const descender = new Descender(null, new Expression(path))\n    return new Matcher(descender.descend())\n  }\n}\n","import {isRecord} from '../util'\nimport {type Probe} from './Probe'\n\n// A default implementation of a probe for vanilla JS _values\nexport class PlainProbe implements Probe {\n  _value: unknown\n  path: (string | number)[]\n\n  constructor(value: unknown, path?: (string | number)[]) {\n    this._value = value\n    this.path = path || []\n  }\n\n  containerType(): 'array' | 'object' | 'primitive' {\n    if (Array.isArray(this._value)) {\n      return 'array'\n    } else if (this._value !== null && typeof this._value === 'object') {\n      return 'object'\n    }\n    return 'primitive'\n  }\n\n  length(): number {\n    if (!Array.isArray(this._value)) {\n      throw new Error(\"Won't return length of non-indexable _value\")\n    }\n\n    return this._value.length\n  }\n\n  getIndex(i: number): false | null | PlainProbe {\n    if (!Array.isArray(this._value)) {\n      return false\n    }\n\n    if (i >= this.length()) {\n      return null\n    }\n\n    return new PlainProbe(this._value[i], this.path.concat(i))\n  }\n\n  hasAttribute(key: string): boolean {\n    if (!isRecord(this._value)) {\n      return false\n    }\n\n    return this._value.hasOwnProperty(key)\n  }\n\n  attributeKeys(): string[] {\n    return isRecord(this._value) ? Object.keys(this._value) : []\n  }\n\n  getAttribute(key: string): null | PlainProbe {\n    if (!isRecord(this._value)) {\n      throw new Error('getAttribute only applies to plain objects')\n    }\n\n    if (!this.hasAttribute(key)) {\n      return null\n    }\n\n    return new PlainProbe(this._value[key], this.path.concat(key))\n  }\n\n  get(): unknown {\n    return this._value\n  }\n}\n","import {compact} from 'lodash'\n\nimport {type Expression} from './Expression'\nimport {Matcher} from './Matcher'\nimport {PlainProbe} from './PlainProbe'\nimport {type Probe} from './Probe'\n\nexport function extractAccessors(path: string, value: unknown): Probe[] {\n  const result: Probe[] = []\n  const matcher = Matcher.fromPath(path).setPayload(function appendResult(values: Probe[]) {\n    result.push(...values)\n  })\n  const accessor = new PlainProbe(value)\n  descend(matcher, accessor)\n  return result\n}\n\nfunction descend(matcher: Matcher, accessor: Probe) {\n  const {leads, delivery} = matcher.match(accessor)\n\n  leads.forEach((lead) => {\n    accessorsFromTarget(lead.target, accessor).forEach((childAccessor) => {\n      descend(lead.matcher, childAccessor)\n    })\n  })\n\n  if (delivery) {\n    delivery.targets.forEach((target) => {\n      if (typeof delivery.payload === 'function') {\n        delivery.payload(accessorsFromTarget(target, accessor))\n      }\n    })\n  }\n}\n\nfunction accessorsFromTarget(target: Expression, accessor: Probe) {\n  const result = []\n  if (target.isIndexReference()) {\n    target.toIndicies(accessor).forEach((i) => {\n      result.push(accessor.getIndex(i))\n    })\n  } else if (target.isAttributeReference()) {\n    result.push(accessor.getAttribute(target.name()))\n  } else if (target.isSelfReference()) {\n    result.push(accessor)\n  } else {\n    throw new Error(`Unable to derive accessor for target ${target.toString()}`)\n  }\n  return compact(result)\n}\n","import {extractAccessors} from './extractAccessors'\n\n/**\n * Extracts values matching the given JsonPath\n *\n * @param path - Path to extract\n * @param value - Value to extract from\n * @returns An array of values matching the given path\n * @public\n */\nexport function extract(path: string, value: unknown): unknown[] {\n  const accessors = extractAccessors(path, value)\n  return accessors.map((acc) => acc.get())\n}\n","import {extractAccessors} from './extractAccessors'\n\n/**\n * Extracts a value for the given JsonPath, and includes the specific path of where it was found\n *\n * @param path - Path to extract\n * @param value - Value to extract from\n * @returns An array of objects with `path` and `value` keys\n * @internal\n */\nexport function extractWithPath(\n  path: string,\n  value: unknown,\n): {path: (string | number)[]; value: unknown}[] {\n  const accessors = extractAccessors(path, value)\n  return accessors.map((acc) => ({path: acc.path, value: acc.get()}))\n}\n","import {applyPatches, parsePatch, type Patch} from '@sanity/diff-match-patch'\n\nimport {type Expression} from '../jsonpath'\nimport {type ImmutableAccessor} from './ImmutableAccessor'\n\nfunction applyPatch(patch: Patch[], oldValue: unknown) {\n  // Silently avoid patching if the value type is not string\n  if (typeof oldValue !== 'string') return oldValue\n  const [result] = applyPatches(patch, oldValue, {allowExceedingIndices: true})\n  return result\n}\n\nexport class DiffMatchPatch {\n  path: string\n  dmpPatch: Patch[]\n  id: string\n\n  constructor(id: string, path: string, dmpPatchSrc: string) {\n    this.id = id\n    this.path = path\n    this.dmpPatch = parsePatch(dmpPatchSrc)\n  }\n\n  apply(targets: Expression[], accessor: ImmutableAccessor): ImmutableAccessor {\n    let result = accessor\n\n    // The target must be a container type\n    if (result.containerType() === 'primitive') {\n      return result\n    }\n\n    for (const target of targets) {\n      if (target.isIndexReference()) {\n        for (const index of target.toIndicies(accessor)) {\n          // Skip patching unless the index actually currently exists\n          const item = result.getIndex(index)\n          if (!item) {\n            continue\n          }\n\n          const oldValue = item.get()\n          const nextValue = applyPatch(this.dmpPatch, oldValue)\n          result = result.setIndex(index, nextValue)\n        }\n\n        continue\n      }\n\n      if (target.isAttributeReference() && result.hasAttribute(target.name())) {\n        const attribute = result.getAttribute(target.name())\n        if (!attribute) {\n          continue\n        }\n\n        const oldValue = attribute.get()\n        const nextValue = applyPatch(this.dmpPatch, oldValue)\n        result = result.setAttribute(target.name(), nextValue)\n        continue\n      }\n\n      throw new Error(`Unable to apply diffMatchPatch to target ${target.toString()}`)\n    }\n\n    return result\n  }\n}\n","import {type Expression} from '../jsonpath'\nimport {type ImmutableAccessor} from './ImmutableAccessor'\n\nfunction performIncrement(previousValue: unknown, delta: number): number {\n  if (typeof previousValue !== 'number' || !Number.isFinite(previousValue)) {\n    return previousValue as number\n  }\n\n  return previousValue + delta\n}\n\nexport class IncPatch {\n  path: string\n  value: number\n  id: string\n\n  constructor(id: string, path: string, value: number) {\n    this.path = path\n    this.value = value\n    this.id = id\n  }\n\n  apply(targets: Expression[], accessor: ImmutableAccessor): ImmutableAccessor {\n    let result = accessor\n\n    // The target must be a container type\n    if (result.containerType() === 'primitive') {\n      return result\n    }\n\n    for (const target of targets) {\n      if (target.isIndexReference()) {\n        for (const index of target.toIndicies(accessor)) {\n          // Skip patching unless the index actually currently exists\n          const item = result.getIndex(index)\n          if (!item) {\n            continue\n          }\n\n          const previousValue = item.get()\n          result = result.setIndex(index, performIncrement(previousValue, this.value))\n        }\n\n        continue\n      }\n\n      if (target.isAttributeReference()) {\n        const attribute = result.getAttribute(target.name())\n        if (!attribute) {\n          continue\n        }\n\n        const previousValue = attribute.get()\n        result = result.setAttribute(target.name(), performIncrement(previousValue, this.value))\n        continue\n      }\n\n      throw new Error(`Unable to apply to target ${target.toString()}`)\n    }\n\n    return result\n  }\n}\n","import {type Expression} from '../jsonpath'\nimport {type ImmutableAccessor} from './ImmutableAccessor'\n\nexport function targetsToIndicies(targets: Expression[], accessor: ImmutableAccessor): number[] {\n  const result: number[] = []\n  targets.forEach((target) => {\n    if (target.isIndexReference()) {\n      result.push(...target.toIndicies(accessor))\n    }\n  })\n  return result.sort()\n}\n","import {max, min} from 'lodash'\n\nimport {type Expression} from '../jsonpath'\nimport {type ImmutableAccessor} from './ImmutableAccessor'\nimport {targetsToIndicies} from './util'\n\nexport class InsertPatch {\n  location: string\n  path: string\n  items: unknown[]\n  id: string\n\n  constructor(id: string, location: string, path: string, items: unknown[]) {\n    this.id = id\n    this.location = location\n    this.path = path\n    this.items = items\n  }\n\n  apply(targets: Expression[], accessor: ImmutableAccessor): ImmutableAccessor {\n    let result = accessor\n    if (accessor.containerType() !== 'array') {\n      throw new Error('Attempt to apply insert patch to non-array value')\n    }\n\n    switch (this.location) {\n      case 'before': {\n        const pos = minIndex(targets, accessor)\n        result = result.insertItemsAt(pos, this.items)\n        break\n      }\n      case 'after': {\n        const pos = maxIndex(targets, accessor)\n        result = result.insertItemsAt(pos + 1, this.items)\n        break\n      }\n      case 'replace': {\n        // TODO: Properly implement ranges in compliance with content lake\n        // This will only properly support single contiguous ranges\n        const indicies = targetsToIndicies(targets, accessor)\n        result = result.unsetIndices(indicies)\n        result = result.insertItemsAt(indicies[0], this.items)\n        break\n      }\n      default: {\n        throw new Error(`Unsupported location atm: ${this.location}`)\n      }\n    }\n    return result\n  }\n}\n\nfunction minIndex(targets: Expression[], accessor: ImmutableAccessor): number {\n  let result = min(targetsToIndicies(targets, accessor)) || 0\n\n  // Ranges may be zero-length and not turn up in indices\n  targets.forEach((target) => {\n    if (target.isRange()) {\n      const {start} = target.expandRange()\n      if (start < result) {\n        result = start\n      }\n    }\n  })\n  return result\n}\n\nfunction maxIndex(targets: Expression[], accessor: ImmutableAccessor): number {\n  let result = max(targetsToIndicies(targets, accessor)) || 0\n\n  // Ranges may be zero-length and not turn up in indices\n  targets.forEach((target) => {\n    if (target.isRange()) {\n      const {end} = target.expandRange()\n      if (end > result) {\n        result = end\n      }\n    }\n  })\n  return result\n}\n","import {type Expression} from '../jsonpath'\nimport {type ImmutableAccessor} from './ImmutableAccessor'\n\nexport class SetIfMissingPatch {\n  id: string\n  path: string\n  value: unknown\n\n  constructor(id: string, path: string, value: unknown) {\n    this.id = id\n    this.path = path\n    this.value = value\n  }\n\n  apply(targets: Expression[], accessor: ImmutableAccessor): ImmutableAccessor {\n    let result = accessor\n    targets.forEach((target) => {\n      if (target.isIndexReference()) {\n        // setIfMissing do not apply to arrays, since Content Lake will reject nulls in arrays\n      } else if (target.isAttributeReference()) {\n        // setting a subproperty on a primitive value overwrites it, eg\n        // `{setIfMissing: {'address.street': 'California St'}}` on `{address: 'Fiction St'}` will\n        // result in `{address: {street: 'California St'}}`\n        if (result.containerType() === 'primitive') {\n          result = result.set({[target.name()]: this.value})\n        } else if (!result.hasAttribute(target.name())) {\n          result = accessor.setAttribute(target.name(), this.value)\n        }\n      } else {\n        throw new Error(`Unable to apply to target ${target.toString()}`)\n      }\n    })\n    return result\n  }\n}\n","import {type Expression} from '../jsonpath'\nimport {type ImmutableAccessor} from './ImmutableAccessor'\n\nexport class SetPatch {\n  id: string\n  path: string\n  value: unknown\n\n  constructor(id: string, path: string, value: unknown) {\n    this.id = id\n    this.path = path\n    this.value = value\n  }\n\n  apply(targets: Expression[], accessor: ImmutableAccessor): ImmutableAccessor {\n    let result = accessor\n    targets.forEach((target) => {\n      if (target.isSelfReference()) {\n        result = result.set(this.value)\n      } else if (target.isIndexReference()) {\n        target.toIndicies(accessor).forEach((i) => {\n          result = result.setIndex(i, this.value)\n        })\n      } else if (target.isAttributeReference()) {\n        // setting a subproperty on a primitive value overwrites it, eg\n        // `{set: {'address.street': 'California St'}}` on `{address: 'Fiction St'}` will result in\n        // `{address: {street: 'California St'}}`\n        if (result.containerType() === 'primitive') {\n          result = result.set({[target.name()]: this.value})\n        } else {\n          result = result.setAttribute(target.name(), this.value)\n        }\n      } else {\n        throw new Error(`Unable to apply to target ${target.toString()}`)\n      }\n    })\n    return result\n  }\n}\n","import {type Expression} from '../jsonpath'\nimport {type ImmutableAccessor} from './ImmutableAccessor'\nimport {targetsToIndicies} from './util'\n\nexport class UnsetPatch {\n  id: string\n  path: string\n  value: unknown\n\n  constructor(id: string, path: string) {\n    this.id = id\n    this.path = path\n  }\n\n  // eslint-disable-next-line class-methods-use-this\n  apply(targets: Expression[], accessor: ImmutableAccessor): ImmutableAccessor {\n    let result = accessor\n    switch (accessor.containerType()) {\n      case 'array':\n        result = result.unsetIndices(targetsToIndicies(targets, accessor))\n        break\n      case 'object':\n        targets.forEach((target) => {\n          result = result.unsetAttribute(target.name())\n        })\n        break\n      default:\n        throw new Error(\n          'Target value is neither indexable or an object. This error should potentially just be silently ignored?',\n        )\n    }\n    return result\n  }\n}\n","import {DiffMatchPatch} from './DiffMatchPatch'\nimport {IncPatch} from './IncPatch'\nimport {InsertPatch} from './InsertPatch'\nimport {SetIfMissingPatch} from './SetIfMissingPatch'\nimport {SetPatch} from './SetPatch'\nimport {type PatchTypes, type SingleDocumentPatch} from './types'\nimport {UnsetPatch} from './UnsetPatch'\n\n// Parses a content lake patch into our own personal patch implementations\nexport function parsePatch(patch: SingleDocumentPatch | SingleDocumentPatch[]): PatchTypes[] {\n  const result: PatchTypes[] = []\n  if (Array.isArray(patch)) {\n    return patch.reduce((r, p) => r.concat(parsePatch(p)), result)\n  }\n\n  const {set, setIfMissing, unset, diffMatchPatch, inc, dec, insert} = patch\n  if (setIfMissing) {\n    Object.keys(setIfMissing).forEach((path) => {\n      result.push(new SetIfMissingPatch(patch.id, path, setIfMissing[path]))\n    })\n  }\n\n  if (set) {\n    Object.keys(set).forEach((path) => {\n      result.push(new SetPatch(patch.id, path, set[path]))\n    })\n  }\n\n  if (unset) {\n    unset.forEach((path) => {\n      result.push(new UnsetPatch(patch.id, path))\n    })\n  }\n\n  if (diffMatchPatch) {\n    Object.keys(diffMatchPatch).forEach((path) => {\n      result.push(new DiffMatchPatch(patch.id, path, diffMatchPatch[path]))\n    })\n  }\n\n  if (inc) {\n    Object.keys(inc).forEach((path) => {\n      result.push(new IncPatch(patch.id, path, inc[path]))\n    })\n  }\n\n  if (dec) {\n    Object.keys(dec).forEach((path) => {\n      result.push(new IncPatch(patch.id, path, -dec[path]))\n    })\n  }\n\n  if (insert) {\n    let location: string\n    let path: string\n    const spec = insert\n    if ('before' in spec) {\n      location = 'before'\n      path = spec.before\n    } else if ('after' in spec) {\n      location = 'after'\n      path = spec.after\n    } else if ('replace' in spec) {\n      location = 'replace'\n      path = spec.replace\n    } else {\n      throw new Error('Invalid insert patch')\n    }\n\n    result.push(new InsertPatch(patch.id, location, path, spec.items))\n  }\n\n  return result\n}\n","import {type Doc} from '../document/types'\nimport {Matcher} from '../jsonpath'\nimport {ImmutableAccessor} from './ImmutableAccessor'\nimport {parsePatch} from './parse'\nimport {SetIfMissingPatch} from './SetIfMissingPatch'\nimport {SetPatch} from './SetPatch'\nimport {type PatchTypes, type SingleDocumentPatch} from './types'\n\nexport interface Patch {\n  id: string\n  path: string\n}\n\nexport class Patcher {\n  patches: PatchTypes[]\n\n  constructor(patch: SingleDocumentPatch | SingleDocumentPatch[]) {\n    this.patches = parsePatch(patch)\n  }\n\n  apply(value: Doc | null): unknown {\n    // Apply just makes a root accessor around the provided\n    // value, then applies the patches. Due to the use of\n    // ImmutableAccessor it is guaranteed to return either the\n    // exact same object it was provided (in the case of no changes),\n    // or a completely new object. It will never mutate the object in place.\n    const accessor = new ImmutableAccessor(value)\n    return this.applyViaAccessor(accessor).get()\n  }\n\n  // If you want to use your own accessor implementation, you can use this method\n  // to invoke the patcher. Since all subsequent accessors for children of this accessor\n  // are obtained through the methods in the accessors, you retain full control of the\n  // implementation throguhgout the application. Have a look in ImmutableAccessor\n  // to see an example of how accessors are implemented.\n  applyViaAccessor(accessor: ImmutableAccessor): ImmutableAccessor {\n    let result = accessor\n    const idAccessor = accessor.getAttribute('_id')\n    if (!idAccessor) {\n      throw new Error('Cannot apply patch to document with no _id')\n    }\n\n    const id = idAccessor.get()\n    for (const patch of this.patches) {\n      if (patch.id !== id) {\n        // Ignore patches that are not targetted at this document\n        continue\n      }\n\n      const matcher = Matcher.fromPath(patch.path).setPayload(patch)\n      result = process(matcher, result)\n    }\n\n    return result\n  }\n}\n\n// Recursively (depth first) follows any leads generated by the matcher, expecting\n// a patch to be the payload. When matchers report a delivery, the\n// apply(targets, accessor) is called on the patch\nfunction process(matcher: Matcher, accessor: ImmutableAccessor) {\n  const isSetPatch =\n    matcher.payload instanceof SetPatch || matcher.payload instanceof SetIfMissingPatch\n\n  let result = accessor\n  // Every time we execute the matcher a new set of leads is generated. Each lead\n  // is a target (being an index, an attribute name or a range) in the form of an\n  // Expression instance. For each lead target there is also a matcher. Our job is to obtain\n  // accessor(s) for each target (there might be more than one, since the targets may\n  // be ranges) and run the provided matcher on those accessors.\n  const {leads, delivery} = matcher.match(accessor)\n  leads.forEach((lead) => {\n    if (lead.target.isIndexReference()) {\n      lead.target.toIndicies().forEach((i) => {\n        const item = result.getIndex(i)\n        if (!item) {\n          throw new Error('Index out of bounds')\n        }\n\n        result = result.setIndexAccessor(i, process(lead.matcher, item))\n      })\n    } else if (lead.target.isAttributeReference()) {\n      // `set`/`setIfMissing` on a primitive value overwrites it\n      if (isSetPatch && result.containerType() === 'primitive') {\n        result = result.set({})\n      }\n\n      let oldValueAccessor = result.getAttribute(lead.target.name())\n\n      // If the patch is a set/setIfMissing patch, we allow deeply setting properties,\n      // creating missing segments as we go.\n      if (!oldValueAccessor && isSetPatch) {\n        result = result.setAttribute(lead.target.name(), {})\n        oldValueAccessor = result.getAttribute(lead.target.name())\n      }\n\n      if (!oldValueAccessor) {\n        // Don't follow lead, no such attribute\n        return\n      }\n\n      const newValueAccessor = process(lead.matcher, oldValueAccessor)\n      if (oldValueAccessor !== newValueAccessor) {\n        result = result.setAttributeAccessor(lead.target.name(), newValueAccessor)\n      }\n    } else {\n      throw new Error(`Unable to handle target ${lead.target.toString()}`)\n    }\n  })\n\n  // Each time we run the matcher, we might also get a delivery. This means that a\n  // term in the jsonpath terminated here and the patch should be applied. The delivery\n  // arrives in the form of an array of targets and a payload (which in this application\n  // is the patch). Conveniently the patches accept an array of targets and an accessor\n  // to do its work, so here we just pass those to the patch and we're done.\n  if (delivery && isPatcher(delivery.payload)) {\n    const patch = delivery.payload\n    result = patch.apply(delivery.targets, result)\n  }\n\n  return result\n}\n\nfunction isPatcher(payload: unknown): payload is PatchTypes {\n  return Boolean(\n    payload &&\n      typeof payload === 'object' &&\n      payload !== null &&\n      'apply' in payload &&\n      typeof (payload as PatchTypes).apply === 'function',\n  )\n}\n","import {uuid} from '@sanity/uuid'\n\n/**\n * Locally unique id's. We use this to generate transaction ids, and they don't have to be\n * cryptographically unique, as the worst that can happen is that they get rejected because\n * of a collision, and then we should just retry with a new id.\n */\nexport const luid: typeof uuid = uuid\n","import {Patcher} from '../patch'\nimport {debug} from './debug'\nimport {luid} from './luid'\nimport {type Doc, type Mut} from './types'\n\n/**\n * Parameters attached to the mutation\n *\n * @internal\n */\nexport interface MutationParams {\n  transactionId?: string\n  transition?: string\n  identity?: string\n  previousRev?: string\n  resultRev?: string\n  mutations: Mut[]\n  timestamp?: string\n  effects?: {apply: unknown; revert: unknown}\n}\n\n/**\n * A mutation describing a number of operations on a single document.\n * This should be considered an immutable structure. Mutations are compiled\n * on first application, and any changes in properties will not effectively\n * change its behavior after that.\n *\n * @internal\n */\nexport class Mutation {\n  params: MutationParams\n\n  compiled?: (doc: Doc | null) => Doc | null\n\n  _appliesToMissingDocument: boolean | undefined\n\n  constructor(options: MutationParams) {\n    this.params = options\n  }\n\n  get transactionId(): string | undefined {\n    return this.params.transactionId\n  }\n\n  get transition(): string | undefined {\n    return this.params.transition\n  }\n\n  get identity(): string | undefined {\n    return this.params.identity\n  }\n\n  get previousRev(): string | undefined {\n    return this.params.previousRev\n  }\n\n  get resultRev(): string | undefined {\n    return this.params.resultRev\n  }\n\n  get mutations(): Mut[] {\n    return this.params.mutations\n  }\n\n  get timestamp(): Date | undefined {\n    if (typeof this.params.timestamp === 'string') {\n      return new Date(this.params.timestamp)\n    }\n\n    return undefined\n  }\n\n  get effects():\n    | {\n        apply: unknown\n        revert: unknown\n      }\n    | undefined {\n    return this.params.effects\n  }\n\n  assignRandomTransactionId(): void {\n    this.params.transactionId = luid()\n    this.params.resultRev = this.params.transactionId\n  }\n\n  appliesToMissingDocument(): boolean {\n    if (typeof this._appliesToMissingDocument !== 'undefined') {\n      return this._appliesToMissingDocument\n    }\n\n    // Only mutations starting with a create operation apply to documents that do not exist ...\n    const firstMut = this.mutations[0]\n    if (firstMut) {\n      this._appliesToMissingDocument = Boolean(\n        firstMut.create || firstMut.createIfNotExists || firstMut.createOrReplace,\n      )\n    } else {\n      this._appliesToMissingDocument = true\n    }\n\n    return this._appliesToMissingDocument\n  }\n\n  // Compiles all mutations into a handy function\n  compile(): void {\n    const operations: ((doc: Doc | null) => Doc | null)[] = []\n\n    // creation requires a _createdAt\n    const getGuaranteedCreatedAt = (doc: Doc): string =>\n      doc?._createdAt || this.params.timestamp || new Date().toISOString()\n\n    this.mutations.forEach((mutation) => {\n      if (mutation.create) {\n        // TODO: Fail entire patch if document did exist\n        const create = (mutation.create || {}) as Doc\n        operations.push((doc): Doc => {\n          if (doc) {\n            return doc\n          }\n\n          return Object.assign(create, {\n            _createdAt: getGuaranteedCreatedAt(create),\n          })\n        })\n        return\n      }\n\n      if (mutation.createIfNotExists) {\n        const createIfNotExists = mutation.createIfNotExists || {}\n        operations.push((doc) =>\n          doc === null\n            ? Object.assign(createIfNotExists, {\n                _createdAt: getGuaranteedCreatedAt(createIfNotExists),\n              })\n            : doc,\n        )\n        return\n      }\n\n      if (mutation.createOrReplace) {\n        const createOrReplace = mutation.createOrReplace || {}\n        operations.push(() =>\n          Object.assign(createOrReplace, {\n            _createdAt: getGuaranteedCreatedAt(createOrReplace),\n          }),\n        )\n        return\n      }\n\n      if (mutation.delete) {\n        operations.push(() => null)\n        return\n      }\n\n      if (mutation.patch) {\n        if ('query' in mutation.patch) {\n          // @todo Warn/throw? Investigate if this can ever happen\n          return\n        }\n\n        const patch = new Patcher(mutation.patch)\n        operations.push((doc) => patch.apply(doc) as Doc | null)\n        return\n      }\n\n      throw new Error(`Unsupported mutation ${JSON.stringify(mutation, null, 2)}`)\n    })\n\n    // Assign `_updatedAt` to the timestamp of the mutation if set\n    if (typeof this.params.timestamp === 'string') {\n      operations.push((doc) => {\n        return doc ? Object.assign(doc, {_updatedAt: this.params.timestamp}) : null\n      })\n    }\n\n    const prevRev = this.previousRev\n    const rev = this.resultRev || this.transactionId\n    this.compiled = (doc: Doc | null) => {\n      if (prevRev && doc && prevRev !== doc._rev) {\n        throw new Error(\n          `Previous revision for this mutation was ${prevRev}, but the document revision is ${doc._rev}`,\n        )\n      }\n\n      let result: Doc | null = doc\n      for (const operation of operations) {\n        result = operation(result)\n      }\n\n      // Should update _rev?\n      if (result && rev) {\n        // Ensure that result is a unique object, even if the operation was a no-op\n        if (result === doc) {\n          result = Object.assign({}, doc)\n        }\n        result._rev = rev\n      }\n\n      return result\n    }\n  }\n\n  apply(document: Doc | null): Doc | null {\n    debug('Applying mutation %O to document %O', this.mutations, document)\n    if (!this.compiled) {\n      this.compile()\n    }\n\n    const result = this.compiled!(document)\n    debug('  => %O', result)\n    return result\n  }\n\n  static applyAll(document: Doc | null, mutations: Mutation[]): Doc | null {\n    return mutations.reduce((doc, mutation) => mutation.apply(doc), document)\n  }\n\n  // Given a number of yet-to-be-committed mutation objects, collects them into one big mutation\n  // any metadata like transactionId is ignored and must be submitted by the client. It is assumed\n  // that all mutations are on the same document.\n  // TOOO: Optimize mutations, eliminating mutations that overwrite themselves!\n  static squash(document: Doc | null, mutations: Mutation[]): Mutation {\n    const squashed = mutations.reduce(\n      (result, mutation) => result.concat(...mutation.mutations),\n      [] as Mut[],\n    )\n    return new Mutation({mutations: squashed})\n  }\n}\n","// TODO: When we have timestamps on mutation notifications, we can reject incoming mutations that are older\n// than the document we are seeing.\n\nimport {isEqual} from 'lodash'\n\nimport {debug} from './debug'\nimport {Mutation} from './Mutation'\nimport {type Doc} from './types'\n\n/**\n * @internal\n */\nexport interface SubmissionResponder {\n  success: () => void\n  failure: () => void\n}\n\n/**\n * Models a document as it is changed by our own local patches and remote patches coming in from\n * the server. Consolidates incoming patches with our own submitted patches and maintains two\n * versions of the document. EDGE is the optimistic document that the user sees that will always\n * immediately reflect whatever she is doing to it, and HEAD which is the confirmed version of the\n * document consistent with the mutations we have received from the server. As long as nothing out of\n * the ordinary happens, we can track all changes by hooking into the onMutation callback, but we\n * must also respect onRebase events that fire when we have to backtrack because one of our optimistically\n * applied patches were rejected, or some bastard was able to slip a mutation in between ours own.\n *\n * @internal\n */\nexport class Document {\n  /**\n   * Incoming patches from the server waiting to be applied to HEAD\n   */\n  incoming: Mutation[] = []\n\n  /**\n   * Patches we know has been subitted to the server, but has not been seen yet in the return channel\n   * so we can't be sure about the ordering yet (someone else might have slipped something between them)\n   */\n  submitted: Mutation[] = []\n\n  /**\n   * Pending mutations\n   */\n  pending: Mutation[] = []\n\n  /**\n   * Our model of the document according to the incoming patches from the server\n   */\n  HEAD: Doc | null\n\n  /**\n   * Our optimistic model of what the document will probably look like as soon as all our patches\n   * have been processed. Updated every time we stage a new mutation, but also might revert back\n   * to previous states if our mutations fail, or could change if unexpected mutations arrive\n   * between our own. The `onRebase` callback will be called when EDGE changes in this manner.\n   */\n  EDGE: Doc | null\n\n  /**\n   * Called with the EDGE document when that document changes for a reason other than us staging\n   * a new patch or receiving a mutation from the server while our EDGE is in sync with HEAD:\n   * I.e. when EDGE changes because the order of mutations has changed in relation to our\n   * optimistic predictions.\n   */\n  onRebase?: (edge: Doc | null, incomingMutations: Mutation[], pendingMutations: Mutation[]) => void\n\n  /**\n   * Called when we receive a patch in the normal order of things, but the mutation is not ours\n   */\n  onMutation?: (msg: {mutation: Mutation; document: Doc | null; remote: boolean}) => void\n\n  /**\n   * Called when consistency state changes with the boolean value of the current consistency state\n   */\n  onConsistencyChanged?: (isConsistent: boolean) => void\n\n  /**\n   * Called whenever a new incoming mutation comes in. These are always ordered correctly.\n   */\n  onRemoteMutation?: (mut: Mutation) => void\n\n  /**\n   * We are consistent when there are no unresolved mutations of our own, and no un-applicable\n   * incoming mutations. When this has been going on for too long, and there has been a while\n   * since we staged a new mutation, it is time to reset your state.\n   */\n  inconsistentAt: Date | null = null\n\n  /**\n   * The last time we staged a patch of our own. If we have been inconsistent for a while, but it\n   * hasn't been long since we staged a new mutation, the reason is probably just because the user\n   * is typing or something.\n   *\n   * Should be used as a guard against resetting state for inconsistency reasons.\n   */\n  lastStagedAt: Date | null = null\n\n  constructor(doc: Doc | null) {\n    this.reset(doc)\n    this.HEAD = doc\n    this.EDGE = doc\n  }\n\n  // Reset the state of the Document, used to recover from unsavory states by reloading the document\n  reset(doc: Doc | null): void {\n    this.incoming = []\n    this.submitted = []\n    this.pending = []\n    this.inconsistentAt = null\n    this.HEAD = doc\n    this.EDGE = doc\n    this.considerIncoming()\n    this.updateConsistencyFlag()\n  }\n\n  // Call when a mutation arrives from Sanity\n  arrive(mutation: Mutation): void {\n    this.incoming.push(mutation)\n    this.considerIncoming()\n    this.updateConsistencyFlag()\n  }\n\n  // Call to signal that we are submitting a mutation. Returns a callback object with a\n  // success and failure handler that must be called according to the outcome of our\n  // submission.\n  stage(mutation: Mutation, silent?: boolean): SubmissionResponder {\n    if (!mutation.transactionId) {\n      throw new Error('Mutations _must_ have transactionId when submitted')\n    }\n    this.lastStagedAt = new Date()\n\n    debug('Staging mutation %s (pushed to pending)', mutation.transactionId)\n    this.pending.push(mutation)\n    this.EDGE = mutation.apply(this.EDGE)\n\n    if (this.onMutation && !silent) {\n      this.onMutation({\n        mutation,\n        document: this.EDGE,\n        remote: false,\n      })\n    }\n\n    const txnId = mutation.transactionId\n\n    this.updateConsistencyFlag()\n\n    return {\n      success: () => {\n        this.pendingSuccessfullySubmitted(txnId)\n        this.updateConsistencyFlag()\n      },\n      failure: () => {\n        this.pendingFailed(txnId)\n        this.updateConsistencyFlag()\n      },\n    }\n  }\n\n  // Call to check if everything is nice and quiet and there are no unresolved mutations.\n  // Means this model thinks both HEAD and EDGE is up to date with what the server sees.\n  isConsistent(): boolean {\n    return !this.inconsistentAt\n  }\n\n  // Private\n\n  // Attempts to apply any resolvable incoming patches to HEAD. Will keep patching as long as there\n  // are applicable patches to be applied\n  considerIncoming(): void {\n    let mustRebase = false\n    let nextMut: Mutation | undefined\n    const rebaseMutations: Mutation[] = []\n\n    // Filter mutations that are older than the document\n    if (this.HEAD && this.HEAD._updatedAt) {\n      const updatedAt = new Date(this.HEAD._updatedAt)\n      if (this.incoming.find((mut) => mut.timestamp && mut.timestamp < updatedAt)) {\n        this.incoming = this.incoming.filter((mut) => mut.timestamp && mut.timestamp < updatedAt)\n      }\n    }\n\n    // Keep applying mutations as long as any apply\n    let protect = 0\n    do {\n      // Find next mutation that can be applied to HEAD (if any)\n      if (this.HEAD) {\n        const HEAD = this.HEAD\n        nextMut = HEAD._rev ? this.incoming.find((mut) => mut.previousRev === HEAD._rev) : undefined\n      } else {\n        // When HEAD is null, that means the document is currently deleted. Only mutations that start with a create\n        // operation will be considered.\n        nextMut = this.incoming.find((mut) => mut.appliesToMissingDocument())\n      }\n\n      if (nextMut) {\n        const applied = this.applyIncoming(nextMut)\n        mustRebase = mustRebase || applied\n        if (mustRebase) {\n          rebaseMutations.push(nextMut)\n        }\n\n        if (protect++ > 10) {\n          throw new Error(\n            `Mutator stuck flushing incoming mutations. Probably stuck here: ${JSON.stringify(\n              nextMut,\n            )}`,\n          )\n        }\n      }\n    } while (nextMut)\n\n    if (this.incoming.length > 0 && debug.enabled) {\n      debug(\n        'Unable to apply mutations %s',\n        this.incoming.map((mut) => mut.transactionId).join(', '),\n      )\n    }\n\n    if (mustRebase) {\n      this.rebase(rebaseMutations)\n    }\n  }\n\n  // check current consistency state, update flag and invoke callback if needed\n  updateConsistencyFlag(): void {\n    const wasConsistent = this.isConsistent()\n    const isConsistent =\n      this.pending.length === 0 && this.submitted.length === 0 && this.incoming.length === 0\n    // Update the consistency state, taking care not to update the timestamp if we were inconsistent and still are\n    if (isConsistent) {\n      this.inconsistentAt = null\n    } else if (!this.inconsistentAt) {\n      this.inconsistentAt = new Date()\n    }\n    // Handle onConsistencyChanged callback\n    if (wasConsistent != isConsistent && this.onConsistencyChanged) {\n      if (isConsistent) {\n        debug('Buffered document is inconsistent')\n      } else {\n        debug('Buffered document is consistent')\n      }\n      this.onConsistencyChanged(isConsistent)\n    }\n  }\n\n  // apply an incoming patch that has been prequalified as the next in line for this document\n  applyIncoming(mut: Mutation | undefined): boolean {\n    if (!mut) {\n      return false\n    }\n\n    if (!mut.transactionId) {\n      throw new Error('Received incoming mutation without a transaction ID')\n    }\n\n    debug(\n      'Applying mutation %s -> %s to rev %s',\n      mut.previousRev,\n      mut.resultRev,\n      this.HEAD && this.HEAD._rev,\n    )\n\n    this.HEAD = mut.apply(this.HEAD)\n\n    if (this.onRemoteMutation) {\n      this.onRemoteMutation(mut)\n    }\n\n    // Eliminate from incoming set\n    this.incoming = this.incoming.filter((m) => m.transactionId !== mut.transactionId)\n\n    if (this.hasUnresolvedMutations()) {\n      const needRebase = this.consumeUnresolved(mut.transactionId)\n      if (debug.enabled) {\n        debug(\n          `Incoming mutation ${mut.transactionId} appeared while there were pending or submitted local mutations`,\n        )\n        debug(`Submitted txnIds: ${this.submitted.map((m) => m.transactionId).join(', ')}`)\n        debug(`Pending txnIds: ${this.pending.map((m) => m.transactionId).join(', ')}`)\n        debug(`needRebase === %s`, needRebase)\n      }\n      return needRebase\n    }\n    debug(\n      `Remote mutation %s arrived w/o any pending or submitted local mutations`,\n      mut.transactionId,\n    )\n    this.EDGE = this.HEAD\n    if (this.onMutation) {\n      this.onMutation({\n        mutation: mut,\n        document: this.EDGE,\n        remote: true,\n      })\n    }\n    return false\n  }\n\n  /**\n   * Returns true if there are unresolved mutations between HEAD and EDGE, meaning we have\n   * mutations that are still waiting to be either submitted, or to be confirmed by the server.\n   *\n   * @returns true if there are unresolved mutations between HEAD and EDGE, false otherwise\n   */\n  hasUnresolvedMutations(): boolean {\n    return this.submitted.length > 0 || this.pending.length > 0\n  }\n\n  /**\n   * When an incoming mutation is applied to HEAD, this is called to remove the mutation from\n   * the unresolved state. If the newly applied patch is the next upcoming unresolved mutation,\n   * no rebase is needed, but we might have the wrong idea about the ordering of mutations, so in\n   * that case we are given the flag `needRebase` to tell us that this mutation arrived out of\n   * order in terms of our optimistic version, so a rebase is needed.\n   *\n   * @param txnId - Transaction ID of the remote mutation\n   * @returns true if rebase is needed, false otherwise\n   */\n  consumeUnresolved(txnId: string): boolean {\n    // If we have nothing queued up, we are in sync and can apply patch with no\n    // rebasing\n    if (this.submitted.length === 0 && this.pending.length === 0) {\n      return false\n    }\n\n    // If we can consume the directly upcoming mutation, we won't have to rebase\n    if (this.submitted.length !== 0) {\n      if (this.submitted[0].transactionId === txnId) {\n        debug(\n          `Remote mutation %s matches upcoming submitted mutation, consumed from 'submitted' buffer`,\n          txnId,\n        )\n        this.submitted.shift()\n        return false\n      }\n    } else if (this.pending.length > 0 && this.pending[0].transactionId === txnId) {\n      // There are no submitted, but some are pending so let's check the upcoming pending\n      debug(\n        `Remote mutation %s matches upcoming pending mutation, consumed from 'pending' buffer`,\n        txnId,\n      )\n      this.pending.shift()\n      return false\n    }\n\n    debug(\n      'The mutation was not the upcoming mutation, scrubbing. Pending: %d, Submitted: %d',\n      this.pending.length,\n      this.submitted.length,\n    )\n\n    // The mutation was not the upcoming mutation, so we'll have to check everything to\n    // see if we have an out of order situation\n    this.submitted = this.submitted.filter((mut) => mut.transactionId !== txnId)\n    this.pending = this.pending.filter((mut) => mut.transactionId !== txnId)\n    debug(`After scrubbing: Pending: %d, Submitted: %d`, this.pending.length, this.submitted.length)\n\n    // Whether we had it or not we have either a reordering, or an unexpected mutation\n    // so must rebase\n    return true\n  }\n\n  pendingSuccessfullySubmitted(pendingTxnId: string): void {\n    if (this.pending.length === 0) {\n      // If there are no pending, it has probably arrived allready\n      return\n    }\n\n    const first = this.pending[0]\n    if (first.transactionId === pendingTxnId) {\n      // Nice, the pending transaction arrived in order\n      this.pending.shift()\n      this.submitted.push(first)\n      return\n    }\n\n    // Oh, no. Submitted out of order.\n    let justSubmitted: Mutation | undefined\n    const stillPending: Mutation[] = []\n    this.pending.forEach((mutation) => {\n      if (mutation.transactionId === pendingTxnId) {\n        justSubmitted = mutation\n        return\n      }\n\n      stillPending.push(mutation)\n    })\n\n    // Not found? Hopefully it has already arrived. Might have been forgotten by now\n    if (justSubmitted) {\n      this.submitted.push(justSubmitted)\n    }\n\n    this.pending = stillPending\n\n    // Must rebase since mutation order has changed\n    this.rebase([])\n  }\n\n  pendingFailed(pendingTxnId: string): void {\n    this.pending = this.pending.filter((mutation) => mutation.transactionId !== pendingTxnId)\n\n    // Rebase to revert document to what it looked like before the failed mutation\n    this.rebase([])\n  }\n\n  rebase(incomingMutations: Mutation[]): void {\n    const oldEdge = this.EDGE\n    this.EDGE = Mutation.applyAll(this.HEAD, this.submitted.concat(this.pending))\n\n    // Copy over rev, since we don't care if it changed, we only care about the content\n    if (oldEdge !== null && this.EDGE !== null) {\n      oldEdge._rev = this.EDGE._rev\n    }\n\n    const changed = !isEqual(this.EDGE, oldEdge)\n    if (changed && this.onRebase) {\n      this.onRebase(this.EDGE, incomingMutations, this.pending)\n    }\n  }\n}\n","import {makePatches, stringifyPatches} from '@sanity/diff-match-patch'\n\nimport {arrayToJSONMatchPath} from '../jsonpath/arrayToJSONMatchPath'\nimport {extractWithPath} from '../jsonpath/extractWithPath'\nimport {debug} from './debug'\nimport {Mutation} from './Mutation'\nimport {type Doc, type Mut} from './types'\n\n/**\n * Implements a buffer for mutations that incrementally optimises the mutations by\n * eliminating set-operations that overwrite earlier set-operations, and rewrite\n * set-operations that change strings into other strings into diffMatchPatch operations.\n *\n * @internal\n */\nexport class SquashingBuffer {\n  /**\n   * The document forming the basis of this squash\n   */\n  BASIS: Doc | null\n\n  /**\n   * The document after the out-Mutation has been applied, but before the staged\n   * operations are committed.\n   */\n  PRESTAGE: Doc | null\n\n  /**\n   * setOperations contain the latest set operation by path. If the set-operations are\n   * updating strings to new strings, they are rewritten as diffMatchPatch operations,\n   * any new set operations on the same paths overwrites any older set operations.\n   * Only set-operations assigning plain values to plain values gets optimized like this.\n   */\n  setOperations: Record<string, Mut | undefined>\n\n  /**\n   * `documentPresent` is true whenever we know that the document must be present due\n   * to preceeding mutations. `false` implies that it may or may not already exist.\n   */\n  documentPresent: boolean\n\n  /**\n   * The operations in the out-Mutation are not able to be optimized any further\n   */\n  out: Mut[] = []\n\n  /**\n   * Staged mutation operations\n   */\n  staged: Mut[]\n\n  constructor(doc: Doc | null) {\n    if (doc) {\n      debug('Reset mutation buffer to rev %s', doc._rev)\n    } else {\n      debug('Reset mutation buffer state to document being deleted')\n    }\n\n    this.staged = []\n    this.setOperations = {}\n    this.documentPresent = false\n\n    this.BASIS = doc\n    this.PRESTAGE = doc\n  }\n\n  add(mut: Mutation): void {\n    mut.mutations.forEach((op) => this.addOperation(op))\n  }\n\n  hasChanges(): boolean {\n    return this.out.length > 0 || Object.keys(this.setOperations).length > 0\n  }\n\n  /**\n   * Extracts the mutations in this buffer.\n   * After this is done, the buffer lifecycle is over and the client should\n   * create an new one with the new, updated BASIS.\n   *\n   * @param txnId - Transaction ID\n   * @returns A `Mutation` instance if we had outgoing mutations pending, null otherwise\n   */\n  purge(txnId?: string): Mutation | null {\n    this.stashStagedOperations()\n    let result = null\n    if (this.out.length > 0) {\n      debug('Purged mutation buffer')\n      result = new Mutation({\n        mutations: this.out,\n        resultRev: txnId,\n        transactionId: txnId,\n      })\n    }\n    this.out = []\n    this.documentPresent = false\n    return result\n  }\n\n  addOperation(op: Mut): void {\n    // Is this a set patch, and only a set patch, and does it apply to the document at hand?\n    if (\n      op.patch &&\n      op.patch.set &&\n      'id' in op.patch &&\n      op.patch.id === this.PRESTAGE?._id &&\n      Object.keys(op.patch).length === 2 // `id` + `set`\n    ) {\n      const setPatch = op.patch.set\n      const unoptimizable: Record<string, unknown> = {}\n      // Apply all optimisable keys in the patch\n      for (const path of Object.keys(setPatch)) {\n        if (setPatch.hasOwnProperty(path)) {\n          if (!this.optimiseSetOperation(path, setPatch[path])) {\n            // If not optimisable, add to unoptimizable set\n            unoptimizable[path] = setPatch[path]\n          }\n        }\n      }\n\n      // If any weren't optimisable, add them to an unoptimised set-operation, then\n      // stash everything.\n      if (Object.keys(unoptimizable).length > 0) {\n        debug('Unoptimizable set-operation detected, purging optimization buffer')\n        this.staged.push({patch: {id: this.PRESTAGE._id, set: unoptimizable}})\n        this.stashStagedOperations()\n      }\n\n      return\n    }\n\n    // Is this a createIfNotExists for our document?\n    if (op.createIfNotExists && this.PRESTAGE && op.createIfNotExists._id === this.PRESTAGE._id) {\n      if (!this.documentPresent) {\n        // If we don't know that it's present we'll have to stage and stash.\n        this.staged.push(op)\n        this.documentPresent = true\n        this.stashStagedOperations()\n      }\n\n      // Otherwise we can fully ignore it.\n      return\n    }\n\n    debug('Unoptimizable mutation detected, purging optimization buffer')\n    // console.log(\"Unoptimizable operation, stashing\", JSON.stringify(op))\n    // Un-optimisable operations causes everything to be stashed\n    this.staged.push(op)\n    this.stashStagedOperations()\n  }\n\n  /**\n   * Attempt to perform one single set operation in an optimised manner, return value\n   * reflects whether or not the operation could be performed.\n\n   * @param path - The JSONPath to the set operation in question\n   * @param nextValue - The value to be set\n   * @returns True of optimized, false otherwise\n   */\n  optimiseSetOperation(path: string, nextValue: unknown): boolean {\n    // console.log('optimiseSetOperation', path, nextValue)\n    // If target value is not a plain value, unable to optimise\n    if (typeof nextValue === 'object') {\n      // console.log(\"Not optimisable because next value is object\")\n      return false\n    }\n\n    // Check the source values, if there is more than one value being assigned,\n    // we won't optimise\n    const matches = extractWithPath(path, this.PRESTAGE)\n    // If we are not overwriting exactly one key, this cannot be optimised, so we bail\n    if (matches.length !== 1) {\n      // console.log('Not optimisable because match count is != 1', JSON.stringify(matches))\n      return false\n    }\n\n    // Okay, we are assigning exactly one value to exactly one existing slot, so we might optimise\n    const match = matches[0]\n    // If the value of the match is an array or object, we cannot safely optimise this since the meaning\n    // of pre-existing operations might change (in theory, at least), so we bail\n    if (typeof match.value === 'object') {\n      // console.log(\"Not optimisable because old value is object\")\n      return false\n    }\n\n    if (!this.PRESTAGE) {\n      // Shouldn't happen, but makes typescript happy\n      return false\n    }\n\n    // If the new and old value are the equal, we optimise this operation by discarding it\n    // Now, let's build the operation\n    let op: Mut | null = null\n    if (match.value === nextValue) {\n      // If new and old values are equal, we optimise this by deleting the operation\n      // console.log(\"Omitting operation\")\n      op = null\n    } else if (typeof match.value === 'string' && typeof nextValue === 'string') {\n      // console.log(\"Rewriting to dmp\")\n      // We are updating a string to another string, so we are making a diffMatchPatch\n      try {\n        const patch = stringifyPatches(makePatches(match.value, nextValue))\n        op = {patch: {id: this.PRESTAGE._id, diffMatchPatch: {[path]: patch}}}\n      } catch {\n        // patch_make failed due to unicode issue https://github.com/google/diff-match-patch/issues/59\n        return false\n      }\n    } else {\n      // console.log(\"Not able to rewrite to dmp, making normal set\")\n      // We are changing the type of the value, so must make a normal set-operation\n      op = {patch: {id: this.PRESTAGE._id, set: {[path]: nextValue}}}\n    }\n\n    // Let's make a plain, concrete path from the array-path. We use this to keep only the latest set\n    // operation touching this path in the buffer.\n    const canonicalPath = arrayToJSONMatchPath(match.path)\n\n    // Store this operation, overwriting any previous operations touching this same path\n    if (op) {\n      this.setOperations[canonicalPath] = op\n    } else {\n      delete this.setOperations[canonicalPath]\n    }\n\n    // Signal that we succeeded in optimizing this patch\n    return true\n  }\n\n  stashStagedOperations(): void {\n    // Short circuit if there are no staged operations\n    const nextOps: Mut[] = []\n\n    // Extract the existing outgoing operations if any\n    Object.keys(this.setOperations).forEach((key) => {\n      const op = this.setOperations[key]\n      if (op) {\n        nextOps.push(op)\n      }\n    })\n\n    nextOps.push(...this.staged)\n    if (nextOps.length > 0) {\n      this.PRESTAGE = new Mutation({mutations: nextOps}).apply(this.PRESTAGE) as Doc\n      this.staged = []\n      this.setOperations = {}\n    }\n\n    this.out.push(...nextOps)\n  }\n\n  /**\n   * Rebases given the new base-document\n   *\n   * @param newBasis - New base document to rebase on\n   * @returns New \"edge\" document with buffered changes integrated\n   */\n  rebase(newBasis: Doc | null): Doc | null {\n    this.stashStagedOperations()\n\n    if (newBasis === null) {\n      // If document was just deleted, we must throw out local changes\n      this.out = []\n      this.BASIS = newBasis\n      this.PRESTAGE = newBasis\n      this.documentPresent = false\n    } else {\n      this.BASIS = newBasis\n\n      // @todo was this supposed to be `this.out.length > 0`?\n      // surely this is always `true`?\n      if (this.out) {\n        this.PRESTAGE = new Mutation({mutations: this.out}).apply(this.BASIS) as Doc\n      } else {\n        this.PRESTAGE = this.BASIS\n      }\n    }\n\n    return this.PRESTAGE\n  }\n}\n","import {isEqual} from 'lodash'\n\nimport {debug} from './debug'\nimport {Document} from './Document'\nimport {Mutation} from './Mutation'\nimport {SquashingBuffer} from './SquashingBuffer'\nimport {type Doc, type Mut} from './types'\n\nconst ONE_MINUTE = 1000 * 60\n\n/**\n * @internal\n */\nexport interface CommitHandlerMessage {\n  mutation: Mutation\n  success: () => void\n  failure: () => void\n  cancel: (error: Error) => void\n}\n\n/**\n * A wrapper for Document that allows the client to gather mutations on the\n * client side and commit them when it wants to.\n */\nclass Commit {\n  mutations: Mutation[]\n  tries: number\n  resolve: () => void\n  reject: (error: Error) => void\n\n  constructor(\n    mutations: Mutation[],\n    {resolve, reject}: {resolve: () => void; reject: (error: Error) => void},\n  ) {\n    this.mutations = mutations\n    this.tries = 0\n    this.resolve = resolve\n    this.reject = reject\n  }\n\n  apply(doc: Doc | null): Doc | null {\n    return Mutation.applyAll(doc, this.mutations)\n  }\n\n  squash(doc: Doc | null) {\n    const result = Mutation.squash(doc, this.mutations)\n    result.assignRandomTransactionId()\n    return result\n  }\n}\n\nconst mutReducerFn = (acc: Mut[], mut: Mutation): Mut[] => acc.concat(mut.mutations)\n\n/**\n * @internal\n */\nexport class BufferedDocument {\n  private mutations: Mutation[]\n\n  /**\n   * The Document we are wrapping\n   */\n  document: Document\n\n  /**\n   * The Document with local changes applied\n   */\n  LOCAL: Doc | null\n\n  /**\n   * Commits that are waiting to be delivered to the server\n   */\n  private commits: Commit[]\n\n  /**\n   * Local mutations that are not scheduled to be committed yet\n   */\n  buffer: SquashingBuffer\n\n  /**\n   * Assignable event handler for when the buffered document applies a mutation\n   */\n  onMutation?: (message: {mutation: Mutation; document: Doc | null; remote: boolean}) => void\n\n  /**\n   * Assignable event handler for when a remote mutation happened\n   */\n  onRemoteMutation?: Document['onRemoteMutation']\n\n  /**\n   * Assignable event handler for when the buffered document rebased\n   */\n  onRebase?: (localDoc: Doc | null, remoteMutations: Mut[], localMutations: Mut[]) => void\n\n  /**\n   * Assignable event handler for when the document is deleted\n   */\n  onDelete?: (doc: Doc | null) => void\n\n  /**\n   * Assignable event handler for when the state of consistency changed\n   */\n  onConsistencyChanged?: (isConsistent: boolean) => void\n\n  /**\n   * Assignable event handler for when the buffered document should commit changes\n   */\n  commitHandler?: (msg: CommitHandlerMessage) => void\n\n  /**\n   * Whether or not we are currently commiting\n   */\n  committerRunning = false\n\n  constructor(doc: Doc | null) {\n    this.buffer = new SquashingBuffer(doc)\n    this.document = new Document(doc)\n    this.document.onMutation = (msg) => this.handleDocMutation(msg)\n    this.document.onRemoteMutation = (mut) => this.onRemoteMutation && this.onRemoteMutation(mut)\n    this.document.onRebase = (edge, remoteMutations, localMutations) =>\n      this.handleDocRebase(edge, remoteMutations, localMutations)\n    this.document.onConsistencyChanged = (msg) => this.handleDocConsistencyChanged(msg)\n    this.LOCAL = doc\n    this.mutations = []\n    this.commits = []\n  }\n\n  // Used to reset the state of the local document model. If the model has been inconsistent\n  // for too long, it has probably missed a notification, and should reload the document from the server\n  reset(doc: Doc | null): void {\n    if (doc) {\n      debug('Document state reset to revision %s', doc._rev)\n    } else {\n      debug('Document state reset to being deleted')\n    }\n    this.document.reset(doc)\n    this.rebase([], [])\n    this.handleDocConsistencyChanged(this.document.isConsistent())\n  }\n\n  // Add a change to the buffer\n  add(mutation: Mutation): void {\n    if (this.onConsistencyChanged) {\n      this.onConsistencyChanged(false)\n    }\n    debug('Staged local mutation')\n    this.buffer.add(mutation)\n    const oldLocal = this.LOCAL\n    this.LOCAL = mutation.apply(this.LOCAL)\n    if (this.onMutation && oldLocal !== this.LOCAL) {\n      debug('onMutation fired')\n      this.onMutation({\n        mutation,\n        document: this.LOCAL,\n        remote: false,\n      })\n      if (this.LOCAL === null && this.onDelete) {\n        this.onDelete(this.LOCAL)\n      }\n    }\n  }\n\n  // Call when a mutation arrives from Sanity\n  arrive(mutation: Mutation): void {\n    debug('Remote mutation arrived %s -> %s', mutation.previousRev, mutation.resultRev)\n    if (mutation.previousRev === mutation.resultRev) {\n      throw new Error(\n        `Mutation ${mutation.transactionId} has previousRev === resultRev (${mutation.previousRev})`,\n      )\n    }\n    return this.document.arrive(mutation)\n  }\n\n  // Submit all mutations in the buffer to be committed\n  commit(): Promise<void> {\n    return new Promise((resolve, reject) => {\n      // Anything to commit?\n      if (!this.buffer.hasChanges()) {\n        resolve()\n        return\n      }\n      debug('Committing local changes')\n      // Collect current staged mutations into a commit and ...\n      const pendingMutations = this.buffer.purge()\n      this.commits.push(new Commit(pendingMutations ? [pendingMutations] : [], {resolve, reject}))\n      // ... clear the table for the next commit.\n      this.buffer = new SquashingBuffer(this.LOCAL)\n      this.performCommits()\n    })\n  }\n\n  // Starts the committer that will try to committ all staged commits to the database\n  // by calling the commitHandler. Will keep running until all commits are successfully\n  // committed.\n  performCommits(): void {\n    if (!this.commitHandler) {\n      throw new Error('No commitHandler configured for this BufferedDocument')\n    }\n    if (this.committerRunning) {\n      // We can have only one committer at any given time\n      return\n    }\n    this._cycleCommitter()\n  }\n\n  // TODO: Error handling, right now retries after every error\n  _cycleCommitter(): void {\n    const commit = this.commits.shift()\n    if (!commit) {\n      this.committerRunning = false\n      return\n    }\n\n    this.committerRunning = true\n    const squashed = commit.squash(this.LOCAL)\n    const docResponder = this.document.stage(squashed, true)\n\n    const responder = {\n      success: () => {\n        debug('Commit succeeded')\n        docResponder.success()\n        commit.resolve()\n        // Keep running the committer until no more commits\n        this._cycleCommitter()\n      },\n\n      failure: () => {\n        debug('Commit failed')\n        // Re stage commit\n        commit.tries += 1\n        if (this.LOCAL !== null) {\n          // Only schedule this commit for a retry of the document still exist to avoid looping\n          // indefinitely when the document was deleted from under our noses\n          this.commits.unshift(commit)\n        }\n        docResponder.failure()\n\n        // Todo: Need better error handling (i.e. propagate to user and provide means of retrying)\n        if (commit.tries < 200) {\n          setTimeout(() => this._cycleCommitter(), Math.min(commit.tries * 1000, ONE_MINUTE))\n        }\n      },\n\n      cancel: (error: Error) => {\n        this.commits.forEach((comm) => comm.reject(error))\n\n        // Throw away waiting commits\n        this.commits = []\n\n        // Reset back to last known state from content lake and cause a rebase that will\n        // reset the view in the form\n        this.reset(this.document.HEAD)\n\n        // Clear the buffer of recent mutations\n        this.buffer = new SquashingBuffer(this.LOCAL)\n\n        // Stop the committer loop\n        this.committerRunning = false\n      },\n    }\n\n    debug('Posting commit')\n    if (this.commitHandler) {\n      this.commitHandler({\n        mutation: squashed,\n        success: responder.success,\n        failure: responder.failure,\n        cancel: responder.cancel,\n      })\n    }\n  }\n\n  handleDocRebase(edge: Doc | null, remoteMutations: Mutation[], localMutations: Mutation[]): void {\n    this.rebase(remoteMutations, localMutations)\n  }\n\n  handleDocumentDeleted(): void {\n    debug('Document deleted')\n    // If the document was just deleted, fire the onDelete event with the absolutely latest\n    // version of the document before someone deleted it so that the client may revive the\n    // document in the last state the user saw it, should they so desire.\n    if (this.LOCAL !== null && this.onDelete) {\n      this.onDelete(this.LOCAL)\n    }\n\n    this.commits = []\n    this.mutations = []\n  }\n\n  handleDocMutation(msg: {mutation: Mutation; document: Doc | null; remote: boolean}): void {\n    // If we have no local changes, we can just pass this on to the client\n    if (this.commits.length === 0 && !this.buffer.hasChanges()) {\n      debug('Document mutated from remote with no local changes')\n      this.LOCAL = this.document.EDGE\n      this.buffer = new SquashingBuffer(this.LOCAL)\n      if (this.onMutation) {\n        this.onMutation(msg)\n      }\n      return\n    }\n\n    debug('Document mutated from remote with local changes')\n\n    // If there are local edits, and the document was deleted, we need to purge those local edits now\n    if (this.document.EDGE === null) {\n      this.handleDocumentDeleted()\n    }\n\n    // We had local changes, so need to signal rebase\n    this.rebase([msg.mutation], [])\n  }\n\n  rebase(remoteMutations: Mutation[], localMutations: Mutation[]): void {\n    debug('Rebasing document')\n    if (this.document.EDGE === null) {\n      this.handleDocumentDeleted()\n    }\n\n    const oldLocal = this.LOCAL\n    this.LOCAL = this.commits.reduce((doc, commit) => commit.apply(doc), this.document.EDGE)\n    this.LOCAL = this.buffer.rebase(this.LOCAL)\n\n    // Copy over rev, since we don't care if it changed, we only care about the content\n    if (oldLocal !== null && this.LOCAL !== null) {\n      oldLocal._rev = this.LOCAL._rev\n    }\n\n    const changed = !isEqual(this.LOCAL, oldLocal)\n    if (changed && this.onRebase) {\n      this.onRebase(\n        this.LOCAL,\n        remoteMutations.reduce(mutReducerFn, []),\n        localMutations.reduce(mutReducerFn, []),\n      )\n    }\n  }\n\n  handleDocConsistencyChanged(isConsistent: boolean): void {\n    if (!this.onConsistencyChanged) {\n      return\n    }\n\n    const hasLocalChanges = this.commits.length > 0 || this.buffer.hasChanges()\n\n    if (isConsistent && !hasLocalChanges) {\n      this.onConsistencyChanged(true)\n    }\n\n    if (!isConsistent) {\n      this.onConsistencyChanged(false)\n    }\n  }\n}\n"],"names":["isRecord","descend","lhs","rhs","parsePatch"],"mappings":";;;;;;;;AAEa,MAAA,QAAQ,QAAQ,kBAAkB;ACKxC,MAAM,kBAAmC;AAAA,EAC9C;AAAA,EACA;AAAA,EAEA,YAAY,OAAgB,MAA4B;AACtD,SAAK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