0
Fork 0
mirror of https://github.com/verdaccio/verdaccio.git synced 2025-01-06 22:40:26 -05:00

chore: migrate vitest packages (#4780)

* chore: migrate api package

* Update distTag.spec.ts

* fix storage test

* Update server.ts

* migrate search package

* chore: migrate plugin local-storage
This commit is contained in:
Juan Picado 2024-08-04 20:17:02 +02:00 committed by GitHub
parent 1f75a416f2
commit 06f68eb0e7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
31 changed files with 229 additions and 230 deletions

View file

@ -1,3 +0,0 @@
const config = require('../../jest/config');
module.exports = Object.assign({}, config, {});

View file

@ -29,7 +29,7 @@
}, },
"scripts": { "scripts": {
"clean": "rimraf ./build", "clean": "rimraf ./build",
"test": "jest", "test": "vitest run",
"type-check": "tsc --noEmit -p tsconfig.build.json", "type-check": "tsc --noEmit -p tsconfig.build.json",
"build:types": "tsc --emitDeclarationOnly -p tsconfig.build.json", "build:types": "tsc --emitDeclarationOnly -p tsconfig.build.json",
"build:js": "babel src/ --out-dir build/ --copy-files --extensions \".ts,.tsx\" --source-maps", "build:js": "babel src/ --out-dir build/ --copy-files --extensions \".ts,.tsx\" --source-maps",

View file

@ -2,6 +2,7 @@ import { Application } from 'express';
import _ from 'lodash'; import _ from 'lodash';
import path from 'path'; import path from 'path';
import supertest from 'supertest'; import supertest from 'supertest';
import { expect } from 'vitest';
import { parseConfigFile } from '@verdaccio/config'; import { parseConfigFile } from '@verdaccio/config';
import { HEADERS, HEADER_TYPE, HTTP_STATUS, TOKEN_BEARER } from '@verdaccio/core'; import { HEADERS, HEADER_TYPE, HTTP_STATUS, TOKEN_BEARER } from '@verdaccio/core';

View file

@ -1,4 +1,5 @@
import supertest from 'supertest'; import supertest from 'supertest';
import { beforeEach, describe, expect, test } from 'vitest';
import { API_MESSAGE, HEADERS, HEADER_TYPE, HTTP_STATUS } from '@verdaccio/core'; import { API_MESSAGE, HEADERS, HEADER_TYPE, HTTP_STATUS } from '@verdaccio/core';

View file

@ -1,5 +1,6 @@
/* eslint-disable jest/no-commented-out-tests */ /* eslint-disable jest/no-commented-out-tests */
import nock from 'nock'; import nock from 'nock';
import { describe, expect, test } from 'vitest';
import { HTTP_STATUS } from '@verdaccio/core'; import { HTTP_STATUS } from '@verdaccio/core';

View file

@ -1,4 +1,5 @@
import supertest from 'supertest'; import supertest from 'supertest';
import { beforeEach, describe, expect, test } from 'vitest';
import { DIST_TAGS, HEADERS, HEADER_TYPE, HTTP_STATUS } from '@verdaccio/core'; import { DIST_TAGS, HEADERS, HEADER_TYPE, HTTP_STATUS } from '@verdaccio/core';
import { Storage } from '@verdaccio/store'; import { Storage } from '@verdaccio/store';

View file

@ -1,4 +1,5 @@
import supertest from 'supertest'; import supertest from 'supertest';
import { describe, expect, test } from 'vitest';
import { HEADERS, HEADER_TYPE, HTTP_STATUS } from '@verdaccio/core'; import { HEADERS, HEADER_TYPE, HTTP_STATUS } from '@verdaccio/core';

View file

@ -1,4 +1,5 @@
import supertest from 'supertest'; import supertest from 'supertest';
import { describe, test } from 'vitest';
import { HEADERS, HEADER_TYPE, HTTP_STATUS, TOKEN_BEARER } from '@verdaccio/core'; import { HEADERS, HEADER_TYPE, HTTP_STATUS, TOKEN_BEARER } from '@verdaccio/core';
import { buildToken } from '@verdaccio/utils'; import { buildToken } from '@verdaccio/utils';

View file

@ -1,6 +1,7 @@
import nock from 'nock'; import nock from 'nock';
import { basename } from 'path'; import { basename } from 'path';
import supertest from 'supertest'; import supertest from 'supertest';
import { describe, expect, test } from 'vitest';
import { HTTP_STATUS } from '@verdaccio/core'; import { HTTP_STATUS } from '@verdaccio/core';
import { API_ERROR, API_MESSAGE, HEADERS, HEADER_TYPE } from '@verdaccio/core'; import { API_ERROR, API_MESSAGE, HEADERS, HEADER_TYPE } from '@verdaccio/core';

View file

@ -1,5 +1,6 @@
import MockDate from 'mockdate'; import MockDate from 'mockdate';
import supertest from 'supertest'; import supertest from 'supertest';
import { beforeEach, describe, expect, test } from 'vitest';
import { HEADERS, HEADER_TYPE, HTTP_STATUS } from '@verdaccio/core'; import { HEADERS, HEADER_TYPE, HTTP_STATUS } from '@verdaccio/core';

View file

@ -1,5 +1,6 @@
import nock from 'nock'; import nock from 'nock';
import supertest from 'supertest'; import supertest from 'supertest';
import { describe, expect, test } from 'vitest';
import { HTTP_STATUS } from '@verdaccio/core'; import { HTTP_STATUS } from '@verdaccio/core';
import { HEADERS, HEADER_TYPE } from '@verdaccio/core'; import { HEADERS, HEADER_TYPE } from '@verdaccio/core';

View file

@ -1,5 +1,6 @@
import _ from 'lodash'; import _ from 'lodash';
import supertest from 'supertest'; import supertest from 'supertest';
import { describe, expect, test } from 'vitest';
import { import {
API_ERROR, API_ERROR,

View file

@ -1,4 +1,5 @@
import supertest from 'supertest'; import supertest from 'supertest';
import { describe, expect, test, vi } from 'vitest';
import { API_ERROR, HEADERS, HEADER_TYPE, HTTP_STATUS, TOKEN_BEARER } from '@verdaccio/core'; import { API_ERROR, HEADERS, HEADER_TYPE, HTTP_STATUS, TOKEN_BEARER } from '@verdaccio/core';
import { buildToken } from '@verdaccio/utils'; import { buildToken } from '@verdaccio/utils';
@ -7,7 +8,7 @@ import { createUser, getPackage, initializeServer } from './_helper';
const FORBIDDEN_VUE = 'authorization required to access package vue'; const FORBIDDEN_VUE = 'authorization required to access package vue';
jest.setTimeout(20000); vi.setConfig({ testTimeout: 20000 });
describe('token', () => { describe('token', () => {
describe('basics', () => { describe('basics', () => {

View file

@ -1,4 +1,5 @@
import supertest from 'supertest'; import supertest from 'supertest';
import { describe, expect, test } from 'vitest';
import { HEADERS, HTTP_STATUS, TOKEN_BEARER } from '@verdaccio/core'; import { HEADERS, HTTP_STATUS, TOKEN_BEARER } from '@verdaccio/core';
import { buildToken } from '@verdaccio/utils'; import { buildToken } from '@verdaccio/utils';

View file

@ -2,6 +2,7 @@
// ensure that all arguments are validated // ensure that all arguments are validated
import fs from 'fs'; import fs from 'fs';
import path from 'path'; import path from 'path';
import { describe, expect, test } from 'vitest';
/** /**
* Validate. * Validate.

View file

@ -1,10 +0,0 @@
const config = require('../../../jest/config');
module.exports = Object.assign({}, config, {
coverageThreshold: {
global: {
// FIXME: increase to 90
lines: 51,
},
},
});

View file

@ -58,7 +58,7 @@
}, },
"scripts": { "scripts": {
"clean": "rimraf ./build", "clean": "rimraf ./build",
"test": "jest --runInBand", "test": "vitest run",
"type-check": "tsc --noEmit -p tsconfig.build.json", "type-check": "tsc --noEmit -p tsconfig.build.json",
"build:types": "tsc --emitDeclarationOnly -p tsconfig.build.json", "build:types": "tsc --emitDeclarationOnly -p tsconfig.build.json",
"build:js": "babel src/ --out-dir build/ --copy-files --extensions \".ts,.tsx\" --source-maps", "build:js": "babel src/ --out-dir build/ --copy-files --extensions \".ts,.tsx\" --source-maps",

View file

@ -1,4 +1,5 @@
import { join } from 'path'; import { join } from 'path';
import { describe, expect, test } from 'vitest';
import { getFolders, searchOnStorage } from '../src/dir-utils'; import { getFolders, searchOnStorage } from '../src/dir-utils';

View file

@ -1,22 +1,23 @@
/* eslint-disable jest/no-mocks-import */ /* eslint-disable jest/no-mocks-import */
import path from 'path'; import path from 'path';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { fileUtils, pluginUtils } from '@verdaccio/core'; import { fileUtils, pluginUtils } from '@verdaccio/core';
import { logger, setup } from '@verdaccio/logger'; import { logger, setup } from '@verdaccio/logger';
import LocalDatabase, { ERROR_DB_LOCKED } from '../src/local-database'; import LocalDatabase, { ERROR_DB_LOCKED } from '../src/local-database';
const mockWrite = jest.fn(() => Promise.resolve()); const mockWrite = vi.fn(() => Promise.resolve());
const mockmkdir = jest.fn(() => Promise.resolve()); const mockmkdir = vi.fn(() => Promise.resolve());
const mockRead = jest.fn(() => Promise.resolve()); const mockRead = vi.fn(() => Promise.resolve());
jest.mock('../src/fs', () => ({ vi.mock('../src/fs', () => ({
mkdirPromise: () => mockRead(), mkdirPromise: () => mockRead(),
readFilePromise: () => mockmkdir(), readFilePromise: () => mockmkdir(),
writeFilePromise: () => mockWrite(), writeFilePromise: () => mockWrite(),
})); }));
setup(); setup({});
const optionsPlugin: pluginUtils.PluginOptions = { const optionsPlugin: pluginUtils.PluginOptions = {
logger, logger,
@ -31,7 +32,6 @@ describe('Local Database', () => {
beforeEach(async () => { beforeEach(async () => {
tmpFolder = await fileUtils.createTempFolder('local-storage-plugin-'); tmpFolder = await fileUtils.createTempFolder('local-storage-plugin-');
const tempFolder = path.join(tmpFolder, 'verdaccio-test.yaml'); const tempFolder = path.join(tmpFolder, 'verdaccio-test.yaml');
// @ts-expect-error
locaDatabase = new LocalDatabase( locaDatabase = new LocalDatabase(
// @ts-expect-error // @ts-expect-error
{ {
@ -46,8 +46,8 @@ describe('Local Database', () => {
}); });
afterEach(() => { afterEach(() => {
jest.resetAllMocks(); vi.resetAllMocks();
jest.clearAllMocks(); vi.clearAllMocks();
}); });
test('should create an instance', () => { test('should create an instance', () => {

View file

@ -1,10 +1,11 @@
import fs from 'fs'; import fs from 'fs';
import path from 'path'; import path from 'path';
import { Readable } from 'stream'; import { Readable } from 'stream';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import { fileUtils } from '@verdaccio/core'; import { fileUtils } from '@verdaccio/core';
import { createTempFolder } from '@verdaccio/test-helper'; import { createTempFolder } from '@verdaccio/test-helper';
import { ILocalPackageManager, Logger, Manifest } from '@verdaccio/types'; import { Logger, Manifest } from '@verdaccio/types';
import LocalDriver from '../src/local-fs'; import LocalDriver from '../src/local-fs';
import pkg from './__fixtures__/pkg'; import pkg from './__fixtures__/pkg';
@ -21,15 +22,17 @@ function checkFileExists(filepath) {
} }
const logger: Logger = { const logger: Logger = {
error: jest.fn(), error: vi.fn(),
info: jest.fn(), info: vi.fn(),
debug: jest.fn(), debug: vi.fn(),
child: jest.fn(), child: vi.fn(),
warn: jest.fn(), warn: vi.fn(),
http: jest.fn(), http: vi.fn(),
trace: jest.fn(), trace: vi.fn(),
}; };
vi.setConfig({ testTimeout: 20000 });
describe('Local FS test', () => { describe('Local FS test', () => {
let tmpFolder; let tmpFolder;
beforeEach(async () => { beforeEach(async () => {
@ -40,7 +43,7 @@ describe('Local FS test', () => {
describe.skip('deletePackage() group', () => { describe.skip('deletePackage() group', () => {
test('should delete a package', async () => { test('should delete a package', async () => {
const localFs = new LocalDriver(path.join(localTempStorage, 'createPackage'), logger); const localFs = new LocalDriver(path.join(localTempStorage, 'createPackage'), logger);
await localFs.createPackag('createPackage', pkg as unknown as Manifest); await localFs.createPackage('createPackage', pkg as unknown as Manifest);
// verdaccio removes the package.json instead the package name // verdaccio removes the package.json instead the package name
await localFs.deletePackage('package.json'); await localFs.deletePackage('package.json');
// verify if the `package.json` does not exist anymore // verify if the `package.json` does not exist anymore
@ -60,25 +63,20 @@ describe('Local FS test', () => {
}); });
test('should successfully remove the package', async () => { test('should successfully remove the package', async () => {
const localFs: ILocalPackageManager = new LocalDriver( const localFs = new LocalDriver(path.join(localTempStorage, '_toDelete'), logger);
path.join(localTempStorage, '_toDelete'),
logger
);
await expect(localFs.removePackage()).resolves.toBeUndefined(); await expect(localFs.removePackage()).resolves.toBeUndefined();
}); });
test('removePackage() fails', async () => { test('removePackage() fails', async () => {
const localFs: ILocalPackageManager = new LocalDriver( const localFs = new LocalDriver(path.join(localTempStorage, '_toDelete_fake'), logger);
path.join(localTempStorage, '_toDelete_fake'),
logger
);
await expect(localFs.removePackage()).rejects.toThrow(/ENOENT/); await expect(localFs.removePackage()).rejects.toThrow(/ENOENT/);
}); });
}); });
describe('writeTarballNext', () => { describe('writeTarballNext', () => {
test('should write a tarball', (done) => { test('should write a tarball', () =>
new Promise((done) => {
const abort = new AbortController(); const abort = new AbortController();
const tmp = createTempFolder('local-fs-write-tarball'); const tmp = createTempFolder('local-fs-write-tarball');
const localFs = new LocalDriver(tmp, logger); const localFs = new LocalDriver(tmp, logger);
@ -86,30 +84,32 @@ describe('Local FS test', () => {
// TODO: verify file exist // TODO: verify file exist
localFs.writeTarball('juan-1.0.0.tgz', { signal: abort.signal }).then((stream) => { localFs.writeTarball('juan-1.0.0.tgz', { signal: abort.signal }).then((stream) => {
stream.on('finish', () => { stream.on('finish', () => {
done(); done(true);
}); });
readableStream.pipe(stream); readableStream.pipe(stream);
}); });
}); }));
}); });
describe('writeTarballNextNoFolder', () => { describe('writeTarballNextNoFolder', () => {
test('should write a tarball even if folder does not exist', (done) => { test('should write a tarball even if folder does not exist', () =>
new Promise((done) => {
const abort = new AbortController(); const abort = new AbortController();
const tmp = path.join(localTempStorage, 'local-fs-write-tarball-new-folder'); const tmp = path.join(localTempStorage, 'local-fs-write-tarball-new-folder');
const localFs = new LocalDriver(tmp, logger); const localFs = new LocalDriver(tmp, logger);
const readableStream = Readable.from('foooo'); const readableStream = Readable.from('foooo');
localFs.writeTarball('juan-1.0.0.tgz', { signal: abort.signal }).then((stream) => { localFs.writeTarball('juan-1.0.0.tgz', { signal: abort.signal }).then((stream) => {
stream.on('finish', () => { stream.on('finish', () => {
done(); done(true);
}); });
readableStream.pipe(stream); readableStream.pipe(stream);
}); });
}); }));
}); });
describe('readTarballNext', () => { describe('readTarballNext', () => {
test('should read a tarball', (done) => { test('should read a tarball', () =>
new Promise((done) => {
const abort = new AbortController(); const abort = new AbortController();
const localFs = new LocalDriver( const localFs = new LocalDriver(
path.join(__dirname, '__fixtures__/readme-test-next'), path.join(__dirname, '__fixtures__/readme-test-next'),
@ -120,12 +120,13 @@ describe('Local FS test', () => {
expect(data.length).toEqual(352); expect(data.length).toEqual(352);
}); });
stream.on('end', () => { stream.on('end', () => {
done(); done(true);
});
}); });
}); });
}));
test('should abort read a tarball', (done) => { test('should abort read a tarball', () =>
new Promise((done) => {
const abort = new AbortController(); const abort = new AbortController();
const localFs = new LocalDriver( const localFs = new LocalDriver(
path.join(__dirname, '__fixtures__/readme-test-next'), path.join(__dirname, '__fixtures__/readme-test-next'),
@ -136,13 +137,14 @@ describe('Local FS test', () => {
// FIXME: might be different results sometimes, need research // FIXME: might be different results sometimes, need research
// expect(error.code).toEqual('ABORT_ERR'); // expect(error.code).toEqual('ABORT_ERR');
expect(error).toBeDefined(); expect(error).toBeDefined();
done(); done(true);
}); });
abort.abort(); abort.abort();
}); });
}); }));
test('fails on read a tarball doex not exist', (done) => { test('fails on read a tarball doex not exist', () =>
new Promise((done) => {
const abort = new AbortController(); const abort = new AbortController();
const localFs = new LocalDriver( const localFs = new LocalDriver(
@ -152,12 +154,13 @@ describe('Local FS test', () => {
localFs.readTarball('does-not-exist-0.0.0.tgz', { signal: abort.signal }).then((stream) => { localFs.readTarball('does-not-exist-0.0.0.tgz', { signal: abort.signal }).then((stream) => {
stream.on('error', (error: any) => { stream.on('error', (error: any) => {
expect(error.code).toEqual('ENOENT'); expect(error.code).toEqual('ENOENT');
done(); done(true);
});
}); });
}); });
}));
test('should return content-length', (done) => { test('should return content-length', () =>
new Promise((done) => {
const localFs = new LocalDriver( const localFs = new LocalDriver(
path.join(__dirname, '__fixtures__/readme-test-next'), path.join(__dirname, '__fixtures__/readme-test-next'),
logger logger
@ -170,9 +173,9 @@ describe('Local FS test', () => {
stream.on('content-length', (content) => { stream.on('content-length', (content) => {
expect(content).toEqual(352); expect(content).toEqual(352);
done(); done(true);
}); });
}); });
}, 100000); }));
}); });
}); });

View file

@ -1,6 +1,7 @@
/* eslint-disable jest/no-mocks-import */ /* eslint-disable jest/no-mocks-import */
import fs from 'fs'; import fs from 'fs';
import path from 'path'; import path from 'path';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { fileUtils } from '@verdaccio/core'; import { fileUtils } from '@verdaccio/core';
import { Logger, Token } from '@verdaccio/types'; import { Logger, Token } from '@verdaccio/types';
@ -8,13 +9,13 @@ import { Logger, Token } from '@verdaccio/types';
import LocalDatabase from '../src/local-database'; import LocalDatabase from '../src/local-database';
const logger: Logger = { const logger: Logger = {
error: jest.fn(), error: vi.fn(),
info: jest.fn(), info: vi.fn(),
debug: jest.fn(), debug: vi.fn(),
child: jest.fn(), child: vi.fn(),
warn: jest.fn(), warn: vi.fn(),
http: jest.fn(), http: vi.fn(),
trace: jest.fn(), trace: vi.fn(),
}; };
describe('Local Database', () => { describe('Local Database', () => {
@ -23,7 +24,7 @@ describe('Local Database', () => {
beforeEach(async () => { beforeEach(async () => {
tmpFolder = await fileUtils.createTempFolder('local-storage-plugin-'); tmpFolder = await fileUtils.createTempFolder('local-storage-plugin-');
const tempFolder = path.join(tmpFolder, 'verdaccio-test.yaml'); const tempFolder = path.join(tmpFolder, 'verdaccio-test.yaml');
const writeMock = jest.spyOn(fs, 'writeFileSync').mockImplementation(); const writeMock = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {});
locaDatabase = new LocalDatabase( // @ts-expect-error locaDatabase = new LocalDatabase( // @ts-expect-error
{ {
storage: 'storage', storage: 'storage',
@ -38,7 +39,7 @@ describe('Local Database', () => {
}); });
afterEach(() => { afterEach(() => {
jest.clearAllMocks(); vi.clearAllMocks();
}); });
describe('token', () => { describe('token', () => {

View file

@ -1,4 +1,5 @@
import path from 'path'; import path from 'path';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import { Logger } from '@verdaccio/types'; import { Logger } from '@verdaccio/types';
@ -8,20 +9,20 @@ import { loadPrivatePackages } from '../src/pkg-utils';
import { _dbGenPath, findPackages } from '../src/utils'; import { _dbGenPath, findPackages } from '../src/utils';
const logger: Logger = { const logger: Logger = {
error: jest.fn(), error: vi.fn(),
info: jest.fn(), info: vi.fn(),
debug: jest.fn(), debug: vi.fn(),
child: jest.fn(), child: vi.fn(),
warn: jest.fn(), warn: vi.fn(),
http: jest.fn(), http: vi.fn(),
trace: jest.fn(), trace: vi.fn(),
}; };
describe('Utitlies', () => { describe('Utitlies', () => {
const loadDb = (name): string => path.join(__dirname, '__fixtures__/databases', `${name}.json`); const loadDb = (name): string => path.join(__dirname, '__fixtures__/databases', `${name}.json`);
beforeEach(() => { beforeEach(() => {
jest.resetModules(); vi.resetModules();
}); });
test('should load private packages', async () => { test('should load private packages', async () => {
@ -45,7 +46,7 @@ describe('Utitlies', () => {
}); });
test('should handle null read values and return empty database', async () => { test('should handle null read values and return empty database', async () => {
const spy = jest.spyOn(readFile, 'readFilePromise'); const spy = vi.spyOn(readFile, 'readFilePromise');
spy.mockResolvedValue(null); spy.mockResolvedValue(null);
const database = loadDb('ok'); const database = loadDb('ok');
const db = await loadPrivatePackages(database, logger); const db = await loadPrivatePackages(database, logger);
@ -60,7 +61,7 @@ describe('Utitlies', () => {
try { try {
await findPackages( await findPackages(
'./no_such_folder_fake', './no_such_folder_fake',
jest.fn(() => true) vi.fn(() => true)
); );
} catch (e: any) { } catch (e: any) {
expect(e.code).toEqual(noSuchFile); expect(e.code).toEqual(noSuchFile);
@ -69,7 +70,7 @@ describe('Utitlies', () => {
test('should fetch all packages from valid storage', async () => { test('should fetch all packages from valid storage', async () => {
const storage = path.join(__dirname, '__fixtures__/findPackages'); const storage = path.join(__dirname, '__fixtures__/findPackages');
const validator = jest.fn((file) => file.indexOf('.') === -1); const validator = vi.fn((file) => file.indexOf('.') === -1);
const pkgs = await findPackages(storage, validator); const pkgs = await findPackages(storage, validator);
// the result is 7 due number of packages on "findPackages" directory // the result is 7 due number of packages on "findPackages" directory
expect(pkgs).toHaveLength(5); expect(pkgs).toHaveLength(5);
@ -82,7 +83,7 @@ describe('Utitlies', () => {
expect( expect(
_dbGenPath('local.db', { _dbGenPath('local.db', {
storage: './storage', storage: './storage',
config_path: '/etc/foo/config.yaml', configPath: '/etc/foo/config.yaml',
}) })
).toMatch('local.db'); ).toMatch('local.db');
}); });
@ -91,7 +92,7 @@ describe('Utitlies', () => {
expect( expect(
_dbGenPath('local.db', { _dbGenPath('local.db', {
storage: '', storage: '',
config_path: '/etc/foo/config.yaml', configPath: '/etc/foo/config.yaml',
}) })
).toMatch('local.db'); ).toMatch('local.db');
}); });
@ -100,7 +101,7 @@ describe('Utitlies', () => {
expect( expect(
_dbGenPath('local.db', { _dbGenPath('local.db', {
storage: '', storage: '',
config_path: '/etc/foo/config.yaml', configPath: '/etc/foo/config.yaml',
}) })
).toMatch('local.db'); ).toMatch('local.db');
}); });
@ -109,7 +110,8 @@ describe('Utitlies', () => {
expect( expect(
_dbGenPath('local.db', { _dbGenPath('local.db', {
storage: './storage', storage: './storage',
config_path: undefined, // @ts-expect-error
configPath: undefined,
}) })
).toMatch('local.db'); ).toMatch('local.db');
}); });

View file

@ -1,11 +0,0 @@
const config = require('../../jest/config');
module.exports = Object.assign({}, config, {
coverageThreshold: {
global: {
branches: 0,
functions: 0,
lines: 0,
},
},
});

View file

@ -30,7 +30,7 @@
}, },
"scripts": { "scripts": {
"clean": "rimraf ./build", "clean": "rimraf ./build",
"test": "jest", "test": "vitest run",
"type-check": "tsc --noEmit -p tsconfig.build.json", "type-check": "tsc --noEmit -p tsconfig.build.json",
"build:types": "tsc --emitDeclarationOnly -p tsconfig.build.json", "build:types": "tsc --emitDeclarationOnly -p tsconfig.build.json",
"build:js": "babel src/ --out-dir build/ --copy-files --extensions \".ts,.tsx\" --source-maps", "build:js": "babel src/ --out-dir build/ --copy-files --extensions \".ts,.tsx\" --source-maps",

View file

@ -1,4 +1,5 @@
import nock from 'nock'; import nock from 'nock';
import { describe, expect, test } from 'vitest';
import { Config, getDefaultConfig } from '@verdaccio/config'; import { Config, getDefaultConfig } from '@verdaccio/config';
import { logger, setup } from '@verdaccio/logger'; import { logger, setup } from '@verdaccio/logger';

View file

@ -144,7 +144,7 @@ export default (async function startServer(configHash: ConfigYaml): Promise<any>
// register middleware plugins // register middleware plugins
debug('loaded filter plugin'); debug('loaded filter plugin');
// @ts-ignore // @ts-ignore
const storage: Storage = new Storage(config); const storage: Storage = new Storage(config, logger);
try { try {
// waits until init calls have been initialized // waits until init calls have been initialized
debug('storage init start'); debug('storage init start');

View file

@ -1,13 +1,14 @@
import { FastifyInstance } from 'fastify'; import { FastifyInstance } from 'fastify';
import fp from 'fastify-plugin'; import fp from 'fastify-plugin';
import { logger } from '@verdaccio/logger';
import { Storage } from '@verdaccio/store'; import { Storage } from '@verdaccio/store';
import { Config as IConfig } from '@verdaccio/types'; import { Config as IConfig } from '@verdaccio/types';
export default fp( export default fp(
async function (fastify: FastifyInstance, opts: { config: IConfig; filters?: unknown }) { async function (fastify: FastifyInstance, opts: { config: IConfig; filters?: unknown }) {
const { config } = opts; const { config } = opts;
const storage: Storage = new Storage(config); const storage: Storage = new Storage(config, logger);
// @ts-ignore // @ts-ignore
await storage.init(config, []); await storage.init(config, []);
fastify.decorate('storage', storage); fastify.decorate('storage', storage);

View file

@ -24,7 +24,6 @@ import {
validatioUtils, validatioUtils,
} from '@verdaccio/core'; } from '@verdaccio/core';
import { asyncLoadPlugin } from '@verdaccio/loaders'; import { asyncLoadPlugin } from '@verdaccio/loaders';
import { logger } from '@verdaccio/logger';
import { import {
IProxy, IProxy,
ISyncUplinksOptions, ISyncUplinksOptions,
@ -101,7 +100,7 @@ class Storage {
public readonly logger: Logger; public readonly logger: Logger;
public readonly uplinks: ProxyInstanceList; public readonly uplinks: ProxyInstanceList;
private searchService: Search; private searchService: Search;
public constructor(config: Config) { public constructor(config: Config, logger: Logger) {
this.config = config; this.config = config;
this.logger = logger.child({ module: 'storage' }); this.logger = logger.child({ module: 'storage' });
this.uplinks = setupUpLinks(config, this.logger); this.uplinks = setupUpLinks(config, this.logger);
@ -501,7 +500,7 @@ class Storage {
try { try {
await this.checkAllowedToChangePackage(manifest, options.requestOptions.username); await this.checkAllowedToChangePackage(manifest, options.requestOptions.username);
} catch (error: any) { } catch (error: any) {
logger.error({ error: error.message }, 'getting package has failed: @{error}'); this.logger.error({ error: error.message }, 'getting package has failed: @{error}');
throw errorUtils.getBadRequest(error.message); throw errorUtils.getBadRequest(error.message);
} }
} }
@ -647,7 +646,7 @@ class Storage {
*/ */
public async init(config: Config): Promise<void> { public async init(config: Config): Promise<void> {
if (this.localStorage === null) { if (this.localStorage === null) {
this.localStorage = new LocalStorage(this.config, logger); this.localStorage = new LocalStorage(this.config, this.logger);
await this.localStorage.init(); await this.localStorage.init();
debug('local init storage initialized'); debug('local init storage initialized');
await this.localStorage.getSecret(config); await this.localStorage.getSecret(config);
@ -713,13 +712,13 @@ class Storage {
return results; return results;
} }
logger.info( this.logger.info(
{ t: query.text, q: query.quality, p: query.popularity, m: query.maintenance, s: query.size }, { t: query.text, q: query.quality, p: query.popularity, m: query.maintenance, s: query.size },
'search by text @{t}| maintenance @{m}| quality @{q}| popularity @{p}' 'search by text @{t}| maintenance @{m}| quality @{q}| popularity @{p}'
); );
if (typeof this.localStorage.getStoragePlugin().search === 'undefined') { if (typeof this.localStorage.getStoragePlugin().search === 'undefined') {
logger.info('plugin search not implemented yet'); this.logger.info('plugin search not implemented yet');
} else { } else {
debug('search on each package by plugin query'); debug('search on each package by plugin query');
const items = await this.localStorage.getStoragePlugin().search(query); const items = await this.localStorage.getStoragePlugin().search(query);
@ -768,10 +767,10 @@ class Storage {
manifest = normalizePackage(manifest); manifest = normalizePackage(manifest);
} catch (err: any) { } catch (err: any) {
if (err.code === STORAGE.NO_SUCH_FILE_ERROR || err.code === HTTP_STATUS.NOT_FOUND) { if (err.code === STORAGE.NO_SUCH_FILE_ERROR || err.code === HTTP_STATUS.NOT_FOUND) {
logger.info({ pkgName, revision }, 'package not found'); this.logger.info({ pkgName, revision }, 'package not found');
throw errorUtils.getNotFound(); throw errorUtils.getNotFound();
} }
logger.error( this.logger.error(
{ pkgName, revision, err: err.message }, { pkgName, revision, err: err.message },
'error @{err} while reading package @{pkgName}-{revision}' 'error @{err} while reading package @{pkgName}-{revision}'
); );
@ -790,7 +789,7 @@ class Storage {
for (let attachment of attachments) { for (let attachment of attachments) {
debug('remove attachment %s', attachment); debug('remove attachment %s', attachment);
await storage.deletePackage(attachment); await storage.deletePackage(attachment);
logger.info({ attachment }, 'attachment @{attachment} removed'); this.logger.info({ attachment }, 'attachment @{attachment} removed');
} }
// remove package.json // remove package.json
debug('remove package.json'); debug('remove package.json');
@ -798,7 +797,7 @@ class Storage {
// remove folder // remove folder
debug('remove package folder'); debug('remove package folder');
await storage.removePackage(); await storage.removePackage();
logger.info({ pkgName }, 'package @{pkgName} removed'); this.logger.info({ pkgName }, 'package @{pkgName} removed');
} catch (err: any) { } catch (err: any) {
this.logger.error({ err }, 'removed package has failed @{err.message}'); this.logger.error({ err }, 'removed package has failed @{err.message}');
throw errorUtils.getBadData(err.message); throw errorUtils.getBadData(err.message);
@ -897,7 +896,7 @@ class Storage {
cache: true, cache: true,
}, },
this.config, this.config,
logger this.logger
); );
} }
return uplink; return uplink;
@ -944,14 +943,14 @@ class Storage {
try { try {
const { name } = mergedManifest; const { name } = mergedManifest;
await this.notify(mergedManifest, `${name}@${version}`); await this.notify(mergedManifest, `${name}@${version}`);
logger.info({ name, version }, 'notify for @{name}@@{version} has been sent'); this.logger.info({ name, version }, 'notify for @{name}@@{version} has been sent');
} catch (error: any) { } catch (error: any) {
logger.error({ error: error.message }, 'notify batch service has failed: @{error}'); this.logger.error({ error: error.message }, 'notify batch service has failed: @{error}');
} }
return message; return message;
} else { } else {
debug('invalid body format'); debug('invalid body format');
logger.warn( this.logger.warn(
{ packageName: options.name }, { packageName: options.name },
`wrong package format on publish a package @{packageName}` `wrong package format on publish a package @{packageName}`
); );
@ -1146,7 +1145,7 @@ class Storage {
} }
} catch (err: any) { } catch (err: any) {
debug('error on change or update a package with %o', err.message); debug('error on change or update a package with %o', err.message);
logger.error({ err: err.message }, 'error on publish new version: @{err}'); this.logger.error({ err: err.message }, 'error on publish new version: @{err}');
throw err; throw err;
} }
@ -1161,7 +1160,7 @@ class Storage {
// addVersion will move the readme from the the published version to the root level // addVersion will move the readme from the the published version to the root level
await this.addVersion(name, versionToPublish, versions[versionToPublish], null, tarballStats); await this.addVersion(name, versionToPublish, versions[versionToPublish], null, tarballStats);
} catch (err: any) { } catch (err: any) {
logger.error({ err: err.message }, 'updated version has failed: @{err}'); this.logger.error({ err: err.message }, 'updated version has failed: @{err}');
debug('error on create a version for %o with error %o', name, err.message); debug('error on create a version for %o with error %o', name, err.message);
throw err; throw err;
} }
@ -1176,7 +1175,7 @@ class Storage {
// 4. update once to the storage (easy peasy) // 4. update once to the storage (easy peasy)
mergedManifest = await this.mergeTagsNext(name, manifest[DIST_TAGS]); mergedManifest = await this.mergeTagsNext(name, manifest[DIST_TAGS]);
} catch (err: any) { } catch (err: any) {
logger.error({ err: err.message }, 'merge version has failed: @{err}'); this.logger.error({ err: err.message }, 'merge version has failed: @{err}');
debug('error on create a version for %o with error %o', name, err.message); debug('error on create a version for %o with error %o', name, err.message);
// TODO: undo if this fails // TODO: undo if this fails
// 1. remove updated version // 1. remove updated version
@ -1190,14 +1189,14 @@ class Storage {
signal: options.signal, signal: options.signal,
}); });
} catch (err: any) { } catch (err: any) {
logger.error({ err: err.message }, 'upload tarball has failed: @{err}'); this.logger.error({ err: err.message }, 'upload tarball has failed: @{err}');
// TODO: undo if this fails // TODO: undo if this fails
// 1. remove updated version // 1. remove updated version
// 2. remove new dist tags // 2. remove new dist tags
throw err; throw err;
} }
logger.info( this.logger.info(
{ name, version: versionToPublish }, { name, version: versionToPublish },
'package @{name}@@{version} has been published' 'package @{name}@@{version} has been published'
); );
@ -2028,7 +2027,7 @@ class Storage {
manifest.maintainers.length > 0 && manifest.maintainers.length > 0 &&
!manifest.maintainers.some((maintainer) => maintainer.name === username) !manifest.maintainers.some((maintainer) => maintainer.name === username)
) { ) {
logger.error({ username }, '@{username} is not a maintainer (package owner)'); this.logger.error({ username }, '@{username} is not a maintainer (package owner)');
throw Error('only owners are allowed to change package'); throw Error('only owners are allowed to change package');
} }
} }

View file

@ -8,7 +8,7 @@ import { generatePackageMetadata } from '@verdaccio/test-helper';
import { Storage } from '../src'; import { Storage } from '../src';
setup({}); const logger = setup({});
describe('search', () => { describe('search', () => {
describe('search manager utils', () => { describe('search manager utils', () => {
@ -39,7 +39,7 @@ describe('search', () => {
...getDefaultConfig(), ...getDefaultConfig(),
storage: await fileUtils.createTempStorageFolder('fix-1'), storage: await fileUtils.createTempStorageFolder('fix-1'),
}); });
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const abort = new AbortController(); const abort = new AbortController();
const pkgName = 'verdaccio'; const pkgName = 'verdaccio';

View file

@ -44,7 +44,7 @@ function generateRandomStorage() {
return path.join(tempRoot, tempStorage); return path.join(tempRoot, tempStorage);
} }
setup({ type: 'stdout', format: 'pretty', level: 'trace' }); const logger = setup({ type: 'stdout', format: 'pretty', level: 'trace' });
const domain = 'https://registry.npmjs.org'; const domain = 'https://registry.npmjs.org';
const fakeHost = 'localhost:4873'; const fakeHost = 'localhost:4873';
@ -149,7 +149,7 @@ describe('storage', () => {
__dirname __dirname
) )
); );
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0'); const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0');
await storage.updateManifest(bodyNewManifest, { await storage.updateManifest(bodyNewManifest, {
@ -194,7 +194,7 @@ describe('storage', () => {
__dirname __dirname
) )
); );
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const ac = new AbortController(); const ac = new AbortController();
setTimeout(() => { setTimeout(() => {
@ -239,7 +239,7 @@ describe('storage', () => {
__dirname __dirname
) )
); );
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
// create a package // create a package
const bodyNewManifest1 = generatePackageMetadata(pkgName, '1.0.0'); const bodyNewManifest1 = generatePackageMetadata(pkgName, '1.0.0');
@ -328,7 +328,7 @@ describe('storage', () => {
__dirname __dirname
) )
); );
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const bodyNewManifest1 = generatePackageMetadata(pkgName, '1.0.0'); const bodyNewManifest1 = generatePackageMetadata(pkgName, '1.0.0');
const bodyNewManifest2 = generatePackageMetadata(pkgName, '1.0.0'); const bodyNewManifest2 = generatePackageMetadata(pkgName, '1.0.0');
@ -365,7 +365,7 @@ describe('storage', () => {
__dirname __dirname
) )
); );
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0'); const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0');
@ -395,7 +395,7 @@ describe('storage', () => {
const mockDate = '2018-01-14T11:17:40.712Z'; const mockDate = '2018-01-14T11:17:40.712Z';
MockDate.set(mockDate); MockDate.set(mockDate);
const config = getConfig('deprecate.yaml'); const config = getConfig('deprecate.yaml');
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0'); const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0');
await storage.updateManifest(bodyNewManifest, { await storage.updateManifest(bodyNewManifest, {
@ -442,7 +442,7 @@ describe('storage', () => {
const mockDate = '2018-01-14T11:17:40.712Z'; const mockDate = '2018-01-14T11:17:40.712Z';
MockDate.set(mockDate); MockDate.set(mockDate);
const config = getConfig('deprecate.yaml'); const config = getConfig('deprecate.yaml');
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
// publish new package // publish new package
const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0'); const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0');
@ -516,7 +516,7 @@ describe('storage', () => {
describe('star', () => { describe('star', () => {
test.each([['foo']])('star package %s', async (pkgName) => { test.each([['foo']])('star package %s', async (pkgName) => {
const config = getConfig('deprecate.yaml'); const config = getConfig('deprecate.yaml');
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0'); const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0');
await storage.updateManifest(bodyNewManifest, { await storage.updateManifest(bodyNewManifest, {
@ -549,7 +549,7 @@ describe('storage', () => {
const mockDate = '2018-01-14T11:17:40.712Z'; const mockDate = '2018-01-14T11:17:40.712Z';
MockDate.set(mockDate); MockDate.set(mockDate);
const config = getConfig('deprecate.yaml'); const config = getConfig('deprecate.yaml');
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0'); const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0');
await storage.updateManifest(bodyNewManifest, { await storage.updateManifest(bodyNewManifest, {
@ -591,7 +591,7 @@ describe('storage', () => {
const mockDate = '2018-01-14T11:17:40.712Z'; const mockDate = '2018-01-14T11:17:40.712Z';
MockDate.set(mockDate); MockDate.set(mockDate);
const config = getConfig('deprecate.yaml'); const config = getConfig('deprecate.yaml');
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0'); const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0');
await storage.updateManifest(bodyNewManifest, { await storage.updateManifest(bodyNewManifest, {
@ -630,7 +630,7 @@ describe('storage', () => {
test.each([['foo']])('should unstar a package %s', async (pkgName) => { test.each([['foo']])('should unstar a package %s', async (pkgName) => {
const config = getConfig('deprecate.yaml'); const config = getConfig('deprecate.yaml');
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0'); const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0');
await storage.updateManifest(bodyNewManifest, { await storage.updateManifest(bodyNewManifest, {
@ -667,7 +667,7 @@ describe('storage', () => {
test.each([['foo']])('should handle missing username %s', async (pkgName) => { test.each([['foo']])('should handle missing username %s', async (pkgName) => {
const config = getConfig('deprecate.yaml'); const config = getConfig('deprecate.yaml');
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0'); const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0');
await storage.updateManifest(bodyNewManifest, { await storage.updateManifest(bodyNewManifest, {
@ -695,7 +695,7 @@ describe('storage', () => {
['foo', 'publishWithOwnerAndCheck.yaml'], ['foo', 'publishWithOwnerAndCheck.yaml'],
])('new package %s, %s (anonymous)', async (pkgName, configFile) => { ])('new package %s, %s (anonymous)', async (pkgName, configFile) => {
const config = getConfig(configFile); const config = getConfig(configFile);
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0'); const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0');
await storage.updateManifest(bodyNewManifest, { await storage.updateManifest(bodyNewManifest, {
@ -717,7 +717,7 @@ describe('storage', () => {
['foo', 'publishWithOwnerAndCheck.yaml'], ['foo', 'publishWithOwnerAndCheck.yaml'],
])('new package %s, %s (logged in)', async (pkgName, configFile) => { ])('new package %s, %s (logged in)', async (pkgName, configFile) => {
const config = getConfig(configFile); const config = getConfig(configFile);
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const owner = { name: 'fooUser', email: '' }; const owner = { name: 'fooUser', email: '' };
const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0'); const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0');
@ -742,7 +742,7 @@ describe('storage', () => {
['foo', 'publishWithOwnerAndCheck.yaml'], ['foo', 'publishWithOwnerAndCheck.yaml'],
])('add/remove owner %s, %s', async (pkgName, configFile) => { ])('add/remove owner %s, %s', async (pkgName, configFile) => {
const config = getConfig(configFile); const config = getConfig(configFile);
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const firstOwner = { name: 'fooUser', email: '' }; const firstOwner = { name: 'fooUser', email: '' };
const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0'); const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0');
@ -802,7 +802,7 @@ describe('storage', () => {
['foo', 'publishWithOwnerAndCheck.yaml'], ['foo', 'publishWithOwnerAndCheck.yaml'],
])('should fail removing last owner %s, %s', async (pkgName, configFile) => { ])('should fail removing last owner %s, %s', async (pkgName, configFile) => {
const config = getConfig(configFile); const config = getConfig(configFile);
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0'); const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0');
const owner = 'fooUser'; const owner = 'fooUser';
@ -830,7 +830,7 @@ describe('storage', () => {
'ok to publish as non-owner without check %s, %s', 'ok to publish as non-owner without check %s, %s',
async (pkgName, configFile) => { async (pkgName, configFile) => {
const config = getConfig(configFile); const config = getConfig(configFile);
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0'); const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0');
const owner = 'fooUser'; const owner = 'fooUser';
@ -860,7 +860,7 @@ describe('storage', () => {
'should fail publishing as non-owner with check %s, %s', 'should fail publishing as non-owner with check %s, %s',
async (pkgName, configFile) => { async (pkgName, configFile) => {
const config = getConfig(configFile); const config = getConfig(configFile);
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0'); const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0');
const owner = 'fooUser'; const owner = 'fooUser';
@ -898,7 +898,7 @@ describe('storage', () => {
storage: generateRandomStorage(), storage: generateRandomStorage(),
}) })
); );
const storage = new Storage(config); const storage = new Storage(config, logger);
storage.init(config).then(() => { storage.init(config).then(() => {
const ac = new AbortController(); const ac = new AbortController();
const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0'); const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0');
@ -938,7 +938,7 @@ describe('storage', () => {
storage: generateRandomStorage(), storage: generateRandomStorage(),
}) })
); );
const storage = new Storage(config); const storage = new Storage(config, logger);
storage.init(config).then(() => { storage.init(config).then(() => {
const abort = new AbortController(); const abort = new AbortController();
storage storage
@ -978,7 +978,7 @@ describe('storage', () => {
__dirname __dirname
) )
); );
const storage = new Storage(config); const storage = new Storage(config, logger);
storage.init(config).then(() => { storage.init(config).then(() => {
const abort = new AbortController(); const abort = new AbortController();
storage storage
@ -1022,7 +1022,7 @@ describe('storage', () => {
__dirname __dirname
) )
); );
const storage = new Storage(config); const storage = new Storage(config, logger);
storage.init(config).then(() => { storage.init(config).then(() => {
const ac = new AbortController(); const ac = new AbortController();
const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0'); const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0');
@ -1086,7 +1086,7 @@ describe('storage', () => {
__dirname __dirname
) )
); );
const storage = new Storage(config); const storage = new Storage(config, logger);
storage.init(config).then(() => { storage.init(config).then(() => {
const req = httpMocks.createRequest({ const req = httpMocks.createRequest({
method: 'GET', method: 'GET',
@ -1139,7 +1139,7 @@ describe('storage', () => {
__dirname __dirname
) )
); );
const storage = new Storage(config); const storage = new Storage(config, logger);
storage.init(config).then(() => { storage.init(config).then(() => {
const ac = new AbortController(); const ac = new AbortController();
const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0'); const bodyNewManifest = generatePackageMetadata(pkgName, '1.0.0');
@ -1196,7 +1196,7 @@ describe('storage', () => {
) )
); );
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
await expect( await expect(
storage.syncUplinksMetadata(fooManifest.name, null, { storage.syncUplinksMetadata(fooManifest.name, null, {
@ -1220,7 +1220,7 @@ describe('storage', () => {
__dirname __dirname
) )
); );
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
await expect( await expect(
storage.syncUplinksMetadata(fooManifest.name, null, { storage.syncUplinksMetadata(fooManifest.name, null, {
@ -1241,7 +1241,7 @@ describe('storage', () => {
__dirname __dirname
) )
); );
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const [manifest] = await storage.syncUplinksMetadata(fooManifest.name, fooManifest, { const [manifest] = await storage.syncUplinksMetadata(fooManifest.name, fooManifest, {
retry: { limit: 0 }, retry: { limit: 0 },
@ -1263,7 +1263,7 @@ describe('storage', () => {
__dirname __dirname
) )
); );
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const [response] = await storage.syncUplinksMetadata(fooManifest.name, fooManifest); const [response] = await storage.syncUplinksMetadata(fooManifest.name, fooManifest);
@ -1304,7 +1304,7 @@ describe('storage', () => {
__dirname __dirname
) )
); );
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const [response] = await storage.syncUplinksMetadata(fooManifest.name, null); const [response] = await storage.syncUplinksMetadata(fooManifest.name, null);
@ -1326,7 +1326,7 @@ describe('storage', () => {
__dirname __dirname
) )
); );
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const [response] = await storage.syncUplinksMetadata(fooManifest.name, fooManifest); const [response] = await storage.syncUplinksMetadata(fooManifest.name, fooManifest);
@ -1350,7 +1350,7 @@ describe('storage', () => {
__dirname __dirname
) )
); );
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const [response] = await storage.syncUplinksMetadata(fooManifest.name, fooManifest, { const [response] = await storage.syncUplinksMetadata(fooManifest.name, fooManifest, {
@ -1379,7 +1379,7 @@ describe('storage', () => {
__dirname __dirname
) )
); );
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const [response] = await storage.syncUplinksMetadata('foo', null, { const [response] = await storage.syncUplinksMetadata('foo', null, {
@ -1400,7 +1400,7 @@ describe('storage', () => {
storage: generateRandomStorage(), storage: generateRandomStorage(),
}) })
); );
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
await expect(storage.getLocalDatabase()).resolves.toHaveLength(0); await expect(storage.getLocalDatabase()).resolves.toHaveLength(0);
}); });
@ -1420,7 +1420,7 @@ describe('storage', () => {
}, },
url: '/', url: '/',
}); });
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const manifest = generatePackageMetadata('foo'); const manifest = generatePackageMetadata('foo');
const ac = new AbortController(); const ac = new AbortController();
@ -1449,7 +1449,7 @@ describe('storage', () => {
storage: generateRandomStorage(), storage: generateRandomStorage(),
}) })
); );
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
await storage.saveToken({ await storage.saveToken({
user: 'foo', user: 'foo',
@ -1471,7 +1471,7 @@ describe('storage', () => {
storage: generateRandomStorage(), storage: generateRandomStorage(),
}) })
); );
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
await storage.saveToken({ await storage.saveToken({
user: 'foo', user: 'foo',
@ -1498,7 +1498,7 @@ describe('storage', () => {
storage: generateRandomStorage(), storage: generateRandomStorage(),
}) })
); );
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
await expect(storage.removeTarball('foo', 'foo-1.0.0.tgz', 'rev', username)).rejects.toThrow( await expect(storage.removeTarball('foo', 'foo-1.0.0.tgz', 'rev', username)).rejects.toThrow(
API_ERROR.NO_PACKAGE API_ERROR.NO_PACKAGE
@ -1524,7 +1524,7 @@ describe('storage', () => {
}, },
url: '/', url: '/',
}); });
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const manifest = generatePackageMetadata('foo'); const manifest = generatePackageMetadata('foo');
@ -1573,7 +1573,7 @@ describe('storage', () => {
test('ok to remove package as non-owner without check', async () => { test('ok to remove package as non-owner without check', async () => {
const config = getConfig('publishWithOwnerDefault.yaml'); const config = getConfig('publishWithOwnerDefault.yaml');
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const owner = 'fooUser'; const owner = 'fooUser';
const options = { ...defaultRequestOptions, username: owner }; const options = { ...defaultRequestOptions, username: owner };
@ -1612,7 +1612,7 @@ describe('storage', () => {
test('should fail as non-owner with check', async () => { test('should fail as non-owner with check', async () => {
const config = getConfig('publishWithOwnerAndCheck.yaml'); const config = getConfig('publishWithOwnerAndCheck.yaml');
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const owner = 'fooUser'; const owner = 'fooUser';
const options = { ...defaultRequestOptions, username: owner }; const options = { ...defaultRequestOptions, username: owner };
@ -1661,7 +1661,7 @@ describe('storage', () => {
}, },
url: '/', url: '/',
}); });
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
await expect( await expect(
storage.getPackageByOptions({ storage.getPackageByOptions({
@ -1693,7 +1693,7 @@ describe('storage', () => {
}, },
url: '/', url: '/',
}); });
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
await expect( await expect(
storage.getPackageByOptions({ storage.getPackageByOptions({
@ -1726,7 +1726,7 @@ describe('storage', () => {
}, },
url: '/', url: '/',
}); });
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
await expect( await expect(
storage.getPackageByOptions({ storage.getPackageByOptions({
@ -1759,7 +1759,7 @@ describe('storage', () => {
}, },
url: '/', url: '/',
}); });
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
await expect( await expect(
storage.getPackageByOptions({ storage.getPackageByOptions({
@ -1799,7 +1799,7 @@ describe('storage', () => {
}, },
url: '/', url: '/',
}); });
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
await expect( await expect(
storage.getPackageByOptions({ storage.getPackageByOptions({
@ -1839,7 +1839,7 @@ describe('storage', () => {
}, },
url: '/', url: '/',
}); });
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
await expect( await expect(
storage.getPackageByOptions({ storage.getPackageByOptions({
@ -1873,7 +1873,7 @@ describe('storage', () => {
}, },
url: '/', url: '/',
}); });
const storage = new Storage(config); const storage = new Storage(config, logger);
await storage.init(config); await storage.init(config);
const manifest = (await storage.getPackageByOptions({ const manifest = (await storage.getPackageByOptions({

View file

@ -6,7 +6,7 @@ import path from 'path';
import { Auth } from '@verdaccio/auth'; import { Auth } from '@verdaccio/auth';
import { Config } from '@verdaccio/config'; import { Config } from '@verdaccio/config';
import { errorUtils } from '@verdaccio/core'; import { errorUtils } from '@verdaccio/core';
import { logger } from '@verdaccio/logger'; import { setup } from '@verdaccio/logger';
import { errorReportingMiddleware, final, handleError } from '@verdaccio/middleware'; import { errorReportingMiddleware, final, handleError } from '@verdaccio/middleware';
import { generateRandomHexString } from '@verdaccio/utils'; import { generateRandomHexString } from '@verdaccio/utils';
@ -18,13 +18,15 @@ export async function initializeServer(
Storage Storage
): Promise<Application> { ): Promise<Application> {
const app = express(); const app = express();
const logger = setup({});
const config = new Config(configName); const config = new Config(configName);
config.storage = path.join(os.tmpdir(), '/storage', generateRandomHexString()); config.storage = path.join(os.tmpdir(), '/storage', generateRandomHexString());
// httpass would get path.basename() for configPath thus we need to create a dummy folder // httpass would get path.basename() for configPath thus we need to create a dummy folder
// to avoid conflics // to avoid conflics
config.configPath = config.storage; config.configPath = config.storage;
debug('storage: %s', config.storage); debug('storage: %s', config.storage);
const storage = new Storage(config);
const storage = new Storage(config, logger);
await storage.init(config, []); await storage.init(config, []);
const auth: Auth = new Auth(config); const auth: Auth = new Auth(config);
await auth.init(); await auth.init();