unsafe-html.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /**
  2. * @license
  3. * Copyright 2017 Google LLC
  4. * SPDX-License-Identifier: BSD-3-Clause
  5. */
  6. import { nothing, noChange } from '../lit-html.js';
  7. import { directive, Directive, PartType } from '../directive.js';
  8. const HTML_RESULT = 1;
  9. export class UnsafeHTMLDirective extends Directive {
  10. constructor(partInfo) {
  11. super(partInfo);
  12. this._value = nothing;
  13. if (partInfo.type !== PartType.CHILD) {
  14. throw new Error(`${this.constructor.directiveName}() can only be used in child bindings`);
  15. }
  16. }
  17. render(value) {
  18. if (value === nothing || value == null) {
  19. this._templateResult = undefined;
  20. return (this._value = value);
  21. }
  22. if (value === noChange) {
  23. return value;
  24. }
  25. if (typeof value != 'string') {
  26. throw new Error(`${this.constructor.directiveName}() called with a non-string value`);
  27. }
  28. if (value === this._value) {
  29. return this._templateResult;
  30. }
  31. this._value = value;
  32. const strings = [value];
  33. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  34. strings.raw = strings;
  35. // WARNING: impersonating a TemplateResult like this is extremely
  36. // dangerous. Third-party directives should not do this.
  37. return (this._templateResult = {
  38. // Cast to a known set of integers that satisfy ResultType so that we
  39. // don't have to export ResultType and possibly encourage this pattern.
  40. // This property needs to remain unminified.
  41. ['_$litType$']: this.constructor
  42. .resultType,
  43. strings,
  44. values: [],
  45. });
  46. }
  47. }
  48. UnsafeHTMLDirective.directiveName = 'unsafeHTML';
  49. UnsafeHTMLDirective.resultType = HTML_RESULT;
  50. /**
  51. * Renders the result as HTML, rather than text.
  52. *
  53. * The values `undefined`, `null`, and `nothing`, will all result in no content
  54. * (empty string) being rendered.
  55. *
  56. * Note, this is unsafe to use with any user-provided input that hasn't been
  57. * sanitized or escaped, as it may lead to cross-site-scripting
  58. * vulnerabilities.
  59. */
  60. export const unsafeHTML = directive(UnsafeHTMLDirective);
  61. //# sourceMappingURL=unsafe-html.js.map