Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 5 additions & 33 deletions src/cli/domain/get-mocked-plugins.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import path from 'node:path';
import fs from 'fs-extra';

import strings from '../../resources/';
import settings from '../../resources/settings';
import type { Logger } from '../logger';
import { getOcConfig } from './ocConfig';

Expand Down Expand Up @@ -98,44 +96,18 @@ const registerDynamicMocks = (
})
.filter((pluginMock): pluginMock is PluginMock => !!pluginMock);

const findPath = (
pathToResolve: string,
fileName: string
): string | undefined => {
const rootDir = fs.realpathSync('.');
const fileToResolve = path.join(pathToResolve, fileName);

if (!fs.existsSync(fileToResolve)) {
if (pathToResolve === rootDir) {
return undefined;
}
const getParent = (pathToResolve: string) =>
pathToResolve.split('/').slice(0, -1).join('/');

const parentDir = pathToResolve ? getParent(pathToResolve) : rootDir;

return findPath(parentDir, fileName);
}

return fileToResolve;
};

export default function getMockedPlugins(
logger: Logger,
componentsDir: string
componentsDir?: string
): PluginMock[] {
componentsDir = path.resolve(componentsDir || '.');

let plugins: PluginMock[] = [];
const ocJsonFileName = settings.configFile.src.replace('./', '');
const ocJsonPath = findPath(componentsDir, ocJsonFileName);

if (!ocJsonPath) {
return plugins;
}

const content = getOcConfig(ocJsonPath);
const ocJsonLocation = ocJsonPath.slice(0, -ocJsonFileName.length);
const content = getOcConfig(componentsDir);
const ocJsonLocation = content.sourcePath
? path.dirname(content.sourcePath)
: componentsDir;

if (!content.development?.plugins) {
return plugins;
Expand Down
42 changes: 35 additions & 7 deletions src/cli/domain/ocConfig.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import fs from 'node:fs';
import path from 'node:path';
import settings from '../../resources/settings';

export interface OpenComponentsConfig {
Expand Down Expand Up @@ -37,6 +38,7 @@ export interface OpenComponentsConfig {
}

type ParsedConfig = {
sourcePath?: string;
registries: string[];
development: {
plugins: {
Expand All @@ -50,6 +52,28 @@ type ParsedConfig = {
};
};

const findPath = (
pathToResolve: string,
fileName: string
): string | undefined => {
const rootDir = fs.realpathSync('.');
const fileToResolve = path.join(pathToResolve, fileName);

if (!fs.existsSync(fileToResolve)) {
if (pathToResolve === rootDir) {
return undefined;
}
const getParent = (pathToResolve: string) =>
pathToResolve.split('/').slice(0, -1).join('/');

const parentDir = pathToResolve ? getParent(pathToResolve) : rootDir;

return findPath(parentDir, fileName);
}

return fileToResolve;
};

function parseConfig(config: OpenComponentsConfig): ParsedConfig {
const plugins = {
...(config.mocks?.plugins || {}),
Expand All @@ -68,12 +92,15 @@ function parseConfig(config: OpenComponentsConfig): ParsedConfig {
return parsedConfig;
}

export function getOcConfig(path?: string): ParsedConfig {
export function getOcConfig(folder?: string): ParsedConfig {
const configPath = folder
? findPath(folder, settings.configFile.src.replace('./', '')) ||
settings.configFile.src
: settings.configFile.src;

try {
const config = JSON.parse(
fs.readFileSync(path || settings.configFile.src, 'utf8')
);
return parseConfig(config);
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
return { ...parseConfig(config), sourcePath: configPath };
} catch {
return {
registries: [],
Expand All @@ -85,8 +112,9 @@ export function getOcConfig(path?: string): ParsedConfig {
}

export function setOcConfig(config: ParsedConfig, path?: string) {
const { sourcePath, ...rest } = config;
fs.writeFileSync(
path || settings.configFile.src,
JSON.stringify(parseConfig(config), null, 2)
path || sourcePath || settings.configFile.src,
JSON.stringify(rest, null, 2)
);
}
5 changes: 2 additions & 3 deletions src/cli/facade/dev.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
import path from 'node:path';
import { promisify } from 'node:util';
import colors from 'colors/safe';
import fs from 'fs-extra';
import getPortCb from 'getport';
import livereload from 'livereload';
import { fromPromise } from 'universalify';

import * as oc from '../../index';
import strings from '../../resources/index';
import settings from '../../resources/settings';
import getMockedPlugins from '../domain/get-mocked-plugins';
import handleDependencies from '../domain/handle-dependencies';
import type { Local } from '../domain/local';
import { getOcConfig } from '../domain/ocConfig';
import watch from '../domain/watch';
import type { Logger } from '../logger';

Expand Down Expand Up @@ -46,7 +45,7 @@ const dev = ({ local, logger }: { logger: Logger; local: Local }) =>
let fallbackClient = false;
if (!fallbackRegistryUrl) {
try {
const localConfig = await fs.readJson(settings.configFile.src);
const localConfig = getOcConfig(componentsDir);
if (
!fallbackRegistryUrl &&
typeof localConfig.development?.fallback?.url === 'string'
Expand Down
2 changes: 1 addition & 1 deletion src/registry/routes/component-preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ function componentPreview(
previewView({
component,
fallbackClient: res.conf.fallbackClient
? res.conf.fallbackRegistryUrl
? `${res.conf.fallbackRegistryUrl.replace(/\/$/, '')}/oc-client/client.dev.js`
: undefined,
href: res.conf.baseUrl,
liveReload,
Expand Down
78 changes: 20 additions & 58 deletions test/unit/cli-domain-get-mocked-plugins.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,28 +51,32 @@ describe('cli : domain : get-mocked-plugins', () => {

describe('when setting up mocked plugins', () => {
describe('when componentsDir parameter is undefined', () => {
const joinStub = sinon.stub();
let getOcConfigMock;

beforeEach(() => {
initialise({ pathJoin: joinStub });
getOcConfigMock = sinon.stub().returns({ registries: [], mocks: { plugins: {} } });
initialise({ getOcConfig: getOcConfigMock });
getMockedPlugins(logMock, undefined);
});

it('should use . as default', () => {
expect(joinStub.args[0][0]).to.equal('.');
expect(getOcConfigMock.called).to.be.true;
expect(getOcConfigMock.args[0][0]).to.equal('.');
});
});

describe('when componentsDir parameter is omitted', () => {
const joinStub = sinon.stub();
let getOcConfigMock;

beforeEach(() => {
initialise({ pathJoin: joinStub });
getOcConfigMock = sinon.stub().returns({ registries: [], mocks: { plugins: {} } });
initialise({ getOcConfig: getOcConfigMock });
getMockedPlugins(logMock);
});

it('should use . as default', () => {
expect(joinStub.args[0][0]).to.equal('.');
expect(getOcConfigMock.called).to.be.true;
expect(getOcConfigMock.args[0][0]).to.equal('.');
});
});

Expand All @@ -90,65 +94,26 @@ describe('cli : domain : get-mocked-plugins', () => {
const getOcConfigMock = sinon.stub().returns(ocJsonComponent);

beforeEach(() => {
initialise({fs: {
existsSync: sinon.stub().returns(true),
}, getOcConfig: getOcConfigMock});
initialise({ getOcConfig: getOcConfigMock });
result = getMockedPlugins(logMock, '/root/components/');
});

it('should use components folder oc.json as default', () => {
it('should return plugins from the provided components folder config', () => {
expect(getOcConfigMock.calledOnce).to.be.true;
expect(getOcConfigMock.args[0][0]).to.equal('/root/components/oc.json');
expect(getOcConfigMock.args[0][0]).to.equal('/root/components/');
expect(result.length).to.equal(2);
});
});

describe('when oc.json is in root folder', () => {
let result;
const ocJsonComponent = {
registries: [],
development: {
plugins: {
static: { foo: 1, bar: 2 }
}
}
};
const ocJsonRoot = {
registries: [],
development: {
plugins: {
static: { foo: 1, bar: 2, baz: 3 }
}
}
};

const getOcConfigMock = sinon.stub();
const existsMock = sinon.stub();

getOcConfigMock.withArgs('/root/components/oc.json').returns(ocJsonComponent);
getOcConfigMock.withArgs('/root/oc.json').returns(ocJsonRoot);

existsMock.withArgs('/root/components/oc.json').returns(false);
existsMock.withArgs('/root/oc.json').returns(true);

beforeEach(() => {
initialise({fs:{
existsSync: existsMock,
}, getOcConfig: getOcConfigMock});
result = getMockedPlugins(logMock, '/root/components/');
});

it('should use root oc.json', () => {
expect(result.length).to.equal(3);
});
});

describe('when oc.json is missing', () => {
let result;
beforeEach(() => {
initialise({fs:{
existsSync: sinon.stub().returns(false)
}});
const getOcConfigMock = sinon.stub().returns({
registries: [],
development: { plugins: {} }
});
initialise({ getOcConfig: getOcConfigMock });
result = getMockedPlugins(logMock, '/root/components/');
});

Expand All @@ -161,16 +126,13 @@ describe('cli : domain : get-mocked-plugins', () => {
let result;
const ocJson = {
registries: [],
mocks: {
development: {
plugins: {}
}
};

beforeEach(() => {
initialise({fs:{
existsSync: sinon.stub().returns(true),
readJsonSync: sinon.stub().returns(ocJson)
}});
initialise({ getOcConfig: sinon.stub().returns(ocJson) });
result = getMockedPlugins(logMock, '/root/components/');
});

Expand Down
Loading