1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156 |
- "use strict";
- const EventEmitter = require("events");
- const { extname, basename } = require("path");
- const { URL } = require("url");
- const { createGunzip, createBrotliDecompress, createInflate } = require("zlib");
- const NormalModule = require("../NormalModule");
- const createSchemaValidation = require("../util/create-schema-validation");
- const createHash = require("../util/createHash");
- const { mkdirp, dirname, join } = require("../util/fs");
- const memoize = require("../util/memoize");
- const getHttp = memoize(() => require("http"));
- const getHttps = memoize(() => require("https"));
- const proxyFetch = (request, proxy) => (url, options, callback) => {
- const eventEmitter = new EventEmitter();
- const doRequest = socket =>
- request
- .get(url, { ...options, ...(socket && { socket }) }, callback)
- .on("error", eventEmitter.emit.bind(eventEmitter, "error"));
- if (proxy) {
- const { hostname: host, port } = new URL(proxy);
- getHttp()
- .request({
- host,
- port,
- method: "CONNECT",
- path: url.host
- })
- .on("connect", (res, socket) => {
- if (res.statusCode === 200) {
-
- doRequest(socket);
- }
- })
- .on("error", err => {
- eventEmitter.emit(
- "error",
- new Error(
- `Failed to connect to proxy server "${proxy}": ${err.message}`
- )
- );
- })
- .end();
- } else {
- doRequest();
- }
- return eventEmitter;
- };
- let inProgressWrite = undefined;
- const validate = createSchemaValidation(
- require("../../schemas/plugins/schemes/HttpUriPlugin.check.js"),
- () => require("../../schemas/plugins/schemes/HttpUriPlugin.json"),
- {
- name: "Http Uri Plugin",
- baseDataPath: "options"
- }
- );
- const toSafePath = str =>
- str
- .replace(/^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$/g, "")
- .replace(/[^a-zA-Z0-9._-]+/g, "_");
- const computeIntegrity = content => {
- const hash = createHash("sha512");
- hash.update(content);
- const integrity = "sha512-" + hash.digest("base64");
- return integrity;
- };
- const verifyIntegrity = (content, integrity) => {
- if (integrity === "ignore") return true;
- return computeIntegrity(content) === integrity;
- };
- const parseKeyValuePairs = str => {
-
- const result = {};
- for (const item of str.split(",")) {
- const i = item.indexOf("=");
- if (i >= 0) {
- const key = item.slice(0, i).trim();
- const value = item.slice(i + 1).trim();
- result[key] = value;
- } else {
- const key = item.trim();
- if (!key) continue;
- result[key] = key;
- }
- }
- return result;
- };
- const parseCacheControl = (cacheControl, requestTime) => {
-
- let storeCache = true;
-
- let storeLock = true;
-
- let validUntil = 0;
- if (cacheControl) {
- const parsed = parseKeyValuePairs(cacheControl);
- if (parsed["no-cache"]) storeCache = storeLock = false;
- if (parsed["max-age"] && !isNaN(+parsed["max-age"])) {
- validUntil = requestTime + +parsed["max-age"] * 1000;
- }
- if (parsed["must-revalidate"]) validUntil = 0;
- }
- return {
- storeLock,
- storeCache,
- validUntil
- };
- };
- const areLockfileEntriesEqual = (a, b) => {
- return (
- a.resolved === b.resolved &&
- a.integrity === b.integrity &&
- a.contentType === b.contentType
- );
- };
- const entryToString = entry => {
- return `resolved: ${entry.resolved}, integrity: ${entry.integrity}, contentType: ${entry.contentType}`;
- };
- class Lockfile {
- constructor() {
- this.version = 1;
-
- this.entries = new Map();
- }
-
- static parse(content) {
-
- const data = JSON.parse(content);
- if (data.version !== 1)
- throw new Error(`Unsupported lockfile version ${data.version}`);
- const lockfile = new Lockfile();
- for (const key of Object.keys(data)) {
- if (key === "version") continue;
- const entry = data[key];
- lockfile.entries.set(
- key,
- typeof entry === "string"
- ? entry
- : {
- resolved: key,
- ...entry
- }
- );
- }
- return lockfile;
- }
-
- toString() {
- let str = "{\n";
- const entries = Array.from(this.entries).sort(([a], [b]) =>
- a < b ? -1 : 1
- );
- for (const [key, entry] of entries) {
- if (typeof entry === "string") {
- str += ` ${JSON.stringify(key)}: ${JSON.stringify(entry)},\n`;
- } else {
- str += ` ${JSON.stringify(key)}: { `;
- if (entry.resolved !== key)
- str += `"resolved": ${JSON.stringify(entry.resolved)}, `;
- str += `"integrity": ${JSON.stringify(
- entry.integrity
- )}, "contentType": ${JSON.stringify(entry.contentType)} },\n`;
- }
- }
- str += ` "version": ${this.version}\n}\n`;
- return str;
- }
- }
- const cachedWithoutKey = fn => {
- let inFlight = false;
-
- let cachedError = undefined;
-
- let cachedResult = undefined;
-
- let cachedCallbacks = undefined;
- return callback => {
- if (inFlight) {
- if (cachedResult !== undefined) return callback(null, cachedResult);
- if (cachedError !== undefined) return callback(cachedError);
- if (cachedCallbacks === undefined) cachedCallbacks = [callback];
- else cachedCallbacks.push(callback);
- return;
- }
- inFlight = true;
- fn((err, result) => {
- if (err) cachedError = err;
- else cachedResult = result;
- const callbacks = cachedCallbacks;
- cachedCallbacks = undefined;
- callback(err, result);
- if (callbacks !== undefined) for (const cb of callbacks) cb(err, result);
- });
- };
- };
- const cachedWithKey = (fn, forceFn = fn) => {
-
-
- const cache = new Map();
- const resultFn = (arg, callback) => {
- const cacheEntry = cache.get(arg);
- if (cacheEntry !== undefined) {
- if (cacheEntry.result !== undefined)
- return callback(null, cacheEntry.result);
- if (cacheEntry.error !== undefined) return callback(cacheEntry.error);
- if (cacheEntry.callbacks === undefined) cacheEntry.callbacks = [callback];
- else cacheEntry.callbacks.push(callback);
- return;
- }
-
- const newCacheEntry = {
- result: undefined,
- error: undefined,
- callbacks: undefined
- };
- cache.set(arg, newCacheEntry);
- fn(arg, (err, result) => {
- if (err) newCacheEntry.error = err;
- else newCacheEntry.result = result;
- const callbacks = newCacheEntry.callbacks;
- newCacheEntry.callbacks = undefined;
- callback(err, result);
- if (callbacks !== undefined) for (const cb of callbacks) cb(err, result);
- });
- };
- resultFn.force = (arg, callback) => {
- const cacheEntry = cache.get(arg);
- if (cacheEntry !== undefined && cacheEntry.force) {
- if (cacheEntry.result !== undefined)
- return callback(null, cacheEntry.result);
- if (cacheEntry.error !== undefined) return callback(cacheEntry.error);
- if (cacheEntry.callbacks === undefined) cacheEntry.callbacks = [callback];
- else cacheEntry.callbacks.push(callback);
- return;
- }
-
- const newCacheEntry = {
- result: undefined,
- error: undefined,
- callbacks: undefined,
- force: true
- };
- cache.set(arg, newCacheEntry);
- forceFn(arg, (err, result) => {
- if (err) newCacheEntry.error = err;
- else newCacheEntry.result = result;
- const callbacks = newCacheEntry.callbacks;
- newCacheEntry.callbacks = undefined;
- callback(err, result);
- if (callbacks !== undefined) for (const cb of callbacks) cb(err, result);
- });
- };
- return resultFn;
- };
- class HttpUriPlugin {
-
- constructor(options) {
- validate(options);
- this._lockfileLocation = options.lockfileLocation;
- this._cacheLocation = options.cacheLocation;
- this._upgrade = options.upgrade;
- this._frozen = options.frozen;
- this._allowedUris = options.allowedUris;
- this._proxy = options.proxy;
- }
-
- apply(compiler) {
- const proxy =
- this._proxy || process.env["http_proxy"] || process.env["HTTP_PROXY"];
- const schemes = [
- {
- scheme: "http",
- fetch: proxyFetch(getHttp(), proxy)
- },
- {
- scheme: "https",
- fetch: proxyFetch(getHttps(), proxy)
- }
- ];
- let lockfileCache;
- compiler.hooks.compilation.tap(
- "HttpUriPlugin",
- (compilation, { normalModuleFactory }) => {
- const intermediateFs = compiler.intermediateFileSystem;
- const fs = compilation.inputFileSystem;
- const cache = compilation.getCache("webpack.HttpUriPlugin");
- const logger = compilation.getLogger("webpack.HttpUriPlugin");
-
- const lockfileLocation =
- this._lockfileLocation ||
- join(
- intermediateFs,
- compiler.context,
- compiler.name
- ? `${toSafePath(compiler.name)}.webpack.lock`
- : "webpack.lock"
- );
-
- const cacheLocation =
- this._cacheLocation !== undefined
- ? this._cacheLocation
- : lockfileLocation + ".data";
- const upgrade = this._upgrade || false;
- const frozen = this._frozen || false;
- const hashFunction = "sha512";
- const hashDigest = "hex";
- const hashDigestLength = 20;
- const allowedUris = this._allowedUris;
- let warnedAboutEol = false;
-
- const cacheKeyCache = new Map();
-
- const getCacheKey = url => {
- const cachedResult = cacheKeyCache.get(url);
- if (cachedResult !== undefined) return cachedResult;
- const result = _getCacheKey(url);
- cacheKeyCache.set(url, result);
- return result;
- };
-
- const _getCacheKey = url => {
- const parsedUrl = new URL(url);
- const folder = toSafePath(parsedUrl.origin);
- const name = toSafePath(parsedUrl.pathname);
- const query = toSafePath(parsedUrl.search);
- let ext = extname(name);
- if (ext.length > 20) ext = "";
- const basename = ext ? name.slice(0, -ext.length) : name;
- const hash = createHash(hashFunction);
- hash.update(url);
- const digest = hash.digest(hashDigest).slice(0, hashDigestLength);
- return `${folder.slice(-50)}/${`${basename}${
- query ? `_${query}` : ""
- }`.slice(0, 150)}_${digest}${ext}`;
- };
- const getLockfile = cachedWithoutKey(
-
- callback => {
- const readLockfile = () => {
- intermediateFs.readFile(lockfileLocation, (err, buffer) => {
- if (err && err.code !== "ENOENT") {
- compilation.missingDependencies.add(lockfileLocation);
- return callback(err);
- }
- compilation.fileDependencies.add(lockfileLocation);
- compilation.fileSystemInfo.createSnapshot(
- compiler.fsStartTime,
- buffer ? [lockfileLocation] : [],
- [],
- buffer ? [] : [lockfileLocation],
- { timestamp: true },
- (err, snapshot) => {
- if (err) return callback(err);
- const lockfile = buffer
- ? Lockfile.parse(buffer.toString("utf-8"))
- : new Lockfile();
- lockfileCache = {
- lockfile,
- snapshot
- };
- callback(null, lockfile);
- }
- );
- });
- };
- if (lockfileCache) {
- compilation.fileSystemInfo.checkSnapshotValid(
- lockfileCache.snapshot,
- (err, valid) => {
- if (err) return callback(err);
- if (!valid) return readLockfile();
- callback(null, lockfileCache.lockfile);
- }
- );
- } else {
- readLockfile();
- }
- }
- );
-
- let lockfileUpdates = undefined;
-
- const storeLockEntry = (lockfile, url, entry) => {
- const oldEntry = lockfile.entries.get(url);
- if (lockfileUpdates === undefined) lockfileUpdates = new Map();
- lockfileUpdates.set(url, entry);
- lockfile.entries.set(url, entry);
- if (!oldEntry) {
- logger.log(`${url} added to lockfile`);
- } else if (typeof oldEntry === "string") {
- if (typeof entry === "string") {
- logger.log(`${url} updated in lockfile: ${oldEntry} -> ${entry}`);
- } else {
- logger.log(
- `${url} updated in lockfile: ${oldEntry} -> ${entry.resolved}`
- );
- }
- } else if (typeof entry === "string") {
- logger.log(
- `${url} updated in lockfile: ${oldEntry.resolved} -> ${entry}`
- );
- } else if (oldEntry.resolved !== entry.resolved) {
- logger.log(
- `${url} updated in lockfile: ${oldEntry.resolved} -> ${entry.resolved}`
- );
- } else if (oldEntry.integrity !== entry.integrity) {
- logger.log(`${url} updated in lockfile: content changed`);
- } else if (oldEntry.contentType !== entry.contentType) {
- logger.log(
- `${url} updated in lockfile: ${oldEntry.contentType} -> ${entry.contentType}`
- );
- } else {
- logger.log(`${url} updated in lockfile`);
- }
- };
- const storeResult = (lockfile, url, result, callback) => {
- if (result.storeLock) {
- storeLockEntry(lockfile, url, result.entry);
- if (!cacheLocation || !result.content)
- return callback(null, result);
- const key = getCacheKey(result.entry.resolved);
- const filePath = join(intermediateFs, cacheLocation, key);
- mkdirp(intermediateFs, dirname(intermediateFs, filePath), err => {
- if (err) return callback(err);
- intermediateFs.writeFile(filePath, result.content, err => {
- if (err) return callback(err);
- callback(null, result);
- });
- });
- } else {
- storeLockEntry(lockfile, url, "no-cache");
- callback(null, result);
- }
- };
- for (const { scheme, fetch } of schemes) {
-
- const resolveContent = (url, integrity, callback) => {
- const handleResult = (err, result) => {
- if (err) return callback(err);
- if ("location" in result) {
- return resolveContent(
- result.location,
- integrity,
- (err, innerResult) => {
- if (err) return callback(err);
- callback(null, {
- entry: innerResult.entry,
- content: innerResult.content,
- storeLock: innerResult.storeLock && result.storeLock
- });
- }
- );
- } else {
- if (
- !result.fresh &&
- integrity &&
- result.entry.integrity !== integrity &&
- !verifyIntegrity(result.content, integrity)
- ) {
- return fetchContent.force(url, handleResult);
- }
- return callback(null, {
- entry: result.entry,
- content: result.content,
- storeLock: result.storeLock
- });
- }
- };
- fetchContent(url, handleResult);
- };
-
-
-
-
-
- const fetchContentRaw = (url, cachedResult, callback) => {
- const requestTime = Date.now();
- fetch(
- new URL(url),
- {
- headers: {
- "accept-encoding": "gzip, deflate, br",
- "user-agent": "webpack",
- "if-none-match": cachedResult
- ? cachedResult.etag || null
- : null
- }
- },
- res => {
- const etag = res.headers["etag"];
- const location = res.headers["location"];
- const cacheControl = res.headers["cache-control"];
- const { storeLock, storeCache, validUntil } = parseCacheControl(
- cacheControl,
- requestTime
- );
-
- const finishWith = partialResult => {
- if ("location" in partialResult) {
- logger.debug(
- `GET ${url} [${res.statusCode}] -> ${partialResult.location}`
- );
- } else {
- logger.debug(
- `GET ${url} [${res.statusCode}] ${Math.ceil(
- partialResult.content.length / 1024
- )} kB${!storeLock ? " no-cache" : ""}`
- );
- }
- const result = {
- ...partialResult,
- fresh: true,
- storeLock,
- storeCache,
- validUntil,
- etag
- };
- if (!storeCache) {
- logger.log(
- `${url} can't be stored in cache, due to Cache-Control header: ${cacheControl}`
- );
- return callback(null, result);
- }
- cache.store(
- url,
- null,
- {
- ...result,
- fresh: false
- },
- err => {
- if (err) {
- logger.warn(
- `${url} can't be stored in cache: ${err.message}`
- );
- logger.debug(err.stack);
- }
- callback(null, result);
- }
- );
- };
- if (res.statusCode === 304) {
- if (
- cachedResult.validUntil < validUntil ||
- cachedResult.storeLock !== storeLock ||
- cachedResult.storeCache !== storeCache ||
- cachedResult.etag !== etag
- ) {
- return finishWith(cachedResult);
- } else {
- logger.debug(`GET ${url} [${res.statusCode}] (unchanged)`);
- return callback(null, {
- ...cachedResult,
- fresh: true
- });
- }
- }
- if (
- location &&
- res.statusCode >= 301 &&
- res.statusCode <= 308
- ) {
- const result = {
- location: new URL(location, url).href
- };
- if (
- !cachedResult ||
- !("location" in cachedResult) ||
- cachedResult.location !== result.location ||
- cachedResult.validUntil < validUntil ||
- cachedResult.storeLock !== storeLock ||
- cachedResult.storeCache !== storeCache ||
- cachedResult.etag !== etag
- ) {
- return finishWith(result);
- } else {
- logger.debug(`GET ${url} [${res.statusCode}] (unchanged)`);
- return callback(null, {
- ...result,
- fresh: true,
- storeLock,
- storeCache,
- validUntil,
- etag
- });
- }
- }
- const contentType = res.headers["content-type"] || "";
- const bufferArr = [];
- const contentEncoding = res.headers["content-encoding"];
- let stream = res;
- if (contentEncoding === "gzip") {
- stream = stream.pipe(createGunzip());
- } else if (contentEncoding === "br") {
- stream = stream.pipe(createBrotliDecompress());
- } else if (contentEncoding === "deflate") {
- stream = stream.pipe(createInflate());
- }
- stream.on("data", chunk => {
- bufferArr.push(chunk);
- });
- stream.on("end", () => {
- if (!res.complete) {
- logger.log(`GET ${url} [${res.statusCode}] (terminated)`);
- return callback(new Error(`${url} request was terminated`));
- }
- const content = Buffer.concat(bufferArr);
- if (res.statusCode !== 200) {
- logger.log(`GET ${url} [${res.statusCode}]`);
- return callback(
- new Error(
- `${url} request status code = ${
- res.statusCode
- }\n${content.toString("utf-8")}`
- )
- );
- }
- const integrity = computeIntegrity(content);
- const entry = { resolved: url, integrity, contentType };
- finishWith({
- entry,
- content
- });
- });
- }
- ).on("error", err => {
- logger.log(`GET ${url} (error)`);
- err.message += `\nwhile fetching ${url}`;
- callback(err);
- });
- };
- const fetchContent = cachedWithKey(
-
- (url, callback) => {
- cache.get(url, null, (err, cachedResult) => {
- if (err) return callback(err);
- if (cachedResult) {
- const isValid = cachedResult.validUntil >= Date.now();
- if (isValid) return callback(null, cachedResult);
- }
- fetchContentRaw(url, cachedResult, callback);
- });
- },
- (url, callback) => fetchContentRaw(url, undefined, callback)
- );
- const isAllowed = uri => {
- for (const allowed of allowedUris) {
- if (typeof allowed === "string") {
- if (uri.startsWith(allowed)) return true;
- } else if (typeof allowed === "function") {
- if (allowed(uri)) return true;
- } else {
- if (allowed.test(uri)) return true;
- }
- }
- return false;
- };
- const getInfo = cachedWithKey(
-
- (url, callback) => {
- if (!isAllowed(url)) {
- return callback(
- new Error(
- `${url} doesn't match the allowedUris policy. These URIs are allowed:\n${allowedUris
- .map(uri => ` - ${uri}`)
- .join("\n")}`
- )
- );
- }
- getLockfile((err, lockfile) => {
- if (err) return callback(err);
- const entryOrString = lockfile.entries.get(url);
- if (!entryOrString) {
- if (frozen) {
- return callback(
- new Error(
- `${url} has no lockfile entry and lockfile is frozen`
- )
- );
- }
- resolveContent(url, null, (err, result) => {
- if (err) return callback(err);
- storeResult(lockfile, url, result, callback);
- });
- return;
- }
- if (typeof entryOrString === "string") {
- const entryTag = entryOrString;
- resolveContent(url, null, (err, result) => {
- if (err) return callback(err);
- if (!result.storeLock || entryTag === "ignore")
- return callback(null, result);
- if (frozen) {
- return callback(
- new Error(
- `${url} used to have ${entryTag} lockfile entry and has content now, but lockfile is frozen`
- )
- );
- }
- if (!upgrade) {
- return callback(
- new Error(
- `${url} used to have ${entryTag} lockfile entry and has content now.
- This should be reflected in the lockfile, so this lockfile entry must be upgraded, but upgrading is not enabled.
- Remove this line from the lockfile to force upgrading.`
- )
- );
- }
- storeResult(lockfile, url, result, callback);
- });
- return;
- }
- let entry = entryOrString;
- const doFetch = lockedContent => {
- resolveContent(url, entry.integrity, (err, result) => {
- if (err) {
- if (lockedContent) {
- logger.warn(
- `Upgrade request to ${url} failed: ${err.message}`
- );
- logger.debug(err.stack);
- return callback(null, {
- entry,
- content: lockedContent
- });
- }
- return callback(err);
- }
- if (!result.storeLock) {
- // When the lockfile entry should be no-cache
- // we need to update the lockfile
- if (frozen) {
- return callback(
- new Error(
- `${url} has a lockfile entry and is no-cache now, but lockfile is frozen\nLockfile: ${entryToString(
- entry
- )}`
- )
- );
- }
- storeResult(lockfile, url, result, callback);
- return;
- }
- if (!areLockfileEntriesEqual(result.entry, entry)) {
- // When the lockfile entry is outdated
- // we need to update the lockfile
- if (frozen) {
- return callback(
- new Error(
- `${url} has an outdated lockfile entry, but lockfile is frozen\nLockfile: ${entryToString(
- entry
- )}\nExpected: ${entryToString(result.entry)}`
- )
- );
- }
- storeResult(lockfile, url, result, callback);
- return;
- }
- if (!lockedContent && cacheLocation) {
- // When the lockfile cache content is missing
- // we need to update the lockfile
- if (frozen) {
- return callback(
- new Error(
- `${url} is missing content in the lockfile cache, but lockfile is frozen\nLockfile: ${entryToString(
- entry
- )}`
- )
- );
- }
- storeResult(lockfile, url, result, callback);
- return;
- }
- return callback(null, result);
- });
- };
- if (cacheLocation) {
- // When there is a lockfile cache
- // we read the content from there
- const key = getCacheKey(entry.resolved);
- const filePath = join(intermediateFs, cacheLocation, key);
- fs.readFile(filePath, (err, result) => {
- const content = /** @type {Buffer} */ (result);
- if (err) {
- if (err.code === "ENOENT") return doFetch();
- return callback(err);
- }
- const continueWithCachedContent = result => {
- if (!upgrade) {
- // When not in upgrade mode, we accept the result from the lockfile cache
- return callback(null, { entry, content });
- }
- return doFetch(content);
- };
- if (!verifyIntegrity(content, entry.integrity)) {
- let contentWithChangedEol;
- let isEolChanged = false;
- try {
- contentWithChangedEol = Buffer.from(
- content.toString("utf-8").replace(/\r\n/g, "\n")
- );
- isEolChanged = verifyIntegrity(
- contentWithChangedEol,
- entry.integrity
- );
- } catch (e) {
- // ignore
- }
- if (isEolChanged) {
- if (!warnedAboutEol) {
- const explainer = `Incorrect end of line sequence was detected in the lockfile cache.
- The lockfile cache is protected by integrity checks, so any external modification will lead to a corrupted lockfile cache.
- When using git make sure to configure .gitattributes correctly for the lockfile cache:
- **
|