From 85108fad6b8872d3b50a80d405f398e2f83f9052 Mon Sep 17 00:00:00 2001
From: Richard Petersen <richard.petersen@open-xchange.com>
Date: Thu, 25 Nov 2021 11:06:50 +0100
Subject: [PATCH] Fix: The hashed version of the vite manifests does not change

Root cause: Hash was computed on array.toString() which does not change much.
Solution: Use the actual content of the vite manifests to compute the version.
---
 spec/headers_test.js |  2 +-
 spec/util_test.js    | 30 ++++++++++++++++++++++++++++++
 src/util.js          |  2 +-
 3 files changed, 32 insertions(+), 2 deletions(-)
 create mode 100644 spec/util_test.js

diff --git a/spec/headers_test.js b/spec/headers_test.js
index 44eb2ed..93f572c 100644
--- a/spec/headers_test.js
+++ b/spec/headers_test.js
@@ -52,7 +52,7 @@ describe('Responses contain custom headers', () => {
   it('index.html has version', async () => {
     const response = await request(app).get('/index.html')
     expect(response.statusCode).toBe(200)
-    expect(response.headers.version).toMatch(/\d*\.3220550168/)
+    expect(response.headers.version).toMatch(/\d*\.\d*/)
   })
 
   it('javascript file contains dependencies', async () => {
diff --git a/spec/util_test.js b/spec/util_test.js
new file mode 100644
index 0000000..eb2bdda
--- /dev/null
+++ b/spec/util_test.js
@@ -0,0 +1,30 @@
+import { describe, it, expect } from '@jest/globals'
+import { hash } from '../src/util'
+import { generateSimpleViteManifest } from './util'
+
+describe('Util', function () {
+  describe('hash function', function () {
+    it('computes the hash', function () {
+      const manifest = generateSimpleViteManifest({
+        'example.js': { imports: ['test.css'] },
+        'test.css': { }
+      })
+      expect(hash(manifest)).toEqual('2245696177')
+    })
+
+    it('the hash changes when the manifest changes', function () {
+      const manifest = generateSimpleViteManifest({
+        'example.js': { imports: ['test.css'] },
+        'test.css': { }
+      })
+      const manifestChanged = generateSimpleViteManifest({
+        'example.js': { imports: ['test1.css'] },
+        'test1.css': { }
+      })
+
+      expect(hash(manifest)).not.toEqual(hash(manifestChanged))
+      expect(hash(manifest)).toEqual('2245696177')
+      expect(hash(manifestChanged)).toEqual('2547998666')
+    })
+  })
+})
diff --git a/src/util.js b/src/util.js
index 0229cba..2238880 100644
--- a/src/util.js
+++ b/src/util.js
@@ -1,6 +1,6 @@
 // totaly awesome hash function. Do not use this for encryption (crypto.subtle.digest etc would be overkill for this)
 export function hash (array) {
-  const string = array.toString()
+  const string = JSON.stringify(array)
   if (!string.length) throw new Error('TypeError: Unexpected data to calculate hash from')
 
   let hash = 0
-- 
GitLab