Skip to content

Commit

Permalink
perf: improve static builds cache
Browse files Browse the repository at this point in the history
Signed-off-by: Andres Correa Casablanca <andreu@kindspells.dev>
  • Loading branch information
castarco committed Mar 15, 2024
1 parent b7a9f6e commit 611e9bc
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 18 deletions.
39 changes: 23 additions & 16 deletions src/core.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -168,24 +168,31 @@ export const updateStaticPageSriHashes = async (
}

if (src) {
/** @type {string | ArrayBuffer | Buffer} */
let resourceContent
if (src.startsWith('/')) {
const resourcePath = resolve(distDir, `.${src}`)
resourceContent = await readFile(resourcePath)
} else if (src.startsWith('http')) {
setCrossorigin = true
const resourceResponse = await fetch(src, { method: 'GET' })
resourceContent = await resourceResponse.arrayBuffer()
const cachedHash = h.perResourceSriHashes[t2].get(src)
if (cachedHash) {
sriHash = cachedHash
h[`ext${t}Hashes`].add(sriHash)
pageHashes[t2].add(sriHash)
} else {
logger.warn(`Unable to process external resource: "${src}"`)
continue
}
/** @type {string | ArrayBuffer | Buffer} */
let resourceContent
if (src.startsWith('/')) {
const resourcePath = resolve(distDir, `.${src}`)
resourceContent = await readFile(resourcePath)
} else if (src.startsWith('http')) {
setCrossorigin = true
const resourceResponse = await fetch(src, { method: 'GET' })
resourceContent = await resourceResponse.arrayBuffer()
} else {
logger.warn(`Unable to process external resource: "${src}"`)
continue
}

sriHash = generateSRIHash(resourceContent)
h[`ext${t}Hashes`].add(sriHash)
pageHashes[t2].add(sriHash)
h.perResourceSriHashes[t2].set(src, sriHash)
sriHash = generateSRIHash(resourceContent)
h[`ext${t}Hashes`].add(sriHash)
pageHashes[t2].add(sriHash)
h.perResourceSriHashes[t2].set(src, sriHash)
}
}
}

Expand Down
4 changes: 2 additions & 2 deletions tests/core.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,7 @@ describe('updateStaticPageSriHashes', () => {
<title>My Test Page</title>
</head>
<body>
<script type="module" src="/core.mjs" integrity="sha256-mBEQGpYqqmUThJOhZ7SIAP3agaHSLAyV/38of2lYhnI="></script>
<script type="module" src="/core.mjs" integrity="sha256-etOR/kKV9aCSESe7t5JeBixVQA1DjUU2Zxk13wsPU8M="></script>
</body>
</html>`

Expand All @@ -379,7 +379,7 @@ describe('updateStaticPageSriHashes', () => {
expect(h.extScriptHashes.size).toBe(1)
expect(
h.extScriptHashes.has(
'sha256-mBEQGpYqqmUThJOhZ7SIAP3agaHSLAyV/38of2lYhnI=',
'sha256-etOR/kKV9aCSESe7t5JeBixVQA1DjUU2Zxk13wsPU8M=',
),
).toBe(true)
expect(h.inlineScriptHashes.size).toBe(0)
Expand Down

0 comments on commit 611e9bc

Please sign in to comment.