Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

hadron-app-registry

Package Overview
Dependencies
Maintainers
33
Versions
524
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

hadron-app-registry - npm Package Compare versions

Comparing version 0.0.0-next-52e439f268b74410212a0d91a5ee39021eb44499 to 0.0.0-next-52fa1200a3e5caa90e6695b0f20be9210f2d1c69

dist/react-context.d.ts

1

.eslintrc.js

@@ -0,1 +1,2 @@

'use strict';
module.exports = {

@@ -2,0 +3,0 @@ root: true,

3

.mocharc.js

@@ -1,1 +0,2 @@

module.exports = require('@mongodb-js/mocha-config-compass');
'use strict';
module.exports = require('@mongodb-js/mocha-config-compass/react');

@@ -1,41 +0,25 @@

/// <reference types="react" />
import type { Store as RefluxStore } from 'reflux';
import type { Store as ReduxStore } from 'redux';
import EventEmitter from 'eventemitter3';
import { Actions } from './actions';
interface Role {
name: string;
component: React.ComponentType<any>;
actionName?: string;
configureActions?: () => any;
storeName?: string;
configureStore?: (storeSetup: any) => any;
order?: number;
hasQueryHistory?: boolean;
import type { ReactReduxContext } from 'react-redux';
export type Store = (ReduxStore | Partial<RefluxStore>) & {
onActivated?: (appRegistry: AppRegistry) => void;
};
export type RefluxActions = Record<string, any>;
export declare function isReduxStore(store: Store): store is ReduxStore;
export interface Plugin {
store: Store;
context?: typeof ReactReduxContext;
actions?: RefluxActions;
deactivate: () => void;
}
type Store = Partial<RefluxStore & {
onActivated?: (appRegistry: AppRegistry) => void;
}>;
export declare class AppRegistry {
_emitter: EventEmitter;
actions: Record<string, unknown>;
components: Record<string, React.ComponentType<any>>;
stores: Record<string, Store>;
roles: Record<string, Role[]>;
storeMisses: Record<string, number>;
plugins: Record<string, Plugin>;
constructor();
static get Actions(): typeof Actions;
static get AppRegistry(): typeof AppRegistry;
deregisterAction(name: string): this;
deregisterComponent(name: string): this;
deregisterRole(name: string, object: Role): this;
deregisterStore(name: string): this;
getAction(name: string): unknown;
getComponent(name: string): React.ComponentType<any> | undefined;
getRole(name: string): Role[] | undefined;
getStore(name: string): Store;
onActivated(): this;
registerAction(name: string, action: unknown): this;
registerComponent(name: string, component: React.ComponentType<any>): this;
registerRole(name: string, role: Role): this;
registerStore(name: string, store: Store): this;
deregisterPlugin(name: string): this;
getPlugin(name: string): Plugin | undefined;
registerPlugin(name: string, plugin: Plugin): this;
deactivate(): void;
addListener(eventName: string, listener: (...args: any[]) => void): this;

@@ -50,6 +34,4 @@ emit(eventName: string, ...args: any[]): boolean;

removeAllListeners(eventName: string): this;
_callOnStores(fn: (store: Store) => void): this;
_roleComparator(a: Role, b: Role): number;
}
export type { Role };
export declare const globalAppRegistry: Readonly<AppRegistry>;
//# sourceMappingURL=app-registry.d.ts.map

@@ -6,113 +6,38 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.AppRegistry = void 0;
const reflux_1 = __importDefault(require("reflux"));
exports.globalAppRegistry = exports.AppRegistry = exports.isReduxStore = void 0;
const eventemitter3_1 = __importDefault(require("eventemitter3"));
const actions_1 = require("./actions");
const INT8_MAX = 127;
const STUB_STORE = reflux_1.default.createStore({});
function isReduxStore(store) {
return (store &&
typeof store === 'object' &&
Object.prototype.hasOwnProperty.call(store, 'dispatch'));
}
exports.isReduxStore = isReduxStore;
class AppRegistry {
constructor() {
this._emitter = new eventemitter3_1.default();
this.actions = {};
this.components = {};
this.stores = {};
this.roles = {};
this.storeMisses = {};
this.plugins = {};
}
static get Actions() {
return actions_1.Actions;
}
static get AppRegistry() {
return AppRegistry;
}
deregisterAction(name) {
delete this.actions[name];
actions_1.Actions.actionDeregistered(name);
deregisterPlugin(name) {
delete this.plugins[name];
return this;
}
deregisterComponent(name) {
delete this.components[name];
actions_1.Actions.componentDeregistered(name);
return this;
getPlugin(name) {
return this.plugins[name];
}
deregisterRole(name, object) {
const roles = this.roles[name];
roles.splice(roles.indexOf(object), 1);
actions_1.Actions.roleDeregistered(name);
registerPlugin(name, plugin) {
this.plugins[name] = plugin;
return this;
}
deregisterStore(name) {
delete this.stores[name];
actions_1.Actions.storeDeregistered(name);
return this;
}
getAction(name) {
return this.actions[name];
}
getComponent(name) {
return this.components[name];
}
getRole(name) {
return this.roles[name];
}
getStore(name) {
const store = this.stores[name];
if (store === undefined) {
this.storeMisses[name] = (this.storeMisses[name] || 0) + 1;
return STUB_STORE;
deactivate() {
for (const [name, plugin] of Object.entries(this.plugins)) {
plugin.deactivate?.();
this.deregisterPlugin(name);
}
return store;
}
onActivated() {
return this._callOnStores((store) => {
if (store.onActivated) {
store.onActivated(this);
}
});
}
registerAction(name, action) {
const overwrite = Object.prototype.hasOwnProperty.call(this.actions, name);
this.actions[name] = action;
if (overwrite) {
actions_1.Actions.actionOverridden(name);
for (const event of this.eventNames()) {
this.removeAllListeners(event);
}
else {
actions_1.Actions.actionRegistered(name);
}
return this;
}
registerComponent(name, component) {
const overwrite = Object.prototype.hasOwnProperty.call(this.components, name);
this.components[name] = component;
if (overwrite) {
actions_1.Actions.componentOverridden(name);
}
else {
actions_1.Actions.componentRegistered(name);
}
return this;
}
registerRole(name, role) {
if (Object.prototype.hasOwnProperty.call(this.roles, name) &&
!this.roles[name].includes(role)) {
this.roles[name].push(role);
this.roles[name].sort(this._roleComparator.bind(this));
}
else {
this.roles[name] = [role];
}
actions_1.Actions.roleRegistered(name);
return this;
}
registerStore(name, store) {
const overwrite = Object.prototype.hasOwnProperty.call(this.stores, name);
this.stores[name] = store;
if (overwrite) {
actions_1.Actions.storeOverridden(name);
}
else {
actions_1.Actions.storeRegistered(name);
}
return this;
}
addListener(eventName, listener) {

@@ -149,16 +74,5 @@ return this.on(eventName, listener);

}
_callOnStores(fn) {
for (const key of Object.keys(this.stores)) {
const store = this.stores[key];
fn(store);
}
return this;
}
_roleComparator(a, b) {
const aOrder = a.order || INT8_MAX;
const bOrder = b.order || INT8_MAX;
return aOrder - bOrder;
}
}
exports.AppRegistry = AppRegistry;
exports.globalAppRegistry = Object.freeze(new AppRegistry());
//# sourceMappingURL=app-registry.js.map

@@ -1,6 +0,7 @@

import { AppRegistry } from './app-registry';
import type { Role } from './app-registry';
export { AppRegistry };
export type { Role };
import { AppRegistry, globalAppRegistry } from './app-registry';
export { AppRegistry, globalAppRegistry };
export { AppRegistryProvider, useGlobalAppRegistry, useLocalAppRegistry, GlobalAppRegistryProvider, } from './react-context';
export type { HadronPluginComponent, HadronPluginConfig, ActivateHelpers, } from './register-plugin';
export { registerHadronPlugin, createActivateHelpers, createServiceLocator, createServiceProvider, } from './register-plugin';
export default AppRegistry;
//# sourceMappingURL=index.d.ts.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AppRegistry = void 0;
exports.createServiceProvider = exports.createServiceLocator = exports.createActivateHelpers = exports.registerHadronPlugin = exports.GlobalAppRegistryProvider = exports.useLocalAppRegistry = exports.useGlobalAppRegistry = exports.AppRegistryProvider = exports.globalAppRegistry = exports.AppRegistry = void 0;
const app_registry_1 = require("./app-registry");
Object.defineProperty(exports, "AppRegistry", { enumerable: true, get: function () { return app_registry_1.AppRegistry; } });
Object.defineProperty(exports, "globalAppRegistry", { enumerable: true, get: function () { return app_registry_1.globalAppRegistry; } });
var react_context_1 = require("./react-context");
Object.defineProperty(exports, "AppRegistryProvider", { enumerable: true, get: function () { return react_context_1.AppRegistryProvider; } });
Object.defineProperty(exports, "useGlobalAppRegistry", { enumerable: true, get: function () { return react_context_1.useGlobalAppRegistry; } });
Object.defineProperty(exports, "useLocalAppRegistry", { enumerable: true, get: function () { return react_context_1.useLocalAppRegistry; } });
Object.defineProperty(exports, "GlobalAppRegistryProvider", { enumerable: true, get: function () { return react_context_1.GlobalAppRegistryProvider; } });
var register_plugin_1 = require("./register-plugin");
Object.defineProperty(exports, "registerHadronPlugin", { enumerable: true, get: function () { return register_plugin_1.registerHadronPlugin; } });
Object.defineProperty(exports, "createActivateHelpers", { enumerable: true, get: function () { return register_plugin_1.createActivateHelpers; } });
Object.defineProperty(exports, "createServiceLocator", { enumerable: true, get: function () { return register_plugin_1.createServiceLocator; } });
Object.defineProperty(exports, "createServiceProvider", { enumerable: true, get: function () { return register_plugin_1.createServiceProvider; } });
exports.default = app_registry_1.AppRegistry;
//# sourceMappingURL=index.js.map

@@ -10,3 +10,3 @@ {

"homepage": "https://github.com/mongodb-js/compass",
"version": "0.0.0-next-52e439f268b74410212a0d91a5ee39021eb44499",
"version": "0.0.0-next-52fa1200a3e5caa90e6695b0f20be9210f2d1c69",
"repository": {

@@ -37,3 +37,3 @@ "type": "git",

"lint": "npm run eslint . && npm run prettier -- --check .",
"depcheck": "depcheck",
"depcheck": "compass-scripts check-peer-deps && depcheck",
"check": "npm run lint && npm run depcheck",

@@ -45,14 +45,17 @@ "check-ci": "npm run check",

"test-ci": "npm run test-cov",
"reformat": "npm run prettier -- --write . && npm run eslint . --fix"
"reformat": "npm run eslint . -- --fix && npm run prettier -- --write ."
},
"dependencies": {
"debug": "^4.2.0",
"eventemitter3": "^4.0.0",
"react": "^17.0.2",
"react-redux": "^8.1.3",
"redux": "^4.2.1",
"reflux": "^0.4.1"
},
"devDependencies": {
"@mongodb-js/eslint-config-compass": "0.0.0-next-52e439f268b74410212a0d91a5ee39021eb44499",
"@mongodb-js/mocha-config-compass": "0.0.0-next-52e439f268b74410212a0d91a5ee39021eb44499",
"@mongodb-js/prettier-config-compass": "0.0.0-next-52e439f268b74410212a0d91a5ee39021eb44499",
"@mongodb-js/tsconfig-compass": "0.0.0-next-52e439f268b74410212a0d91a5ee39021eb44499",
"@mongodb-js/eslint-config-compass": "0.0.0-next-52fa1200a3e5caa90e6695b0f20be9210f2d1c69",
"@mongodb-js/mocha-config-compass": "0.0.0-next-52fa1200a3e5caa90e6695b0f20be9210f2d1c69",
"@mongodb-js/prettier-config-compass": "0.0.0-next-52fa1200a3e5caa90e6695b0f20be9210f2d1c69",
"@mongodb-js/tsconfig-compass": "0.0.0-next-52fa1200a3e5caa90e6695b0f20be9210f2d1c69",
"@testing-library/react": "^12.1.5",
"@types/chai": "^4.2.21",

@@ -70,3 +73,3 @@ "@types/mocha": "^9.0.0",

},
"gitHead": "52e439f268b74410212a0d91a5ee39021eb44499"
"gitHead": "52fa1200a3e5caa90e6695b0f20be9210f2d1c69"
}

@@ -1,36 +0,176 @@

# hadron-app-registry [![][npm_img]][npm_url]
# hadron-app-registry
> Hadron App Registry
## Concepts
## Installation
> [!IMPORTANT]
> Use a plugin instead of a regular component for self-contained parts of
> the application which may need to keep state beyond the raw React
> component's lifetime.
Compass uses a special form of React components referred to as **Plugins**,
distinguished from regular components in that they:
- Maintain state that can persist beyond their React component's lifetime
- Use a custom dependency injection mechanism for consuming dependencies that
are used when initializing the plugin state
These dependencies are generally referred to as **Services**. For example,
logging or telemetry in Compass are generally consumed by plugins as a
service.
Compass uses a concept of scopes called **App Registries**. Currently, there
are two levels of nesting:
- The global app registry, global in the sense of being a per-browser-window
singleton
- A local app registry, where "local" currently means scoped to a single tab
(not a technical restriction, just a convention).
The lifetime of a plugin's state is not tied to the lifetime of their React
component, but rather to the lifetime of the local app registry (or the global
one, if there is none).
> [!TIP]
> Most plugins in Compass use a **Redux store** to keep track of their state.
> Some legacy plugins may still use **Reflux** or a similar mechanism where the
> state is provided to the top-level component of the plugin as a plain object.
Other than tracking plugin lifetimes, app registries provide a communication
channel between plugins by being event emitters.
If possible, new code should avoid this communication channel, as it is untyped
and the specific method of passing messages should be an implementation detail.
Alternative methods of passing messages between plugins include using React
contexts to provide an API that can be used by nested plugins, or if that is
not possible, your plugin can expose methods that other plugins can then access.
(`WorkspacesServiceProvider` is currently an example of this pattern.)
## Usage
For details on the usage of individual components or functions, refer to
doc comments in the package itself.
```tsx
import {
globalAppRegistry,
AppRegistry,
AppRegistryProvider,
registerHadronPlugin,
} from 'hadron-app-registry';
import CompassLogging from '@mongodb-js/compass-logging';
import {
LoggingProvider,
loggingLocator,
} from '@mongodb-js/compass-logging/provider';
const PluginWithLogger = registerHadronPlugin(
{
name: 'LoggingPlugin',
component: function () {
return <>...</>;
},
activate(opts, { logging }) {
logging.log('Plugin activated!');
},
},
{ logging: loggingLocator }
);
ReactDOM.render(
<AppRegistryProvider>
<LoggingProvider>
<PluginWithLogger />
</LoggingProvider>
</AppRegistryProvider>
);
```
npm install --save hadron-app-registry
## Writing a service
Services are consumed by plugins through **service locators**, which are
functions that return the instance of the service that the plugin is
intended to use.
Typically, these functions are implemented using React contexts.
```typescript
import { createServiceLocator } from 'hadron-app-registry';
const ConnectionStorageContext = createContext<ConnectionStorage | null>(null);
function useConnectionStorageContext(): ConnectionStorage {
const connectionStorage = useContext(ConnectionStorageContext);
if (!connectionStorage) {
throw new Error('...');
}
return connectionStorage;
}
export const ConnectionStorageProvider = ConnectionStorageContext.Provider;
export const connectionStorageLocator = createServiceLocator(
useConnectionStorageContext,
'connectionStorageLocator'
);
```
### Usage
> [!TIP]
> If you need to use a service locator from inside a provider component, for
> example because your service depends on another service, you can use the
> `createServiceProvider()` method to achieve this. Otherwise, service locators
> can only be called by plugins during their initial activation.
```javascript
const { AppRegistry } = require('hadron-app-registry');
## Writing plugins
var registry = new AppRegistry();
Plugins consist of:
registry.registerAction('Action::MyAction', action);
registry.registerComponent('Component::MyComponent', component);
registry.registerStore('Store::MyStore', store);
- A name that identifies the plugin
- A top-level React component that serves as the plugin's React entry point
- An `activate` function that is called before the plugin is first rendered
and which creates a (Redux) store for maintaining plugin state.
registry.actions; //=> { 'Action::MyAction': action }
registry.components; //=> { 'Component::MyComponent': component }
registry.stores; //=> { 'Store::MyStore':: store }
The `activate` function is expected to also return a cleanup function that
is called when the lifetime of the plugin ends (i.e. the local app registry
associated with it is destroyed). In order to make this easier, helpers are
provided that automatically register cleanup functions:
registry.getAction('Action::MyAction'); //=> action
registry.getComponent('Component::MyComponent'); //=> component
registry.getStore('Store::MyStore'); //=> store
```js
const Plugin = registerHadronPlugin({
name: 'TestPlugin',
component: TestPluginComponent,
activate(props, services, { on, addCleanup, cleanup }) {
const store = configureStore();
registry.deregisterAction('Action::MyAction');
registry.deregisterComponent('Component::MyComponent');
registry.deregisterStore('Store::MyStore');
// Automatically removes event listeners when plugin is deactivated
on(someEventEmitter, 'some-event', () => ...);
addCleanup(() => { ... });
return { store, deactivate: cleanup };
}
}, { /* services */});
```
[npm_img]: https://img.shields.io/npm/v/hadron-app-registry.svg?style=flat-square
[npm_url]: https://www.npmjs.org/package/hadron-app-registry
> [!NOTE]
> The `props` and `services` parameters reflect the React properties passed
> to the plugin (`Plugin` in the example above) at the time of the first
> instantiation and the services returned by the service locators at that time;
> changes to the values returned from these will not have an effect on the
> already-instantiated plugin.
## Testing support
For easier testing, plugins can be rendered with fixed services that are not
looked up through the usual service locators. Additionally, the rendering of
child plugins can be disabled, which can be used to speed up tests or avoid
having to specify service dependencies for those child plugins.
```tsx
import { render, cleanup, screen, waitFor } from '@testing-library/react';
const PluginWithMockServices = WorkspacesPlugin.withMockServices(
{
dataService: sinon.stub(),
},
{ disableChildPluginRendering: true }
);
return render(<PluginWithMockServices />);
```
import { expect } from 'chai';
import sinon from 'sinon';
import Reflux from 'reflux';
import { AppRegistry } from './';
import { Actions } from './actions';
describe('AppRegistry', function () {
describe('getStore', function () {
context('when the store does not exist', function () {
let registry: AppRegistry;
let storeLike;
before(function () {
registry = new AppRegistry();
storeLike = registry.getStore('Test.Store');
});
it('does not return undefined', function () {
expect(storeLike).to.not.equal(undefined);
});
it('returns a store-like object', function (done) {
const unsubscribe = storeLike.listen((value) => {
expect(value).to.equal('test');
unsubscribe();
done();
});
storeLike.trigger('test');
});
it('flags the non-existant request', function () {
expect(registry.storeMisses['Test.Store']).to.equal(1);
});
context('when asking for a missing store more than once', function () {
before(function () {
registry.getStore('Test.Store');
});
it('updates the miss count', function () {
expect(registry.storeMisses['Test.Store']).to.equal(2);
});
});
});
});
describe('#onActivated', function () {
context('when the method is defined on the store', function () {
let registry: AppRegistry;
let spyOne: any;
let spyTwo: any;
let storeOne: any;
let storeTwo: any;
beforeEach(function () {
spyOne = sinon.spy();
spyTwo = sinon.spy();
storeOne = Reflux.createStore({
onActivated: (reg) => {
spyOne(reg);
},
});
storeTwo = Reflux.createStore({
onActivated: (reg) => {
spyTwo(reg);
},
});
registry = new AppRegistry()
.registerStore('TestStore1', storeOne)
.registerStore('TestStore2', storeTwo);
});
it('calls onActivated on the store', function () {
registry.onActivated();
expect(spyOne.calledWith(registry)).to.equal(true);
expect(spyTwo.calledWith(registry)).to.equal(true);
});
});
context('when the method is not defined on the store', function () {
let registry: AppRegistry;
let store: any;
beforeEach(function () {
store = Reflux.createStore({});
registry = new AppRegistry().registerStore('TestStore', store);
});
it('does not call onActivated on the store', function () {
expect(registry.onActivated()).to.equal(registry);
});
});
});
describe('#emit data-service-connected', function () {
context('when a listener exists', function () {
let registry: AppRegistry;
let spy: any;
let store: any;
beforeEach(function () {
spy = sinon.spy();
store = Reflux.createStore({
onActivated: (ar) => {
ar.on('data-service-connected', (error, ds) => {
spy(error, ds);
});
},
});
registry = new AppRegistry().registerStore('TestStore', store);
registry.onActivated();
});
it('calls onConnected on the store', function () {
registry.emit('data-service-connected', 'error', 'ds');
expect(spy.callCount).to.equal(1);
});
});
});
describe('#registerAction', function () {
let registry: AppRegistry;
beforeEach(function () {
registry = new AppRegistry().registerAction('TestAction', 'testing');
});
it('registers the action', function () {
expect(registry.actions.TestAction).to.equal('testing');
});
it('allows access via the getter', function () {
expect(registry.getAction('TestAction')).to.equal('testing');
});
it('publishes an action registered action', function (done) {
const unsubscribe = Actions.actionRegistered.listen((name) => {
expect(name).to.equal('TestAction');
unsubscribe();
done();
});
});
context('when the action already exists', function () {
beforeEach(function () {
registry.registerAction('TestAction', 'override');
});
it('publishes an action overridden action', function (done) {
const unsubscribe = Actions.actionOverridden.listen((name) => {
expect(name).to.equal('TestAction');
unsubscribe();
done();
});
});
});
});
describe('#registerComponent', function () {
let registry: AppRegistry;
beforeEach(function () {
registry = new AppRegistry().registerComponent('IndexView', 'testing');
});
it('registers the component', function () {
expect(registry.components.IndexView).to.equal('testing');
});
it('allows access via the getter', function () {
expect(registry.getComponent('IndexView')).to.equal('testing');
});
it('publishes a component registered action', function (done) {
const unsubscribe = Actions.componentRegistered.listen((name) => {
expect(name).to.equal('IndexView');
unsubscribe();
done();
});
});
context('when the component already exists', function () {
beforeEach(function () {
registry.registerComponent('IndexView', 'override');
});
it('publishes a component overridden action', function (done) {
const unsubscribe = Actions.componentOverridden.listen((name) => {
expect(name).to.equal('IndexView');
unsubscribe();
done();
});
});
});
});
describe('#registerRole', function () {
let registry: AppRegistry;
const role = {
component: 'collection-tab',
name: 'another tab',
order: 2,
};
const roleTwo = {
component: 'collection-tab-two',
name: 'another tab two',
order: 1,
};
const roleThree = {
component: 'collection-tab-three',
name: 'another tab three',
};
beforeEach(function () {
registry = new AppRegistry().registerRole('Role.Collection.Tab', role);
});
it('registers the component', function () {
expect(registry.roles['Role.Collection.Tab']).to.deep.equal([role]);
});
it('allows access via the getter', function () {
expect(registry.getRole('Role.Collection.Tab')).to.deep.equal([role]);
});
it('publishes a role registered action', function (done) {
const unsubscribe = Actions.roleRegistered.listen((name) => {
expect(name).to.equal('Role.Collection.Tab');
unsubscribe();
done();
});
});
context('when the component already exists', function () {
beforeEach(function () {
registry.registerRole('Role.Collection.Tab', role);
});
it('does not register the duplicate', function () {
expect(registry.roles['Role.Collection.Tab']).to.deep.equal([role]);
});
});
context('when the component does not already exists', function () {
context('when the role defines an order', function () {
beforeEach(function () {
registry.registerRole('Role.Collection.Tab', roleTwo);
});
it('registers the additional component in order', function () {
expect(registry.roles['Role.Collection.Tab']).to.deep.equal([
roleTwo,
role,
]);
});
});
context('when the role does not define an order', function () {
beforeEach(function () {
registry
.registerRole('Role.Collection.Tab', roleTwo)
.registerRole('Role.Collection.Tab', roleThree);
});
it('registers the additional component in order', function () {
expect(registry.roles['Role.Collection.Tab']).to.deep.equal([
roleTwo,
role,
roleThree,
]);
});
});
});
});
describe('#registerStore', function () {
let registry: AppRegistry;
beforeEach(function () {
registry = new AppRegistry().registerStore('IndexStore', 'testing');
});
it('registers the store', function () {
expect(registry.stores.IndexStore).to.equal('testing');
});
it('allows access via the getter', function () {
expect(registry.getStore('IndexStore')).to.equal('testing');
});
it('publishes a store registered action', function (done) {
const unsubscribe = Actions.storeRegistered.listen((name) => {
expect(name).to.equal('IndexStore');
unsubscribe();
done();
});
});
context('when the store already exists', function () {
beforeEach(function () {
registry.registerStore('IndexStore', 'override');
});
it('publishes a store overridden action', function (done) {
const unsubscribe = Actions.storeOverridden.listen((name) => {
expect(name).to.equal('IndexStore');
unsubscribe();
done();
});
});
});
});
describe('#deregisterAction', function () {
context('when the action exists', function () {
let registry: AppRegistry;
beforeEach(function () {
registry = new AppRegistry()
.registerAction('TestAction', 'testing')
.deregisterAction('TestAction');
});
it('deregisters the action', function () {
expect(registry.actions.TestAction).to.equal(undefined);
});
it('publishes an action deregisted action', function (done) {
const unsubscribe = Actions.actionDeregistered.listen((name) => {
expect(name).to.equal('TestAction');
unsubscribe();
done();
});
});
});
});
describe('#deregisterComponent', function () {
context('when the component exists', function () {
let registry: AppRegistry;
beforeEach(function () {
registry = new AppRegistry()
.registerComponent('TestComponent', 'testing')
.deregisterComponent('TestComponent');
});
it('deregisters the component', function () {
expect(registry.components.TestComponent).to.equal(undefined);
});
it('publishes a component deregisted action', function (done) {
const unsubscribe = Actions.componentDeregistered.listen((name) => {
expect(name).to.equal('TestComponent');
unsubscribe();
done();
});
});
});
});
describe('#deregisterRole', function () {
const role = {
component: 'collection-tab',
name: 'another tab',
order: 2,
};
const roleTwo = {
component: 'collection-tab-two',
name: 'another tab two',
order: 1,
};
context('when the role exists', function () {
let registry: AppRegistry;
beforeEach(function () {
registry = new AppRegistry()
.registerRole('TestRole', role)
.registerRole('TestRole', roleTwo)
.deregisterRole('TestRole', roleTwo);
});
it('deregisters the role', function () {
expect(registry.roles.TestRole).to.deep.equal([role]);
});
it('publishes a role deregisted action', function (done) {
const unsubscribe = Actions.roleDeregistered.listen((name) => {
expect(name).to.equal('TestRole');
unsubscribe();
done();
});
});
});
});
describe('#deregisterStore', function () {
context('when the store exists', function () {
let registry: AppRegistry;
beforeEach(function () {
registry = new AppRegistry()
.registerStore('TestStore', 'testing')
.deregisterStore('TestStore');
});
it('deregisters the store', function () {
expect(registry.stores.TestStore).to.equal(undefined);
});
it('publishes a store deregisted action', function (done) {
const unsubscribe = Actions.storeDeregistered.listen((name) => {
expect(name).to.equal('TestStore');
unsubscribe();
done();
});
});
});
});
describe('#emit', function () {

@@ -584,39 +163,3 @@ let registry: AppRegistry;

});
context('when registering an object', function () {
const registerStore = () => {
registry.registerStore('test', 'testing');
};
it('allows the registration', function () {
expect(registerStore).to.not.throw();
});
});
context('when deregistering an object', function () {
beforeEach(function () {
registry.registerStore('test', 'testing');
});
const deregisterStore = () => {
registry.registerStore('test');
};
it('allows the registration', function () {
expect(deregisterStore).to.not.throw();
});
});
context('when modifying the object', function () {
const modify = () => {
registry.emit = () => {
/* ignore */
};
};
it('raises an error', function () {
expect(modify).to.throw();
});
});
});
});
import type { Store as RefluxStore } from 'reflux';
import Reflux from 'reflux';
import type { Store as ReduxStore } from 'redux';
import EventEmitter from 'eventemitter3';
import { Actions } from './actions';
import type { ReactReduxContext } from 'react-redux';
/**
* A non-magic number that is still small and higher than
* the number of components registered for a single role
* that we would expect.
*/
const INT8_MAX = 127;
export type Store = (ReduxStore | Partial<RefluxStore>) & {
onActivated?: (appRegistry: AppRegistry) => void;
};
/**
* Returning a fake store when asking for a store that does not
* exist.
*/
const STUB_STORE = Reflux.createStore({});
// This is basically what createActions will return, this doesn't exactly match
// reflux.Actions type
export type RefluxActions = Record<string, any>;
interface Role {
name: string;
component: React.ComponentType<any>;
actionName?: string;
configureActions?: () => any;
storeName?: string;
configureStore?: (storeSetup: any) => any;
order?: number;
hasQueryHistory?: boolean;
export function isReduxStore(store: Store): store is ReduxStore {
return (
store &&
typeof store === 'object' &&
Object.prototype.hasOwnProperty.call(store, 'dispatch')
);
}
type Store = Partial<
RefluxStore & {
onActivated?: (appRegistry: AppRegistry) => void;
}
>;
export interface Plugin {
/**
* Redux or reflux store that will be automatically passed to a
* corresponding provider
*/
store: Store;
/**
* Optional, only relevant for plugins using redux stores in cases where
* exposed plugin methods need access to plugin store in react tree where
* another redux store is mounted
*/
context?: typeof ReactReduxContext;
/**
* Optional, only relevant for plugins still using reflux
*/
actions?: RefluxActions;
/**
* Will be called to clean up plugin subscriptions when it is deactivated by
* app registry scope
*/
deactivate: () => void;
}

@@ -42,7 +51,3 @@ /**

_emitter: EventEmitter;
actions: Record<string, unknown>;
components: Record<string, React.ComponentType<any>>;
stores: Record<string, Store>;
roles: Record<string, Role[]>;
storeMisses: Record<string, number>;
plugins: Record<string, Plugin>;

@@ -54,15 +59,6 @@ /**

this._emitter = new EventEmitter();
this.actions = {};
this.components = {};
this.stores = {};
this.roles = {};
this.storeMisses = {};
this.plugins = {};
}
// Helper until this module is 'proper' fake ESM
static get Actions(): typeof Actions {
return Actions;
}
// Helper until this module is 'proper' fake ESM
static get AppRegistry(): typeof AppRegistry {

@@ -72,201 +68,27 @@ return AppRegistry;

/**
* Deregister an Actions.
*
* @param {String} name - The action to deregister.
*
* @returns {AppRegistry} This instance.
*/
deregisterAction(name: string): this {
delete this.actions[name];
Actions.actionDeregistered(name);
deregisterPlugin(name: string): this {
delete this.plugins[name];
return this;
}
/**
* Deregister a component.
*
* @param {String} name - The component to deregister.
*
* @returns {AppRegistry} This instance.
*/
deregisterComponent(name: string): this {
delete this.components[name];
Actions.componentDeregistered(name);
return this;
getPlugin(name: string): Plugin | undefined {
return this.plugins[name];
}
/**
* Deregister a role.
*
* @param {String} name - The role name.
* @param {Object} object - The role to deregister.
*
* @returns {AppRegistry} This instance.
*/
deregisterRole(name: string, object: Role): this {
const roles = this.roles[name];
roles.splice(roles.indexOf(object), 1);
Actions.roleDeregistered(name);
registerPlugin(name: string, plugin: Plugin): this {
this.plugins[name] = plugin;
return this;
}
/**
* Deregister a store.
*
* @param {String} name - The store to deregister.
*
* @returns {AppRegistry} This instance.
*/
deregisterStore(name: string): this {
delete this.stores[name];
Actions.storeDeregistered(name);
return this;
}
/**
* Get an action for the name.
*
* @param {String} name - The action name.
*
* @returns {Action} The Actions.
*/
getAction(name: string): unknown {
return this.actions[name];
}
/**
* Get a component by name.
*
* @param {String} name - The component name.
*
* @returns {Component} The component.
*/
getComponent(name: string): React.ComponentType<any> | undefined {
return this.components[name];
}
/**
* Get a role by name.
*
* @param {String} name - The role name.
*
* @returns {Array} The role components.
*/
getRole(name: string): Role[] | undefined {
return this.roles[name];
}
/**
* Get a store by name.
*
* @param {String} name - The store name.
*
* @returns {Store} The store.
*/
getStore(name: string): Store {
const store = this.stores[name];
if (store === undefined) {
this.storeMisses[name] = (this.storeMisses[name] || 0) + 1;
return STUB_STORE;
deactivate() {
for (const [name, plugin] of Object.entries(this.plugins)) {
plugin.deactivate?.();
this.deregisterPlugin(name);
}
return store;
}
/**
* Calls onActivated on all the stores in the registry.
*
* @returns {AppRegistry} The app registry.
*/
onActivated(): this {
return this._callOnStores((store) => {
if (store.onActivated) {
store.onActivated(this);
}
});
}
/**
* Register an action in the registry.
*
* @param {String} name - The name of the Actions.
* @param {Action} action - The Actions.
*
* @returns {AppRegistry} This instance.
*/
registerAction(name: string, action: unknown): this {
const overwrite = Object.prototype.hasOwnProperty.call(this.actions, name);
this.actions[name] = action;
if (overwrite) {
Actions.actionOverridden(name);
} else {
Actions.actionRegistered(name);
for (const event of this.eventNames()) {
this.removeAllListeners(event);
}
return this;
}
/**
* Register a component in the registry.
*
* @param {String} name - The name of the component.
* @param {Component} component - The React Component.
*
* @returns {AppRegistry} This instance.
*/
registerComponent(name: string, component: React.ComponentType<any>): this {
const overwrite = Object.prototype.hasOwnProperty.call(
this.components,
name
);
this.components[name] = component;
if (overwrite) {
Actions.componentOverridden(name);
} else {
Actions.componentRegistered(name);
}
return this;
}
/**
* Register a role.
*
* @param {String} name - The role name.
* @param {Object} role - The role object.
*
* @returns {AppRegistry} This instance.
*/
registerRole(name: string, role: Role): this {
if (
Object.prototype.hasOwnProperty.call(this.roles, name) &&
!this.roles[name].includes(role)
) {
this.roles[name].push(role);
this.roles[name].sort(this._roleComparator.bind(this));
} else {
this.roles[name] = [role];
}
Actions.roleRegistered(name);
return this;
}
/**
* Register a store in the registry.
*
* @param name - The name of the store.
* @param store - The Reflux store.
*
* @returns This instance.
*/
registerStore(name: string, store: Store): this {
const overwrite = Object.prototype.hasOwnProperty.call(this.stores, name);
this.stores[name] = store;
if (overwrite) {
Actions.storeOverridden(name);
} else {
Actions.storeRegistered(name);
}
return this;
}
/**
* Adds a listener for the event name to the underlying event emitter.

@@ -377,18 +199,7 @@ *

}
_callOnStores(fn: (store: Store) => void): this {
for (const key of Object.keys(this.stores)) {
const store = this.stores[key];
fn(store);
}
return this;
}
_roleComparator(a: Role, b: Role): number {
const aOrder = a.order || INT8_MAX;
const bOrder = b.order || INT8_MAX;
return aOrder - bOrder;
}
}
export type { Role };
/**
* Create a global app registry and prevent modification.
*/
export const globalAppRegistry = Object.freeze(new AppRegistry());

@@ -1,5 +0,20 @@

import { AppRegistry } from './app-registry';
import type { Role } from './app-registry';
export { AppRegistry };
export type { Role };
import { AppRegistry, globalAppRegistry } from './app-registry';
export { AppRegistry, globalAppRegistry };
export {
AppRegistryProvider,
useGlobalAppRegistry,
useLocalAppRegistry,
GlobalAppRegistryProvider,
} from './react-context';
export type {
HadronPluginComponent,
HadronPluginConfig,
ActivateHelpers,
} from './register-plugin';
export {
registerHadronPlugin,
createActivateHelpers,
createServiceLocator,
createServiceProvider,
} from './register-plugin';
export default AppRegistry;
{
"extends": "@mongodb-js/tsconfig-compass/tsconfig.common.json",
"extends": "@mongodb-js/tsconfig-compass/tsconfig.react.json",
"compilerOptions": {

@@ -4,0 +4,0 @@ "outDir": "dist"

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc