plugin.js 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { TronWeb } from '../tronweb.js';
  2. import utils from '../utils/index.js';
  3. import semver from 'semver';
  4. export class Plugin {
  5. tronWeb;
  6. pluginNoOverride;
  7. disablePlugins;
  8. constructor(tronWeb, options = {}) {
  9. if (!tronWeb || !(tronWeb instanceof TronWeb))
  10. throw new Error('Expected instance of TronWeb');
  11. this.tronWeb = tronWeb;
  12. this.pluginNoOverride = ['register'];
  13. this.disablePlugins = !!options.disablePlugins;
  14. }
  15. register(Plugin, options) {
  16. let pluginInterface = {
  17. requires: '0.0.0',
  18. components: {},
  19. };
  20. const result = {
  21. libs: [],
  22. plugged: [],
  23. skipped: [],
  24. error: undefined,
  25. };
  26. if (this.disablePlugins) {
  27. result.error = 'This instance of TronWeb has plugins disabled.';
  28. return result;
  29. }
  30. const plugin = new Plugin(this.tronWeb);
  31. if (utils.isFunction(plugin.pluginInterface)) {
  32. pluginInterface = plugin.pluginInterface(options);
  33. }
  34. if (semver.satisfies(TronWeb.version, pluginInterface.requires)) {
  35. if (pluginInterface.fullClass) {
  36. // plug the entire class at the same level of tronWeb.trx
  37. const className = plugin.constructor.name;
  38. const classInstanceName = className.substring(0, 1).toLowerCase() + className.substring(1);
  39. if (className !== classInstanceName) {
  40. Object.assign(TronWeb, {
  41. [className]: Plugin,
  42. });
  43. Object.assign(this.tronWeb, {
  44. [classInstanceName]: plugin,
  45. });
  46. result.libs.push(className);
  47. }
  48. }
  49. else {
  50. // plug methods into a class, like trx
  51. for (const component in pluginInterface.components) {
  52. // eslint-disable-next-line no-prototype-builtins
  53. if (!this.tronWeb.hasOwnProperty(component)) {
  54. continue;
  55. }
  56. const methods = pluginInterface.components[component];
  57. const pluginNoOverride = this.tronWeb[component].pluginNoOverride || [];
  58. for (const method in methods) {
  59. if (method === 'constructor' ||
  60. (this.tronWeb[component][method] &&
  61. (pluginNoOverride.includes(method) || // blacklisted methods
  62. /^_/.test(method))) // private methods
  63. ) {
  64. result.skipped.push(method);
  65. continue;
  66. }
  67. this.tronWeb[component][method] = methods[method].bind(this.tronWeb[component]);
  68. result.plugged.push(method);
  69. }
  70. }
  71. }
  72. }
  73. else {
  74. throw new Error('The plugin is not compatible with this version of TronWeb');
  75. }
  76. return result;
  77. }
  78. }
  79. //# sourceMappingURL=plugin.js.map