How to create hash of Y.Doc?

I want to check if a doc’s changed in the server easily, so I decided to compare the hash of the docs between client and server.

However, I do not know and can’t find a proper way to calculate the hash.

I tried this

async function calulateHashFromDoc() {
      const vec = Y.encodeStateVector(ydoc);

      const hash = await crypto.subtle.digest('SHA-1', vec);

      const hex = Array.from(new Uint8Array(hash))
        .map((b) => b.toString(16).padStart(2, '0'))
        .join('');

      return hex;
}

ydoc.on('update',() => console.log(calulateHashFromDoc()));

It seems to work well, but there are two problems:

  1. Sometimes, the update is triggered and the doc is changed, but the hash result is the same
  2. I do not know whether the calculated hash is consistent between synced clients (though it seems be)

For problem one, this is the update event (from Y.logUpdate):

Could anyone help me?

Hi, welcome.

State vectors do not include deletes, so your code will not pick up updates that consist only of the deletion of an item from a map.

Instead of hashing the state vector, hash a snapshot. Snapshots include both the state vector and the delete set.

const snap = Y.encodeSnapshot(Y.snapshot(ydoc));
const hash = await crypto.subtle.digest('SHA-1', snap);

The hash will be consistent between any two clients that are perfectly in sync.

Cool! Very thanks for your help!