api.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. var asn1 = require('../asn1');
  2. var inherits = require('inherits');
  3. var api = exports;
  4. api.define = function define(name, body) {
  5. return new Entity(name, body);
  6. };
  7. function Entity(name, body) {
  8. this.name = name;
  9. this.body = body;
  10. this.decoders = {};
  11. this.encoders = {};
  12. };
  13. Entity.prototype._createNamed = function createNamed(base) {
  14. var named;
  15. try {
  16. named = require('vm').runInThisContext(
  17. '(function ' + this.name + '(entity) {\n' +
  18. ' this._initNamed(entity);\n' +
  19. '})'
  20. );
  21. } catch (e) {
  22. named = function (entity) {
  23. this._initNamed(entity);
  24. };
  25. }
  26. inherits(named, base);
  27. named.prototype._initNamed = function initnamed(entity) {
  28. base.call(this, entity);
  29. };
  30. return new named(this);
  31. };
  32. Entity.prototype._getDecoder = function _getDecoder(enc) {
  33. enc = enc || 'der';
  34. // Lazily create decoder
  35. if (!this.decoders.hasOwnProperty(enc))
  36. this.decoders[enc] = this._createNamed(asn1.decoders[enc]);
  37. return this.decoders[enc];
  38. };
  39. Entity.prototype.decode = function decode(data, enc, options) {
  40. return this._getDecoder(enc).decode(data, options);
  41. };
  42. Entity.prototype._getEncoder = function _getEncoder(enc) {
  43. enc = enc || 'der';
  44. // Lazily create encoder
  45. if (!this.encoders.hasOwnProperty(enc))
  46. this.encoders[enc] = this._createNamed(asn1.encoders[enc]);
  47. return this.encoders[enc];
  48. };
  49. Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) {
  50. return this._getEncoder(enc).encode(data, reporter);
  51. };