forked from webdriverio/webdriverio
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathplugins.ts
More file actions
165 lines (154 loc) · 5.89 KB
/
plugins.ts
File metadata and controls
165 lines (154 loc) · 5.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
import cp, { type ExecException } from 'node:child_process'
import url from 'node:url'
import path from 'node:path'
import util from 'node:util'
import chalk from 'chalk'
import { rimraf } from 'rimraf'
import { copy } from 'esbuild-plugin-copy'
import type { Plugin, BuildOptions } from 'esbuild'
import type { PackageJson } from 'type-fest'
const MAX_RETRIES = 3
const __dirname = path.dirname(url.fileURLToPath(import.meta.url))
const exec = util.promisify(cp.exec)
const tscPath = path.resolve(path.dirname(url.fileURLToPath(import.meta.resolve('typescript'))), '..', 'bin', 'tsc')
const l = {
format: (format: string = 'unknown') => chalk.yellowBright(format),
file: (file: string = 'unknown') => chalk.blueBright(file),
name: (name: string = 'unknown') => chalk.hex('#EA5907')(`[${name}]`)
}
/**
* little logger plugin for Esbuild
* @param {BuildOptions} options Esbuild options
* @param {PackageJson} pkg package.json of given project as object
* @returns
*/
export function log(options: BuildOptions, pkg: PackageJson): Plugin {
const srcFile = path.relative(options.absWorkingDir || process.cwd(), (options.entryPoints as string[])[0])
const outFile = path.relative(options.absWorkingDir || process.cwd(), options.outfile || options.outdir as string)
return {
name: 'LogPlugin',
setup(build) {
build.onStart(() => {
console.log(`${l.name(pkg.name)} 🏗️ Building ${l.format(`${options.platform}:${options.format}`)} package: ${l.file(srcFile)} → ${l.file(outFile)}`)
})
build.onEnd((result) => {
if (result.errors.length === 0) {
console.log(`${l.name(pkg.name)} ✅ Success building ${l.format(`${options.platform}:${options.format}`)} package: ${l.file(srcFile)} → ${l.file(outFile)}`)
}
})
}
}
}
/**
* clear previously generated build files
* @param {string} outfile directory that Esbuild usually compiles to
* @returns an Esbuild plugin
*/
export function clear(config: BuildOptions): Plugin {
const rimrafOptions = { maxRetries: 1 }
const outfile = config.outfile || config.outdir
if (!outfile) {
throw new Error('No outfile defined')
}
return {
name: 'ClearPlugin',
async setup() {
await Promise.all([
rimraf(path.dirname(outfile), rimrafOptions),
])
}
}
}
/**
* Generates type definition files (d.ts) for a given package.
*
* @param {string} cwd - The current working directory.
* @param {PackageJson} pkg - The package JSON object.
* @param {number} [retry=MAX_RETRIES] - The number of retries.
* @return {Promise<void>} A promise that resolves when the types are generated.
*/
function generateTypes(cwd: string, pkg: PackageJson, retry = MAX_RETRIES): Promise<void> {
const child = exec(`node ${tscPath} --emitDeclarationOnly --declarationMap false`, { cwd })
return child.then(() => { }, (err) => {
if (retry > 0) {
console.log(`${l.name(pkg.name)} ↻ Retrying (${MAX_RETRIES - (retry - 1)}/${MAX_RETRIES}) building types for ${pkg.name}`)
return generateTypes(cwd, pkg, retry - 1)
}
const error: ExecException = err instanceof Error ? err : new Error(`unknown error: ${err}`)
throw new Error(`[${pkg.name}] Failed to generate d.ts files: ${error.message}\n${error.stdout}`)
})
}
/**
* generate type definition files (d.ts) for working dir
* @param {string} absWorkingDir absolute path to the working directory
* @returns an Esbuild plugin
*/
export function generateDts(absWorkingDir: string, pkg: PackageJson): Plugin {
return {
name: 'TypeScriptDeclarationsPlugin',
setup(build) {
build.onEnd(async (result) => {
/**
* don't build types if we failed already somewhere else
*/
if (result.errors.length > 0) {
return
}
await generateTypes(absWorkingDir, pkg)
})
}
}
}
/**
* Plugin to copy EJS templates from the `@wdio/cli` package to build directory
* @returns {Plugin} an Esbuild plugin
*/
export function copyEJSTemplates() {
const cliPackage = path.resolve(__dirname, '..', '..', '..', 'packages', 'wdio-cli')
return copy({
resolveFrom: cliPackage,
assets: [{
from: [path.resolve(cliPackage, 'src', 'templates', '**', '*.ejs')],
to: path.resolve(cliPackage, 'build', 'templates')
}, {
from: [path.resolve(cliPackage, 'src', 'templates', '**', '*.feature')],
to: path.resolve(cliPackage, 'build', 'templates')
}]
})
}
/**
* Plugin to mark all WebdriverIO scripts in `packages/webdriverio/src/scripts` as external
*/
export function externalScripts(): Plugin {
const name = 'ExternalScripts'
return {
name,
setup(build) {
build.onResolve({ filter: /\/scripts\// }, (args) => ({
path: `./scripts/${path.basename(args.path)}`,
external: true,
pluginName: name
}))
}
}
}
export function runBuildScript(absWorkingDir: string, pkg: PackageJson): Plugin {
return {
name: `build-${pkg.name || 'unknown'}`,
setup(build) {
build.onEnd(async () => {
const child = cp.spawn('pnpm',
['run', 'build'],
{ cwd: absWorkingDir, stdio: 'inherit' }
)
child.on('exit', (code) => {
if (code !== 0) {
console.log(`${l.name(pkg.name)} ❌ Failed run build script for ${pkg.name}`)
return
}
console.log(`${l.name(pkg.name)} ✅ Successfully ran build script for ${pkg.name}: "${pkg.scripts?.build}"`)
})
})
}
}
}