-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathplugin.ts
434 lines (358 loc) · 15.1 KB
/
plugin.ts
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
import globby from 'globby'
import {join, parse, relative, sep} from 'node:path'
import {inspect} from 'node:util'
import Cache from '../cache'
import {Command} from '../command'
import {CLIError, error} from '../errors'
import {Manifest} from '../interfaces/manifest'
import {CommandDiscovery, HookOptions, PJSON} from '../interfaces/pjson'
import {Plugin as IPlugin, PluginOptions} from '../interfaces/plugin'
import {Topic} from '../interfaces/topic'
import {load, loadWithData, loadWithDataFromManifest} from '../module-loader'
import {OCLIF_MARKER_OWNER, Performance} from '../performance'
import {SINGLE_COMMAND_CLI_SYMBOL} from '../symbols'
import {cacheCommand} from '../util/cache-command'
import {findRoot} from '../util/find-root'
import {readJson} from '../util/fs'
import {readPjson} from '../util/read-pjson'
import {castArray, compact} from '../util/util'
import {tsPath} from './ts-path'
import {getCommandIdPermutations, makeDebug} from './util'
const _pjson = Cache.getInstance().get('@oclif/core')
function topicsToArray(input: any, base?: string): Topic[] {
if (!input) return []
base = base ? `${base}:` : ''
if (Array.isArray(input)) {
return [...input, input.flatMap((t) => topicsToArray(t.subtopics, `${base}${t.name}`))]
}
return Object.keys(input).flatMap((k) => {
input[k].name = k
return [{...input[k], name: `${base}${k}`}, ...topicsToArray(input[k].subtopics, `${base}${input[k].name}`)]
})
}
const cachedCommandCanBeUsed = (manifest: Manifest | undefined, id: string): boolean =>
Boolean(manifest?.commands[id] && 'isESM' in manifest.commands[id] && 'relativePath' in manifest.commands[id])
const searchForCommandClass = (cmd: any) => {
if (typeof cmd.run === 'function') return cmd
if (cmd.default && cmd.default.run) return cmd.default
return Object.values(cmd).find((cmd: any) => typeof cmd.run === 'function')
}
const ensureCommandClass = (cmd: any) => {
if (cmd && typeof cmd.run === 'function') return cmd
}
const GLOB_PATTERNS = [
'**/*.+(js|cjs|mjs|ts|tsx|mts|cts)',
'!**/*.+(d.ts|test.ts|test.js|spec.ts|spec.js|d.mts|d.cts)?(x)',
]
function processCommandIds(files: string[]): string[] {
return files.map((file) => {
const p = parse(file)
const topics = p.dir.split('/')
const command = p.name !== 'index' && p.name
const id = [...topics, command].filter(Boolean).join(':')
return id === '' ? SINGLE_COMMAND_CLI_SYMBOL : id
})
}
function determineCommandDiscoveryOptions(
commandDiscovery: string | CommandDiscovery | undefined,
): CommandDiscovery | undefined {
if (!commandDiscovery) return
if (typeof commandDiscovery === 'string') {
return {globPatterns: GLOB_PATTERNS, strategy: 'pattern', target: commandDiscovery}
}
if (!commandDiscovery.target) throw new CLIError('`oclif.commandDiscovery.target` is required.')
if (!commandDiscovery.strategy) throw new CLIError('`oclif.commandDiscovery.strategy` is required.')
if (commandDiscovery.strategy === 'explicit' && !commandDiscovery.identifier) {
commandDiscovery.identifier = 'default'
}
return commandDiscovery
}
function determineHookOptions(hook: string | HookOptions): HookOptions {
if (typeof hook === 'string') return {identifier: 'default', target: hook}
if (!hook.identifier) return {...hook, identifier: 'default'}
return hook
}
/**
* Cached commands, where the key is the command ID and the value is the command class.
*
* This is only populated if the `strategy` is `explicit` and the `target` is a file that default exports the id-to-command-class object.
* Or if the strategy is `single` and the `target` is the file containing a command class.
*/
type CommandCache = Record<string, Command.Class>
export class Plugin implements IPlugin {
alias!: string
alreadyLoaded = false
children: Plugin[] = []
commandIDs: string[] = []
// This will be initialized in the _manifest() method, which gets called in the load() method.
commands!: Command.Loadable[]
commandsDir: string | undefined
hasManifest = false
hooks!: {[key: string]: HookOptions[]}
isRoot = false
manifest!: Manifest
moduleType!: 'commonjs' | 'module'
name!: string
parent?: Plugin | undefined
pjson!: PJSON
root!: string
tag?: string | undefined
type!: string
valid = false
version!: string
_base = `${_pjson.name}@${_pjson.version}`
protected _debug = makeDebug()
private commandCache: CommandCache | undefined
private commandDiscoveryOpts: CommandDiscovery | undefined
private flexibleTaxonomy!: boolean
constructor(public options: PluginOptions) {}
public get topics(): Topic[] {
return topicsToArray(this.pjson.oclif.topics || {})
}
public async findCommand(id: string, opts: {must: true}): Promise<Command.Class>
public async findCommand(id: string, opts?: {must: boolean}): Promise<Command.Class | undefined>
public async findCommand(id: string, opts: {must?: boolean} = {}): Promise<Command.Class | undefined> {
const marker = Performance.mark(OCLIF_MARKER_OWNER, `plugin.findCommand#${this.name}.${id}`, {
id,
plugin: this.name,
})
const fetch = async () => {
if (this.commandDiscoveryOpts?.strategy === 'pattern') {
const commandsDir = await this.getCommandsDir()
if (!commandsDir) return
let module
let isESM: boolean | undefined
let filePath: string | undefined
try {
;({filePath, isESM, module} = cachedCommandCanBeUsed(this.manifest, id)
? await loadWithDataFromManifest(this.manifest.commands[id], this.root)
: await loadWithData(this, join(commandsDir ?? this.pjson.oclif.commands, ...id.split(':'))))
this._debug(isESM ? '(import)' : '(require)', filePath)
} catch (error: any) {
if (!opts.must && error.code === 'MODULE_NOT_FOUND') return
throw error
}
const cmd = searchForCommandClass(module)
if (!cmd) return
cmd.id = id
cmd.plugin = this
cmd.isESM = isESM
cmd.relativePath = relative(this.root, filePath || '').split(sep)
return cmd
}
if (this.commandDiscoveryOpts?.strategy === 'single' || this.commandDiscoveryOpts?.strategy === 'explicit') {
const commandCache = await this.loadCommandsFromTarget()
const cmd = ensureCommandClass(commandCache?.[id])
if (!cmd) return
cmd.id = id
cmd.plugin = this
return cmd
}
}
const cmd = await fetch()
if (!cmd && opts.must) error(`command ${id} not found`)
marker?.stop()
return cmd
}
public async load(): Promise<void> {
this.type = this.options.type ?? 'core'
this.tag = this.options.tag
this.isRoot = this.options.isRoot ?? false
if (this.options.parent) this.parent = this.options.parent as Plugin
// Linked plugins already have a root so there's no need to search for it.
// However there could be child plugins nested inside the linked plugin, in which
// case we still need to search for the child plugin's root.
const root =
this.options.pjson && this.options.isRoot
? this.options.root
: this.type === 'link' && !this.parent
? this.options.root
: await findRoot(this.options.name, this.options.root)
if (!root) throw new CLIError(`could not find package.json with ${inspect(this.options)}`)
this.root = root
this._debug(`loading ${this.type} plugin from ${root}`)
this.pjson = this.options.pjson ?? (await readPjson(root))
this.flexibleTaxonomy = this.options?.flexibleTaxonomy || this.pjson.oclif?.flexibleTaxonomy || false
this.moduleType = this.pjson.type === 'module' ? 'module' : 'commonjs'
this.name = this.pjson.name
this.alias = this.options.name ?? this.pjson.name
if (!this.name) throw new CLIError(`no name in package.json (${root})`)
this._debug = makeDebug(this.name)
this.version = this.pjson.version
if (this.pjson.oclif) {
this.valid = true
} else {
this.pjson.oclif = this.pjson['cli-engine'] || {}
}
this.hooks = Object.fromEntries(
Object.entries(this.pjson.oclif.hooks ?? {}).map(([k, v]) => [
k,
castArray<string | HookOptions>(v).map((v) => determineHookOptions(v)),
]),
)
this.commandDiscoveryOpts = determineCommandDiscoveryOptions(this.pjson.oclif?.commands)
this._debug('command discovery options', this.commandDiscoveryOpts)
this.manifest = await this._manifest()
this.commands = Object.entries(this.manifest.commands)
.map(([id, c]) => ({
...c,
load: async () => this.findCommand(id, {must: true}),
pluginAlias: this.alias,
pluginType: c.pluginType === 'jit' ? 'jit' : this.type,
}))
.sort((a, b) => a.id.localeCompare(b.id))
}
private async _manifest(): Promise<Manifest> {
const ignoreManifest = Boolean(this.options.ignoreManifest)
const errorOnManifestCreate = Boolean(this.options.errorOnManifestCreate)
const respectNoCacheDefault = Boolean(this.options.respectNoCacheDefault)
const readManifest = async (dotfile = false): Promise<Manifest | undefined> => {
try {
const p = join(this.root, `${dotfile ? '.' : ''}oclif.manifest.json`)
const manifest = await readJson<Manifest>(p)
if (!process.env.OCLIF_NEXT_VERSION && manifest.version.split('-')[0] !== this.version.split('-')[0]) {
process.emitWarning(
`Mismatched version in ${this.name} plugin manifest. Expected: ${this.version} Received: ${manifest.version}\nThis usually means you have an oclif.manifest.json file that should be deleted in development. This file should be automatically generated when publishing.`,
)
} else {
this._debug('using manifest from', p)
this.hasManifest = true
return manifest
}
} catch (error: any) {
if (error.code === 'ENOENT') {
if (!dotfile) return readManifest(true)
} else {
this.warn(error, 'readManifest')
}
}
}
const marker = Performance.mark(OCLIF_MARKER_OWNER, `plugin.manifest#${this.name}`, {plugin: this.name})
if (!ignoreManifest) {
const manifest = await readManifest()
if (manifest) {
marker?.addDetails({commandCount: Object.keys(manifest.commands).length, fromCache: true})
marker?.stop()
this.commandIDs = Object.keys(manifest.commands)
return manifest
}
}
this.commandIDs = await this.getCommandIDs()
const manifest = {
commands: (
await Promise.all(
this.commandIDs.map(async (id) => {
try {
const found = await this.findCommand(id, {must: true})
const cached = await cacheCommand(found, this, respectNoCacheDefault)
// Ensure that id is set to the id being processed
// This is necessary because the id is set by findCommand but if there
// are multiple instances of a Command, then the id will be set to the
// last one found.
cached.id = id
if (this.flexibleTaxonomy) {
const permutations = getCommandIdPermutations(id)
const aliasPermutations = cached.aliases.flatMap((a) => getCommandIdPermutations(a))
return [id, {...cached, aliasPermutations, permutations} as Command.Cached]
}
return [id, cached]
} catch (error: any) {
const scope = `findCommand (${id})`
if (Boolean(errorOnManifestCreate) === false) this.warn(error, scope)
else throw this.addErrorScope(error, scope)
}
}),
)
)
// eslint-disable-next-line unicorn/prefer-native-coercion-functions
.filter((f): f is [string, Command.Cached] => Boolean(f))
.reduce<{[k: string]: Command.Cached}>((commands, [id, c]) => {
commands[id] = c
return commands
}, {}),
version: this.version,
}
marker?.addDetails({commandCount: Object.keys(manifest.commands).length, fromCache: false})
marker?.stop()
return manifest
}
private addErrorScope(err: any, scope?: string) {
err.name = err.name ?? inspect(err).trim()
err.detail = compact([
err.detail,
`module: ${this._base}`,
scope && `task: ${scope}`,
`plugin: ${this.name}`,
`root: ${this.root}`,
...(err.code ? [`code: ${err.code}`] : []),
...(err.message ? [`message: ${err.message}`] : []),
'See more details with DEBUG=*',
]).join('\n')
return err
}
private async getCommandIDs(): Promise<string[]> {
const marker = Performance.mark(OCLIF_MARKER_OWNER, `plugin.getCommandIDs#${this.name}`, {plugin: this.name})
let ids: string[]
switch (this.commandDiscoveryOpts?.strategy) {
case 'explicit': {
ids = (await this.getCommandIdsFromTarget()) ?? []
break
}
case 'pattern': {
ids = await this.getCommandIdsFromPattern()
break
}
case 'single': {
ids = (await this.getCommandIdsFromTarget()) ?? []
break
}
default: {
ids = []
}
}
this._debug('found commands', ids)
marker?.addDetails({count: ids.length})
marker?.stop()
return ids
}
private async getCommandIdsFromPattern(): Promise<string[]> {
const commandsDir = await this.getCommandsDir()
if (!commandsDir) return []
this._debug(`loading IDs from ${commandsDir}`)
const files = await globby(this.commandDiscoveryOpts?.globPatterns ?? GLOB_PATTERNS, {cwd: commandsDir})
return processCommandIds(files)
}
private async getCommandIdsFromTarget(): Promise<string[] | undefined> {
const commandsFromExport = await this.loadCommandsFromTarget()
if (commandsFromExport) {
return Object.entries((await this.loadCommandsFromTarget()) ?? [])
.filter(([, cmd]) => ensureCommandClass(cmd))
.map(([id]) => id)
}
}
private async getCommandsDir(): Promise<string | undefined> {
if (this.commandsDir) return this.commandsDir
this.commandsDir = await tsPath(this.root, this.commandDiscoveryOpts?.target, this)
return this.commandsDir
}
private async loadCommandsFromTarget(): Promise<CommandCache | undefined> {
if (this.commandCache) return this.commandCache
if (this.commandDiscoveryOpts?.strategy === 'explicit' && this.commandDiscoveryOpts.target) {
const filePath = await tsPath(this.root, this.commandDiscoveryOpts.target, this)
const module = await load<Record<string, CommandCache>>(this, filePath)
this.commandCache = module[this.commandDiscoveryOpts?.identifier ?? 'default'] ?? {}
return this.commandCache
}
if (this.commandDiscoveryOpts?.strategy === 'single' && this.commandDiscoveryOpts.target) {
const filePath = await tsPath(this.root, this.commandDiscoveryOpts?.target ?? this.root, this)
const module = await load(this, filePath)
this.commandCache = {[SINGLE_COMMAND_CLI_SYMBOL]: searchForCommandClass(module)}
return this.commandCache
}
}
private warn(err: CLIError | Error | string, scope?: string): void {
if (typeof err === 'string') err = new Error(err)
const warning = this.addErrorScope(err, scope)
process.emitWarning(warning.name, warning)
}
}