File size: 1,551 Bytes
6778ee0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import fs from 'fs'
import path from 'path'
import crypto from 'crypto'
import { fileURLToPath } from 'url'

const __dirname = path.dirname(fileURLToPath(import.meta.url))

const LAST_HASH_FILEPATH = path.join(__dirname, './last-hash.txt')

// Re-compilation is only required if any of these files have been changed.
const COMPILE_DEPENDENCIES = [
  path.join(__dirname, './index.js'),
  path.join(__dirname, '../compile.js'),
  path.join(__dirname, '../src/plausible.js')
]

function currentHash() {
  const combinedHash = crypto.createHash('sha256')

  for (const filePath of COMPILE_DEPENDENCIES) {
    try {
      const fileContent = fs.readFileSync(filePath)
      const fileHash = crypto.createHash('sha256').update(fileContent).digest()
      combinedHash.update(fileHash)
    } catch (error) {
      throw new Error(`Failed to read or hash ${filePath}: ${error.message}`)
    }
  }

  return combinedHash.digest('hex')
}

function lastHash() {
  if (fs.existsSync(LAST_HASH_FILEPATH)) {
    return fs.readFileSync(LAST_HASH_FILEPATH).toString()
  }
}

/**
 * Returns a boolean indicating whether the tracker compilation can be skipped.
 * Every time this function gets executed, the hash of the tracker dependencies
 * will be updated. Compilation can be skipped if the hash hasn't changed since
 * the last execution.
 */
export function canSkipCompile() {
  const current = currentHash()
  const last = lastHash()

  if (current === last) {
    return true
  } else {
    fs.writeFileSync(LAST_HASH_FILEPATH, current)
    return false
  }
}