attribute_impl.mjs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /**
  2. * @license
  3. * SPDX-License-Identifier: Apache-2.0
  4. */
  5. import '../environment/dev';
  6. import { ensureTokenIsValid, secretToken } from './secrets';
  7. /** A prefix with which an attribute is safe to set using plain strings. */
  8. export class SafeAttributePrefix {
  9. // @ts-ignore: error TS6133: 'brand' is declared but its value is never read.
  10. brand; // To prevent structural typing.
  11. }
  12. /** Implementation for `SafeAttributePrefix` */
  13. class AttributePrefixImpl extends SafeAttributePrefix {
  14. privateDoNotAccessOrElseWrappedAttrPrefix;
  15. constructor(attrPrefix, token) {
  16. super();
  17. if (process.env.NODE_ENV !== 'production') {
  18. ensureTokenIsValid(token);
  19. }
  20. this.privateDoNotAccessOrElseWrappedAttrPrefix = attrPrefix;
  21. }
  22. toString() {
  23. return this.privateDoNotAccessOrElseWrappedAttrPrefix;
  24. }
  25. }
  26. /**
  27. * Builds a new `SafeAttribute` from the given string, without enforcing
  28. * safety guarantees. This shouldn't be exposed to application developers, and
  29. * must only be used as a step towards safe builders or safe constants.
  30. */
  31. export function createAttributePrefix(attrPrefix) {
  32. return new AttributePrefixImpl(attrPrefix, secretToken);
  33. }
  34. /**
  35. * Returns the string value of the passed `SafeAttributePrefix` object while
  36. * ensuring it has the correct type.
  37. */
  38. export function unwrapAttributePrefix(value) {
  39. if (value instanceof AttributePrefixImpl) {
  40. return value.privateDoNotAccessOrElseWrappedAttrPrefix;
  41. }
  42. else {
  43. let message = '';
  44. if (process.env.NODE_ENV !== 'production') {
  45. message = 'Unexpected type when unwrapping SafeAttributePrefix';
  46. }
  47. throw new Error(message);
  48. }
  49. }