properties.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. "use strict";
  2. /**
  3. * Property helper functions.
  4. *
  5. * @_subsection api/utils:Properties [about-properties]
  6. */
  7. Object.defineProperty(exports, "__esModule", { value: true });
  8. exports.defineProperties = exports.resolveProperties = void 0;
  9. function checkType(value, type, name) {
  10. const types = type.split("|").map(t => t.trim());
  11. for (let i = 0; i < types.length; i++) {
  12. switch (type) {
  13. case "any":
  14. return;
  15. case "bigint":
  16. case "boolean":
  17. case "number":
  18. case "string":
  19. if (typeof (value) === type) {
  20. return;
  21. }
  22. }
  23. }
  24. const error = new Error(`invalid value for type ${type}`);
  25. error.code = "INVALID_ARGUMENT";
  26. error.argument = `value.${name}`;
  27. error.value = value;
  28. throw error;
  29. }
  30. /**
  31. * Resolves to a new object that is a copy of %%value%%, but with all
  32. * values resolved.
  33. */
  34. async function resolveProperties(value) {
  35. const keys = Object.keys(value);
  36. const results = await Promise.all(keys.map((k) => Promise.resolve(value[k])));
  37. return results.reduce((accum, v, index) => {
  38. accum[keys[index]] = v;
  39. return accum;
  40. }, {});
  41. }
  42. exports.resolveProperties = resolveProperties;
  43. /**
  44. * Assigns the %%values%% to %%target%% as read-only values.
  45. *
  46. * It %%types%% is specified, the values are checked.
  47. */
  48. function defineProperties(target, values, types) {
  49. for (let key in values) {
  50. let value = values[key];
  51. const type = (types ? types[key] : null);
  52. if (type) {
  53. checkType(value, type, key);
  54. }
  55. Object.defineProperty(target, key, { enumerable: true, value, writable: false });
  56. }
  57. }
  58. exports.defineProperties = defineProperties;
  59. //# sourceMappingURL=properties.js.map