From 0cef7a904574e4a80df9ce4aa23570fd4315544c Mon Sep 17 00:00:00 2001 From: Luke Karrys Date: Mon, 6 May 2024 00:10:52 -0700 Subject: [PATCH] fix: wait for size event from body for contentLength --- lib/registry.js | 8 +++++++- test/registry.js | 5 +++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/lib/registry.js b/lib/registry.js index b6a8d49b..3d575016 100644 --- a/lib/registry.js +++ b/lib/registry.js @@ -9,6 +9,8 @@ const ssri = require('ssri') const crypto = require('crypto') const npa = require('npm-package-arg') const sigstore = require('sigstore') +const { isStream } = require('minipass') +const { once } = require('node:stream') // Corgis are cute. 🐕🐶 const corgiDoc = 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*' @@ -96,7 +98,11 @@ class RegistryFetcher extends Fetcher { integrity: null, }) const packument = await res.json() - packument._contentLength = +res.headers.get('content-length') + let contentLength = res.headers.get('content-length') ?? null + if (contentLength === null && isStream(res.body)) { + contentLength = await once(res.body, 'size').then(r => r[0]) + } + packument._contentLength = +contentLength if (this.packumentCache) { this.packumentCache.set(this.packumentUrl, packument) } diff --git a/test/registry.js b/test/registry.js index 95ea5bc7..0ff511f8 100644 --- a/test/registry.js +++ b/test/registry.js @@ -1188,6 +1188,11 @@ t.test('a manifest that lacks integrity', async t => { t.equal(await f.packument(), await f2.packument(), 'serve cached packument') }) +t.test('packument has contentLength', async t => { + const f = new RegistryFetcher('underscore', { registry, cache }) + t.match(await f.packument(), { _contentLength: 40966 }, 'got contentLength from body') +}) + t.test('packument that has been cached', async t => { const packumentUrl = `${registry}asdf` const packument = {