Skip to content

feat: implement plugin execution order #6411

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions packages/@vue/cli-plugin-typescript/__tests__/tsGenerator.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,19 +65,34 @@ test('use with Babel', async () => {
})

test('use with router', async () => {
const tsApply = require('../generator')

expect(tsApply.after).toBe('@vue/cli-plugin-router')

const { files } = await generateWithPlugin([
{
id: '@vue/cli-plugin-router',
apply: require('@vue/cli-plugin-router/generator'),
id: '@vue/cli-service',
apply: require('@vue/cli-service/generator'),
options: {
plugins: {
'@vue/cli-service': {},
'@vue/cli-plugin-router': {},
'@vue/cli-plugin-typescript': {}
}
}
},
{
id: '@vue/cli-plugin-typescript',
apply: tsApply,
options: {}
},
{
id: 'ts',
apply: require('../generator'),
id: '@vue/cli-plugin-router',
apply: require('@vue/cli-plugin-router/generator'),
options: {}
}
])
expect(files['src/views/Home.vue']).toMatch('<div class="home">')
expect(files['src/views/Home.vue']).toMatch('Welcome to Your Vue.js + TypeScript App')
})

test('tsconfig.json should be valid json', async () => {
Expand Down
2 changes: 2 additions & 0 deletions packages/@vue/cli-plugin-typescript/generator/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,5 @@ module.exports = (

require('./convert')(api, { convertJsToTs })
}

module.exports.after = '@vue/cli-plugin-router'
47 changes: 47 additions & 0 deletions packages/@vue/cli-service/__tests__/Service.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -381,3 +381,50 @@ test('api: hasPlugin', async () => {
}
])
})

test('order: service plugins order', async () => {
const applyCallOrder = []
function apply (id, order) {
order = order || {}
const fn = jest.fn(() => { applyCallOrder.push(id) })
fn.after = order.after
return fn
}
const service = new Service('/', {
plugins: [
{
id: 'vue-cli-plugin-foo',
apply: apply('vue-cli-plugin-foo')
},
{
id: 'vue-cli-plugin-bar',
apply: apply('vue-cli-plugin-bar', { after: 'vue-cli-plugin-baz' })
},
{
id: 'vue-cli-plugin-baz',
apply: apply('vue-cli-plugin-baz')
}
]
})
expect(service.plugins.map(p => p.id)).toEqual([
'built-in:commands/serve',
'built-in:commands/build',
'built-in:commands/inspect',
'built-in:commands/help',
'built-in:config/base',
'built-in:config/assets',
'built-in:config/css',
'built-in:config/prod',
'built-in:config/app',
'vue-cli-plugin-foo',
'vue-cli-plugin-baz',
'vue-cli-plugin-bar'
])

await service.init()
expect(applyCallOrder).toEqual([
'vue-cli-plugin-foo',
'vue-cli-plugin-baz',
'vue-cli-plugin-bar'
])
})
8 changes: 6 additions & 2 deletions packages/@vue/cli-service/lib/Service.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const PluginAPI = require('./PluginAPI')
const dotenv = require('dotenv')
const dotenvExpand = require('dotenv-expand')
const defaultsDeep = require('lodash.defaultsdeep')
const { warn, error, isPlugin, resolvePluginId, loadModule, resolvePkg, resolveModule } = require('@vue/cli-shared-utils')
const { warn, error, isPlugin, resolvePluginId, loadModule, resolvePkg, resolveModule, sortPlugins } = require('@vue/cli-shared-utils')

const { defaults } = require('./options')
const checkWebpack = require('./util/checkWebpack')
Expand Down Expand Up @@ -224,8 +224,12 @@ module.exports = class Service {
apply: loadModule(`./${file}`, this.pkgContext)
})))
}
debug('vue:plugins')(plugins)

return plugins
const orderedPlugins = sortPlugins(plugins)
debug('vue:plugins-ordered')(orderedPlugins)

return orderedPlugins
}

async run (name, args = {}, rawArgv = []) {
Expand Down
73 changes: 73 additions & 0 deletions packages/@vue/cli-shared-utils/__tests__/pluginOrder.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
const { topologicalSorting } = require('../lib/pluginOrder')
const { logs } = require('../lib/logger')

/**
*
* @param {string} id
* @param {{stage: number, after: string|Array<string>}} [order]
*/
function plugin (id, order) {
order = order || {}
const { after } = order

// use object instead of function here
const apply = {}
apply.after = after
return {
id,
apply
}
}

describe('topologicalSorting', () => {
test(`no specifying 'after' will preserve sort order`, () => {
const plugins = [
plugin('foo'),
plugin('bar'),
plugin('baz')
]
const orderPlugins = topologicalSorting(plugins)
expect(orderPlugins).toEqual(plugins)
})

test(`'after' specified`, () => {
const plugins = [
plugin('foo', { after: 'bar' }),
plugin('bar', { after: 'baz' }),
plugin('baz')
]
const orderPlugins = topologicalSorting(plugins)
expect(orderPlugins).toEqual([
plugin('baz'),
plugin('bar', { after: 'baz' }),
plugin('foo', { after: 'bar' })
])
})

test(`'after' can be Array<string>`, () => {
const plugins = [
plugin('foo', { after: ['bar', 'baz'] }),
plugin('bar'),
plugin('baz')
]
const orderPlugins = topologicalSorting(plugins)
expect(orderPlugins).toEqual([
plugin('bar'),
plugin('baz'),
plugin('foo', { after: ['bar', 'baz'] })
])
})

test('it is not possible to sort plugins because of cyclic graph, return original plugins directly', () => {
logs.warn = []
const plugins = [
plugin('foo', { after: 'bar' }),
plugin('bar', { after: 'baz' }),
plugin('baz', { after: 'foo' })
]
const orderPlugins = topologicalSorting(plugins)
expect(orderPlugins).toEqual(plugins)

expect(logs.warn.length).toBe(1)
})
})
1 change: 1 addition & 0 deletions packages/@vue/cli-shared-utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
'openBrowser',
'pkg',
'pluginResolution',
'pluginOrder',
'launch',
'request',
'spinner',
Expand Down
110 changes: 110 additions & 0 deletions packages/@vue/cli-shared-utils/lib/pluginOrder.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
// @ts-check
const { warn } = require('./logger')

/** @typedef {{after?: string|Array<string>}} Apply */
/** @typedef {{id: string, apply: Apply}} Plugin */
/** @typedef {{after: Set<string>}} OrderParams */

/** @type {Map<string, OrderParams>} */
const orderParamsCache = new Map()

/**
*
* @param {Plugin} plugin
* @returns {OrderParams}
*/
function getOrderParams (plugin) {
if (!process.env.VUE_CLI_TEST && orderParamsCache.has(plugin.id)) {
return orderParamsCache.get(plugin.id)
}
const apply = plugin.apply

let after = new Set()
if (typeof apply.after === 'string') {
after = new Set([apply.after])
} else if (Array.isArray(apply.after)) {
after = new Set(apply.after)
}
if (!process.env.VUE_CLI_TEST) {
orderParamsCache.set(plugin.id, { after })
}

return { after }
}

/**
* See leetcode 210
* @param {Array<Plugin>} plugins
* @returns {Array<Plugin>}
*/
function topologicalSorting (plugins) {
/** @type {Map<string, Plugin>} */
const pluginsMap = new Map(plugins.map(p => [p.id, p]))

/** @type {Map<Plugin, number>} */
const indegrees = new Map()

/** @type {Map<Plugin, Array<Plugin>>} */
const graph = new Map()

plugins.forEach(p => {
const after = getOrderParams(p).after
indegrees.set(p, after.size)
if (after.size === 0) return
for (const id of after) {
const prerequisite = pluginsMap.get(id)
// remove invalid data
if (!prerequisite) {
indegrees.set(p, indegrees.get(p) - 1)
continue
}

if (!graph.has(prerequisite)) {
graph.set(prerequisite, [])
}
graph.get(prerequisite).push(p)
}
})

const res = []
const queue = []
indegrees.forEach((d, p) => {
if (d === 0) queue.push(p)
})
while (queue.length) {
const cur = queue.shift()
res.push(cur)
const neighbors = graph.get(cur)
if (!neighbors) continue

neighbors.forEach(n => {
const degree = indegrees.get(n) - 1
indegrees.set(n, degree)
if (degree === 0) {
queue.push(n)
}
})
}
const valid = res.length === plugins.length
if (!valid) {
warn(`No proper plugin execution order found.`)
return plugins
}
return res
}

/**
* Arrange plugins by 'after' property.
* @param {Array<Plugin>} plugins
* @returns {Array<Plugin>}
*/
function sortPlugins (plugins) {
if (plugins.length < 2) return plugins

return topologicalSorting(plugins)
}

module.exports = {
topologicalSorting,
sortPlugins
}
Loading