function npmMiddleware({ source = 'npm', alias, optimize, cwd } = {}) {
	return async (req, res, next) => {
		const url = new URL(req.url, 'https://localhost');
		// @ts-ignore
		const mod = url.pathname.replace(/^\//, '');

		const meta = normalizeSpecifier(mod);

		try {
			await resolvePackageVersion(meta);
		} catch (e) {
			return next(e);
		}

		try {
			// The package name + path + version is a strong ETag since versions are immutable
			const etag = Buffer.from(`${meta.specifier}${meta.version}`).toString('base64');
			const ifNoneMatch = String(req.headers['if-none-match']).replace(/-(gz|br)$/g, '');
			if (ifNoneMatch === etag) {
				return res.writeHead(304).end();
			}
			res.setHeader('etag', etag);

			// CSS files and proxy modules don't use Rollup.
			if (/\.((css|s[ac]ss|less)|wasm|txt|json)$/.test(meta.path)) {
				return handleAsset(meta, res, url.searchParams.has('module'));
			}

			res.setHeader('content-type', 'application/javascript;charset=utf-8');
			if (hasDebugFlag()) {
				// eslint-disable-next-line no-console
				console.log(`  ${kl.dim('middleware:') + kl.bold(kl.magenta('npm'))}  ${JSON.stringify(meta.specifier)}`);
			}
			// serve from memory and disk caches:
			const cached = await getCachedBundle(etag, meta, cwd);
			if (cached) return sendCachedBundle(req, res, cached);

			// const start = Date.now();
			const code = await bundleNpmModule(mod, { source, alias, cwd });
			// console.log(`Bundle dep: ${mod}: ${Date.now() - start}ms`);

			// send it!
			res.writeHead(200, { 'content-length': Buffer.byteLength(code) }).end(code);

			// store the bundle in memory and disk caches
			setCachedBundle(etag, code, meta, cwd);

			// this is a new bundle, we'll compress it with terser and brotli shortly
			if (optimize !== false) {
				enqueueCompress(etag);
			}
		} catch (e) {
			console.error(`Error bundling ${mod}: `, e);
			next(e);
		}
	};
}
@param {object} [options]
@param {'npm'|'unpkg'} [options.source = 'npm'] How to fetch package files
@param {Record<string,string>} [options.alias]
@param {boolean} [options.optimize = true] Progressively minify and compress dependency bundles?
@param {string} [options.cwd] Virtual cwd
@returns {import('polka').Middleware}