assertRecord.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $TypeError = GetIntrinsic('%TypeError%');
  4. var $SyntaxError = GetIntrinsic('%SyntaxError%');
  5. var has = require('has');
  6. var isMatchRecord = require('./isMatchRecord');
  7. var predicates = {
  8. // https://262.ecma-international.org/6.0/#sec-property-descriptor-specification-type
  9. 'Property Descriptor': function isPropertyDescriptor(Desc) {
  10. var allowed = {
  11. '[[Configurable]]': true,
  12. '[[Enumerable]]': true,
  13. '[[Get]]': true,
  14. '[[Set]]': true,
  15. '[[Value]]': true,
  16. '[[Writable]]': true
  17. };
  18. for (var key in Desc) { // eslint-disable-line
  19. if (has(Desc, key) && !allowed[key]) {
  20. return false;
  21. }
  22. }
  23. var isData = has(Desc, '[[Value]]');
  24. var IsAccessor = has(Desc, '[[Get]]') || has(Desc, '[[Set]]');
  25. if (isData && IsAccessor) {
  26. throw new $TypeError('Property Descriptors may not be both accessor and data descriptors');
  27. }
  28. return true;
  29. },
  30. // https://262.ecma-international.org/13.0/#sec-match-records
  31. 'Match Record': isMatchRecord,
  32. 'Iterator Record': function isIteratorRecord(value) {
  33. return has(value, '[[Iterator]]') && has(value, '[[NextMethod]]') && has(value, '[[Done]]');
  34. },
  35. 'PromiseCapability Record': function isPromiseCapabilityRecord(value) {
  36. return value
  37. && has(value, '[[Resolve]]')
  38. && typeof value['[[Resolve]]'] === 'function'
  39. && has(value, '[[Reject]]')
  40. && typeof value['[[Reject]]'] === 'function'
  41. && has(value, '[[Promise]]')
  42. && value['[[Promise]]']
  43. && typeof value['[[Promise]]'].then === 'function';
  44. },
  45. 'AsyncGeneratorRequest Record': function isAsyncGeneratorRequestRecord(value) {
  46. return value
  47. && has(value, '[[Completion]]') // TODO: confirm is a completion record
  48. && has(value, '[[Capability]]')
  49. && predicates['PromiseCapability Record'](value['[[Capability]]']);
  50. }
  51. };
  52. module.exports = function assertRecord(Type, recordType, argumentName, value) {
  53. var predicate = predicates[recordType];
  54. if (typeof predicate !== 'function') {
  55. throw new $SyntaxError('unknown record type: ' + recordType);
  56. }
  57. if (Type(value) !== 'Object' || !predicate(value)) {
  58. throw new $TypeError(argumentName + ' must be a ' + recordType);
  59. }
  60. };