Compare commits

...

5 Commits

Author SHA1 Message Date
github-actions[bot]
c2a76c3f53 Version Packages 2021-10-03 17:15:38 +02:00
Thomas Allmer
70bb7a128e feat: update all packages to use new plugins-manager api 2021-10-03 17:10:18 +02:00
Thomas Allmer
3c342473d7 feat(plugin-manager): new type safe API
Co-authored-by: Benny Powers <web@bennypowers.com>
2021-10-03 17:10:18 +02:00
Thomas Allmer
9e0579ab19 chore: version linting considering valid semver 2021-09-13 15:22:52 +02:00
Thomas Allmer
de202da0a5 chore: reenable all tests 2021-09-13 15:22:52 +02:00
72 changed files with 1121 additions and 542 deletions

View File

@@ -1,4 +1,3 @@
# Presets >> Launch || 20
- [Preset](./preset/)
- [Custom Elements](./custom-elements/)

View File

@@ -1,4 +1,3 @@
# Presets >> Search || 10
- [Preset](./preset/)
- [Custom Elements](./custom-elements/)

View File

@@ -3,6 +3,111 @@
The Plugins Manager replaces the specific registration/execution (with options) in a given plugin system by an intend to use a plugin (with these options).
This allows your users to adjust the options before actually applying the plugins.
## Setup
1. Install npm package
```bash
npm i plugins-manager
```
2. Change your public API from an array of plugin "instances" to an array of setup functions
```diff
import myPlugin from 'my-plugin';
+ import { addPlugin } from 'plugins-manager';
export default {
- plugins: [myPlugin],
+ setupPlugins: [addPlugin(myPlugin)]
}
```
3. Convert setup function to plugins
```js
import { applyPlugins } from 'plugins-manager';
const finalConfig = applyPlugins(config); // "converts" setupPlugins to plugins
// work with plugins or pass it on to another tool
const bundle = await rollup(finalConfig);
```
## Usage
As you users in most cases you will need to either add or adjust a given plugin in a config file.
👉 `my-tool.config.js`
```js
import { addPlugin, adjustPluginOptions } from 'plugins-manager';
import json from '@rollup/plugin-json';
import { nodeResolve } from '@rollup/plugin-node-resolve';
export default {
setupPlugins: [
// add a new plugin with optional plugin options
addPlugin(json, {
/* ... */
}),
// adjust the options of a plugin that is already registered
adjustPluginOptions(nodeResolve, {
/* ... */
}),
],
};
```
## Plugins can be functions or classes
### Function Plugins
```js
function myPlugin({ lastName: 'initial-second' }) {
// ...
}
export default {
setupPlugins: [addPlugin(myPlugin)],
};
// function parameters are type safe
addPlugin(myPlugin, { lastName: 'new name' }); // ts ok
addPlugin(myPlugin, { otherProp: 'new name' }); // ts error
```
### Class Plugins
The options are passed to the constructor.
```js
/**
* @typedef {object} MyClassOptions
* @property {string} lastName
*/
class MyClass {
/** @type {MyClassOptions} */
options = {
lastName: 'initial-second',
};
/**
* @param {Partial<MyClassOptions>} options
*/
constructor(options = {}) {
this.options = { ...this.options, ...options };
}
// ...
}
export default {
setupPlugins: [addPlugin(MyClass)],
};
// constructor parameters are type safe
addPlugin(MyClass, { lastName: 'new name' }); // ts ok
addPlugin(MyClass, { otherProp: 'new name' }); // ts error
```
## Problem
Many plugin systems require you to either execute a plugin function like in `rollup`.
@@ -48,18 +153,14 @@ This means if you wish to define default plugins and allow your user to override
The plugins manager lets you orchestrate a set of "meta plugins" which are defined by
- name
- plugin
- options
- plugin (class or function)
- it's options
```js
import beep from '@rollup/plugin-beep';
import url from '@rollup/plugin-url';
let metaPlugins = [
{ name: 'beep', plugin: beep },
{ name: 'url', plugin: url, options: { limit: 10000 } },
];
let metaPlugins = [{ plugin: beep }, { plugin: url, options: { limit: 10000 } }];
```
This array can be modified by adding/removing or adjusting options.
@@ -94,16 +195,13 @@ export default {
### Adding Helpers
Doing array manipulations is kinda error-prone so we offer encourage to use an array of setup function. Where as each setup function can either add a new plugin (with a unique name) or adjust an already existing plugin.
Doing array manipulations is kinda error-prone so we encourage to use an array of setup function. Where as each setup function can either add a new plugin (with a unique name) or adjust an already existing plugin.
```js
import { addPlugin, adjustPluginOptions } from 'plugins-manager';
const systemSetupFunctions = [
addPlugin({ name: 'first', plugin: first }),
addPlugin({ name: 'second', plugin: second }),
];
const userSetupFunctions = [adjustPluginOptions('first', { my: 'options' })];
const systemSetupFunctions = [addPlugin(first), addPlugin(second)];
const userSetupFunctions = [adjustPluginOptions(first, { my: 'options' })];
```
Arrays of functions can by merged like so
@@ -115,9 +213,9 @@ const finalSetupFunctions = [...systemSetupFunctions, ...userSetupFunctions];
and then converted to the final output.
```js
import { metaPluginsToRollupPlugins } from 'plugins-manager';
import { applyPlugins } from 'plugins-manager';
const plugins = metaPluginsToRollupPlugins(finalSetupFunctions, metaPlugins);
const plugins = applyPlugins(finalSetupFunctions, metaPlugins);
```
## Adding a Plugin
@@ -133,18 +231,27 @@ By default it adds at the bottom.
import json from '@rollup/plugin-json';
import { addPlugin } from 'plugins-manager';
const userSetupFunctions = [
addPlugin({ name: 'json', plugin: json, options: { preferConst: true } }),
];
const userSetupFunctions = [addPlugin(json, { preferConst: true })];
```
Example usage:
```js
addPlugin({ name: 'json', plugin: json }); // Add at the bottom (default)
addPlugin({ name: 'json', plugin: json, location: 'top' }); // Add at the top/beginning of the array
addPlugin({ name: 'json', plugin: json, location: 'beep' }); // Add after (default) plugin 'beep'
addPlugin({ name: 'json', plugin: json, location: 'beep', how: 'before' }); // Add before plugin 'beep'
addPlugin(json); // Add at the bottom (default)
addPlugin(json, {}, { location: 'top' }); // Add at the top/beginning of the array
addPlugin(json, {}, { location: beep }); // Add after (default) plugin 'beep'
addPlugin(json, {}, { location: beep, how: 'before' }); // Add before plugin 'beep'
```
This is type safe and typescript will throw an error if you pass the wrong type.
```js
function myPlugin({ myFlag = false } = {}) {
// ...
}
addPlugin(myPlugin, { myFlag: true }); // ts ok
addPlugin(myPlugin, { notExisting: true }); // ts error
```
## Adjusting Plugin Options
@@ -154,12 +261,14 @@ Adjusting options means to either
- flatly merge objects (e.g. only the first level will be preserved)
- calling a function to do the merge yourself
- setting the raw value (if not an object or function)
- you need to have a reference to the plugin (which is used to auto complete the available options via typescript)
```js
import json from '@rollup/plugin-json';
import { adjustPluginOptions } from 'plugins-manager';
const userSetupFunctions = [
adjustPluginOptions('json', { preferConst: false, anotherOption: 'format' }),
adjustPluginOptions(json, { preferConst: false, anotherOption: 'format' }),
];
```
@@ -167,36 +276,53 @@ Example usage:
```js
// given
addPlugin({
name: 'json',
plugin: json,
options: {
other: {
nested: 'other.nested',
nested2: 'other.nested2',
},
main: true,
addPlugin(json, {
other: {
nested: 'other.nested',
nested2: 'other.nested2',
},
main: true,
});
// merge objects flately
adjustPluginOptions('json', { other: { nested: '--overwritten--' } });
adjustPluginOptions(json, { other: { nested: '--overwritten--' } });
// resulting options = { other: { nested: '--overwritten--' }, main: true }
// NOTE: nested2 is removed
// merge via function
adjustPluginOptions('json', config => ({ other: { ...config.other, nested: '--overwritten--' } }));
adjustPluginOptions(json, config => ({ other: { ...config.other, nested: '--overwritten--' } }));
// resulting options = { other: { nested: '--overwritten--', nested2: 'other.nested2' }, main: true }
// merge via function to override full options
adjustPluginOptions('json', config => ({ only: 'this' }));
adjustPluginOptions(json, config => ({ only: 'this' }));
// resulting options = { only: 'this' }
// setting a raw value
adjustPluginOptions('json', false);
adjustPluginOptions(json, false);
// resulting options = false
```
This is type safe and typescript will throw an error if you pass the wrong type.
```js
function myPlugin({ myFlag = false } = {}) {
// ...
}
adjustPluginOptions(myPlugin, { myFlag: true }); // ts ok
adjustPluginOptions(myPlugin, { notExisting: true }); // ts error
```
## Remove Plugin
Sometimes you would like to remove a default plugin from the config.
```js
export default {
setupPlugins: [removePlugin(json)],
};
```
## Converting metaPlugins to an Actual Plugin
To execute all setup function you can use this little helper
@@ -227,25 +353,9 @@ Rollup has a more specific helper that handles
Note: if you provide `config.plugins` then it will return that directly ignoring `setupPlugins`
```js
import { metaConfigToRollupConfig } from 'plugins-manager';
import { applyPlugins } from 'plugins-manager';
const finalConfig = metaConfigToRollupConfig(currentConfig, defaultMetaPlugins);
```
Web Dev Server has a more specific helper that handles
- `config.setupPlugins`
- `config.setupRollupPlugins`
Note: if you provide `config.plugins` then it will return that directly ignoring `setupPlugins` and `setupRollupPlugins`
```js
import { metaConfigToWebDevServerConfig } from 'plugins-manager';
import { fromRollup } from '@web/dev-server-rollup';
const finalConfig = metaConfigToWebDevServerConfig(currentConfig, defaultMetaPlugins, {
rollupWrapperFunction: fromRollup,
});
const finalConfig = applyPlugins(currentConfig, defaultMetaPlugins);
```
Eleventy

View File

@@ -33,8 +33,8 @@
"setup": "npm run setup:ts-configs && npm run build:packages",
"setup:patches": "npx patch-package",
"setup:ts-configs": "node scripts/generate-ts-configs.mjs",
"prestart": "yarn analyze",
"start": "node packages/cli/src/cli.js start",
"xprestart": "yarn analyze",
"start": "node --trace-warnings packages/cli/src/cli.js start",
"test": "yarn test:node && yarn test:web",
"test:node": "mocha \"packages/*/test-node/**/*.test.{ts,js,mjs,cjs}\" --timeout 5000 --reporter dot --exit",
"test:web": "web-test-runner",
@@ -80,6 +80,7 @@
"onchange": "^7.1.0",
"prettier": "^2.2.1",
"prettier-plugin-package": "^1.3.0",
"publish-docs": "^0.1.2",
"puppeteer": "^9.0.0",
"remark-emoji": "^2.1.0",
"rimraf": "^3.0.2",

View File

@@ -1,5 +1,32 @@
# @rocket/blog
## 0.4.0
### Minor Changes
- 70bb7a1: BREAKING CHANGE: Update to latest plugins manager to get type safe options
There is no longer a name string as a key for a plugin. It is identified by it's function/class. You will need to adjust your code if you are adding or adjusting plugins.
```diff
- addPlugin({ name: 'my-plugin', plugin: myPlugin, options: { myFlag: true }, location: 'top' });
+ addPlugin(myPlugin, { myFlag: true }, { location: 'top' });
- adjustPluginOptions('my-plugin', { myFlag: true });
+ adjustPluginOptions(myPlugin, { myFlag: true });
```
For more details please see the [Changelog](https://github.com/modernweb-dev/rocket/blob/main/packages/plugins-manager/CHANGELOG.md#030) of the plugins-manager package.
### Patch Changes
- Updated dependencies [70bb7a1]
- Updated dependencies [70bb7a1]
- Updated dependencies [70bb7a1]
- Updated dependencies [70bb7a1]
- Updated dependencies [70bb7a1]
- Updated dependencies [70bb7a1]
- plugins-manager@0.3.0
## 0.3.3
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "@rocket/blog",
"version": "0.3.3",
"version": "0.4.0",
"publishConfig": {
"access": "public"
},
@@ -38,6 +38,6 @@
"testing"
],
"dependencies": {
"plugins-manager": "^0.2.4"
"plugins-manager": "^0.3.0"
}
}

View File

@@ -47,6 +47,6 @@ export function rocketBlog({ section = SECTION, postCollection = POST_COLLECTION
return {
path: path.resolve(__dirname),
setupEleventyPlugins: [addPlugin({ name: 'rocket-blog', plugin: eleventyPluginRocketBlog })],
setupEleventyPlugins: [addPlugin(eleventyPluginRocketBlog)],
};
}

View File

@@ -1,5 +1,22 @@
# @rocket/building-rollup
## 0.4.0
### Minor Changes
- 70bb7a1: BREAKING CHANGE: Update to latest plugins manager to get type safe options
There is no longer a name string as a key for a plugin. It is identified by it's function/class. You will need to adjust your code if you are adding or adjusting plugins.
```diff
- addPlugin({ name: 'my-plugin', plugin: myPlugin, options: { myFlag: true }, location: 'top' });
+ addPlugin(myPlugin, { myFlag: true }, { location: 'top' });
- adjustPluginOptions('my-plugin', { myFlag: true });
+ adjustPluginOptions(myPlugin, { myFlag: true });
```
For more details please see the [Changelog](https://github.com/modernweb-dev/rocket/blob/main/packages/plugins-manager/CHANGELOG.md#030) of the plugins-manager package.
## 0.3.1
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "@rocket/building-rollup",
"version": "0.3.1",
"version": "0.4.0",
"publishConfig": {
"access": "public"
},

View File

@@ -2,13 +2,13 @@ import resolve from '@rollup/plugin-node-resolve';
import { terser } from 'rollup-plugin-terser';
import babelPkg from '@rollup/plugin-babel';
import { metaConfigToRollupConfig } from 'plugins-manager';
import { applyPlugins } from 'plugins-manager';
const { babel } = babelPkg;
export function createBasicConfig(userConfig) {
const { config, metaPlugins } = createBasicMetaConfig(userConfig);
return metaConfigToRollupConfig(config, metaPlugins);
return applyPlugins(config, metaPlugins);
}
export function createBasicMetaConfig(userConfig = { output: {} }) {
@@ -39,14 +39,12 @@ export function createBasicMetaConfig(userConfig = { output: {} }) {
let metaPlugins = [
{
name: 'node-resolve',
plugin: resolve,
options: {
moduleDirectories: ['node_modules', 'web_modules'],
},
},
{
name: 'babel',
plugin: babel,
options: {
babelHelpers: 'bundled',
@@ -73,7 +71,6 @@ export function createBasicMetaConfig(userConfig = { output: {} }) {
},
},
{
name: 'terser',
plugin: terser,
},
];

View File

@@ -1,10 +1,11 @@
import { createSpaMetaConfig } from './createSpaConfig.js';
import { adjustPluginOptions, metaConfigToRollupConfig } from 'plugins-manager';
import { adjustPluginOptions, applyPlugins } from 'plugins-manager';
import { rollupPluginHTML } from '@web/rollup-plugin-html';
export function createMpaConfig(userConfig) {
const { config, metaPlugins } = createMpaMetaConfig(userConfig);
const final = metaConfigToRollupConfig(config, metaPlugins);
const final = applyPlugins(config, metaPlugins);
return final;
}
@@ -12,7 +13,7 @@ export function createMpaMetaConfig(userConfig = { output: {}, setupPlugins: []
const { config, metaPlugins } = createSpaMetaConfig(userConfig);
config.setupPlugins = [
adjustPluginOptions('html', {
adjustPluginOptions(rollupPluginHTML, {
flattenOutput: false,
}),
...config.setupPlugins,

View File

@@ -3,13 +3,13 @@ import { terser } from 'rollup-plugin-terser';
import babelPkg from '@rollup/plugin-babel';
import replace from '@rollup/plugin-replace';
import { metaConfigToRollupConfig } from 'plugins-manager';
import { applyPlugins } from 'plugins-manager';
const { babel } = babelPkg;
export function createServiceWorkerConfig(userConfig) {
const { config, metaPlugins } = createServiceWorkerMetaConfig(userConfig);
return metaConfigToRollupConfig(config, metaPlugins);
return applyPlugins(config, metaPlugins);
}
export function createServiceWorkerMetaConfig(userConfig = { output: {} }) {
@@ -33,21 +33,18 @@ export function createServiceWorkerMetaConfig(userConfig = { output: {} }) {
let metaPlugins = [
{
name: 'node-resolve',
plugin: resolve,
options: {
moduleDirectories: ['node_modules', 'web_modules'],
},
},
{
name: 'replace',
plugin: replace,
options: {
'process.env.NODE_ENV': JSON.stringify(developmentMode ? 'development' : 'production'),
},
},
{
name: 'babel',
plugin: babel,
options: {
babelHelpers: 'bundled',
@@ -74,7 +71,6 @@ export function createServiceWorkerMetaConfig(userConfig = { output: {} }) {
},
},
{
name: 'terser',
plugin: terser,
options: {
mangle: {

View File

@@ -1,13 +1,13 @@
import { rollupPluginHTML } from '@web/rollup-plugin-html';
import { importMetaAssets } from '@web/rollup-plugin-import-meta-assets';
import { polyfillsLoader } from '@web/rollup-plugin-polyfills-loader';
import { metaConfigToRollupConfig } from 'plugins-manager';
import { applyPlugins } from 'plugins-manager';
import { createBasicMetaConfig } from './createBasicConfig.js';
export function createSpaConfig(userConfig) {
const { config, metaPlugins } = createSpaMetaConfig(userConfig);
return metaConfigToRollupConfig(config, metaPlugins);
return applyPlugins(config, metaPlugins);
}
export function createSpaMetaConfig(userConfig = { output: {} }) {
@@ -30,7 +30,6 @@ export function createSpaMetaConfig(userConfig = { output: {} }) {
const spaMetaPlugins = [
...metaPlugins,
{
name: 'html',
plugin: rollupPluginHTML,
options: {
rootDir,
@@ -38,11 +37,9 @@ export function createSpaMetaConfig(userConfig = { output: {} }) {
},
},
{
name: 'import-meta-assets',
plugin: importMetaAssets,
},
{
name: 'polyfills-loader',
plugin: polyfillsLoader,
options: {
polyfills: {},

View File

@@ -1,5 +1,36 @@
# @rocket/cli
## 0.10.0
### Minor Changes
- 70bb7a1: BREAKING CHANGE: Update to latest plugins manager to get type safe options
There is no longer a name string as a key for a plugin. It is identified by it's function/class. You will need to adjust your code if you are adding or adjusting plugins.
```diff
- addPlugin({ name: 'my-plugin', plugin: myPlugin, options: { myFlag: true }, location: 'top' });
+ addPlugin(myPlugin, { myFlag: true }, { location: 'top' });
- adjustPluginOptions('my-plugin', { myFlag: true });
+ adjustPluginOptions(myPlugin, { myFlag: true });
```
For more details please see the [Changelog](https://github.com/modernweb-dev/rocket/blob/main/packages/plugins-manager/CHANGELOG.md#030) of the plugins-manager package.
### Patch Changes
- Updated dependencies [70bb7a1]
- Updated dependencies [70bb7a1]
- Updated dependencies [70bb7a1]
- Updated dependencies [70bb7a1]
- Updated dependencies [70bb7a1]
- Updated dependencies [70bb7a1]
- Updated dependencies [70bb7a1]
- Updated dependencies [70bb7a1]
- plugins-manager@0.3.0
- @rocket/eleventy-plugin-mdjs-unified@0.6.0
- @rocket/building-rollup@0.4.0
## 0.9.11
### Patch Changes

View File

@@ -1,10 +1,26 @@
const { setComputedConfig, getComputedConfig } = require('./src/public/computedConfig.cjs');
const { generateEleventyComputed } = require('./src/public/generateEleventyComputed.cjs');
const {
generateEleventyComputed,
LayoutPlugin,
TitleMetaPlugin,
TitlePlugin,
EleventyNavigationPlugin,
SectionPlugin,
SocialMediaImagePlugin,
JoiningBlocksPlugin,
} = require('./src/public/generateEleventyComputed.cjs');
const { createSocialImage } = require('./src/public/createSocialImage.cjs');
module.exports = {
setComputedConfig,
getComputedConfig,
generateEleventyComputed,
LayoutPlugin,
TitleMetaPlugin,
TitlePlugin,
EleventyNavigationPlugin,
SectionPlugin,
SocialMediaImagePlugin,
JoiningBlocksPlugin,
createSocialImage,
};

View File

@@ -1,3 +1,16 @@
/** @typedef {import('@rocket/cli/types/main').RocketCliOptions} RocketCliOptions */
export { setComputedConfig, getComputedConfig } from './src/public/computedConfig.cjs';
export {
generateEleventyComputed,
LayoutPlugin,
TitleMetaPlugin,
TitlePlugin,
EleventyNavigationPlugin,
SectionPlugin,
SocialMediaImagePlugin,
JoiningBlocksPlugin,
} from './src/public/generateEleventyComputed.cjs';
export { createSocialImage } from './src/public/createSocialImage.cjs';
export { RocketCli } from './src/RocketCli.js';

View File

@@ -1,6 +1,6 @@
{
"name": "@rocket/cli",
"version": "0.9.11",
"version": "0.10.0",
"publishConfig": {
"access": "public"
},
@@ -57,9 +57,9 @@
"dependencies": {
"@11ty/eleventy": "^0.11.1",
"@11ty/eleventy-img": "^0.9.0",
"@rocket/building-rollup": "^0.3.1",
"@rocket/building-rollup": "^0.4.0",
"@rocket/core": "^0.1.2",
"@rocket/eleventy-plugin-mdjs-unified": "^0.5.2",
"@rocket/eleventy-plugin-mdjs-unified": "^0.6.0",
"@rocket/eleventy-rocket-nav": "^0.3.0",
"@rollup/plugin-babel": "^5.2.2",
"@rollup/plugin-node-resolve": "^11.0.1",
@@ -72,7 +72,7 @@
"command-line-usage": "^6.1.1",
"fs-extra": "^9.0.1",
"micromatch": "^4.0.2",
"plugins-manager": "^0.2.4",
"plugins-manager": "^0.3.0",
"slash": "^3.0.0",
"utf8": "^3.0.0",
"workbox-window": "^6.1.5"

View File

@@ -5,6 +5,7 @@ import { rollup } from 'rollup';
import fs from 'fs-extra';
import path from 'path';
import { copy } from '@web/rollup-plugin-copy';
import { rollupPluginHTML } from '@web/rollup-plugin-html';
import { createMpaConfig, createServiceWorkerConfig } from '@rocket/building-rollup';
import { addPlugin, adjustPluginOptions } from 'plugins-manager';
@@ -25,18 +26,14 @@ async function buildAndWrite(config) {
async function productionBuild(config) {
const defaultSetupPlugins = [
addPlugin({
name: 'copy',
plugin: copy,
options: {
patterns: ['!(*.md|*.html)*', '_merged_assets/_static/**/*'],
rootDir: config.outputDevDir,
},
addPlugin(copy, {
patterns: ['!(*.md|*.html)*', '_merged_assets/_static/**/*'],
rootDir: config.outputDevDir,
}),
];
if (config.pathPrefix) {
defaultSetupPlugins.push(
adjustPluginOptions('html', { absolutePathPrefix: config.pathPrefix }),
adjustPluginOptions(rollupPluginHTML, { absolutePathPrefix: config.pathPrefix }),
);
}

View File

@@ -1,11 +1,61 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
import { startDevServer } from '@web/dev-server';
import { fromRollup } from '@web/dev-server-rollup';
import { metaConfigToWebDevServerConfig } from 'plugins-manager';
import { executeSetupFunctions } from 'plugins-manager';
/** @typedef {import('../types/main').RocketCliOptions} RocketCliOptions */
/** @typedef {import('@web/dev-server').DevServerConfig} DevServerConfig */
/**
* @param {any} config
* @param {MetaPluginWrapable[]} metaPlugins
* @param {object} [options]
* @param {function | null} [options.rollupWrapperFunction]
*/
export function metaConfigToWebDevServerConfig(
config,
metaPlugins,
{ rollupWrapperFunction = null } = {},
) {
if (config.plugins) {
delete config.setupPlugins;
delete config.setupRollupPlugins;
return config;
}
const metaPluginsNoWrap = metaPlugins.map(pluginObj => {
pluginObj.__noWrap = true;
return pluginObj;
});
const rollupPlugins = /** @type {MetaPluginWrapable[]} */ (executeSetupFunctions(
config.setupRollupPlugins,
[...metaPluginsNoWrap],
));
const wrappedRollupPlugins = rollupPlugins.map(pluginObj => {
if (typeof rollupWrapperFunction === 'function' && pluginObj.__noWrap !== true) {
pluginObj.plugin = rollupWrapperFunction(pluginObj.plugin);
}
return pluginObj;
});
const _metaPlugins = executeSetupFunctions(config.setupPlugins, [...wrappedRollupPlugins]);
const plugins = _metaPlugins.map(pluginObj => {
if (pluginObj.options) {
return pluginObj.plugin(pluginObj.options);
} else {
return pluginObj.plugin();
}
});
config.plugins = plugins;
delete config.setupPlugins;
delete config.setupRollupPlugins;
return config;
}
export class RocketStart {
static pluginName = 'RocketStart';
commands = ['start'];

View File

@@ -174,11 +174,7 @@ export async function normalizeConfig(inConfig) {
config._presetPaths.push(path.resolve(_inputDirCwdRelative));
/** @type {MetaPlugin[]} */
let pluginsMeta = [
{ name: 'RocketStart', plugin: RocketStart },
{ name: 'RocketBuild', plugin: RocketBuild },
{ name: 'RocketLint', plugin: RocketLint },
];
let pluginsMeta = [{ plugin: RocketStart }, { plugin: RocketBuild }, { plugin: RocketLint }];
if (Array.isArray(config.setupCliPlugins)) {
for (const setupFn of config.setupCliPlugins) {

View File

@@ -5,8 +5,10 @@ const { createSocialImage: defaultCreateSocialImage } = require('./createSocialI
const { getComputedConfig } = require('./computedConfig.cjs');
const { executeSetupFunctions } = require('plugins-manager');
function titleMetaPlugin() {
return async data => {
class TitleMetaPlugin {
static dataName = 'titleMeta';
async execute(data) {
if (data.titleMeta) {
return data.titleMeta;
}
@@ -17,29 +19,35 @@ function titleMetaPlugin() {
return titleMetaFromContent;
}
return {};
};
}
}
function titlePlugin() {
return async data => {
class TitlePlugin {
static dataName = 'title';
async execute(data) {
if (data.title) {
return data.title;
}
return data.titleMeta?.title;
};
}
}
function eleventyNavigationPlugin() {
return async data => {
class EleventyNavigationPlugin {
static dataName = 'eleventyNavigation';
async execute(data) {
if (data.eleventyNavigation) {
return data.eleventyNavigation;
}
return data.titleMeta?.eleventyNavigation;
};
}
}
function sectionPlugin() {
return async data => {
class SectionPlugin {
static dataName = 'section';
async execute(data) {
if (data.section) {
return data.section;
}
@@ -52,11 +60,17 @@ function sectionPlugin() {
return parts[1];
}
}
};
}
}
function layoutPlugin({ defaultLayout = 'layout-default' } = {}) {
return async data => {
class LayoutPlugin {
static dataName = 'layout';
constructor({ defaultLayout = 'layout-default' } = {}) {
this.defaultLayout = defaultLayout;
}
async execute(data) {
if (data.layout) {
return data.layout;
}
@@ -66,22 +80,29 @@ function layoutPlugin({ defaultLayout = 'layout-default' } = {}) {
return 'layout-index';
}
}
return defaultLayout;
};
return this.defaultLayout;
}
}
function socialMediaImagePlugin(args = {}) {
const { createSocialImage = defaultCreateSocialImage, rocketConfig = {} } = args;
class SocialMediaImagePlugin {
static dataName = 'socialMediaImage';
const cleanedUpArgs = { ...args };
delete cleanedUpArgs.createSocialImage;
constructor(args = {}) {
const { createSocialImage = defaultCreateSocialImage, rocketConfig = {} } = args;
return async data => {
this.cleanedUpArgs = { ...args };
delete this.cleanedUpArgs.createSocialImage;
this.rocketConfig = rocketConfig;
this.createSocialImage = createSocialImage;
}
async execute(data) {
if (data.socialMediaImage) {
return data.socialMediaImage;
}
if (rocketConfig.createSocialMediaImages === false) {
if (this.rocketConfig.createSocialMediaImages === false) {
return;
}
@@ -95,15 +116,15 @@ function socialMediaImagePlugin(args = {}) {
const section = data.section ? ' ' + data.section[0].toUpperCase() + data.section.slice(1) : '';
const footer = `${data.site.name}${section}`;
const imgUrl = await createSocialImage({
const imgUrl = await this.createSocialImage({
title,
subTitle,
footer,
section,
...cleanedUpArgs,
...this.cleanedUpArgs,
});
return imgUrl;
};
}
}
function sortByOrder(a, b) {
@@ -146,26 +167,31 @@ async function dirToTree(sourcePath, extra = '') {
return sortedTree;
}
function joiningBlocksPlugin(rocketConfig) {
const { _inputDirCwdRelative } = rocketConfig;
const partialsSource = path.resolve(_inputDirCwdRelative, '_merged_includes');
return async () => {
const joiningBlocks = await dirToTree(partialsSource, '_joiningBlocks');
class JoiningBlocksPlugin {
static dataName = '_joiningBlocks';
constructor(rocketConfig) {
const { _inputDirCwdRelative } = rocketConfig;
this.partialsSource = path.resolve(_inputDirCwdRelative, '_merged_includes');
}
async execute() {
const joiningBlocks = await dirToTree(this.partialsSource, '_joiningBlocks');
return joiningBlocks;
};
}
}
function generateEleventyComputed() {
const rocketConfig = getComputedConfig();
let metaPlugins = [
{ name: 'titleMeta', plugin: titleMetaPlugin },
{ name: 'title', plugin: titlePlugin },
{ name: 'eleventyNavigation', plugin: eleventyNavigationPlugin },
{ name: 'section', plugin: sectionPlugin },
{ name: 'socialMediaImage', plugin: socialMediaImagePlugin, options: { rocketConfig } },
{ name: '_joiningBlocks', plugin: joiningBlocksPlugin, options: rocketConfig },
{ name: 'layout', plugin: layoutPlugin },
{ plugin: TitleMetaPlugin, options: {} },
{ plugin: TitlePlugin, options: {} },
{ plugin: EleventyNavigationPlugin, options: {} },
{ plugin: SectionPlugin, options: {} },
{ plugin: SocialMediaImagePlugin, options: { rocketConfig } },
{ plugin: JoiningBlocksPlugin, options: rocketConfig },
{ plugin: LayoutPlugin, options: {} },
];
const finalMetaPlugins = executeSetupFunctions(
@@ -176,13 +202,24 @@ function generateEleventyComputed() {
const eleventyComputed = {};
for (const pluginObj of finalMetaPlugins) {
if (pluginObj.options) {
eleventyComputed[pluginObj.name] = pluginObj.plugin(pluginObj.options);
const inst = new pluginObj.plugin(pluginObj.options);
eleventyComputed[inst.constructor.dataName] = inst.execute.bind(inst);
} else {
eleventyComputed[pluginObj.name] = pluginObj.plugin();
const inst = new pluginObj.plugin();
eleventyComputed[inst.constructor.dataName] = inst.execute.bind(inst);
}
}
return eleventyComputed;
}
module.exports = { generateEleventyComputed };
module.exports = {
generateEleventyComputed,
LayoutPlugin,
TitleMetaPlugin,
TitlePlugin,
EleventyNavigationPlugin,
SectionPlugin,
SocialMediaImagePlugin,
JoiningBlocksPlugin,
};

View File

@@ -1,5 +1,6 @@
const eleventyPluginMdjsUnified = require('@rocket/eleventy-plugin-mdjs-unified');
const eleventyRocketNav = require('@rocket/eleventy-rocket-nav');
const remark2rehype = require('remark-rehype');
const { getComputedConfig } = require('../public/computedConfig.cjs');
const rocketFilters = require('../eleventy-plugins/rocketFilters.cjs');
@@ -9,7 +10,7 @@ const { adjustPluginOptions } = require('plugins-manager');
const image = require('./mdjsImageHandler.cjs');
const defaultSetupUnifiedPlugins = [
adjustPluginOptions('remark2rehype', {
adjustPluginOptions(remark2rehype, {
handlers: {
image,
},
@@ -23,28 +24,24 @@ module.exports = function (eleventyConfig) {
let metaPlugins = [
{
name: 'rocket-filters',
plugin: rocketFilters,
options: { _inputDirCwdRelative },
},
{
name: 'rocket-copy',
plugin: rocketCopy,
options: { _inputDirCwdRelative },
},
{
name: 'eleventy-plugin-mdjs-unified',
plugin: eleventyPluginMdjsUnified,
options: {
setupUnifiedPlugins: [...defaultSetupUnifiedPlugins, ...config.setupUnifiedPlugins],
},
},
{
name: 'eleventy-rocket-nav',
plugin: eleventyRocketNav,
options: {},
},
{
name: 'rocket-collections',
plugin: rocketCollections,
options: { _inputDirCwdRelative },
},

View File

@@ -19,7 +19,7 @@ describe('RocketCli preset', () => {
}
});
it.only('offers a default layout (with head, header, content, footer, bottom) and raw layout', async () => {
it('offers a default layout (with head, header, content, footer, bottom) and raw layout', async () => {
cli = await executeStart('preset-fixtures/default/rocket.config.js');
const rawHtml = await readStartOutput(cli, 'raw/index.html');

View File

@@ -31,7 +31,7 @@ describe('RocketCli e2e', () => {
}
});
it.only('will add a script to inject the service worker', async () => {
it('will add a script to inject the service worker', async () => {
cli = await executeBuild('e2e-fixtures/service-worker/rocket.config.js');
const indexHtml = await readStartOutput(cli, 'index.html');
const indexInject = getInjectServiceWorker(indexHtml);

View File

@@ -1,3 +1,4 @@
import remark2rehype from 'remark-rehype';
import { adjustPluginOptions } from 'plugins-manager';
function image(h, node) {
@@ -10,7 +11,7 @@ function image(h, node) {
/** @type {Partial<import("../../../types/main").RocketCliOptions>} */
const config = {
setupUnifiedPlugins: [
adjustPluginOptions('remark2rehype', {
adjustPluginOptions(remark2rehype, {
handlers: {
image,
},

View File

@@ -1,8 +1,16 @@
import { addPlugin } from 'plugins-manager';
class Test {
static dataName = 'test';
execute() {
return 'test-value';
}
}
/** @type {Partial<import("../../../types/main").RocketCliOptions>} */
const config = {
setupEleventyComputedConfig: [addPlugin({ name: 'test', plugin: () => 'test-value' })],
setupEleventyComputedConfig: [addPlugin(Test)],
};
export default config;

View File

@@ -1,4 +1,5 @@
import { adjustPluginOptions } from 'plugins-manager';
import { SocialMediaImagePlugin } from '@rocket/cli';
/** @type {Partial<import("../../../types/main").RocketCliOptions>} */
const config = {
@@ -6,7 +7,7 @@ const config = {
createSocialMediaImages: true,
},
setupEleventyComputedConfig: [
adjustPluginOptions('socialMediaImage', {
adjustPluginOptions(SocialMediaImagePlugin, {
createSocialImageSvg: async () => {
return `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 630">

View File

@@ -1,11 +1,14 @@
// @ts-no-check
import json from '@rollup/plugin-json';
import { rollupPluginHTML } from '@web/rollup-plugin-html';
import { addPlugin, adjustPluginOptions } from 'plugins-manager';
/** @type {Partial<import("../../../types/main").RocketCliOptions>} */
const config = {
setupDevAndBuildPlugins: [addPlugin({ name: 'json', plugin: json, location: 'top' })],
setupBuildPlugins: [adjustPluginOptions('html', { absoluteBaseUrl: 'https://test-me.com' })],
setupDevAndBuildPlugins: [addPlugin(json, {}, { location: 'top' })],
setupBuildPlugins: [
adjustPluginOptions(rollupPluginHTML, { absoluteBaseUrl: 'https://test-me.com' }),
],
};
export default config;

View File

@@ -1,10 +1,9 @@
// @ts-no-check
import json from '@rollup/plugin-json';
import { addPlugin } from 'plugins-manager';
/** @type {Partial<import("../../../types/main").RocketCliOptions>} */
const config = {
setupDevAndBuildPlugins: [addPlugin({ name: 'json', plugin: json, location: 'top' })],
setupDevAndBuildPlugins: [addPlugin(json, {}, { location: 'top' })],
devServer: {
mimeTypes: {
// serve all json files as js

View File

@@ -1,10 +1,11 @@
// @ts-check
import emoji from 'remark-emoji';
import { addPlugin } from 'plugins-manager';
import markdown from 'remark-parse';
/** @type {Partial<import("../../../types/main").RocketCliOptions>} */
const config = {
setupUnifiedPlugins: [addPlugin({ location: 'markdown', name: 'emoji', plugin: emoji })],
setupUnifiedPlugins: [addPlugin(emoji, {}, { location: markdown })],
};
export default config;

View File

@@ -1,5 +1,16 @@
# @rocket/eleventy-plugin-mdjs-unified
## 0.6.0
### Minor Changes
- 70bb7a1: BREAKING CHANGE: Updating to latest version of `@mdjs/core` which requires the latest version of `plugins-manager`
### Patch Changes
- Updated dependencies [70bb7a1]
- @mdjs/core@0.9.0
## 0.5.2
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "@rocket/eleventy-plugin-mdjs-unified",
"version": "0.5.2",
"version": "0.6.0",
"publishConfig": {
"access": "public"
},
@@ -31,7 +31,7 @@
"mdjs"
],
"dependencies": {
"@mdjs/core": "^0.8.2",
"@mdjs/core": "^0.9.0",
"es-module-lexer": "^0.3.26",
"unist-util-visit": "^2.0.3"
},

View File

@@ -5,6 +5,7 @@ const fs = require('fs');
const { mdjsProcess } = require('@mdjs/core');
const visit = require('unist-util-visit');
const { init, parse } = require('es-module-lexer');
const markdown = require('remark-parse');
// @ts-ignore
const { parseTitle } = require('@rocket/core/title');
@@ -45,12 +46,12 @@ function cleanupTitleHeadline() {
* @param {MdjsProcessPlugin[]} plugins
*/
function addCleanupTitleHeadline(plugins) {
if (plugins.findIndex(plugin => plugin.name === 'cleanupTitleHeadline') === -1) {
if (plugins.findIndex(pluginObj => pluginObj.plugin === cleanupTitleHeadline) === -1) {
// add plugins right after markdown
const markdownPluginIndex = plugins.findIndex(plugin => plugin.name === 'markdown');
const markdownPluginIndex = plugins.findIndex(pluginObj => pluginObj.plugin === markdown);
plugins.splice(markdownPluginIndex + 1, 0, {
name: 'cleanupTitleHeadline',
plugin: cleanupTitleHeadline,
options: {},
});
}
return plugins;

View File

@@ -1,8 +1,9 @@
const htmlHeading = require('rehype-autolink-headings');
const pluginMdjs = require('../../../index.js');
function addClassAnchorToHtmlHeading(plugins) {
return plugins.map(pluginObj => {
if (pluginObj.name === 'htmlHeading') {
if (pluginObj.plugin === htmlHeading) {
return {
...pluginObj,
options: {

View File

@@ -1,5 +1,22 @@
# @rocket/launch
## 0.6.0
### Minor Changes
- 70bb7a1: BREAKING CHANGE: Update to latest plugins manager to get type safe options
There is no longer a name string as a key for a plugin. It is identified by it's function/class. You will need to adjust your code if you are adding or adjusting plugins.
```diff
- addPlugin({ name: 'my-plugin', plugin: myPlugin, options: { myFlag: true }, location: 'top' });
+ addPlugin(myPlugin, { myFlag: true }, { location: 'top' });
- adjustPluginOptions('my-plugin', { myFlag: true });
+ adjustPluginOptions(myPlugin, { myFlag: true });
```
For more details please see the [Changelog](https://github.com/modernweb-dev/rocket/blob/main/packages/plugins-manager/CHANGELOG.md#030) of the plugins-manager package.
## 0.5.6
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "@rocket/launch",
"version": "0.5.6",
"version": "0.6.0",
"publishConfig": {
"access": "public"
},

View File

@@ -2,12 +2,14 @@ import path from 'path';
import { adjustPluginOptions } from 'plugins-manager';
// import { addPlugin } from 'plugins-manager';
import { fileURLToPath } from 'url';
import { LayoutPlugin } from '@rocket/cli';
import htmlHeading from 'rehype-autolink-headings';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
function addOcticonToHeadlines(plugins) {
return plugins.map(pluginObj => {
if (pluginObj.name === 'htmlHeading') {
if (pluginObj.plugin === htmlHeading) {
return {
...pluginObj,
options: {
@@ -50,7 +52,7 @@ export function rocketLaunch() {
path: path.resolve(__dirname),
setupUnifiedPlugins: [addOcticonToHeadlines],
setupEleventyComputedConfig: [
adjustPluginOptions('layout', { defaultLayout: 'layout-sidebar' }),
adjustPluginOptions(LayoutPlugin, { defaultLayout: 'layout-sidebar' }),
],
adjustImagePresets: imagePresets => ({
...imagePresets,

View File

@@ -19,7 +19,7 @@ describe('RocketLaunch preset', () => {
}
});
it.only('sets layout-sidebar as default', async () => {
it('sets layout-sidebar as default', async () => {
cli = await executeStart('fixtures/layout-sidebar/rocket.config.js');
const indexHtml = await readStartOutput(cli, 'page/index.html', {
@@ -502,12 +502,6 @@ describe('RocketLaunch preset', () => {
' </footer>',
'',
' <script type="module" src="/_merged_assets/scripts/init-navigation.js"></script>',
'',
' <script',
' type="module"',
' inject-service-worker=""',
' src="/_merged_assets/scripts/registerServiceWorker.js"',
' ></script>',
' </body>',
'</html>',
].join('\n'),

View File

@@ -1,5 +1,32 @@
# Change Log
## 0.9.0
### Minor Changes
- 70bb7a1: BREAKING CHANGE: Update to latest plugins manager to get type safe options
There is no longer a name string as a key for a plugin. It is identified by it's function/class. You will need to adjust your code if you are adding or adjusting plugins.
```diff
- addPlugin({ name: 'my-plugin', plugin: myPlugin, options: { myFlag: true }, location: 'top' });
+ addPlugin(myPlugin, { myFlag: true }, { location: 'top' });
- adjustPluginOptions('my-plugin', { myFlag: true });
+ adjustPluginOptions(myPlugin, { myFlag: true });
```
For more details please see the [Changelog](https://github.com/modernweb-dev/rocket/blob/main/packages/plugins-manager/CHANGELOG.md#030) of the plugins-manager package.
### Patch Changes
- Updated dependencies [70bb7a1]
- Updated dependencies [70bb7a1]
- Updated dependencies [70bb7a1]
- Updated dependencies [70bb7a1]
- Updated dependencies [70bb7a1]
- Updated dependencies [70bb7a1]
- plugins-manager@0.3.0
## 0.8.2
### Patch Changes

View File

@@ -3,6 +3,7 @@
/** @typedef {import('@mdjs/core/types/code').MdjsProcessPlugin} MdjsProcessPlugin */
const { mdjsParse } = require('./src/mdjsParse.js');
const { mdjsSetupCode } = require('./src/mdjsSetupCode.js');
const { mdjsStoryParse } = require('./src/mdjsStoryParse.js');
const { mdjsDocPage } = require('./src/mdjsDocPage.js');
const { mdjsProcess } = require('./src/mdjsProcess.js');
@@ -14,4 +15,5 @@ module.exports = {
mdjsDocPage,
mdjsProcess,
isMdjsContent,
mdjsSetupCode,
};

View File

@@ -1,5 +1,12 @@
import cjsEntrypoint from './index.js';
const { mdjsParse, mdjsStoryParse, mdjsDocPage, mdjsProcess, isMdjsContent } = cjsEntrypoint;
const {
mdjsParse,
mdjsStoryParse,
mdjsDocPage,
mdjsProcess,
isMdjsContent,
mdjsSetupCode,
} = cjsEntrypoint;
export { mdjsParse, mdjsStoryParse, mdjsDocPage, mdjsProcess, isMdjsContent };
export { mdjsParse, mdjsStoryParse, mdjsDocPage, mdjsProcess, isMdjsContent, mdjsSetupCode };

View File

@@ -1,6 +1,6 @@
{
"name": "@mdjs/core",
"version": "0.8.2",
"version": "0.9.0",
"publishConfig": {
"access": "public"
},
@@ -49,7 +49,7 @@
"@types/unist": "^2.0.3",
"es-module-lexer": "^0.3.26",
"github-markdown-css": "^4.0.0",
"plugins-manager": "^0.2.4",
"plugins-manager": "^0.3.0",
"rehype-autolink-headings": "^5.0.1",
"rehype-prism-template": "^0.4.1",
"rehype-raw": "^5.0.0",

View File

@@ -1,8 +1,8 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
/** @typedef {import('@mdjs/core/types/code').Story} Story */
/** @typedef {import('@mdjs/core/types/code').ParseResult} ParseResult */
/** @typedef {import('@mdjs/core/types/code').ProcessResult} ProcessResult */
/** @typedef {import('@mdjs/core/types/code').MdjsProcessPlugin} MdjsProcessPlugin */
/** @typedef {import('../types/code').Story} Story */
/** @typedef {import('../types/code').ParseResult} ParseResult */
/** @typedef {import('../types/code').ProcessResult} ProcessResult */
/** @typedef {import('../types/code').MdjsProcessPlugin} MdjsProcessPlugin */
const unified = require('unified');
const markdown = require('remark-parse');
@@ -22,23 +22,23 @@ const { mdjsSetupCode } = require('./mdjsSetupCode.js');
/** @type {MdjsProcessPlugin[]} */
const defaultMetaPlugins = [
{ name: 'markdown', plugin: markdown },
{ name: 'gfm', plugin: gfm },
{ name: 'mdjsParse', plugin: mdjsParse },
{ name: 'mdjsStoryParse', plugin: mdjsStoryParse },
{ name: 'mdjsSetupCode', plugin: mdjsSetupCode },
{ plugin: markdown, options: {} },
{ plugin: gfm, options: {} },
{ plugin: mdjsParse, options: {} },
{ plugin: mdjsStoryParse, options: {} },
{ plugin: mdjsSetupCode, options: {} },
// @ts-ignore
{ name: 'remark2rehype', plugin: remark2rehype, options: { allowDangerousHtml: true } },
{ plugin: remark2rehype, options: { allowDangerousHtml: true } },
// @ts-ignore
{ name: 'rehypePrism', plugin: rehypePrism },
{ plugin: rehypePrism, options: {} },
// @ts-ignore
{ name: 'raw', plugin: raw },
{ plugin: raw, options: {} },
// @ts-ignore
{ name: 'htmlSlug', plugin: htmlSlug },
{ plugin: htmlSlug, options: {} },
// @ts-ignore
{ name: 'htmlHeading', plugin: htmlHeading },
{ plugin: htmlHeading, options: {} },
// @ts-ignore
{ name: 'htmlStringify', plugin: htmlStringify },
{ plugin: htmlStringify, options: {} },
];
/**
@@ -57,33 +57,8 @@ async function mdjsProcess(mdjs, { setupUnifiedPlugins = [] } = {}) {
const metaPlugins = executeSetupFunctions(setupUnifiedPlugins, defaultMetaPlugins);
/**
* @param {string} code
*/
async function highlightCode(code) {
// @ts-ignore
const codePlugins = metaPlugins.filter(pluginObj =>
['markdown', 'remark2rehype', 'rehypePrism', 'htmlStringify'].includes(pluginObj.name),
);
const codeParser = unified();
// @ts-ignore
for (const pluginObj of codePlugins) {
codeParser.use(pluginObj.plugin, pluginObj.options);
}
const codeResult = await codeParser.process(code);
return codeResult.contents;
}
// @ts-ignore
for (const pluginObj of metaPlugins) {
if (pluginObj.name === 'mdjsSetupCode') {
if (pluginObj.options && !pluginObj.options.highlightCode) {
pluginObj.options.highlightCode = highlightCode;
}
if (!pluginObj.options) {
pluginObj.options = { highlightCode };
}
}
// @ts-ignore
parser.use(pluginObj.plugin, pluginObj.options);
}

View File

@@ -3,6 +3,8 @@
const chai = require('chai');
const { adjustPluginOptions } = require('plugins-manager');
const { mdjsProcess } = require('../src/mdjsProcess.js');
const { mdjsSetupCode } = require('../src/mdjsSetupCode.js');
const { mdjsStoryParse } = require('../src/mdjsStoryParse.js');
const { expect } = chai;
@@ -106,7 +108,7 @@ describe('mdjsProcess', () => {
function replaceStoryTag(plugins) {
return plugins.map(pluginObj => {
if (pluginObj.name === 'mdjsStoryParse') {
if (pluginObj.plugin === mdjsStoryParse) {
return {
...pluginObj,
options: {
@@ -136,7 +138,7 @@ describe('mdjsProcess', () => {
function replaceStoryTag2(plugins) {
return plugins.map(pluginObj => {
if (pluginObj.name === 'mdjsStoryParse') {
if (pluginObj.plugin === mdjsStoryParse) {
return {
...pluginObj,
options: {
@@ -202,7 +204,7 @@ describe('mdjsProcess', () => {
].join('\n');
const result = await mdjsProcess(input, {
setupUnifiedPlugins: [
adjustPluginOptions('mdjsSetupCode', {
adjustPluginOptions(mdjsSetupCode, {
simulationSettings: { languages: [{ key: 'en', name: 'English' }] },
}),
],

View File

@@ -31,4 +31,4 @@ export interface ParseResult {
};
}
export type MdjsProcessPlugin = MetaPlugin<unified.Plugin, unified.Settings>;
export type MdjsProcessPlugin = MetaPlugin<unified.Plugin>;

View File

@@ -1,5 +1,92 @@
# plugins-manager
## 0.3.0
### Minor Changes
- 70bb7a1: BREAKING CHANGE: `addPlugin` API changed
```diff
- addPlugin({ name: 'my-plugin', plugin: myPlugin, options: { myFlag: true }, location: 'top' });
+ addPlugin(myPlugin, { myFlag: true }, { location: 'top' });
```
This is now type safe and typescript will throw an error if you pass the wrong type.
```js
function myPlugin({ myFlag = false } = {}) {
// ...
}
addPlugin(myPlugin, { myFlag: true }); // ts ok
addPlugin(myPlugin, { notExisting: true }); // ts error
```
- 70bb7a1: BREAKING CHANGE: `adjustPluginOptions` API changed
```diff
- adjustPluginOptions('my-plugin', { myFlag: true });
+ adjustPluginOptions(myPlugin, { myFlag: true });
```
This is now type safe and typescript will throw an error if you pass the wrong type.
```js
function myPlugin({ myFlag = false } = {}) {
// ...
}
adjustPluginOptions(myPlugin, { myFlag: true }); // ts ok
adjustPluginOptions(myPlugin, { notExisting: true }); // ts error
```
- 70bb7a1: Add `removePlugin` functionality
```js
export default {
setupPlugins: [removePlugin(json)],
};
```
- 70bb7a1: BREAKING CHANGE: `metaConfigToRollupConfig` has been renamed to `applyPlugins`
```diff
- const finalConfig = metaConfigToRollupConfig(currentConfig, defaultMetaPlugins);
+ const finalConfig = applyPlugins(currentConfig, defaultMetaPlugins);
```
- 70bb7a1: BREAKING CHANGE: `metaConfigToWebDevServerConfig` has been removed
- 70bb7a1: Plugins can now be classes as well. The options are passed to the constructor.
```js
/**
* @typedef {object} MyClassOptions
* @property {string} lastName
*/
class MyClass {
/** @type {MyClassOptions} */
options = {
lastName: 'initial-second',
};
/**
* @param {Partial<MyClassOptions>} options
*/
constructor(options = {}) {
this.options = { ...this.options, ...options };
}
}
export default {
setupPlugins: [addPlugin(MyClass)],
};
// constructor parameters are type safe
addPlugin(MyClass, { lastName: 'new name' }); // ts ok
addPlugin(MyClass, { otherProp: 'new name' }); // ts error
```
## 0.2.4
### Patch Changes

View File

@@ -1,6 +1,3 @@
# Plugins Manager
The Plugins Manager replaces the specific registration/execution (with options) in a given plugin system by an intent to use a plugin (with these options).
This allows your users to adjust the options before actually applying the plugins.
For docs please see our homepage [https://rocket.modern-web.dev/docs/plugins-manager/overview/](https://rocket.modern-web.dev/docs/plugins-manager/overview/).
[=> See Source <=](../../docs/docs/tools/plugins-manager.md)

View File

@@ -1,9 +1,11 @@
/** @typedef {import('./types/main').MetaPlugin} MetaPlugin */
/** @typedef {import('./types/main').AddPluginFn} AddPluginFn */
/** @typedef {import('./types/main').AddPluginType} AddPluginType */
/**
* @template T
* @typedef {import('./types/main').MetaPlugin<T>} MetaPlugin
**/
/** @typedef {import('./types/main').Plugin} Plugin */
export { addPlugin } from './src/addPlugin.js';
export { removePlugin } from './src/removePlugin.js';
export { adjustPluginOptions } from './src/adjustPluginOptions.js';
export { metaConfigToRollupConfig } from './src/metaConfigToRollupConfig.js';
export { metaConfigToWebDevServerConfig } from './src/metaConfigToWebDevServerConfig.js';
export { applyPlugins } from './src/applyPlugins.js';
export { executeSetupFunctions } from './src/executeSetupFunctions.js';

View File

@@ -1,6 +1,6 @@
{
"name": "plugins-manager",
"version": "0.2.4",
"version": "0.3.0",
"publishConfig": {
"access": "public"
},
@@ -25,7 +25,8 @@
"build:package": "rimraf dist && esbuild --platform=node --format=cjs --bundle --outfile=dist/index.cjs ./index.js",
"test": "mocha --timeout 5000 test-node/**/*.test.{js,cjs} test-node/*.test.{js,cjs}",
"test:watch": "onchange 'src/**/*.{js,cjs}' 'test-node/**/*.{js,cjs}' -- npm test",
"types:copy": "copyfiles \"./types/**/*.d.ts\" dist-types/"
"types:copy": "copyfiles \"./types/**/*.d.ts\" dist-types/",
"prepublishOnly": "publish-docs --github-url https://github.com/modernweb-dev/rocket/ --git-root-dir ../../"
},
"files": [
"*.js",

View File

@@ -1,26 +1,19 @@
/** @typedef {import('../types/main').MetaPlugin} MetaPlugin */
/**
* @template {Function} T
* @param {import('../types/main').AddPluginOptions<T>} metaPluginAndOptions
* @template {import('../types/main').Plugin} T
* @param {T} plugin
* @param {import('../types/main').GetPluginOptions<T>} [options]
* @param {import('../types/main').ManagerOptions} [managerOptions]
*/
export function addPlugin(metaPluginAndOptions) {
const {
name,
plugin,
options = undefined,
how = 'after',
location = 'bottom',
} = metaPluginAndOptions;
export function addPlugin(plugin, options = {}, { how = 'after', location = 'bottom' } = {}) {
/**
* @param {MetaPlugin[]} plugins
* @param {import('../types/main').MetaPlugin<T>[]} plugins
*/
const addPluginFn = plugins => {
if (plugins === undefined) {
plugins = [];
}
// only add if name is not already in the meta plugin list
if (plugins.findIndex(pluginObj => pluginObj.name === name) === -1) {
if (plugins.findIndex(pluginObj => pluginObj.plugin === plugin) === -1) {
let index = -1;
let _how = how;
switch (location) {
@@ -33,11 +26,12 @@ export function addPlugin(metaPluginAndOptions) {
_how = 'fixed';
break;
default:
index = plugins.findIndex(plugin => plugin.name === location);
index = plugins.findIndex(pluginObj => pluginObj.plugin === location);
}
if (index < 0) {
const errorName = location === 'top' || location === 'bottom' ? location : location.name;
throw new Error(
`Could not find a plugin with the name "${location}" to insert "${name}" ${how} it.`,
`Could not find a plugin with the name "${errorName}" to insert "${plugin.name}" ${how} it.`,
);
}
@@ -46,7 +40,6 @@ export function addPlugin(metaPluginAndOptions) {
}
plugins.splice(index, 0, {
name,
plugin,
options,
});

View File

@@ -1,4 +1,4 @@
/** @typedef {import('../types/main').MetaPlugin} MetaPlugin */
/** @typedef {import('../types/main').Plugin} Plugin */
/**
* @param {any} obj
@@ -8,23 +8,35 @@ function isObject(obj) {
}
/**
* @param {string} pluginName
* @param {any} mergeOptions
* @param {*} x
* @returns {x is function}
*/
export function adjustPluginOptions(pluginName, mergeOptions) {
function isFunction(x) {
return typeof x === 'function';
}
/**
* @template {import('../types/main').Plugin} T
* @param {T} plugin
* @param {import('../types/main').adjustPluginOptionsOptions<T>} mergeOptions
*/
export function adjustPluginOptions(plugin, mergeOptions) {
/**
* @param {MetaPlugin[]} plugins
* @template {Function} T
* @param {import('../types/main').MetaPlugin<T>[]} plugins
*/
const adjustPluginOptionsFn = plugins => {
const index = plugins.findIndex(plugin => plugin.name === pluginName);
const index = plugins.findIndex(pluginObj => pluginObj.plugin === plugin);
if (index === -1) {
throw new Error(
`Could not find a plugin with the name "${pluginName}" to adjust the options.`,
`Could not find a plugin with the name "${
plugin.name
}" to adjust it's options with:\n${JSON.stringify(mergeOptions, null, 2)}`,
);
}
if (typeof mergeOptions === 'function') {
if (isFunction(mergeOptions)) {
plugins[index].options = mergeOptions(plugins[index].options);
} else if (isObject(plugins[index].options)) {
plugins[index].options = { ...plugins[index].options, ...mergeOptions };

View File

@@ -0,0 +1,46 @@
import { executeSetupFunctions } from './executeSetupFunctions.js';
/** @typedef {import('../types/main').Constructor} Constructor */
/** @typedef {import('../types/main').AnyFn} AnyFn */
/**
* @param {unknown} func
* @returns {boolean}
*/
function isClass(func) {
if (typeof func === 'function' && func.prototype) {
try {
func.arguments && func.caller;
} catch (error) {
return true;
}
}
return false;
}
/**
* @template {import('../types/main').Plugin} T
* @param {any} config
* @param {import('../types/main').MetaPlugin<T>[]} [defaultPlugins]
*/
export function applyPlugins(config, defaultPlugins = []) {
if (config.plugins) {
delete config.setupPlugins;
return config;
}
const _metaPlugins = executeSetupFunctions(config.setupPlugins, [...defaultPlugins]);
const plugins = _metaPlugins.map(pluginObj => {
if (isClass(pluginObj.plugin)) {
const ClassPlugin = /** @type {Constructor} */ (pluginObj.plugin);
return pluginObj.options ? new ClassPlugin(pluginObj.options) : new ClassPlugin();
} else {
const fnPlugin = /** @type {AnyFn} */ (pluginObj.plugin);
return pluginObj.options ? fnPlugin(pluginObj.options) : fnPlugin();
}
});
config.plugins = plugins;
delete config.setupPlugins;
return config;
}

View File

@@ -1,9 +1,8 @@
/** @typedef {import('../types/main').MetaPlugin} MetaPlugin */
/**
* @template T
* @param {function[]} setupFunctions
* @param {MetaPlugin[]} metaPlugins
* @return {MetaPlugin[]}
* @param {import('../types/main').MetaPlugin<T>[]} metaPlugins
* @return {import('../types/main').MetaPlugin<T>[]}
*/
export function executeSetupFunctions(setupFunctions, metaPlugins = []) {
let _metaPlugins = [...metaPlugins];

View File

@@ -1,27 +0,0 @@
/** @typedef {import('../types/main').MetaPlugin} MetaPlugin */
import { executeSetupFunctions } from 'plugins-manager';
/**
* @param {any} config
* @param {MetaPlugin[]} [metaPlugins]
*/
export function metaConfigToRollupConfig(config, metaPlugins = []) {
if (config.plugins) {
delete config.setupPlugins;
return config;
}
const _metaPlugins = executeSetupFunctions(config.setupPlugins, [...metaPlugins]);
const plugins = _metaPlugins.map(pluginObj => {
if (pluginObj.options) {
return pluginObj.plugin(pluginObj.options);
} else {
return pluginObj.plugin();
}
});
config.plugins = plugins;
delete config.setupPlugins;
return config;
}

View File

@@ -1,53 +0,0 @@
/** @typedef {import('../types/main').MetaPluginWrapable} MetaPluginWrapable */
import { executeSetupFunctions } from 'plugins-manager';
/**
* @param {any} config
* @param {MetaPluginWrapable[]} metaPlugins
* @param {object} [options]
* @param {function | null} [options.rollupWrapperFunction]
*/
export function metaConfigToWebDevServerConfig(
config,
metaPlugins,
{ rollupWrapperFunction = null } = {},
) {
if (config.plugins) {
delete config.setupPlugins;
delete config.setupRollupPlugins;
return config;
}
const metaPluginsNoWrap = metaPlugins.map(pluginObj => {
pluginObj.__noWrap = true;
return pluginObj;
});
const rollupPlugins = /** @type {MetaPluginWrapable[]} */ (executeSetupFunctions(
config.setupRollupPlugins,
[...metaPluginsNoWrap],
));
const wrappedRollupPlugins = rollupPlugins.map(pluginObj => {
if (typeof rollupWrapperFunction === 'function' && pluginObj.__noWrap !== true) {
pluginObj.plugin = rollupWrapperFunction(pluginObj.plugin);
}
return pluginObj;
});
const _metaPlugins = executeSetupFunctions(config.setupPlugins, [...wrappedRollupPlugins]);
const plugins = _metaPlugins.map(pluginObj => {
if (pluginObj.options) {
return pluginObj.plugin(pluginObj.options);
} else {
return pluginObj.plugin();
}
});
config.plugins = plugins;
delete config.setupPlugins;
delete config.setupRollupPlugins;
return config;
}

View File

@@ -0,0 +1,23 @@
/** @typedef {import('../types/main').Plugin} Plugin */
/**
* @param {import('../types/main').Plugin} plugin
*/
export function removePlugin(plugin) {
/**
* @template {Function} T
* @param {import('../types/main').MetaPlugin<T>[]} plugins
*/
const removePluginFn = plugins => {
const index = plugins.findIndex(pluginObj => pluginObj.plugin === plugin);
if (index === -1) {
throw new Error(`Could not find a plugin with the name "${plugin.name}" to remove.`);
}
plugins.splice(index, 1);
return plugins;
};
return removePluginFn;
}

View File

@@ -1,82 +1,93 @@
import chai from 'chai';
import { addPlugin, metaConfigToRollupConfig } from 'plugins-manager';
import { addPlugin, applyPlugins } from '../index.js';
const { expect } = chai;
describe('addPlugin', () => {
const insertPlugin = (options = 'insert') => `-- ${options}Plugin --`;
const oneExistingPlugin = [{ name: 'first', plugin: () => 'firstPlugin' }];
const insertPlugin = ({ firstName = 'first', lastName = 'last' } = {}) =>
`-- ${firstName} ${lastName} Plugin --`;
const firstPlugin = () => 'firstPlugin';
const secondPlugin = () => 'secondPlugin';
const thirdPlugin = () => 'thirdPlugin';
/**
* @template T
* @type {import('../types/main.js').MetaPlugin<T>[]}
*/
const oneExistingPlugin = [{ plugin: firstPlugin, options: {} }];
/**
* @template T
* @type {import('../types/main.js').MetaPlugin<T>[]}
*/
const threeExistingPlugins = [
{ name: 'first', plugin: () => 'firstPlugin' },
{ name: 'second', plugin: () => 'secondPlugin' },
{ name: 'third', plugin: () => 'thirdPlugin' },
{ plugin: firstPlugin, options: {} },
{ plugin: secondPlugin, options: {} },
{ plugin: thirdPlugin, options: {} },
];
it('adds plugins at the bottom by default', async () => {
const config = metaConfigToRollupConfig({
setupPlugins: [addPlugin({ name: 'insert', plugin: insertPlugin })],
const config = applyPlugins({
setupPlugins: [addPlugin(insertPlugin)],
});
expect(config.plugins).to.deep.equal(['-- insertPlugin --']);
expect(config.plugins).to.deep.equal(['-- first last Plugin --']);
const config2 = metaConfigToRollupConfig(
const config2 = applyPlugins(
{
setupPlugins: [addPlugin({ name: 'insert', plugin: insertPlugin })],
setupPlugins: [addPlugin(insertPlugin)],
},
oneExistingPlugin,
);
expect(config2.plugins).to.deep.equal(['firstPlugin', '-- insertPlugin --']);
expect(config2.plugins).to.deep.equal(['firstPlugin', '-- first last Plugin --']);
});
it('can add at the top', async () => {
const config = metaConfigToRollupConfig(
const config = applyPlugins(
{
setupPlugins: [addPlugin({ name: 'insert', plugin: insertPlugin, location: 'top' })],
setupPlugins: [addPlugin(insertPlugin, undefined, { location: 'top' })],
},
oneExistingPlugin,
);
expect(config.plugins).to.deep.equal(['-- insertPlugin --', 'firstPlugin']);
expect(config.plugins).to.deep.equal(['-- first last Plugin --', 'firstPlugin']);
});
it('handles inserting "before" the 0 index ', async () => {
const config = metaConfigToRollupConfig(
const config = applyPlugins(
{
setupPlugins: [
addPlugin({ name: 'insert', plugin: insertPlugin, location: 'top', how: 'before' }),
],
setupPlugins: [addPlugin(insertPlugin, undefined, { location: 'top', how: 'before' })],
},
oneExistingPlugin,
);
expect(config.plugins).to.deep.equal(['-- insertPlugin --', 'firstPlugin']);
expect(config.plugins).to.deep.equal(['-- first last Plugin --', 'firstPlugin']);
});
it('adds after a given location by default', async () => {
const config = metaConfigToRollupConfig(
const config = applyPlugins(
{
setupPlugins: [addPlugin({ name: 'insert', plugin: insertPlugin, location: 'second' })],
setupPlugins: [addPlugin(insertPlugin, undefined, { location: secondPlugin })],
},
threeExistingPlugins,
);
expect(config.plugins).to.deep.equal([
'firstPlugin',
'secondPlugin',
'-- insertPlugin --',
'-- first last Plugin --',
'thirdPlugin',
]);
});
it('can adds before a given location', async () => {
const config = metaConfigToRollupConfig(
const config = applyPlugins(
{
setupPlugins: [
addPlugin({ name: 'insert', plugin: insertPlugin, location: 'second', how: 'before' }),
addPlugin(insertPlugin, undefined, { location: secondPlugin, how: 'before' }),
],
},
threeExistingPlugins,
);
expect(config.plugins).to.deep.equal([
'firstPlugin',
'-- insertPlugin --',
'-- first last Plugin --',
'secondPlugin',
'thirdPlugin',
]);
@@ -84,16 +95,18 @@ describe('addPlugin', () => {
it('throws if given location does not exist', async () => {
expect(() => {
metaConfigToRollupConfig({
setupPlugins: [addPlugin({ name: 'insert', plugin: insertPlugin, location: 'not-found' })],
applyPlugins({
setupPlugins: [addPlugin(insertPlugin, undefined, { location: firstPlugin })],
});
}).to.throw('Could not find a plugin with the name "not-found" to insert "insert" after it.');
}).to.throw(
'Could not find a plugin with the name "firstPlugin" to insert "insertPlugin" after it.',
);
});
it('accepts options', async () => {
const config = metaConfigToRollupConfig({
setupPlugins: [addPlugin({ name: 'insert', plugin: insertPlugin, options: 'extra' })],
const config = applyPlugins({
setupPlugins: [addPlugin(insertPlugin, { firstName: 'newFirst' })],
});
expect(config.plugins).to.deep.equal(['-- extraPlugin --']);
expect(config.plugins).to.deep.equal(['-- newFirst last Plugin --']);
});
});

View File

@@ -1,33 +1,43 @@
// @ts-check
import chai from 'chai';
import { adjustPluginOptions, metaConfigToRollupConfig } from 'plugins-manager';
import { adjustPluginOptions, applyPlugins } from '../index.js';
const { expect } = chai;
describe('adjustPluginOptions', () => {
const firstPlugin = ({ flag = 'default-flag' } = {}) => `firstPlugin-${flag}`;
/**
* @param {object} options
* @param {object} [options.other]
* @param {string} [options.other.nested]
* @param {string} [options.other.nested2]
* @returns
*/
const secondPlugin = ({ other = { nested: 'other.nested', nested2: 'other.nested2' } } = {}) =>
`secondPlugin-${other.nested}-${other.nested2}`;
const thirdPlugin = ({ name = 'name' }) => `thirdPlugin-${name}`;
const defaultCurrentMetaPlugins = [
{ plugin: firstPlugin, options: { flag: 'firstSettings' } },
{
name: 'first',
plugin: options => `firstPlugin-${options.flag}`,
options: { flag: 'firstSettings' },
},
{
name: 'second',
plugin: options => `secondPlugin-${options.other.nested}-${options.other.nested2}`,
plugin: secondPlugin,
options: { other: { nested: 'other.nested', nested2: 'other.nested2' } },
},
{ name: 'third', plugin: options => `thirdPlugin-${options}`, options: 'aString' },
{ plugin: thirdPlugin, options: { name: 'name' } },
];
function newCurrentMetaPlugins() {
return defaultCurrentMetaPlugins.map(obj => ({ ...obj }));
}
it('will merge options objects (flatly)', async () => {
const config = metaConfigToRollupConfig(
const config = applyPlugins(
{
setupPlugins: [
adjustPluginOptions('first', { flag: '#mod#FirstSettings' }),
adjustPluginOptions('second', { other: { nested: '#mod#other.nested' } }),
adjustPluginOptions(firstPlugin, { flag: '#mod#FirstSettings' }),
adjustPluginOptions(secondPlugin, { other: { nested: '#mod#other.nested' } }),
],
},
newCurrentMetaPlugins(),
@@ -35,14 +45,14 @@ describe('adjustPluginOptions', () => {
expect(config.plugins).to.deep.equal([
'firstPlugin-#mod#FirstSettings',
'secondPlugin-#mod#other.nested-undefined',
'thirdPlugin-aString',
'thirdPlugin-name',
]);
});
it('will override non object settings', async () => {
const config = metaConfigToRollupConfig(
const config = applyPlugins(
{
setupPlugins: [adjustPluginOptions('third', '#mod#aString')],
setupPlugins: [adjustPluginOptions(thirdPlugin, { name: '#mod#aString' })],
},
newCurrentMetaPlugins(),
);
@@ -54,11 +64,11 @@ describe('adjustPluginOptions', () => {
});
it('accepts a function as a setting to manually merge objects', async () => {
const config = metaConfigToRollupConfig(
const config = applyPlugins(
{
setupPlugins: [
adjustPluginOptions('second', config => ({
other: { ...config.other, nested: '#mod#other.nested' },
adjustPluginOptions(secondPlugin, config => ({
other: { ...config?.other, nested: '#mod#other.nested' },
})),
],
},
@@ -67,15 +77,76 @@ describe('adjustPluginOptions', () => {
expect(config.plugins).to.deep.equal([
'firstPlugin-firstSettings',
'secondPlugin-#mod#other.nested-other.nested2',
'thirdPlugin-aString',
'thirdPlugin-name',
]);
});
it('throws if given location does not exist', async () => {
it('throws if given plugin does not exist', async () => {
expect(() => {
metaConfigToRollupConfig({
setupPlugins: [adjustPluginOptions('not-found', '#mod#aString')],
applyPlugins({
setupPlugins: [adjustPluginOptions(firstPlugin, { flag: 'newFlag' })],
});
}).to.throw('Could not find a plugin with the name "not-found" to adjust the options.');
}).to.throw(
[
'Could not find a plugin with the name "firstPlugin" to adjust it\'s options with:',
'{',
' "flag": "newFlag"',
'}',
].join('\n'),
);
});
it('works with classes', async () => {
class FirstClass {
constructor({ firstName = 'initial-first' } = {}) {
this.options = { firstName };
}
render() {
return `[[ firstName: ${this.options.firstName} ]]`;
}
}
/**
* @typedef {object} SecondClassOptions
* @property {string} lastName
*/
class SecondClass {
/** @type {SecondClassOptions} */
options = {
lastName: 'initial-second',
};
/**
* @param {Partial<SecondClassOptions>} options
*/
constructor(options = {}) {
this.options = { ...this.options, ...options };
}
render() {
return `[[ lastName: ${this.options.lastName} ]]`;
}
}
const config = applyPlugins(
{
setupPlugins: [
adjustPluginOptions(SecondClass, { lastName: 'set-via-adjustPluginOptions' }),
],
},
[
{ plugin: FirstClass, options: {} },
{ plugin: SecondClass, options: {} },
],
);
expect(
config.plugins.map(/** @param {FirstClass | SecondClass} cls */ cls => cls.render()),
).to.deep.equal([
'[[ firstName: initial-first ]]',
'[[ lastName: set-via-adjustPluginOptions ]]',
]);
});
});

View File

@@ -0,0 +1,92 @@
import chai from 'chai';
import { applyPlugins, addPlugin } from '../index.js';
const { expect } = chai;
describe('applyPlugins', () => {
const insertPlugin = () => `-- insertPlugin --`;
/**
* @template T
* @type {import('../types/main.js').MetaPlugin<T>[]}
*/
const oneExistingPlugin = [{ plugin: () => 'firstPlugin', options: {} }];
/**
* @template T
* @type {import('../types/main.js').MetaPlugin<T>[]}
*/
const threeExistingPlugin = [
{ plugin: () => 'firstPlugin', options: {} },
{ plugin: () => 'secondPlugin', options: {} },
{ plugin: () => 'thirdPlugin', options: {} },
];
it('converts meta config by executing the plugins and assigning it to the config', async () => {
const config = applyPlugins({}, threeExistingPlugin);
expect(config.plugins).to.deep.equal(['firstPlugin', 'secondPlugin', 'thirdPlugin']);
});
it('incorporates "setupPlugin" functions in the config & removes "setupPlugins"', async () => {
const config = applyPlugins(
{
setupPlugins: [addPlugin(insertPlugin)],
},
oneExistingPlugin,
);
expect(config.plugins).to.deep.equal(['firstPlugin', '-- insertPlugin --']);
expect(config.setupPlugins).to.be.undefined;
});
it('a provided plugins property will always win even if it is an empty array', async () => {
const config = applyPlugins({
setupPlugins: [addPlugin(insertPlugin)],
plugins: [],
});
expect(config.plugins).to.deep.equal([]);
expect(config.setupPlugins).to.be.undefined;
});
it('prefers a user set config.plugins', async () => {
const config = applyPlugins(
{
setupPlugins: [addPlugin(insertPlugin)],
plugins: ['user-set'],
},
threeExistingPlugin,
);
expect(config.plugins).to.deep.equal(['user-set']);
expect(config.setupPlugins).to.be.undefined;
});
it('works with classes', async () => {
class FirstClass {
constructor({ firstName = 'initial-first' } = {}) {
this.options = { firstName };
}
render() {
return `[[ firstName: ${this.options.firstName} ]]`;
}
}
class SecondClass {
constructor({ lastName = 'initial-second' } = {}) {
this.options = { lastName };
}
render() {
return `[[ lastName: ${this.options.lastName} ]]`;
}
}
const config = applyPlugins({
setupPlugins: [
addPlugin(FirstClass),
addPlugin(SecondClass, { lastName: 'set-via-addPlugin' }),
],
});
expect(
config.plugins.map(/** @param {FirstClass | SecondClass} cls */ cls => cls.render()),
).to.deep.equal(['[[ firstName: initial-first ]]', '[[ lastName: set-via-addPlugin ]]']);
});
});

View File

@@ -1,6 +1,6 @@
import chai from 'chai';
import { executeSetupFunctions, addPlugin } from 'plugins-manager';
import { executeSetupFunctions, addPlugin } from '../index.js';
const { expect } = chai;
@@ -9,27 +9,28 @@ describe('executeSetupFunctions', () => {
const secondPlugin = () => 'secondPlugin';
const thirdPlugin = () => 'thirdPlugin';
/**
* @template T
* @type {import('../types/main.js').MetaPlugin<T>[]}
*/
const threeExistingPlugin = [
{ name: 'first', plugin: firstPlugin },
{ name: 'second', plugin: secondPlugin },
{ name: 'third', plugin: thirdPlugin },
{ plugin: firstPlugin, options: {} },
{ plugin: secondPlugin, options: {} },
{ plugin: thirdPlugin, options: {} },
];
it('executes and returns a new array not adjusting the original', async () => {
const metaPlugins = executeSetupFunctions(
[
addPlugin({ name: 'add-a', plugin: () => 'a' }),
addPlugin({ name: 'add-b', plugin: () => 'b' }),
],
[addPlugin(() => 'a'), addPlugin(() => 'b')],
threeExistingPlugin,
);
expect(metaPlugins.length).to.equal(5);
// does not change original array
expect(threeExistingPlugin).to.deep.equal([
{ name: 'first', plugin: firstPlugin },
{ name: 'second', plugin: secondPlugin },
{ name: 'third', plugin: thirdPlugin },
{ plugin: firstPlugin, options: {} },
{ plugin: secondPlugin, options: {} },
{ plugin: thirdPlugin, options: {} },
]);
});
});

View File

@@ -1,43 +0,0 @@
import chai from 'chai';
import { metaConfigToRollupConfig, addPlugin } from 'plugins-manager';
const { expect } = chai;
describe('metaConfigToRollupConfig', () => {
const insertPlugin = () => `-- insertPlugin --`;
const oneExistingPlugin = [{ name: 'first', plugin: () => 'firstPlugin' }];
const threeExistingPlugin = [
{ name: 'first', plugin: () => 'firstPlugin' },
{ name: 'second', plugin: () => 'secondPlugin' },
{ name: 'third', plugin: () => 'thirdPlugin' },
];
it('converts meta config by executing the plugins and assigning it to the config', async () => {
const config = metaConfigToRollupConfig({}, threeExistingPlugin);
expect(config.plugins).to.deep.equal(['firstPlugin', 'secondPlugin', 'thirdPlugin']);
});
it('incorporates "setupPlugin" functions in the config & removes "setupPlugins"', async () => {
const config = metaConfigToRollupConfig(
{
setupPlugins: [addPlugin({ name: 'insert', plugin: insertPlugin })],
},
oneExistingPlugin,
);
expect(config.plugins).to.deep.equal(['firstPlugin', '-- insertPlugin --']);
expect(config.setupPlugins).to.be.undefined;
});
it('prefers a user set config.plugins', async () => {
const config = metaConfigToRollupConfig(
{
setupPlugins: [addPlugin({ name: 'insert', plugin: insertPlugin })],
plugins: ['user-set'],
},
threeExistingPlugin,
);
expect(config.plugins).to.deep.equal(['user-set']);
expect(config.setupPlugins).to.be.undefined;
});
});

View File

@@ -1,56 +0,0 @@
import chai from 'chai';
import { metaConfigToWebDevServerConfig, addPlugin } from 'plugins-manager';
const { expect } = chai;
describe('metaConfigToWebDevServerConfig', () => {
const twoExistingPlugin = [
{ name: 'first', plugin: () => 'firstPlugin' },
{ name: 'second', plugin: () => 'secondPlugin' },
];
it('accepts a rollupWrapperFunction for setupRollupPlugins', async () => {
function rollupWrapperFunction(srcFn) {
return () => `*wrapped* ${srcFn()}`;
}
const config = metaConfigToWebDevServerConfig(
{
setupRollupPlugins: [
addPlugin({ name: 'third', plugin: () => 'thirdPlugin' }),
addPlugin({ name: 'fourth', plugin: () => 'fourthPlugin' }),
],
setupPlugins: [
addPlugin({ name: 'fifth', plugin: () => 'fifthPlugin' }),
addPlugin({ name: 'sixth', plugin: () => 'sixthPlugin' }),
],
},
twoExistingPlugin,
{ rollupWrapperFunction },
);
expect(config.plugins).to.deep.equal([
'firstPlugin',
'secondPlugin',
'*wrapped* thirdPlugin',
'*wrapped* fourthPlugin',
'fifthPlugin',
'sixthPlugin',
]);
});
it('prefers a user set config.plugins', async () => {
const config = metaConfigToWebDevServerConfig(
{
setupPlugins: [addPlugin({ name: 'first', plugin: () => 'firstPlugin' })],
setupRollupPlugins: [addPlugin({ name: 'second', plugin: () => 'secondPlugin' })],
plugins: ['user-set'],
},
twoExistingPlugin,
);
expect(config.plugins).to.deep.equal(['user-set']);
expect(config.setupPlugins).to.be.undefined;
expect(config.setupRollupPlugins).to.be.undefined;
});
});

View File

@@ -0,0 +1,39 @@
import chai from 'chai';
import { removePlugin, applyPlugins } from '../index.js';
const { expect } = chai;
describe('removePlugin', () => {
const firstPlugin = () => 'firstPlugin';
const secondPlugin = () => 'secondPlugin';
const thirdPlugin = () => 'thirdPlugin';
const fourthPlugin = () => 'fourthPlugin';
const defaultCurrentMetaPlugins = [
{ plugin: firstPlugin, options: {} },
{ plugin: secondPlugin, options: {} },
{ plugin: thirdPlugin, options: {} },
];
function newCurrentMetaPlugins() {
return defaultCurrentMetaPlugins.map(obj => ({ ...obj }));
}
it('removes a plugin', async () => {
const config = applyPlugins(
{
setupPlugins: [removePlugin(secondPlugin)],
},
newCurrentMetaPlugins(),
);
expect(config.plugins).to.deep.equal(['firstPlugin', 'thirdPlugin']);
});
it('throws if given plugin does not exist', async () => {
expect(() => {
applyPlugins({
setupPlugins: [removePlugin(fourthPlugin)],
});
}).to.throw('Could not find a plugin with the name "fourthPlugin" to remove.');
});
});

View File

@@ -1,24 +1,25 @@
// using `{}` as the default type for Constructor is a well-established pattern which we'll adopt here
// eslint-disable-next-line @typescript-eslint/ban-types
type Constructor<T = {}> = { new (...args: any[]): T };
type AnyFn = (...args: any[]) => any;
type Plugin = Constructor | AnyFn;
export interface MetaPlugin<F = AnyFn> {
name: string;
plugin: F extends (options?: infer O) => unknown ? F : any;
options?: /* prettier-ignore */ (
F extends (eleventyConfig: any, options?: infer O) => void ? O
: F extends (options: infer O) => unknown ? O
: any
);
export type GetPluginOptions<T> = T extends Constructor
? ConstructorParameters<T>[0]
: T extends AnyFn
? Parameters<T>[0]
: Partial<T>;
export interface MetaPlugin<T> {
plugin: Plugin;
options: GetPluginOptions<T>;
}
export interface MetaPluginWrapable extends MetaPlugin {
__noWrap?: boolean;
}
export type AddPluginOptions<T> = MetaPlugin<T> & {
export interface ManagerOptions {
how?: 'after' | 'before' | 'fixed';
location?: 'top' | 'bottom' | string;
};
location?: 'top' | 'bottom' | Plugin;
}
export type AddPluginFn = (plugins: MetaPlugin[]) => MetaPlugin[];
export type AddPluginType = <F>(metaPluginAndOptions: AddPluginOptions<F>) => AddPluginFn;
export type adjustPluginOptionsOptions<T> =
| GetPluginOptions<T>
| ((options: GetPluginOptions<T>) => GetPluginOptions<T>);

View File

@@ -1,5 +1,32 @@
# @rocket/search
## 0.5.0
### Minor Changes
- 70bb7a1: BREAKING CHANGE: Update to latest plugins manager to get type safe options
There is no longer a name string as a key for a plugin. It is identified by it's function/class. You will need to adjust your code if you are adding or adjusting plugins.
```diff
- addPlugin({ name: 'my-plugin', plugin: myPlugin, options: { myFlag: true }, location: 'top' });
+ addPlugin(myPlugin, { myFlag: true }, { location: 'top' });
- adjustPluginOptions('my-plugin', { myFlag: true });
+ adjustPluginOptions(myPlugin, { myFlag: true });
```
For more details please see the [Changelog](https://github.com/modernweb-dev/rocket/blob/main/packages/plugins-manager/CHANGELOG.md#030) of the plugins-manager package.
### Patch Changes
- Updated dependencies [70bb7a1]
- Updated dependencies [70bb7a1]
- Updated dependencies [70bb7a1]
- Updated dependencies [70bb7a1]
- Updated dependencies [70bb7a1]
- Updated dependencies [70bb7a1]
- plugins-manager@0.3.0
## 0.4.1
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "@rocket/search",
"version": "0.4.1",
"version": "0.5.0",
"publishConfig": {
"access": "public"
},
@@ -48,7 +48,7 @@
"@open-wc/scoped-elements": "^2.0.0-next.3",
"chalk": "^4.0.0",
"minisearch": "^3.0.2",
"plugins-manager": "^0.2.4",
"plugins-manager": "^0.3.0",
"sax-wasm": "^2.0.0"
},
"customElements": "custom-elements.json"

View File

@@ -8,6 +8,6 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
export function rocketSearch() {
return {
path: path.resolve(__dirname),
setupCliPlugins: [addPlugin({ name: 'rocket-search', plugin: RocketSearchPlugin })],
setupCliPlugins: [addPlugin(RocketSearchPlugin)],
};
}

View File

@@ -3,8 +3,10 @@ import { rocketBlog } from '@rocket/blog';
import { rocketSearch } from '@rocket/search';
import { absoluteBaseUrlNetlify } from '@rocket/core/helpers';
import { adjustPluginOptions } from 'plugins-manager';
import { codeTabs } from 'rocket-preset-code-tabs';
import { customElementsManifest } from 'rocket-preset-custom-elements-manifest';
import { mdjsSetupCode } from '@mdjs/core';
// TODO: preset needs to be updated to use the new plugin manager
// import { codeTabs } from 'rocket-preset-code-tabs';
// import { customElementsManifest } from 'rocket-preset-custom-elements-manifest';
/** @type {import('./packages/cli/types/main').RocketCliOptions} */
export default {
@@ -14,20 +16,20 @@ export default {
rocketLaunch(),
rocketBlog(),
rocketSearch(),
codeTabs({
collections: {
packageManagers: {
npm: { label: 'NPM', iconHref: '/_merged_assets/_static/logos/npm.svg' },
yarn: { label: 'Yarn', iconHref: '/_merged_assets/_static/logos/yarn.svg' },
pnpm: { label: 'PNPM', iconHref: '/_merged_assets/_static/logos/pnpm.svg' },
},
},
}),
customElementsManifest(),
// codeTabs({
// collections: {
// packageManagers: {
// npm: { label: 'NPM', iconHref: '/_merged_assets/_static/logos/npm.svg' },
// yarn: { label: 'Yarn', iconHref: '/_merged_assets/_static/logos/yarn.svg' },
// pnpm: { label: 'PNPM', iconHref: '/_merged_assets/_static/logos/pnpm.svg' },
// },
// },
// }),
// customElementsManifest(),
],
setupUnifiedPlugins: [
adjustPluginOptions('mdjsSetupCode', {
adjustPluginOptions(mdjsSetupCode, {
simulationSettings: {
simulatorUrl: '/simulator/',
themes: [

View File

@@ -40,7 +40,7 @@ function compareVersions(versionsA, versionsB) {
versionsA[dep] &&
versionsB[dep] &&
versionsA[dep] !== versionsB[dep] &&
!semver.satisfies(versionsA[dep], versionsB[dep])
!semver.intersects(versionsA[dep], versionsB[dep])
) {
output += ` - "${dep}" should be "${versionsA[dep]}" but is "${versionsB[dep]}"\n`;
}

View File

@@ -4343,6 +4343,16 @@ fs-extra@^8.1.0:
jsonfile "^4.0.0"
universalify "^0.1.0"
fs-extra@^9.0.0:
version "9.1.0"
resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-9.1.0.tgz#5954460c764a8da2094ba3554bf839e6b9a7c86d"
integrity sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==
dependencies:
at-least-node "^1.0.0"
graceful-fs "^4.2.0"
jsonfile "^6.0.1"
universalify "^2.0.0"
fs-extra@^9.0.1:
version "9.0.1"
resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-9.0.1.tgz#910da0062437ba4c39fedd863f1675ccfefcb9fc"
@@ -7508,6 +7518,15 @@ pseudomap@^1.0.2:
resolved "https://registry.yarnpkg.com/pseudomap/-/pseudomap-1.0.2.tgz#f052a28da70e618917ef0a8ac34c1ae5a68286b3"
integrity sha1-8FKijacOYYkX7wqKw0wa5aaChrM=
publish-docs@^0.1.2:
version "0.1.2"
resolved "https://registry.yarnpkg.com/publish-docs/-/publish-docs-0.1.2.tgz#5e3040fd55164381d24a084e19ee5aac704b4a9c"
integrity sha512-h6weNnTDtgDW0RXfCeY0ffYZQhJyv+4rbJc+NUFVIqqL54sXHXFyT/H7OyjkyoIpVTwTsqhmBYx8zrrhhN+gJQ==
dependencies:
command-line-args "^5.1.1"
fs-extra "^9.0.0"
glob "^7.1.6"
pug-attrs@^2.0.4:
version "2.0.4"
resolved "https://registry.yarnpkg.com/pug-attrs/-/pug-attrs-2.0.4.tgz#b2f44c439e4eb4ad5d4ef25cac20d18ad28cc336"