Skip to content

Commit

Permalink
fix: moved function into closure to avoid typing
Browse files Browse the repository at this point in the history
  • Loading branch information
wyattjoh committed Aug 22, 2022
1 parent 5a61e0c commit 2e08b49
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 48 deletions.
89 changes: 41 additions & 48 deletions packages/next/build/webpack/plugins/subresource-integrity-plugin.ts
Expand Up @@ -6,10 +6,6 @@ const PLUGIN_NAME = 'SubresourceIntegrityPlugin'

export type SubresourceIntegrityAlgorithm = 'sha256' | 'sha384' | 'sha512'

export type CompilationAssets = Parameters<
Parameters<webpack.Compilation['hooks']['afterOptimizeAssets']['tap']>[1]
>[0]

export class SubresourceIntegrityPlugin {
constructor(private readonly algorithm: SubresourceIntegrityAlgorithm) {}

Expand All @@ -20,51 +16,48 @@ export class SubresourceIntegrityPlugin {
name: PLUGIN_NAME,
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
},
(assets) => this.createAsset(assets, compilation)
(assets) => {
// Collect all the entrypoint files.
let files = new Set<string>()
for (const entrypoint of compilation.entrypoints.values()) {
const iterator = entrypoint?.getFiles()
if (!iterator) {
continue
}

for (const file of iterator) {
files.add(file)
}
}

// For each file, deduped, calculate the file hash.
const hashes: Record<string, string> = {}
for (const file of files.values()) {
// Get the buffer for the asset.
const asset = assets[file]
if (!asset) {
throw new Error(`could not get asset: ${file}`)
}

// Get the buffer for the asset.
const buffer = asset.buffer()

// Create the hash for the content.
const hash = crypto
.createHash(this.algorithm)
.update(buffer)
.digest()
.toString('base64')

hashes[file] = `${this.algorithm}-${hash}`
}

const json = JSON.stringify(hashes, null, 2)
assets[SUBRESOURCE_INTEGRITY_MANIFEST] = new sources.RawSource(
json
) as any
}
)
})
}

private createAsset(
assets: CompilationAssets,
compilation: webpack.Compilation
) {
// Collect all the entrypoint files.
let files = new Set<string>()
for (const entrypoint of compilation.entrypoints.values()) {
const iterator = entrypoint?.getFiles()
if (!iterator) {
continue
}

for (const file of iterator) {
files.add(file)
}
}

// For each file, deduped, calculate the file hash.
const hashes: Record<string, string> = {}
for (const file of files.values()) {
// Get the buffer for the asset.
const asset = assets[file]
if (!asset) {
throw new Error(`could not get asset: ${file}`)
}

// Get the buffer for the asset.
const buffer = asset.buffer()

// Create the hash for the content.
const hash = crypto
.createHash(this.algorithm)
.update(buffer)
.digest()
.toString('base64')

hashes[file] = `${this.algorithm}-${hash}`
}

const json = JSON.stringify(hashes, null, 2)
assets[SUBRESOURCE_INTEGRITY_MANIFEST] = new sources.RawSource(json) as any
}
}

0 comments on commit 2e08b49

Please sign in to comment.