@salla.sa/ui-ai-kit-core 1.1.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/dist/cjs/ai-card.cjs.entry.js +2 -2
  2. package/dist/cjs/ai-chat-container.cjs.entry.js +84 -57
  3. package/dist/cjs/ai-chat-header.cjs.entry.js +29 -19
  4. package/dist/cjs/ai-chat-message.cjs.entry.js +1456 -21
  5. package/dist/cjs/ai-conversation-list.cjs.entry.js +80 -0
  6. package/dist/cjs/ai-conversation-summary.cjs.entry.js +33 -0
  7. package/dist/cjs/ai-icon.cjs.entry.js +2 -2
  8. package/dist/cjs/ai-link.cjs.entry.js +4 -4
  9. package/dist/cjs/ai-loading.cjs.entry.js +35 -22
  10. package/dist/cjs/ai-message-input.cjs.entry.js +48 -15
  11. package/dist/cjs/ai-rating.cjs.entry.js +2 -2
  12. package/dist/cjs/ai-route-decision.cjs.entry.js +48 -0
  13. package/dist/cjs/ai-suggestion.cjs.entry.js +4 -4
  14. package/dist/cjs/ai-voice-input.cjs.entry.js +75 -21
  15. package/dist/cjs/{icon-registry-dmfLA-Dj.js → icon-registry-BKb9-2Nt.js} +24 -0
  16. package/dist/cjs/{index-DLJcLHFH.js → index-BkNg07SW.js} +1 -1
  17. package/dist/cjs/loader.cjs.js +2 -2
  18. package/dist/cjs/ui-ai-kit.cjs.js +2 -2
  19. package/dist/collection/collection-manifest.json +3 -0
  20. package/dist/collection/components/ai-card/ai-card.css +5 -8
  21. package/dist/collection/components/ai-chat-container/ai-chat-container.css +17 -14
  22. package/dist/collection/components/ai-chat-container/ai-chat-container.js +125 -53
  23. package/dist/collection/components/ai-chat-header/ai-chat-header.css +50 -17
  24. package/dist/collection/components/ai-chat-header/ai-chat-header.js +53 -18
  25. package/dist/collection/components/ai-chat-message/ai-chat-message.css +47 -38
  26. package/dist/collection/components/ai-chat-message/ai-chat-message.js +68 -18
  27. package/dist/collection/components/ai-conversation-list/ai-conversation-list.css +196 -0
  28. package/dist/collection/components/ai-conversation-list/ai-conversation-list.js +176 -0
  29. package/dist/collection/components/ai-conversation-summary/ai-conversation-summary.css +103 -0
  30. package/dist/collection/components/ai-conversation-summary/ai-conversation-summary.js +118 -0
  31. package/dist/collection/components/ai-icon/ai-icon.js +1 -1
  32. package/dist/collection/components/ai-link/ai-link.css +3 -7
  33. package/dist/collection/components/ai-link/ai-link.js +1 -1
  34. package/dist/collection/components/ai-loading/ai-loading.css +149 -20
  35. package/dist/collection/components/ai-loading/ai-loading.js +100 -23
  36. package/dist/collection/components/ai-message-input/ai-message-input.css +41 -37
  37. package/dist/collection/components/ai-message-input/ai-message-input.js +100 -19
  38. package/dist/collection/components/ai-rating/ai-rating.css +8 -14
  39. package/dist/collection/components/ai-route-decision/ai-route-decision.css +132 -0
  40. package/dist/collection/components/ai-route-decision/ai-route-decision.js +195 -0
  41. package/dist/collection/components/ai-suggestion/ai-suggestion.css +5 -11
  42. package/dist/collection/components/ai-suggestion/ai-suggestion.js +2 -2
  43. package/dist/collection/components/ai-voice-input/ai-voice-input.css +27 -22
  44. package/dist/collection/components/ai-voice-input/ai-voice-input.js +116 -20
  45. package/dist/collection/utils/icon-registry.js +24 -0
  46. package/dist/components/ai-card.js +1 -1
  47. package/dist/components/ai-chat-container.js +1 -1
  48. package/dist/components/ai-chat-header.js +1 -1
  49. package/dist/components/ai-chat-message.js +2 -1
  50. package/dist/components/ai-conversation-list.d.ts +11 -0
  51. package/dist/components/ai-conversation-list.js +1 -0
  52. package/dist/components/ai-conversation-summary.d.ts +11 -0
  53. package/dist/components/ai-conversation-summary.js +1 -0
  54. package/dist/components/ai-icon.js +1 -1
  55. package/dist/components/ai-link.js +1 -1
  56. package/dist/components/ai-loading.js +1 -1
  57. package/dist/components/ai-message-input.js +1 -1
  58. package/dist/components/ai-rating.js +1 -1
  59. package/dist/components/ai-route-decision.d.ts +11 -0
  60. package/dist/components/ai-route-decision.js +1 -0
  61. package/dist/components/ai-suggestion.js +1 -1
  62. package/dist/components/ai-voice-input.js +1 -1
  63. package/dist/components/index.js +1 -1
  64. package/dist/components/p-CX1Yp79q.js +1 -0
  65. package/dist/components/p-DnO4dikr.js +1 -0
  66. package/dist/components/{p-CY6emva2.js → p-Dr2tAPV7.js} +1 -1
  67. package/dist/{ui-ai-kit/p-DYv5ef4M.js → components/p-SJZ6Ujn9.js} +1 -1
  68. package/dist/esm/ai-card.entry.js +2 -2
  69. package/dist/esm/ai-chat-container.entry.js +84 -57
  70. package/dist/esm/ai-chat-header.entry.js +29 -19
  71. package/dist/esm/ai-chat-message.entry.js +1456 -21
  72. package/dist/esm/ai-conversation-list.entry.js +78 -0
  73. package/dist/esm/ai-conversation-summary.entry.js +31 -0
  74. package/dist/esm/ai-icon.entry.js +2 -2
  75. package/dist/esm/ai-link.entry.js +4 -4
  76. package/dist/esm/ai-loading.entry.js +35 -22
  77. package/dist/esm/ai-message-input.entry.js +48 -15
  78. package/dist/esm/ai-rating.entry.js +2 -2
  79. package/dist/esm/ai-route-decision.entry.js +46 -0
  80. package/dist/esm/ai-suggestion.entry.js +4 -4
  81. package/dist/esm/ai-voice-input.entry.js +75 -21
  82. package/dist/esm/{icon-registry-DYv5ef4M.js → icon-registry-SJZ6Ujn9.js} +24 -0
  83. package/dist/esm/{index-7hrZ8FOQ.js → index-B0yIzgh4.js} +1 -1
  84. package/dist/esm/loader.js +3 -3
  85. package/dist/esm/ui-ai-kit.js +3 -3
  86. package/dist/types/components/ai-chat-container/ai-chat-container.d.ts +11 -1
  87. package/dist/types/components/ai-chat-header/ai-chat-header.d.ts +7 -2
  88. package/dist/types/components/ai-conversation-list/ai-conversation-list.d.ts +24 -0
  89. package/dist/types/components/ai-conversation-summary/ai-conversation-summary.d.ts +12 -0
  90. package/dist/types/components/ai-loading/ai-loading.d.ts +12 -6
  91. package/dist/types/components/ai-message-input/ai-message-input.d.ts +17 -3
  92. package/dist/types/components/ai-route-decision/ai-route-decision.d.ts +21 -0
  93. package/dist/types/components/ai-voice-input/ai-voice-input.d.ts +7 -0
  94. package/dist/types/components.d.ts +335 -11
  95. package/dist/types/index.d.ts +2 -0
  96. package/dist/types/utils/icon-registry.d.ts +1 -1
  97. package/dist/ui-ai-kit/p-2955439f.entry.js +1 -0
  98. package/dist/ui-ai-kit/p-5c9e9822.entry.js +1 -0
  99. package/dist/ui-ai-kit/p-5caf1c38.entry.js +1 -0
  100. package/dist/ui-ai-kit/p-74c5c83f.entry.js +1 -0
  101. package/dist/ui-ai-kit/p-76195745.entry.js +1 -0
  102. package/dist/ui-ai-kit/p-79c78d8e.entry.js +1 -0
  103. package/dist/ui-ai-kit/p-87e9739b.entry.js +1 -0
  104. package/dist/ui-ai-kit/p-9c4c6c01.entry.js +1 -0
  105. package/dist/ui-ai-kit/p-B0yIzgh4.js +2 -0
  106. package/dist/{components/p-DYv5ef4M.js → ui-ai-kit/p-SJZ6Ujn9.js} +1 -1
  107. package/dist/ui-ai-kit/p-a099fcfb.entry.js +1 -0
  108. package/dist/ui-ai-kit/p-b28af13a.entry.js +1 -0
  109. package/dist/ui-ai-kit/p-d1bb1ad0.entry.js +1 -0
  110. package/dist/ui-ai-kit/p-eb0c7e7a.entry.js +1 -0
  111. package/dist/ui-ai-kit/{p-455daa17.entry.js → p-eec6f083.entry.js} +1 -1
  112. package/dist/ui-ai-kit/p-ef07638f.entry.js +2 -0
  113. package/dist/ui-ai-kit/ui-ai-kit.css +1 -1
  114. package/dist/ui-ai-kit/ui-ai-kit.esm.js +1 -1
  115. package/package.json +5 -13
  116. package/dist/collection/components/ai-card/ai-card.stories.js +0 -52
  117. package/dist/collection/components/ai-chat-container/ai-chat-container.stories.js +0 -160
  118. package/dist/collection/components/ai-chat-header/ai-chat-header.stories.js +0 -138
  119. package/dist/collection/components/ai-chat-message/ai-chat-message.stories.js +0 -164
  120. package/dist/collection/components/ai-link/ai-link.stories.js +0 -79
  121. package/dist/collection/components/ai-loading/ai-loading.stories.js +0 -145
  122. package/dist/collection/components/ai-message-input/ai-message-input.stories.js +0 -125
  123. package/dist/collection/components/ai-rating/ai-rating.stories.js +0 -78
  124. package/dist/collection/components/ai-suggestion/ai-suggestion.stories.js +0 -62
  125. package/dist/collection/components/ai-voice-input/ai-voice-input.stories.js +0 -118
  126. package/dist/components/p-CWjXxYJI.js +0 -1
  127. package/dist/types/components/ai-card/ai-card.stories.d.ts +0 -7
  128. package/dist/types/components/ai-chat-container/ai-chat-container.stories.d.ts +0 -7
  129. package/dist/types/components/ai-chat-header/ai-chat-header.stories.d.ts +0 -8
  130. package/dist/types/components/ai-chat-message/ai-chat-message.stories.d.ts +0 -10
  131. package/dist/types/components/ai-link/ai-link.stories.d.ts +0 -8
  132. package/dist/types/components/ai-loading/ai-loading.stories.d.ts +0 -10
  133. package/dist/types/components/ai-message-input/ai-message-input.stories.d.ts +0 -13
  134. package/dist/types/components/ai-rating/ai-rating.stories.d.ts +0 -8
  135. package/dist/types/components/ai-suggestion/ai-suggestion.stories.d.ts +0 -8
  136. package/dist/types/components/ai-voice-input/ai-voice-input.stories.d.ts +0 -9
  137. package/dist/ui-ai-kit/p-11facfad.entry.js +0 -1
  138. package/dist/ui-ai-kit/p-128a2ed4.entry.js +0 -1
  139. package/dist/ui-ai-kit/p-227bdb8f.entry.js +0 -1
  140. package/dist/ui-ai-kit/p-56163e8c.entry.js +0 -1
  141. package/dist/ui-ai-kit/p-6d21d0fd.entry.js +0 -1
  142. package/dist/ui-ai-kit/p-6ddcd77b.entry.js +0 -1
  143. package/dist/ui-ai-kit/p-7hrZ8FOQ.js +0 -2
  144. package/dist/ui-ai-kit/p-8e90143e.entry.js +0 -1
  145. package/dist/ui-ai-kit/p-9938c277.entry.js +0 -1
  146. package/dist/ui-ai-kit/p-dc5b4a7f.entry.js +0 -1
  147. package/dist/ui-ai-kit/p-fb1702de.entry.js +0 -1
@@ -1,8 +1,1398 @@
1
- import { r as registerInstance, c as createEvent, h, H as Host } from './index-7hrZ8FOQ.js';
2
- import { i as iconRegistry } from './icon-registry-DYv5ef4M.js';
1
+ import { r as registerInstance, c as createEvent, h, H as Host } from './index-B0yIzgh4.js';
2
+ import { i as iconRegistry } from './icon-registry-SJZ6Ujn9.js';
3
3
 
4
- const aiChatMessageCss = () => `:host{--ai-msg-user-bg:var(--ai-user-bubble-bg, #F4F4F4);--ai-msg-user-color:var(--ai-text-primary, #333333);--ai-msg-user-border:1px solid var(--ai-border-default, #eee);--ai-msg-agent-bg:var(--ai-agent-bubble-bg, #ffffff);--ai-msg-agent-color:var(--ai-text-primary, #333333);--ai-msg-agent-border:1px solid var(--ai-border-default, #eee);--ai-msg-border-radius:16px;--ai-msg-padding:16px;--ai-msg-font-size:14px;--ai-msg-action-active-bg:var(--ai-accent, #a4ffe5);--ai-msg-timestamp-color:var(--ai-text-secondary, #737373);--ai-user-msg-max-width:80%;--ai-agent-msg-max-width:80%;display:block;direction:rtl;font-family:var(--ai-font-family, "PingARLT", sans-serif)}.message-row{display:flex}.user-row{flex-direction:column;align-items:flex-end}.user-bubble{background:var(--ai-msg-user-bg);color:var(--ai-msg-user-color);border:var(--ai-msg-user-border);border-radius:var(--ai-msg-border-radius);padding:var(--ai-msg-padding);font-size:var(--ai-msg-font-size);max-width:var(--ai-user-msg-max-width);line-height:1.5;word-break:break-word;box-shadow:0px 1px 2px 0px rgba(18, 18, 23, 0.05)}.user-row .timestamp{font-size:12px;color:var(--ai-msg-timestamp-color);margin-top:4px}.agent-row{flex-direction:row;justify-content:flex-start}.agent-bubble-wrapper{display:flex;flex-direction:column;gap:6px;width:100%;max-width:var(--ai-msg-agent-max-width);min-width:0}.agent-bubble{background:var(--ai-msg-agent-bg);color:var(--ai-msg-agent-color);border:var(--ai-msg-agent-border);border-radius:var(--ai-msg-border-radius);padding:var(--ai-msg-padding);font-size:var(--ai-msg-font-size);line-height:1.6;word-break:break-word;box-shadow:0px 1px 2px 0px rgba(18, 18, 23, 0.05);display:flex;flex-direction:column;gap:12px}.message-content{white-space:pre-wrap}.message-content p{margin:0 0 8px 0}.message-content p:last-child{margin-bottom:0}.message-content h2{font-size:16px;font-weight:700;margin:0 0 8px 0}.message-content h3{font-size:15px;font-weight:600;margin:0 0 6px 0}.message-content strong{font-weight:700}.message-content em{font-style:italic}.message-content code{background:var(--ai-bg-surface, #f3f4f6);border-radius:4px;padding:1px 5px;font-family:monospace;font-size:13px;color:var(--ai-text-primary, #374151)}.message-content pre{background:var(--ai-bg-surface, #f3f4f6);border-radius:8px;padding:10px 12px;overflow-x:auto;margin:8px 0}.message-content pre code{background:none;padding:0;font-size:13px}.message-content ul,.message-content ol{padding-inline-start:20px;margin:4px 0 8px 0}.message-content li{margin-bottom:3px}.actions-bar{display:flex;flex-direction:row;align-items:center;justify-content:flex-start;gap:6px;height:0;overflow:hidden;opacity:0;pointer-events:none;transition:height 0.15s ease, opacity 0.15s ease}.agent-bubble:hover .actions-bar{height:32px;opacity:1;pointer-events:auto}.action-btn{display:flex;align-items:center;justify-content:center;width:32px;height:32px;border-radius:8px;background:var(--ai-bg-card, #ffffff);border:1px solid var(--ai-border-default, #eee);cursor:pointer;color:var(--ai-text-primary, #333333);transition:background 0.15s, color 0.15s;padding:0;flex-shrink:0}.action-btn:hover{background:var(--ai-bg-surface, #f3f4f6)}.action-btn.copy-success{background:var(--ai-msg-action-active-bg);color:var(--ai-accent-text);border-color:var(--ai-accent)}.feedback-group{display:flex;align-items:center;border:1px solid var(--ai-border-default, #eee);border-radius:8px;overflow:hidden;background:var(--ai-bg-card, #ffffff)}.feedback-btn{display:flex;align-items:center;justify-content:center;height:32px;padding:0 8px;background:var(--ai-bg-card, #ffffff);border:none;border-inline-start:1px solid var(--ai-border-default, #eee);cursor:pointer;color:var(--ai-text-primary, #333333);transition:background 0.15s, color 0.15s}.feedback-btn:first-child{border-inline-start:none}.feedback-btn:hover{background:var(--ai-bg-surface, #f3f4f6)}.feedback-btn.active{background:var(--ai-msg-action-active-bg);color:var(--ai-accent-text)}.icon-wrap{display:flex;align-items:center;justify-content:center;line-height:0}.agent-info{display:flex;flex-direction:row;align-items:center;justify-content:flex-start;gap:6px;color:var(--ai-text-muted, #9ca3af)}.agent-info-name,.agent-info-time{font-size:12px;color:inherit;line-height:16px;white-space:nowrap}.agent-info .icon-wrap{display:flex;align-items:center;color:inherit;opacity:0.6;flex-shrink:0}.typing-indicator{display:flex;align-items:center;gap:5px;padding:4px 2px}.typing-dot{width:8px;height:8px;border-radius:50%;background:var(--ai-text-muted, #9ca3af);animation:typingBounce 1.2s ease-in-out infinite}.typing-dot:nth-child(2){animation-delay:0.2s}.typing-dot:nth-child(3){animation-delay:0.4s}@keyframes typingBounce{0%,60%,100%{transform:translateY(0)}30%{transform:translateY(-6px)}}.streaming-cursor{display:inline-block;width:2px;height:1em;background:currentColor;vertical-align:text-bottom;margin-inline-start:2px;animation:cursorBlink 0.8s step-start infinite}@keyframes cursorBlink{0%,100%{opacity:1}50%{opacity:0}}`;
4
+ /*! @license DOMPurify 3.3.3 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.3.3/LICENSE */
5
5
 
6
+ const {
7
+ entries,
8
+ setPrototypeOf,
9
+ isFrozen,
10
+ getPrototypeOf,
11
+ getOwnPropertyDescriptor
12
+ } = Object;
13
+ let {
14
+ freeze,
15
+ seal,
16
+ create
17
+ } = Object; // eslint-disable-line import/no-mutable-exports
18
+ let {
19
+ apply,
20
+ construct
21
+ } = typeof Reflect !== 'undefined' && Reflect;
22
+ if (!freeze) {
23
+ freeze = function freeze(x) {
24
+ return x;
25
+ };
26
+ }
27
+ if (!seal) {
28
+ seal = function seal(x) {
29
+ return x;
30
+ };
31
+ }
32
+ if (!apply) {
33
+ apply = function apply(func, thisArg) {
34
+ for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
35
+ args[_key - 2] = arguments[_key];
36
+ }
37
+ return func.apply(thisArg, args);
38
+ };
39
+ }
40
+ if (!construct) {
41
+ construct = function construct(Func) {
42
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
43
+ args[_key2 - 1] = arguments[_key2];
44
+ }
45
+ return new Func(...args);
46
+ };
47
+ }
48
+ const arrayForEach = unapply(Array.prototype.forEach);
49
+ const arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);
50
+ const arrayPop = unapply(Array.prototype.pop);
51
+ const arrayPush = unapply(Array.prototype.push);
52
+ const arraySplice = unapply(Array.prototype.splice);
53
+ const stringToLowerCase = unapply(String.prototype.toLowerCase);
54
+ const stringToString = unapply(String.prototype.toString);
55
+ const stringMatch = unapply(String.prototype.match);
56
+ const stringReplace = unapply(String.prototype.replace);
57
+ const stringIndexOf = unapply(String.prototype.indexOf);
58
+ const stringTrim = unapply(String.prototype.trim);
59
+ const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);
60
+ const regExpTest = unapply(RegExp.prototype.test);
61
+ const typeErrorCreate = unconstruct(TypeError);
62
+ /**
63
+ * Creates a new function that calls the given function with a specified thisArg and arguments.
64
+ *
65
+ * @param func - The function to be wrapped and called.
66
+ * @returns A new function that calls the given function with a specified thisArg and arguments.
67
+ */
68
+ function unapply(func) {
69
+ return function (thisArg) {
70
+ if (thisArg instanceof RegExp) {
71
+ thisArg.lastIndex = 0;
72
+ }
73
+ for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
74
+ args[_key3 - 1] = arguments[_key3];
75
+ }
76
+ return apply(func, thisArg, args);
77
+ };
78
+ }
79
+ /**
80
+ * Creates a new function that constructs an instance of the given constructor function with the provided arguments.
81
+ *
82
+ * @param func - The constructor function to be wrapped and called.
83
+ * @returns A new function that constructs an instance of the given constructor function with the provided arguments.
84
+ */
85
+ function unconstruct(Func) {
86
+ return function () {
87
+ for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
88
+ args[_key4] = arguments[_key4];
89
+ }
90
+ return construct(Func, args);
91
+ };
92
+ }
93
+ /**
94
+ * Add properties to a lookup table
95
+ *
96
+ * @param set - The set to which elements will be added.
97
+ * @param array - The array containing elements to be added to the set.
98
+ * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.
99
+ * @returns The modified set with added elements.
100
+ */
101
+ function addToSet(set, array) {
102
+ let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;
103
+ if (setPrototypeOf) {
104
+ // Make 'in' and truthy checks like Boolean(set.constructor)
105
+ // independent of any properties defined on Object.prototype.
106
+ // Prevent prototype setters from intercepting set as a this value.
107
+ setPrototypeOf(set, null);
108
+ }
109
+ let l = array.length;
110
+ while (l--) {
111
+ let element = array[l];
112
+ if (typeof element === 'string') {
113
+ const lcElement = transformCaseFunc(element);
114
+ if (lcElement !== element) {
115
+ // Config presets (e.g. tags.js, attrs.js) are immutable.
116
+ if (!isFrozen(array)) {
117
+ array[l] = lcElement;
118
+ }
119
+ element = lcElement;
120
+ }
121
+ }
122
+ set[element] = true;
123
+ }
124
+ return set;
125
+ }
126
+ /**
127
+ * Clean up an array to harden against CSPP
128
+ *
129
+ * @param array - The array to be cleaned.
130
+ * @returns The cleaned version of the array
131
+ */
132
+ function cleanArray(array) {
133
+ for (let index = 0; index < array.length; index++) {
134
+ const isPropertyExist = objectHasOwnProperty(array, index);
135
+ if (!isPropertyExist) {
136
+ array[index] = null;
137
+ }
138
+ }
139
+ return array;
140
+ }
141
+ /**
142
+ * Shallow clone an object
143
+ *
144
+ * @param object - The object to be cloned.
145
+ * @returns A new object that copies the original.
146
+ */
147
+ function clone(object) {
148
+ const newObject = create(null);
149
+ for (const [property, value] of entries(object)) {
150
+ const isPropertyExist = objectHasOwnProperty(object, property);
151
+ if (isPropertyExist) {
152
+ if (Array.isArray(value)) {
153
+ newObject[property] = cleanArray(value);
154
+ } else if (value && typeof value === 'object' && value.constructor === Object) {
155
+ newObject[property] = clone(value);
156
+ } else {
157
+ newObject[property] = value;
158
+ }
159
+ }
160
+ }
161
+ return newObject;
162
+ }
163
+ /**
164
+ * This method automatically checks if the prop is function or getter and behaves accordingly.
165
+ *
166
+ * @param object - The object to look up the getter function in its prototype chain.
167
+ * @param prop - The property name for which to find the getter function.
168
+ * @returns The getter function found in the prototype chain or a fallback function.
169
+ */
170
+ function lookupGetter(object, prop) {
171
+ while (object !== null) {
172
+ const desc = getOwnPropertyDescriptor(object, prop);
173
+ if (desc) {
174
+ if (desc.get) {
175
+ return unapply(desc.get);
176
+ }
177
+ if (typeof desc.value === 'function') {
178
+ return unapply(desc.value);
179
+ }
180
+ }
181
+ object = getPrototypeOf(object);
182
+ }
183
+ function fallbackValue() {
184
+ return null;
185
+ }
186
+ return fallbackValue;
187
+ }
188
+
189
+ const html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'search', 'section', 'select', 'shadow', 'slot', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']);
190
+ const svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'enterkeyhint', 'exportparts', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'inputmode', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'part', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);
191
+ const svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']);
192
+ // List of SVG elements that are disallowed by default.
193
+ // We still need to know them so that we can do namespace
194
+ // checks properly in case one wants to add them to
195
+ // allow-list.
196
+ const svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);
197
+ const mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']);
198
+ // Similarly to SVG, we want to know all MathML elements,
199
+ // even those that we disallow by default.
200
+ const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
201
+ const text = freeze(['#text']);
202
+
203
+ const html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'exportparts', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inert', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'part', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns', 'slot']);
204
+ const svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'mask-type', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);
205
+ const mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);
206
+ const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
207
+
208
+ // eslint-disable-next-line unicorn/better-regex
209
+ const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode
210
+ const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
211
+ const TMPLIT_EXPR = seal(/\$\{[\w\W]*/gm); // eslint-disable-line unicorn/better-regex
212
+ const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape
213
+ const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
214
+ const IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape
215
+ );
216
+ const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
217
+ const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex
218
+ );
219
+ const DOCTYPE_NAME = seal(/^html$/i);
220
+ const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);
221
+
222
+ var EXPRESSIONS = /*#__PURE__*/Object.freeze({
223
+ __proto__: null,
224
+ ARIA_ATTR: ARIA_ATTR,
225
+ ATTR_WHITESPACE: ATTR_WHITESPACE,
226
+ CUSTOM_ELEMENT: CUSTOM_ELEMENT,
227
+ DATA_ATTR: DATA_ATTR,
228
+ DOCTYPE_NAME: DOCTYPE_NAME,
229
+ ERB_EXPR: ERB_EXPR,
230
+ IS_ALLOWED_URI: IS_ALLOWED_URI,
231
+ IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA,
232
+ MUSTACHE_EXPR: MUSTACHE_EXPR,
233
+ TMPLIT_EXPR: TMPLIT_EXPR
234
+ });
235
+
236
+ /* eslint-disable @typescript-eslint/indent */
237
+ // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
238
+ const NODE_TYPE = {
239
+ element: 1,
240
+ text: 3,
241
+ // Deprecated
242
+ progressingInstruction: 7,
243
+ comment: 8,
244
+ document: 9};
245
+ const getGlobal = function getGlobal() {
246
+ return typeof window === 'undefined' ? null : window;
247
+ };
248
+ /**
249
+ * Creates a no-op policy for internal use only.
250
+ * Don't export this function outside this module!
251
+ * @param trustedTypes The policy factory.
252
+ * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).
253
+ * @return The policy created (or null, if Trusted Types
254
+ * are not supported or creating the policy failed).
255
+ */
256
+ const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {
257
+ if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
258
+ return null;
259
+ }
260
+ // Allow the callers to control the unique policy name
261
+ // by adding a data-tt-policy-suffix to the script element with the DOMPurify.
262
+ // Policy creation with duplicate names throws in Trusted Types.
263
+ let suffix = null;
264
+ const ATTR_NAME = 'data-tt-policy-suffix';
265
+ if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {
266
+ suffix = purifyHostElement.getAttribute(ATTR_NAME);
267
+ }
268
+ const policyName = 'dompurify' + (suffix ? '#' + suffix : '');
269
+ try {
270
+ return trustedTypes.createPolicy(policyName, {
271
+ createHTML(html) {
272
+ return html;
273
+ },
274
+ createScriptURL(scriptUrl) {
275
+ return scriptUrl;
276
+ }
277
+ });
278
+ } catch (_) {
279
+ // Policy creation failed (most likely another DOMPurify script has
280
+ // already run). Skip creating the policy, as this will only cause errors
281
+ // if TT are enforced.
282
+ console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
283
+ return null;
284
+ }
285
+ };
286
+ const _createHooksMap = function _createHooksMap() {
287
+ return {
288
+ afterSanitizeAttributes: [],
289
+ afterSanitizeElements: [],
290
+ afterSanitizeShadowDOM: [],
291
+ beforeSanitizeAttributes: [],
292
+ beforeSanitizeElements: [],
293
+ beforeSanitizeShadowDOM: [],
294
+ uponSanitizeAttribute: [],
295
+ uponSanitizeElement: [],
296
+ uponSanitizeShadowNode: []
297
+ };
298
+ };
299
+ function createDOMPurify() {
300
+ let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
301
+ const DOMPurify = root => createDOMPurify(root);
302
+ DOMPurify.version = '3.3.3';
303
+ DOMPurify.removed = [];
304
+ if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {
305
+ // Not running in a browser, provide a factory function
306
+ // so that you can pass your own Window
307
+ DOMPurify.isSupported = false;
308
+ return DOMPurify;
309
+ }
310
+ let {
311
+ document
312
+ } = window;
313
+ const originalDocument = document;
314
+ const currentScript = originalDocument.currentScript;
315
+ const {
316
+ DocumentFragment,
317
+ HTMLTemplateElement,
318
+ Node,
319
+ Element,
320
+ NodeFilter,
321
+ NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap,
322
+ HTMLFormElement,
323
+ DOMParser,
324
+ trustedTypes
325
+ } = window;
326
+ const ElementPrototype = Element.prototype;
327
+ const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
328
+ const remove = lookupGetter(ElementPrototype, 'remove');
329
+ const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
330
+ const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
331
+ const getParentNode = lookupGetter(ElementPrototype, 'parentNode');
332
+ // As per issue #47, the web-components registry is inherited by a
333
+ // new document created via createHTMLDocument. As per the spec
334
+ // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
335
+ // a new empty registry is used when creating a template contents owner
336
+ // document, so we use that as our parent document to ensure nothing
337
+ // is inherited.
338
+ if (typeof HTMLTemplateElement === 'function') {
339
+ const template = document.createElement('template');
340
+ if (template.content && template.content.ownerDocument) {
341
+ document = template.content.ownerDocument;
342
+ }
343
+ }
344
+ let trustedTypesPolicy;
345
+ let emptyHTML = '';
346
+ const {
347
+ implementation,
348
+ createNodeIterator,
349
+ createDocumentFragment,
350
+ getElementsByTagName
351
+ } = document;
352
+ const {
353
+ importNode
354
+ } = originalDocument;
355
+ let hooks = _createHooksMap();
356
+ /**
357
+ * Expose whether this browser supports running the full DOMPurify.
358
+ */
359
+ DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;
360
+ const {
361
+ MUSTACHE_EXPR,
362
+ ERB_EXPR,
363
+ TMPLIT_EXPR,
364
+ DATA_ATTR,
365
+ ARIA_ATTR,
366
+ IS_SCRIPT_OR_DATA,
367
+ ATTR_WHITESPACE,
368
+ CUSTOM_ELEMENT
369
+ } = EXPRESSIONS;
370
+ let {
371
+ IS_ALLOWED_URI: IS_ALLOWED_URI$1
372
+ } = EXPRESSIONS;
373
+ /**
374
+ * We consider the elements and attributes below to be safe. Ideally
375
+ * don't add any new ones but feel free to remove unwanted ones.
376
+ */
377
+ /* allowed element names */
378
+ let ALLOWED_TAGS = null;
379
+ const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);
380
+ /* Allowed attribute names */
381
+ let ALLOWED_ATTR = null;
382
+ const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);
383
+ /*
384
+ * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.
385
+ * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)
386
+ * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)
387
+ * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.
388
+ */
389
+ let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {
390
+ tagNameCheck: {
391
+ writable: true,
392
+ configurable: false,
393
+ enumerable: true,
394
+ value: null
395
+ },
396
+ attributeNameCheck: {
397
+ writable: true,
398
+ configurable: false,
399
+ enumerable: true,
400
+ value: null
401
+ },
402
+ allowCustomizedBuiltInElements: {
403
+ writable: true,
404
+ configurable: false,
405
+ enumerable: true,
406
+ value: false
407
+ }
408
+ }));
409
+ /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
410
+ let FORBID_TAGS = null;
411
+ /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
412
+ let FORBID_ATTR = null;
413
+ /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */
414
+ const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, {
415
+ tagCheck: {
416
+ writable: true,
417
+ configurable: false,
418
+ enumerable: true,
419
+ value: null
420
+ },
421
+ attributeCheck: {
422
+ writable: true,
423
+ configurable: false,
424
+ enumerable: true,
425
+ value: null
426
+ }
427
+ }));
428
+ /* Decide if ARIA attributes are okay */
429
+ let ALLOW_ARIA_ATTR = true;
430
+ /* Decide if custom data attributes are okay */
431
+ let ALLOW_DATA_ATTR = true;
432
+ /* Decide if unknown protocols are okay */
433
+ let ALLOW_UNKNOWN_PROTOCOLS = false;
434
+ /* Decide if self-closing tags in attributes are allowed.
435
+ * Usually removed due to a mXSS issue in jQuery 3.0 */
436
+ let ALLOW_SELF_CLOSE_IN_ATTR = true;
437
+ /* Output should be safe for common template engines.
438
+ * This means, DOMPurify removes data attributes, mustaches and ERB
439
+ */
440
+ let SAFE_FOR_TEMPLATES = false;
441
+ /* Output should be safe even for XML used within HTML and alike.
442
+ * This means, DOMPurify removes comments when containing risky content.
443
+ */
444
+ let SAFE_FOR_XML = true;
445
+ /* Decide if document with <html>... should be returned */
446
+ let WHOLE_DOCUMENT = false;
447
+ /* Track whether config is already set on this instance of DOMPurify. */
448
+ let SET_CONFIG = false;
449
+ /* Decide if all elements (e.g. style, script) must be children of
450
+ * document.body. By default, browsers might move them to document.head */
451
+ let FORCE_BODY = false;
452
+ /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
453
+ * string (or a TrustedHTML object if Trusted Types are supported).
454
+ * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
455
+ */
456
+ let RETURN_DOM = false;
457
+ /* Decide if a DOM `DocumentFragment` should be returned, instead of a html
458
+ * string (or a TrustedHTML object if Trusted Types are supported) */
459
+ let RETURN_DOM_FRAGMENT = false;
460
+ /* Try to return a Trusted Type object instead of a string, return a string in
461
+ * case Trusted Types are not supported */
462
+ let RETURN_TRUSTED_TYPE = false;
463
+ /* Output should be free from DOM clobbering attacks?
464
+ * This sanitizes markups named with colliding, clobberable built-in DOM APIs.
465
+ */
466
+ let SANITIZE_DOM = true;
467
+ /* Achieve full DOM Clobbering protection by isolating the namespace of named
468
+ * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.
469
+ *
470
+ * HTML/DOM spec rules that enable DOM Clobbering:
471
+ * - Named Access on Window (§7.3.3)
472
+ * - DOM Tree Accessors (§3.1.5)
473
+ * - Form Element Parent-Child Relations (§4.10.3)
474
+ * - Iframe srcdoc / Nested WindowProxies (§4.8.5)
475
+ * - HTMLCollection (§4.2.10.2)
476
+ *
477
+ * Namespace isolation is implemented by prefixing `id` and `name` attributes
478
+ * with a constant string, i.e., `user-content-`
479
+ */
480
+ let SANITIZE_NAMED_PROPS = false;
481
+ const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';
482
+ /* Keep element content when removing element? */
483
+ let KEEP_CONTENT = true;
484
+ /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
485
+ * of importing it into a new Document and returning a sanitized copy */
486
+ let IN_PLACE = false;
487
+ /* Allow usage of profiles like html, svg and mathMl */
488
+ let USE_PROFILES = {};
489
+ /* Tags to ignore content of when KEEP_CONTENT is true */
490
+ let FORBID_CONTENTS = null;
491
+ const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
492
+ /* Tags that are safe for data: URIs */
493
+ let DATA_URI_TAGS = null;
494
+ const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
495
+ /* Attributes safe for values like "javascript:" */
496
+ let URI_SAFE_ATTRIBUTES = null;
497
+ const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);
498
+ const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
499
+ const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
500
+ const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
501
+ /* Document namespace */
502
+ let NAMESPACE = HTML_NAMESPACE;
503
+ let IS_EMPTY_INPUT = false;
504
+ /* Allowed XHTML+XML namespaces */
505
+ let ALLOWED_NAMESPACES = null;
506
+ const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
507
+ let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
508
+ let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);
509
+ // Certain elements are allowed in both SVG and HTML
510
+ // namespace. We need to specify them explicitly
511
+ // so that they don't get erroneously deleted from
512
+ // HTML namespace.
513
+ const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);
514
+ /* Parsing of strict XHTML documents */
515
+ let PARSER_MEDIA_TYPE = null;
516
+ const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];
517
+ const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
518
+ let transformCaseFunc = null;
519
+ /* Keep a reference to config to pass to hooks */
520
+ let CONFIG = null;
521
+ /* Ideally, do not touch anything below this line */
522
+ /* ______________________________________________ */
523
+ const formElement = document.createElement('form');
524
+ const isRegexOrFunction = function isRegexOrFunction(testValue) {
525
+ return testValue instanceof RegExp || testValue instanceof Function;
526
+ };
527
+ /**
528
+ * _parseConfig
529
+ *
530
+ * @param cfg optional config literal
531
+ */
532
+ // eslint-disable-next-line complexity
533
+ const _parseConfig = function _parseConfig() {
534
+ let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
535
+ if (CONFIG && CONFIG === cfg) {
536
+ return;
537
+ }
538
+ /* Shield configuration object from tampering */
539
+ if (!cfg || typeof cfg !== 'object') {
540
+ cfg = {};
541
+ }
542
+ /* Shield configuration object from prototype pollution */
543
+ cfg = clone(cfg);
544
+ PARSER_MEDIA_TYPE =
545
+ // eslint-disable-next-line unicorn/prefer-includes
546
+ SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;
547
+ // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
548
+ transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
549
+ /* Set configuration parameters */
550
+ ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
551
+ ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
552
+ ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
553
+ URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES;
554
+ DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS') ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS;
555
+ FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
556
+ FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({});
557
+ FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({});
558
+ USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES : false;
559
+ ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
560
+ ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
561
+ ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
562
+ ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true
563
+ SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
564
+ SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true
565
+ WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
566
+ RETURN_DOM = cfg.RETURN_DOM || false; // Default false
567
+ RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
568
+ RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false
569
+ FORCE_BODY = cfg.FORCE_BODY || false; // Default false
570
+ SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
571
+ SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
572
+ KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
573
+ IN_PLACE = cfg.IN_PLACE || false; // Default false
574
+ IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI;
575
+ NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
576
+ MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS;
577
+ HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS;
578
+ CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {};
579
+ if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
580
+ CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
581
+ }
582
+ if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
583
+ CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
584
+ }
585
+ if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {
586
+ CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
587
+ }
588
+ if (SAFE_FOR_TEMPLATES) {
589
+ ALLOW_DATA_ATTR = false;
590
+ }
591
+ if (RETURN_DOM_FRAGMENT) {
592
+ RETURN_DOM = true;
593
+ }
594
+ /* Parse profile info */
595
+ if (USE_PROFILES) {
596
+ ALLOWED_TAGS = addToSet({}, text);
597
+ ALLOWED_ATTR = create(null);
598
+ if (USE_PROFILES.html === true) {
599
+ addToSet(ALLOWED_TAGS, html$1);
600
+ addToSet(ALLOWED_ATTR, html);
601
+ }
602
+ if (USE_PROFILES.svg === true) {
603
+ addToSet(ALLOWED_TAGS, svg$1);
604
+ addToSet(ALLOWED_ATTR, svg);
605
+ addToSet(ALLOWED_ATTR, xml);
606
+ }
607
+ if (USE_PROFILES.svgFilters === true) {
608
+ addToSet(ALLOWED_TAGS, svgFilters);
609
+ addToSet(ALLOWED_ATTR, svg);
610
+ addToSet(ALLOWED_ATTR, xml);
611
+ }
612
+ if (USE_PROFILES.mathMl === true) {
613
+ addToSet(ALLOWED_TAGS, mathMl$1);
614
+ addToSet(ALLOWED_ATTR, mathMl);
615
+ addToSet(ALLOWED_ATTR, xml);
616
+ }
617
+ }
618
+ /* Prevent function-based ADD_ATTR / ADD_TAGS from leaking across calls */
619
+ if (!objectHasOwnProperty(cfg, 'ADD_TAGS')) {
620
+ EXTRA_ELEMENT_HANDLING.tagCheck = null;
621
+ }
622
+ if (!objectHasOwnProperty(cfg, 'ADD_ATTR')) {
623
+ EXTRA_ELEMENT_HANDLING.attributeCheck = null;
624
+ }
625
+ /* Merge configuration parameters */
626
+ if (cfg.ADD_TAGS) {
627
+ if (typeof cfg.ADD_TAGS === 'function') {
628
+ EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;
629
+ } else {
630
+ if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
631
+ ALLOWED_TAGS = clone(ALLOWED_TAGS);
632
+ }
633
+ addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
634
+ }
635
+ }
636
+ if (cfg.ADD_ATTR) {
637
+ if (typeof cfg.ADD_ATTR === 'function') {
638
+ EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;
639
+ } else {
640
+ if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
641
+ ALLOWED_ATTR = clone(ALLOWED_ATTR);
642
+ }
643
+ addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
644
+ }
645
+ }
646
+ if (cfg.ADD_URI_SAFE_ATTR) {
647
+ addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
648
+ }
649
+ if (cfg.FORBID_CONTENTS) {
650
+ if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
651
+ FORBID_CONTENTS = clone(FORBID_CONTENTS);
652
+ }
653
+ addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
654
+ }
655
+ if (cfg.ADD_FORBID_CONTENTS) {
656
+ if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
657
+ FORBID_CONTENTS = clone(FORBID_CONTENTS);
658
+ }
659
+ addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);
660
+ }
661
+ /* Add #text in case KEEP_CONTENT is set to true */
662
+ if (KEEP_CONTENT) {
663
+ ALLOWED_TAGS['#text'] = true;
664
+ }
665
+ /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */
666
+ if (WHOLE_DOCUMENT) {
667
+ addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
668
+ }
669
+ /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */
670
+ if (ALLOWED_TAGS.table) {
671
+ addToSet(ALLOWED_TAGS, ['tbody']);
672
+ delete FORBID_TAGS.tbody;
673
+ }
674
+ if (cfg.TRUSTED_TYPES_POLICY) {
675
+ if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {
676
+ throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
677
+ }
678
+ if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {
679
+ throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
680
+ }
681
+ // Overwrite existing TrustedTypes policy.
682
+ trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
683
+ // Sign local variables required by `sanitize`.
684
+ emptyHTML = trustedTypesPolicy.createHTML('');
685
+ } else {
686
+ // Uninitialized policy, attempt to initialize the internal dompurify policy.
687
+ if (trustedTypesPolicy === undefined) {
688
+ trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
689
+ }
690
+ // If creating the internal policy succeeded sign internal variables.
691
+ if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {
692
+ emptyHTML = trustedTypesPolicy.createHTML('');
693
+ }
694
+ }
695
+ // Prevent further manipulation of configuration.
696
+ // Not available in IE8, Safari 5, etc.
697
+ if (freeze) {
698
+ freeze(cfg);
699
+ }
700
+ CONFIG = cfg;
701
+ };
702
+ /* Keep track of all possible SVG and MathML tags
703
+ * so that we can perform the namespace checks
704
+ * correctly. */
705
+ const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);
706
+ const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);
707
+ /**
708
+ * @param element a DOM element whose namespace is being checked
709
+ * @returns Return false if the element has a
710
+ * namespace that a spec-compliant parser would never
711
+ * return. Return true otherwise.
712
+ */
713
+ const _checkValidNamespace = function _checkValidNamespace(element) {
714
+ let parent = getParentNode(element);
715
+ // In JSDOM, if we're inside shadow DOM, then parentNode
716
+ // can be null. We just simulate parent in this case.
717
+ if (!parent || !parent.tagName) {
718
+ parent = {
719
+ namespaceURI: NAMESPACE,
720
+ tagName: 'template'
721
+ };
722
+ }
723
+ const tagName = stringToLowerCase(element.tagName);
724
+ const parentTagName = stringToLowerCase(parent.tagName);
725
+ if (!ALLOWED_NAMESPACES[element.namespaceURI]) {
726
+ return false;
727
+ }
728
+ if (element.namespaceURI === SVG_NAMESPACE) {
729
+ // The only way to switch from HTML namespace to SVG
730
+ // is via <svg>. If it happens via any other tag, then
731
+ // it should be killed.
732
+ if (parent.namespaceURI === HTML_NAMESPACE) {
733
+ return tagName === 'svg';
734
+ }
735
+ // The only way to switch from MathML to SVG is via`
736
+ // svg if parent is either <annotation-xml> or MathML
737
+ // text integration points.
738
+ if (parent.namespaceURI === MATHML_NAMESPACE) {
739
+ return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
740
+ }
741
+ // We only allow elements that are defined in SVG
742
+ // spec. All others are disallowed in SVG namespace.
743
+ return Boolean(ALL_SVG_TAGS[tagName]);
744
+ }
745
+ if (element.namespaceURI === MATHML_NAMESPACE) {
746
+ // The only way to switch from HTML namespace to MathML
747
+ // is via <math>. If it happens via any other tag, then
748
+ // it should be killed.
749
+ if (parent.namespaceURI === HTML_NAMESPACE) {
750
+ return tagName === 'math';
751
+ }
752
+ // The only way to switch from SVG to MathML is via
753
+ // <math> and HTML integration points
754
+ if (parent.namespaceURI === SVG_NAMESPACE) {
755
+ return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
756
+ }
757
+ // We only allow elements that are defined in MathML
758
+ // spec. All others are disallowed in MathML namespace.
759
+ return Boolean(ALL_MATHML_TAGS[tagName]);
760
+ }
761
+ if (element.namespaceURI === HTML_NAMESPACE) {
762
+ // The only way to switch from SVG to HTML is via
763
+ // HTML integration points, and from MathML to HTML
764
+ // is via MathML text integration points
765
+ if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
766
+ return false;
767
+ }
768
+ if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
769
+ return false;
770
+ }
771
+ // We disallow tags that are specific for MathML
772
+ // or SVG and should never appear in HTML namespace
773
+ return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
774
+ }
775
+ // For XHTML and XML documents that support custom namespaces
776
+ if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
777
+ return true;
778
+ }
779
+ // The code should never reach this place (this means
780
+ // that the element somehow got namespace that is not
781
+ // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).
782
+ // Return false just in case.
783
+ return false;
784
+ };
785
+ /**
786
+ * _forceRemove
787
+ *
788
+ * @param node a DOM node
789
+ */
790
+ const _forceRemove = function _forceRemove(node) {
791
+ arrayPush(DOMPurify.removed, {
792
+ element: node
793
+ });
794
+ try {
795
+ // eslint-disable-next-line unicorn/prefer-dom-node-remove
796
+ getParentNode(node).removeChild(node);
797
+ } catch (_) {
798
+ remove(node);
799
+ }
800
+ };
801
+ /**
802
+ * _removeAttribute
803
+ *
804
+ * @param name an Attribute name
805
+ * @param element a DOM node
806
+ */
807
+ const _removeAttribute = function _removeAttribute(name, element) {
808
+ try {
809
+ arrayPush(DOMPurify.removed, {
810
+ attribute: element.getAttributeNode(name),
811
+ from: element
812
+ });
813
+ } catch (_) {
814
+ arrayPush(DOMPurify.removed, {
815
+ attribute: null,
816
+ from: element
817
+ });
818
+ }
819
+ element.removeAttribute(name);
820
+ // We void attribute values for unremovable "is" attributes
821
+ if (name === 'is') {
822
+ if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
823
+ try {
824
+ _forceRemove(element);
825
+ } catch (_) {}
826
+ } else {
827
+ try {
828
+ element.setAttribute(name, '');
829
+ } catch (_) {}
830
+ }
831
+ }
832
+ };
833
+ /**
834
+ * _initDocument
835
+ *
836
+ * @param dirty - a string of dirty markup
837
+ * @return a DOM, filled with the dirty markup
838
+ */
839
+ const _initDocument = function _initDocument(dirty) {
840
+ /* Create a HTML document */
841
+ let doc = null;
842
+ let leadingWhitespace = null;
843
+ if (FORCE_BODY) {
844
+ dirty = '<remove></remove>' + dirty;
845
+ } else {
846
+ /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
847
+ const matches = stringMatch(dirty, /^[\r\n\t ]+/);
848
+ leadingWhitespace = matches && matches[0];
849
+ }
850
+ if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {
851
+ // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
852
+ dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
853
+ }
854
+ const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
855
+ /*
856
+ * Use the DOMParser API by default, fallback later if needs be
857
+ * DOMParser not work for svg when has multiple root element.
858
+ */
859
+ if (NAMESPACE === HTML_NAMESPACE) {
860
+ try {
861
+ doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
862
+ } catch (_) {}
863
+ }
864
+ /* Use createHTMLDocument in case DOMParser is not available */
865
+ if (!doc || !doc.documentElement) {
866
+ doc = implementation.createDocument(NAMESPACE, 'template', null);
867
+ try {
868
+ doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;
869
+ } catch (_) {
870
+ // Syntax error if dirtyPayload is invalid xml
871
+ }
872
+ }
873
+ const body = doc.body || doc.documentElement;
874
+ if (dirty && leadingWhitespace) {
875
+ body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
876
+ }
877
+ /* Work on whole document or just its body */
878
+ if (NAMESPACE === HTML_NAMESPACE) {
879
+ return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
880
+ }
881
+ return WHOLE_DOCUMENT ? doc.documentElement : body;
882
+ };
883
+ /**
884
+ * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.
885
+ *
886
+ * @param root The root element or node to start traversing on.
887
+ * @return The created NodeIterator
888
+ */
889
+ const _createNodeIterator = function _createNodeIterator(root) {
890
+ return createNodeIterator.call(root.ownerDocument || root, root,
891
+ // eslint-disable-next-line no-bitwise
892
+ NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);
893
+ };
894
+ /**
895
+ * _isClobbered
896
+ *
897
+ * @param element element to check for clobbering attacks
898
+ * @return true if clobbered, false if safe
899
+ */
900
+ const _isClobbered = function _isClobbered(element) {
901
+ return element instanceof HTMLFormElement && (typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function');
902
+ };
903
+ /**
904
+ * Checks whether the given object is a DOM node.
905
+ *
906
+ * @param value object to check whether it's a DOM node
907
+ * @return true is object is a DOM node
908
+ */
909
+ const _isNode = function _isNode(value) {
910
+ return typeof Node === 'function' && value instanceof Node;
911
+ };
912
+ function _executeHooks(hooks, currentNode, data) {
913
+ arrayForEach(hooks, hook => {
914
+ hook.call(DOMPurify, currentNode, data, CONFIG);
915
+ });
916
+ }
917
+ /**
918
+ * _sanitizeElements
919
+ *
920
+ * @protect nodeName
921
+ * @protect textContent
922
+ * @protect removeChild
923
+ * @param currentNode to check for permission to exist
924
+ * @return true if node was killed, false if left alive
925
+ */
926
+ const _sanitizeElements = function _sanitizeElements(currentNode) {
927
+ let content = null;
928
+ /* Execute a hook if present */
929
+ _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
930
+ /* Check if element is clobbered or can clobber */
931
+ if (_isClobbered(currentNode)) {
932
+ _forceRemove(currentNode);
933
+ return true;
934
+ }
935
+ /* Now let's check the element's type and name */
936
+ const tagName = transformCaseFunc(currentNode.nodeName);
937
+ /* Execute a hook if present */
938
+ _executeHooks(hooks.uponSanitizeElement, currentNode, {
939
+ tagName,
940
+ allowedTags: ALLOWED_TAGS
941
+ });
942
+ /* Detect mXSS attempts abusing namespace confusion */
943
+ if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) {
944
+ _forceRemove(currentNode);
945
+ return true;
946
+ }
947
+ /* Remove any occurrence of processing instructions */
948
+ if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {
949
+ _forceRemove(currentNode);
950
+ return true;
951
+ }
952
+ /* Remove any kind of possibly harmful comments */
953
+ if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) {
954
+ _forceRemove(currentNode);
955
+ return true;
956
+ }
957
+ /* Remove element if anything forbids its presence */
958
+ if (!(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName])) {
959
+ /* Check if we have a custom element to handle */
960
+ if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
961
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
962
+ return false;
963
+ }
964
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
965
+ return false;
966
+ }
967
+ }
968
+ /* Keep content except for bad-listed elements */
969
+ if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
970
+ const parentNode = getParentNode(currentNode) || currentNode.parentNode;
971
+ const childNodes = getChildNodes(currentNode) || currentNode.childNodes;
972
+ if (childNodes && parentNode) {
973
+ const childCount = childNodes.length;
974
+ for (let i = childCount - 1; i >= 0; --i) {
975
+ const childClone = cloneNode(childNodes[i], true);
976
+ childClone.__removalCount = (currentNode.__removalCount || 0) + 1;
977
+ parentNode.insertBefore(childClone, getNextSibling(currentNode));
978
+ }
979
+ }
980
+ }
981
+ _forceRemove(currentNode);
982
+ return true;
983
+ }
984
+ /* Check whether element has a valid namespace */
985
+ if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
986
+ _forceRemove(currentNode);
987
+ return true;
988
+ }
989
+ /* Make sure that older browsers don't get fallback-tag mXSS */
990
+ if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {
991
+ _forceRemove(currentNode);
992
+ return true;
993
+ }
994
+ /* Sanitize element content to be template-safe */
995
+ if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
996
+ /* Get the element's text content */
997
+ content = currentNode.textContent;
998
+ arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
999
+ content = stringReplace(content, expr, ' ');
1000
+ });
1001
+ if (currentNode.textContent !== content) {
1002
+ arrayPush(DOMPurify.removed, {
1003
+ element: currentNode.cloneNode()
1004
+ });
1005
+ currentNode.textContent = content;
1006
+ }
1007
+ }
1008
+ /* Execute a hook if present */
1009
+ _executeHooks(hooks.afterSanitizeElements, currentNode, null);
1010
+ return false;
1011
+ };
1012
+ /**
1013
+ * _isValidAttribute
1014
+ *
1015
+ * @param lcTag Lowercase tag name of containing element.
1016
+ * @param lcName Lowercase attribute name.
1017
+ * @param value Attribute value.
1018
+ * @return Returns true if `value` is valid, otherwise false.
1019
+ */
1020
+ // eslint-disable-next-line complexity
1021
+ const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
1022
+ /* FORBID_ATTR must always win, even if ADD_ATTR predicate would allow it */
1023
+ if (FORBID_ATTR[lcName]) {
1024
+ return false;
1025
+ }
1026
+ /* Make sure attribute cannot clobber */
1027
+ if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
1028
+ return false;
1029
+ }
1030
+ /* Allow valid data-* attributes: At least one character after "-"
1031
+ (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
1032
+ XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
1033
+ We don't need to check the value; it's always URI safe. */
1034
+ if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) ; else if (EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
1035
+ if (
1036
+ // First condition does a very basic check if a) it's basically a valid custom element tagname AND
1037
+ // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1038
+ // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
1039
+ _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName, lcTag)) ||
1040
+ // Alternative, second condition checks if it's an `is`-attribute, AND
1041
+ // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1042
+ lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else {
1043
+ return false;
1044
+ }
1045
+ /* Check value is safe. First, is attr inert? If so, is safe */
1046
+ } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if (value) {
1047
+ return false;
1048
+ } else ;
1049
+ return true;
1050
+ };
1051
+ /**
1052
+ * _isBasicCustomElement
1053
+ * checks if at least one dash is included in tagName, and it's not the first char
1054
+ * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name
1055
+ *
1056
+ * @param tagName name of the tag of the node to sanitize
1057
+ * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.
1058
+ */
1059
+ const _isBasicCustomElement = function _isBasicCustomElement(tagName) {
1060
+ return tagName !== 'annotation-xml' && stringMatch(tagName, CUSTOM_ELEMENT);
1061
+ };
1062
+ /**
1063
+ * _sanitizeAttributes
1064
+ *
1065
+ * @protect attributes
1066
+ * @protect nodeName
1067
+ * @protect removeAttribute
1068
+ * @protect setAttribute
1069
+ *
1070
+ * @param currentNode to sanitize
1071
+ */
1072
+ const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
1073
+ /* Execute a hook if present */
1074
+ _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);
1075
+ const {
1076
+ attributes
1077
+ } = currentNode;
1078
+ /* Check if we have attributes; if not we might have a text node */
1079
+ if (!attributes || _isClobbered(currentNode)) {
1080
+ return;
1081
+ }
1082
+ const hookEvent = {
1083
+ attrName: '',
1084
+ attrValue: '',
1085
+ keepAttr: true,
1086
+ allowedAttributes: ALLOWED_ATTR,
1087
+ forceKeepAttr: undefined
1088
+ };
1089
+ let l = attributes.length;
1090
+ /* Go backwards over all attributes; safely remove bad ones */
1091
+ while (l--) {
1092
+ const attr = attributes[l];
1093
+ const {
1094
+ name,
1095
+ namespaceURI,
1096
+ value: attrValue
1097
+ } = attr;
1098
+ const lcName = transformCaseFunc(name);
1099
+ const initValue = attrValue;
1100
+ let value = name === 'value' ? initValue : stringTrim(initValue);
1101
+ /* Execute a hook if present */
1102
+ hookEvent.attrName = lcName;
1103
+ hookEvent.attrValue = value;
1104
+ hookEvent.keepAttr = true;
1105
+ hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
1106
+ _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);
1107
+ value = hookEvent.attrValue;
1108
+ /* Full DOM Clobbering protection via namespace isolation,
1109
+ * Prefix id and name attributes with `user-content-`
1110
+ */
1111
+ if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {
1112
+ // Remove the attribute with this value
1113
+ _removeAttribute(name, currentNode);
1114
+ // Prefix the value and later re-create the attribute with the sanitized value
1115
+ value = SANITIZE_NAMED_PROPS_PREFIX + value;
1116
+ }
1117
+ /* Work around a security issue with comments inside attributes */
1118
+ if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) {
1119
+ _removeAttribute(name, currentNode);
1120
+ continue;
1121
+ }
1122
+ /* Make sure we cannot easily use animated hrefs, even if animations are allowed */
1123
+ if (lcName === 'attributename' && stringMatch(value, 'href')) {
1124
+ _removeAttribute(name, currentNode);
1125
+ continue;
1126
+ }
1127
+ /* Did the hooks approve of the attribute? */
1128
+ if (hookEvent.forceKeepAttr) {
1129
+ continue;
1130
+ }
1131
+ /* Did the hooks approve of the attribute? */
1132
+ if (!hookEvent.keepAttr) {
1133
+ _removeAttribute(name, currentNode);
1134
+ continue;
1135
+ }
1136
+ /* Work around a security issue in jQuery 3.0 */
1137
+ if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
1138
+ _removeAttribute(name, currentNode);
1139
+ continue;
1140
+ }
1141
+ /* Sanitize attribute content to be template-safe */
1142
+ if (SAFE_FOR_TEMPLATES) {
1143
+ arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1144
+ value = stringReplace(value, expr, ' ');
1145
+ });
1146
+ }
1147
+ /* Is `value` valid for this attribute? */
1148
+ const lcTag = transformCaseFunc(currentNode.nodeName);
1149
+ if (!_isValidAttribute(lcTag, lcName, value)) {
1150
+ _removeAttribute(name, currentNode);
1151
+ continue;
1152
+ }
1153
+ /* Handle attributes that require Trusted Types */
1154
+ if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {
1155
+ if (namespaceURI) ; else {
1156
+ switch (trustedTypes.getAttributeType(lcTag, lcName)) {
1157
+ case 'TrustedHTML':
1158
+ {
1159
+ value = trustedTypesPolicy.createHTML(value);
1160
+ break;
1161
+ }
1162
+ case 'TrustedScriptURL':
1163
+ {
1164
+ value = trustedTypesPolicy.createScriptURL(value);
1165
+ break;
1166
+ }
1167
+ }
1168
+ }
1169
+ }
1170
+ /* Handle invalid data-* attribute set by try-catching it */
1171
+ if (value !== initValue) {
1172
+ try {
1173
+ if (namespaceURI) {
1174
+ currentNode.setAttributeNS(namespaceURI, name, value);
1175
+ } else {
1176
+ /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
1177
+ currentNode.setAttribute(name, value);
1178
+ }
1179
+ if (_isClobbered(currentNode)) {
1180
+ _forceRemove(currentNode);
1181
+ } else {
1182
+ arrayPop(DOMPurify.removed);
1183
+ }
1184
+ } catch (_) {
1185
+ _removeAttribute(name, currentNode);
1186
+ }
1187
+ }
1188
+ }
1189
+ /* Execute a hook if present */
1190
+ _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);
1191
+ };
1192
+ /**
1193
+ * _sanitizeShadowDOM
1194
+ *
1195
+ * @param fragment to iterate over recursively
1196
+ */
1197
+ const _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {
1198
+ let shadowNode = null;
1199
+ const shadowIterator = _createNodeIterator(fragment);
1200
+ /* Execute a hook if present */
1201
+ _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);
1202
+ while (shadowNode = shadowIterator.nextNode()) {
1203
+ /* Execute a hook if present */
1204
+ _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);
1205
+ /* Sanitize tags and elements */
1206
+ _sanitizeElements(shadowNode);
1207
+ /* Check attributes next */
1208
+ _sanitizeAttributes(shadowNode);
1209
+ /* Deep shadow DOM detected */
1210
+ if (shadowNode.content instanceof DocumentFragment) {
1211
+ _sanitizeShadowDOM(shadowNode.content);
1212
+ }
1213
+ }
1214
+ /* Execute a hook if present */
1215
+ _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);
1216
+ };
1217
+ // eslint-disable-next-line complexity
1218
+ DOMPurify.sanitize = function (dirty) {
1219
+ let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1220
+ let body = null;
1221
+ let importedNode = null;
1222
+ let currentNode = null;
1223
+ let returnNode = null;
1224
+ /* Make sure we have a string to sanitize.
1225
+ DO NOT return early, as this will return the wrong type if
1226
+ the user has requested a DOM object rather than a string */
1227
+ IS_EMPTY_INPUT = !dirty;
1228
+ if (IS_EMPTY_INPUT) {
1229
+ dirty = '<!-->';
1230
+ }
1231
+ /* Stringify, in case dirty is an object */
1232
+ if (typeof dirty !== 'string' && !_isNode(dirty)) {
1233
+ if (typeof dirty.toString === 'function') {
1234
+ dirty = dirty.toString();
1235
+ if (typeof dirty !== 'string') {
1236
+ throw typeErrorCreate('dirty is not a string, aborting');
1237
+ }
1238
+ } else {
1239
+ throw typeErrorCreate('toString is not a function');
1240
+ }
1241
+ }
1242
+ /* Return dirty HTML if DOMPurify cannot run */
1243
+ if (!DOMPurify.isSupported) {
1244
+ return dirty;
1245
+ }
1246
+ /* Assign config vars */
1247
+ if (!SET_CONFIG) {
1248
+ _parseConfig(cfg);
1249
+ }
1250
+ /* Clean up removed elements */
1251
+ DOMPurify.removed = [];
1252
+ /* Check if dirty is correctly typed for IN_PLACE */
1253
+ if (typeof dirty === 'string') {
1254
+ IN_PLACE = false;
1255
+ }
1256
+ if (IN_PLACE) {
1257
+ /* Do some early pre-sanitization to avoid unsafe root nodes */
1258
+ if (dirty.nodeName) {
1259
+ const tagName = transformCaseFunc(dirty.nodeName);
1260
+ if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
1261
+ throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
1262
+ }
1263
+ }
1264
+ } else if (dirty instanceof Node) {
1265
+ /* If dirty is a DOM element, append to an empty document to avoid
1266
+ elements being stripped by the parser */
1267
+ body = _initDocument('<!---->');
1268
+ importedNode = body.ownerDocument.importNode(dirty, true);
1269
+ if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') {
1270
+ /* Node is already a body, use as is */
1271
+ body = importedNode;
1272
+ } else if (importedNode.nodeName === 'HTML') {
1273
+ body = importedNode;
1274
+ } else {
1275
+ // eslint-disable-next-line unicorn/prefer-dom-node-append
1276
+ body.appendChild(importedNode);
1277
+ }
1278
+ } else {
1279
+ /* Exit directly if we have nothing to do */
1280
+ if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
1281
+ // eslint-disable-next-line unicorn/prefer-includes
1282
+ dirty.indexOf('<') === -1) {
1283
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
1284
+ }
1285
+ /* Initialize the document to work on */
1286
+ body = _initDocument(dirty);
1287
+ /* Check we have a DOM node from the data */
1288
+ if (!body) {
1289
+ return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
1290
+ }
1291
+ }
1292
+ /* Remove first element node (ours) if FORCE_BODY is set */
1293
+ if (body && FORCE_BODY) {
1294
+ _forceRemove(body.firstChild);
1295
+ }
1296
+ /* Get node iterator */
1297
+ const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);
1298
+ /* Now start iterating over the created document */
1299
+ while (currentNode = nodeIterator.nextNode()) {
1300
+ /* Sanitize tags and elements */
1301
+ _sanitizeElements(currentNode);
1302
+ /* Check attributes next */
1303
+ _sanitizeAttributes(currentNode);
1304
+ /* Shadow DOM detected, sanitize it */
1305
+ if (currentNode.content instanceof DocumentFragment) {
1306
+ _sanitizeShadowDOM(currentNode.content);
1307
+ }
1308
+ }
1309
+ /* If we sanitized `dirty` in-place, return it. */
1310
+ if (IN_PLACE) {
1311
+ return dirty;
1312
+ }
1313
+ /* Return sanitized string or DOM */
1314
+ if (RETURN_DOM) {
1315
+ if (RETURN_DOM_FRAGMENT) {
1316
+ returnNode = createDocumentFragment.call(body.ownerDocument);
1317
+ while (body.firstChild) {
1318
+ // eslint-disable-next-line unicorn/prefer-dom-node-append
1319
+ returnNode.appendChild(body.firstChild);
1320
+ }
1321
+ } else {
1322
+ returnNode = body;
1323
+ }
1324
+ if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {
1325
+ /*
1326
+ AdoptNode() is not used because internal state is not reset
1327
+ (e.g. the past names map of a HTMLFormElement), this is safe
1328
+ in theory but we would rather not risk another attack vector.
1329
+ The state that is cloned by importNode() is explicitly defined
1330
+ by the specs.
1331
+ */
1332
+ returnNode = importNode.call(originalDocument, returnNode, true);
1333
+ }
1334
+ return returnNode;
1335
+ }
1336
+ let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
1337
+ /* Serialize doctype if allowed */
1338
+ if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
1339
+ serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
1340
+ }
1341
+ /* Sanitize final string template-safe */
1342
+ if (SAFE_FOR_TEMPLATES) {
1343
+ arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1344
+ serializedHTML = stringReplace(serializedHTML, expr, ' ');
1345
+ });
1346
+ }
1347
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
1348
+ };
1349
+ DOMPurify.setConfig = function () {
1350
+ let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1351
+ _parseConfig(cfg);
1352
+ SET_CONFIG = true;
1353
+ };
1354
+ DOMPurify.clearConfig = function () {
1355
+ CONFIG = null;
1356
+ SET_CONFIG = false;
1357
+ };
1358
+ DOMPurify.isValidAttribute = function (tag, attr, value) {
1359
+ /* Initialize shared config vars if necessary. */
1360
+ if (!CONFIG) {
1361
+ _parseConfig({});
1362
+ }
1363
+ const lcTag = transformCaseFunc(tag);
1364
+ const lcName = transformCaseFunc(attr);
1365
+ return _isValidAttribute(lcTag, lcName, value);
1366
+ };
1367
+ DOMPurify.addHook = function (entryPoint, hookFunction) {
1368
+ if (typeof hookFunction !== 'function') {
1369
+ return;
1370
+ }
1371
+ arrayPush(hooks[entryPoint], hookFunction);
1372
+ };
1373
+ DOMPurify.removeHook = function (entryPoint, hookFunction) {
1374
+ if (hookFunction !== undefined) {
1375
+ const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);
1376
+ return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];
1377
+ }
1378
+ return arrayPop(hooks[entryPoint]);
1379
+ };
1380
+ DOMPurify.removeHooks = function (entryPoint) {
1381
+ hooks[entryPoint] = [];
1382
+ };
1383
+ DOMPurify.removeAllHooks = function () {
1384
+ hooks = _createHooksMap();
1385
+ };
1386
+ return DOMPurify;
1387
+ }
1388
+ var purify = createDOMPurify();
1389
+
1390
+ const aiChatMessageCss = () => `:host{--ai-msg-user-bg:var(--ai-user-bubble-bg);--ai-msg-user-border:1px solid var(--ai-border-default);--ai-msg-agent-bg:var(--ai-agent-bubble-bg);--ai-msg-agent-border:1px solid var(--ai-border-default);--ai-msg-border-radius:16px;--ai-msg-padding:16px;--ai-msg-font-size:14px;--ai-msg-action-active-bg:var(--ai-accent);--ai-user-msg-max-width:80%;--ai-agent-msg-max-width:80%;display:block}.message-row{display:flex}.user-row{flex-direction:column;align-items:flex-end}.user-bubble{background:var(--ai-msg-user-bg);color:var(--ai-text-primary);border:var(--ai-msg-user-border);border-radius:var(--ai-msg-border-radius);padding:var(--ai-msg-padding);font-size:var(--ai-msg-font-size);max-width:var(--ai-user-msg-max-width);line-height:1.5;word-break:break-word;box-shadow:var(--ai-shadow-sm)}.user-row .timestamp{font-size:12px;color:var(--ai-text-secondary);margin-top:4px}.agent-row{flex-direction:row;justify-content:flex-start}.agent-bubble-wrapper{display:flex;flex-direction:column;gap:6px;width:100%;max-width:var(--ai-msg-agent-max-width);min-width:0}.agent-bubble{background:var(--ai-msg-agent-bg);color:var(--ai-text-primary);border:var(--ai-msg-agent-border);border-radius:var(--ai-msg-border-radius);padding:var(--ai-msg-padding);font-size:var(--ai-msg-font-size);line-height:1.6;word-break:break-word;box-shadow:var(--ai-shadow-sm);display:flex;flex-direction:column;gap:12px}.message-content{white-space:pre-wrap}.message-content p{margin:0 0 8px 0}.message-content p:last-child{margin-bottom:0}.message-content h2{font-size:16px;font-weight:700;margin:0 0 8px 0}.message-content h3{font-size:15px;font-weight:600;margin:0 0 6px 0}.message-content strong{font-weight:700}.message-content em{font-style:italic}.message-content code{background:var(--ai-bg-surface);border-radius:4px;padding:1px 5px;font-family:var(--ai-font-family-mono);font-size:13px;color:var(--ai-text-primary)}.message-content pre{background:var(--ai-bg-surface);border-radius:8px;padding:10px 12px;overflow-x:auto;margin:8px 0}.message-content pre code{background:none;padding:0;font-size:13px}.message-content ul,.message-content ol{padding-inline-start:20px;margin:4px 0 8px 0}.message-content li{margin-bottom:3px}.actions-bar{display:flex;flex-direction:row;align-items:center;justify-content:flex-start;gap:6px;height:0;overflow:hidden;opacity:0;pointer-events:none;transition:height 0.15s ease, opacity 0.15s ease}.agent-bubble:hover .actions-bar{height:32px;opacity:1;pointer-events:auto}.action-btn{display:flex;align-items:center;justify-content:center;width:32px;height:32px;border-radius:8px;background:var(--ai-bg-card);border:1px solid var(--ai-border-default);cursor:pointer;color:var(--ai-text-primary);transition:background 0.15s, color 0.15s;padding:0;flex-shrink:0}.action-btn:hover{background:var(--ai-bg-surface)}.action-btn.copy-success{background:var(--ai-msg-action-active-bg);color:var(--ai-accent-text);border-color:var(--ai-accent)}.feedback-group{display:flex;align-items:center;border:1px solid var(--ai-border-default);border-radius:8px;overflow:hidden;background:var(--ai-bg-card)}.feedback-btn{display:flex;align-items:center;justify-content:center;height:32px;padding:0 8px;background:var(--ai-bg-card);border:none;border-inline-start:1px solid var(--ai-border-default);cursor:pointer;color:var(--ai-text-primary);transition:background 0.15s, color 0.15s}.feedback-btn:first-child{border-inline-start:none}.feedback-btn:hover{background:var(--ai-bg-surface)}.feedback-btn.active{background:var(--ai-msg-action-active-bg);color:var(--ai-accent-text)}.icon-wrap{display:flex;align-items:center;justify-content:center;line-height:0}.agent-info{display:flex;flex-direction:row;align-items:center;justify-content:flex-start;gap:6px;color:var(--ai-text-muted)}.agent-info-name,.agent-info-time{font-size:12px;color:inherit;line-height:16px;white-space:nowrap}.agent-info .icon-wrap{display:flex;align-items:center;color:inherit;opacity:0.6;flex-shrink:0}.typing-indicator{display:flex;align-items:center;gap:5px;padding:4px 2px}.typing-dot{width:8px;height:8px;border-radius:50%;background:var(--ai-text-muted);animation:typingBounce 1.2s ease-in-out infinite}.typing-dot:nth-child(2){animation-delay:0.2s}.typing-dot:nth-child(3){animation-delay:0.4s}@keyframes typingBounce{0%,60%,100%{transform:translateY(0)}30%{transform:translateY(-6px)}}.streaming-cursor{display:inline-block;width:2px;height:1em;background:currentColor;vertical-align:text-bottom;margin-inline-start:2px;animation:cursorBlink 0.8s step-start infinite}@keyframes cursorBlink{0%,100%{opacity:1}50%{opacity:0}}`;
1391
+
1392
+ const SANITIZE_CONFIG = {
1393
+ ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'del', 'code', 'pre', 'ul', 'ol', 'li', 'h2', 'h3', 'a', 'blockquote', 'table', 'thead', 'tbody', 'tr', 'th', 'td'],
1394
+ ALLOWED_ATTR: ['href', 'target', 'rel'],
1395
+ };
6
1396
  const AiChatMessage = class {
7
1397
  constructor(hostRef) {
8
1398
  registerInstance(this, hostRef);
@@ -37,16 +1427,59 @@ const AiChatMessage = class {
37
1427
  parseMarkdown(text) {
38
1428
  let html = text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
39
1429
  const blocks = [];
1430
+ // Fenced code blocks
40
1431
  html = html.replace(/```(?:\w+)?\n?([\s\S]*?)```/g, (_, code) => {
41
1432
  const idx = blocks.length;
42
1433
  blocks.push(`<pre><code>${code}</code></pre>`);
43
1434
  return `\x00BLOCK${idx}\x00`;
44
1435
  });
1436
+ // Pipe tables (must run before paragraph wrapping)
1437
+ html = html.replace(/((?:^[ \t]*\|.+\|\n?)+)/gm, match => {
1438
+ const rows = match.trim().split('\n').filter(l => l.trim());
1439
+ if (rows.length < 2)
1440
+ return match;
1441
+ const isSep = (r) => /^[\s|:-]+$/.test(r);
1442
+ let tableHtml = '<table>';
1443
+ let inBody = false;
1444
+ rows.forEach((row, i) => {
1445
+ if (isSep(row)) {
1446
+ inBody = true;
1447
+ tableHtml += '<tbody>';
1448
+ return;
1449
+ }
1450
+ const cells = row.split('|').filter((_, j, a) => j > 0 && j < a.length - 1);
1451
+ if (!inBody && i === 0) {
1452
+ tableHtml += `<thead><tr>${cells.map(c => `<th>${c.trim()}</th>`).join('')}</tr></thead>`;
1453
+ }
1454
+ else {
1455
+ tableHtml += `<tr>${cells.map(c => `<td>${c.trim()}</td>`).join('')}</tr>`;
1456
+ }
1457
+ });
1458
+ if (inBody)
1459
+ tableHtml += '</tbody>';
1460
+ tableHtml += '</table>';
1461
+ const idx = blocks.length;
1462
+ blocks.push(tableHtml);
1463
+ return `\x00BLOCK${idx}\x00`;
1464
+ });
1465
+ // Blockquotes — &gt; because > was already escaped
1466
+ html = html.replace(/((?:^&gt; .+\n?)+)/gm, match => {
1467
+ const content = match.replace(/^&gt; /gm, '').trim();
1468
+ const idx = blocks.length;
1469
+ blocks.push(`<blockquote>${content}</blockquote>`);
1470
+ return `\x00BLOCK${idx}\x00`;
1471
+ });
1472
+ // Inline code
45
1473
  html = html.replace(/`([^`]+)`/g, '<code>$1</code>');
1474
+ // Headings
46
1475
  html = html.replace(/^## (.+)$/gm, '<h2>$1</h2>');
47
1476
  html = html.replace(/^### (.+)$/gm, '<h3>$1</h3>');
1477
+ // Bold, italic, strikethrough, links
48
1478
  html = html.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
49
1479
  html = html.replace(/\*([^*\n]+)\*/g, '<em>$1</em>');
1480
+ html = html.replace(/~~(.+?)~~/g, '<del>$1</del>');
1481
+ html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');
1482
+ // Unordered lists
50
1483
  html = html.replace(/((?:^[ \t]*[-*] .+\n?)+)/gm, match => {
51
1484
  const items = match
52
1485
  .trim()
@@ -54,11 +1487,11 @@ const AiChatMessage = class {
54
1487
  .filter(l => l.trim())
55
1488
  .map(l => `<li>${l.replace(/^[ \t]*[-*] /, '')}</li>`)
56
1489
  .join('');
57
- return `\x00BLOCK${blocks.length}\x00${(() => {
58
- blocks.push(`<ul>${items}</ul>`);
59
- return '';
60
- })()}`;
1490
+ const idx = blocks.length;
1491
+ blocks.push(`<ul>${items}</ul>`);
1492
+ return `\x00BLOCK${idx}\x00`;
61
1493
  });
1494
+ // Ordered lists
62
1495
  html = html.replace(/((?:^[ \t]*\d+\. .+\n?)+)/gm, match => {
63
1496
  const items = match
64
1497
  .trim()
@@ -66,10 +1499,9 @@ const AiChatMessage = class {
66
1499
  .filter(l => l.trim())
67
1500
  .map(l => `<li>${l.replace(/^[ \t]*\d+\. /, '')}</li>`)
68
1501
  .join('');
69
- return `\x00BLOCK${blocks.length}\x00${(() => {
70
- blocks.push(`<ol>${items}</ol>`);
71
- return '';
72
- })()}`;
1502
+ const idx = blocks.length;
1503
+ blocks.push(`<ol>${items}</ol>`);
1504
+ return `\x00BLOCK${idx}\x00`;
73
1505
  });
74
1506
  html = html
75
1507
  .split(/\n{2,}/)
@@ -88,8 +1520,7 @@ const AiChatMessage = class {
88
1520
  getRenderedContent() {
89
1521
  if (!this.content)
90
1522
  return '';
91
- let html = this.parseMarkdown(this.content);
92
- return html;
1523
+ return purify.sanitize(this.parseMarkdown(this.content), SANITIZE_CONFIG);
93
1524
  }
94
1525
  getRelativeTime() {
95
1526
  if (!this.timestamp)
@@ -98,15 +1529,19 @@ const AiChatMessage = class {
98
1529
  const date = new Date(this.timestamp);
99
1530
  if (isNaN(date.getTime()))
100
1531
  return this.timestamp;
101
- const diffMin = Math.floor((Date.now() - date.getTime()) / 60000);
1532
+ const diffMs = Date.now() - date.getTime();
1533
+ const diffMin = Math.floor(diffMs / 60000);
1534
+ const diffHour = Math.floor(diffMin / 60);
1535
+ const diffDay = Math.floor(diffHour / 24);
1536
+ const lang = (typeof document !== 'undefined' && document.documentElement.lang) || 'ar';
1537
+ const rtf = new Intl.RelativeTimeFormat(lang, { numeric: 'auto' });
102
1538
  if (diffMin < 1)
103
- return 'الآن';
1539
+ return rtf.format(0, 'second');
104
1540
  if (diffMin < 60)
105
- return `منذ ${diffMin} دقيقة`;
106
- const hours = Math.floor(diffMin / 60);
107
- if (hours < 24)
108
- return `منذ ${hours} ساعة`;
109
- return `منذ ${Math.floor(hours / 24)} يوم`;
1541
+ return rtf.format(-diffMin, 'minute');
1542
+ if (diffHour < 24)
1543
+ return rtf.format(-diffHour, 'hour');
1544
+ return rtf.format(-diffDay, 'day');
110
1545
  }
111
1546
  catch {
112
1547
  return this.timestamp;
@@ -154,7 +1589,7 @@ const AiChatMessage = class {
154
1589
  } })), h("slot", null), showActions && this.renderActionsBar()), (this.agentName || this.timestamp) && (h("div", { class: "agent-info" }, this.agentName && h("span", { class: "agent-info-name" }, this.agentName), this.agentName && this.timestamp && this.renderIcon('eclipse', 10), this.timestamp && h("span", { class: "agent-info-time" }, this.getRelativeTime()))))));
155
1590
  }
156
1591
  render() {
157
- return h(Host, { key: '77dd0c46a676c211fdfba283d51bd0e0d2594b24' }, this.role === 'user' ? this.renderUserMessage() : this.renderAgentMessage());
1592
+ return h(Host, { key: 'a3da55a7f023469f2538b363ff691674c241227e' }, this.role === 'user' ? this.renderUserMessage() : this.renderAgentMessage());
158
1593
  }
159
1594
  };
160
1595
  AiChatMessage.style = aiChatMessageCss();