# How does it work?

This article mostly is for the contributors who are willing to enhance the Mosaic's core package's (`@tilework/mosaic`) behaviour with additional functionality.

Read the code for more information, or feel free to use our [Github Discussions](https://github.com/tilework/mosaic/discussions) to ask us for specifics!

## Features

`middleware` - a method to attach a namespace to a piece of functionality and ensure the plugins work for that namespace

`Extensible` - a method to ensure proper context during the construction of the given class. Important for interception of class properties being declared with [class property syntax](https://babeljs.io/docs/en/babel-plugin-proposal-class-properties/) during their initialisation in the constructor

`setPlugins` - a method that accepts an array of modules (which are `.plugin.js` files), sets the internal property and exposes it to the window object.

## How ?

The `middleware` function wraps functionality (further - "middlewarable") into a [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy), and assigns a [namespace](https://docs.mosaic.js.org/develop-an-extension/namespaces) to it.

#### If the middlewarable is a function

When it is called, the following happens:

1. The plugins are being extracted from the `lib/plugins/plugin-storage`&#x20;
2. These plugins are wrapped around the initial function, thus generating a new function&#x20;
3. This function is called on the original arguments

#### If the middlewarable is a class

During the `new` call, the following happens:

1. `Extensible` ensures that the instance is a [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) from the very beginning, this Proxy intercepts all members' accesses and applies plugins on the fly
2. All of the `member-property` plugins are applied to it, replacing the original properties with the ones the plugins result into.

Afterwards, when the object is used,  the following happens:

1. When calling any member of the instance, the plugin storage is scanned for the plugins for that member, and if any are found - they are applied to the callable member before executing it

Also, the following is applied to the class itself

1. The class itself is a [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy), to ensure that calls to static properties are handled as member properties - by immediate replacement. It is a proxy only when is accessed from within its instance, otherwise it is not a proxy.

#### If the middlewarable is a primitive

This is not supported
