| 13 | } |
| 14 | |
| 15 | export class Command implements ICommand { |
| 16 | private commands: Map<string, IPublicTypeCommand> = new Map(); |
| 17 | private commandErrors: Function[] = []; |
| 18 | |
| 19 | registerCommand(command: IPublicTypeCommand, options?: ICommandOptions): void { |
| 20 | if (!options?.commandScope) { |
| 21 | throw new Error('plugin meta.commandScope is required.'); |
| 22 | } |
| 23 | const name = `${options.commandScope}:${command.name}`; |
| 24 | if (this.commands.has(name)) { |
| 25 | throw new Error(`Command '${command.name}' is already registered.`); |
| 26 | } |
| 27 | this.commands.set(name, { |
| 28 | ...command, |
| 29 | name, |
| 30 | }); |
| 31 | } |
| 32 | |
| 33 | unregisterCommand(name: string): void { |
| 34 | if (!this.commands.has(name)) { |
| 35 | throw new Error(`Command '${name}' is not registered.`); |
| 36 | } |
| 37 | this.commands.delete(name); |
| 38 | } |
| 39 | |
| 40 | executeCommand(name: string, args: IPublicTypeCommandHandlerArgs): void { |
| 41 | const command = this.commands.get(name); |
| 42 | if (!command) { |
| 43 | throw new Error(`Command '${name}' is not registered.`); |
| 44 | } |
| 45 | command.parameters?.forEach(d => { |
| 46 | if (!checkPropTypes(args[d.name], d.name, d.propType, 'command')) { |
| 47 | throw new Error(`Command '${name}' arguments ${d.name} is invalid.`); |
| 48 | } |
| 49 | }); |
| 50 | try { |
| 51 | command.handler(args); |
| 52 | } catch (error) { |
| 53 | if (this.commandErrors && this.commandErrors.length) { |
| 54 | this.commandErrors.forEach(callback => callback(name, error)); |
| 55 | } else { |
| 56 | throw error; |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | batchExecuteCommand(commands: { name: string; args: IPublicTypeCommandHandlerArgs }[], pluginContext: IPublicModelPluginContext): void { |
| 62 | if (!commands || !commands.length) { |
| 63 | return; |
| 64 | } |
| 65 | pluginContext.common.utils.executeTransaction(() => { |
| 66 | commands.forEach(command => this.executeCommand(command.name, command.args)); |
| 67 | }, IPublicEnumTransitionType.REPAINT); |
| 68 | } |
| 69 | |
| 70 | listCommands(): IPublicTypeListCommand[] { |
| 71 | return Array.from(this.commands.values()).map(d => { |
| 72 | const result: IPublicTypeListCommand = { |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…