@ohos-ports/html-minifier-next 8.4.2-beta.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 (51) hide show
  1. package/LICENSE.txt +23 -0
  2. package/README.md +776 -0
  3. package/cli.js +1209 -0
  4. package/dist/types/htmlminifier.d.ts +556 -0
  5. package/dist/types/htmlminifier.d.ts.map +1 -0
  6. package/dist/types/htmlparser.d.ts +25 -0
  7. package/dist/types/htmlparser.d.ts.map +1 -0
  8. package/dist/types/lib/attributes.d.ts +155 -0
  9. package/dist/types/lib/attributes.d.ts.map +1 -0
  10. package/dist/types/lib/constants.d.ts +110 -0
  11. package/dist/types/lib/constants.d.ts.map +1 -0
  12. package/dist/types/lib/content.d.ts +51 -0
  13. package/dist/types/lib/content.d.ts.map +1 -0
  14. package/dist/types/lib/elements.d.ts +57 -0
  15. package/dist/types/lib/elements.d.ts.map +1 -0
  16. package/dist/types/lib/fragments.d.ts +46 -0
  17. package/dist/types/lib/fragments.d.ts.map +1 -0
  18. package/dist/types/lib/option-definitions.d.ts +33 -0
  19. package/dist/types/lib/option-definitions.d.ts.map +1 -0
  20. package/dist/types/lib/options.d.ts +120 -0
  21. package/dist/types/lib/options.d.ts.map +1 -0
  22. package/dist/types/lib/unused-css.d.ts +46 -0
  23. package/dist/types/lib/unused-css.d.ts.map +1 -0
  24. package/dist/types/lib/urls.d.ts +15 -0
  25. package/dist/types/lib/urls.d.ts.map +1 -0
  26. package/dist/types/lib/utils.d.ts +102 -0
  27. package/dist/types/lib/utils.d.ts.map +1 -0
  28. package/dist/types/lib/whitespace.d.ts +45 -0
  29. package/dist/types/lib/whitespace.d.ts.map +1 -0
  30. package/dist/types/presets.d.ts +49 -0
  31. package/dist/types/presets.d.ts.map +1 -0
  32. package/dist/types/tokenchain.d.ts +26 -0
  33. package/dist/types/tokenchain.d.ts.map +1 -0
  34. package/html-minifier-next.schema.json +306 -0
  35. package/package.json +100 -0
  36. package/src/htmlminifier.js +2294 -0
  37. package/src/htmlparser.js +1069 -0
  38. package/src/lib/attributes.js +928 -0
  39. package/src/lib/constants.js +285 -0
  40. package/src/lib/content.js +190 -0
  41. package/src/lib/elements.js +274 -0
  42. package/src/lib/file-pool.js +177 -0
  43. package/src/lib/fragments.js +274 -0
  44. package/src/lib/option-definitions.js +231 -0
  45. package/src/lib/options.js +730 -0
  46. package/src/lib/unused-css.js +379 -0
  47. package/src/lib/urls.js +155 -0
  48. package/src/lib/utils.js +861 -0
  49. package/src/lib/whitespace.js +321 -0
  50. package/src/presets.js +57 -0
  51. package/src/tokenchain.js +123 -0
@@ -0,0 +1,285 @@
1
+ /**
2
+ * Regex patterns, element sets, and default configuration
3
+ */
4
+
5
+ const RE_WS_START = /^[ \n\r\t\f]+/;
6
+ const RE_WS_END = /[ \n\r\t\f]+$/;
7
+ const RE_WS_ONLY = /^[ \n\r\t\f]+$/;
8
+ const RE_WS_NBSP_END = /[ \n\r\t\f\xA0]$/;
9
+ const RE_ALL_WS_NBSP = /[ \n\r\t\f\xA0]+/g;
10
+ const RE_NBSP_LEADING_GROUP = /(^|\xA0+)[^\xA0]+/g;
11
+ const RE_NBSP_LEAD_GROUP = /(\xA0+)[^\xA0]+/g;
12
+ const RE_NBSP_TRAILING_GROUP = /[^\xA0]+(\xA0+)/g;
13
+ const RE_NBSP_TRAILING_STRIP = /[^\xA0]+$/;
14
+ const RE_EVENT_ATTR_DEFAULT = /^on[a-z]{3,}$/;
15
+ const RE_CAN_REMOVE_ATTR_QUOTES = /^[^ \t\n\f\r"'`=<>]+$/;
16
+ const RE_TRAILING_SEMICOLON = /;$/;
17
+ const RE_AMP_ENTITY = /&(#?[0-9a-zA-Z]+;)/g;
18
+ const RE_LEGACY_ENTITIES = /&((?:Iacute|aacute|uacute|plusmn|Otilde|otilde|agrave|Agrave|Yacute|yacute|Oslash|oslash|atilde|Atilde|brvbar|ccedil|Ccedil|Ograve|curren|divide|eacute|Eacute|ograve|Oacute|egrave|Egrave|Ugrave|frac12|frac14|frac34|ugrave|oacute|iacute|Ntilde|ntilde|Uacute|middot|igrave|Igrave|iquest|Aacute|cedil|laquo|micro|iexcl|Icirc|icirc|acirc|Ucirc|Ecirc|ocirc|Ocirc|ecirc|ucirc|Aring|aring|AElig|aelig|acute|pound|raquo|Acirc|times|THORN|szlig|thorn|COPY|auml|ordf|ordm|Uuml|macr|uuml|Auml|ouml|Ouml|para|nbsp|euml|quot|QUOT|Euml|yuml|cent|sect|copy|sup1|sup2|sup3|iuml|Iuml|ETH|shy|reg|not|yen|amp|AMP|REG|uml|eth|deg|gt|GT|LT|lt)(?!;)|(?:#?[0-9a-zA-Z]+;))/g;
19
+ const RE_ESCAPE_LT = /</g;
20
+ // In escapable raw text only the element’s own end tag ends the element, so nothing else
21
+ // that `decodeEntities` decoded to a `<` needs escaping there
22
+ // (the record has no prototype, so a tag named after an inherited property—`constructor`,
23
+ // `__proto__`—finds nothing here and falls back to escaping every `<`)
24
+ const RE_ESCAPE_LT_RAW_TEXT = /** @type {Record<string, RegExp>} */ (Object.assign(Object.create(null), {
25
+ textarea: /<(?=\/textarea[\s/>])/gi,
26
+ title: /<(?=\/title[\s/>])/gi
27
+ }));
28
+ // Encodings that make an `annotation-xml` element hold HTML rather than MathML
29
+ // https://html.spec.whatwg.org/multipage/parsing.html#html-integration-point
30
+ const RE_HTML_ENCODING = /^(text\/html|application\/xhtml\+xml)$/i;
31
+ const RE_ATTR_WS_CHECK = /[ \n\r\t\f]/;
32
+ const RE_ATTR_WS_COLLAPSE = /[ \n\r\t\f]+/g;
33
+ const RE_ATTR_WS_TRIM = /^[ \n\r\t\f]+|[ \n\r\t\f]+$/g;
34
+ const RE_STYLE_ELEMENT = /<style[\s/>]/i;
35
+ const RE_EMPTY_ATTRIBUTE = new RegExp(
36
+ '^(?:class|id|style|title|lang|dir|on(?:focus|blur|change|click|dblclick|mouse(' +
37
+ '?:down|up|over|move|out)|key(?:press|down|up)))$');
38
+
39
+ // Inline element sets for whitespace handling
40
+
41
+ // Non-empty elements that will maintain whitespace around them
42
+ const inlineElementsToKeepWhitespaceAround = new Set(['a', 'abbr', 'acronym', 'b', 'bdi', 'bdo', 'big', 'button', 'cite', 'code', 'del', 'dfn', 'em', 'font', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'mark', 'math', 'meter', 'nobr', 'object', 'output', 'progress', 'q', 'rb', 'rp', 'rt', 'rtc', 'ruby', 's', 'samp', 'select', 'small', 'span', 'strike', 'strong', 'sub', 'sup', 'svg', 'textarea', 'time', 'tt', 'u', 'var', 'wbr']);
43
+
44
+ // Non-empty elements that will maintain whitespace within them
45
+ const inlineElementsToKeepWhitespaceWithin = new Set(['a', 'abbr', 'acronym', 'b', 'big', 'del', 'em', 'font', 'i', 'ins', 'kbd', 'mark', 'nobr', 's', 'samp', 'small', 'span', 'strike', 'strong', 'sub', 'sup', 'time', 'tt', 'u', 'var']);
46
+
47
+ // Elements that will always maintain whitespace around them
48
+ const inlineElementsToKeepWhitespace = new Set(['comment', 'img', 'input', 'wbr']);
49
+
50
+ // Form control elements (for conditional whitespace collapsing)
51
+ const formControlElements = new Set(['input', 'button', 'select', 'textarea', 'output', 'meter', 'progress']);
52
+
53
+ // Default attribute values
54
+
55
+ // Default attribute values (could apply to any element)
56
+ const generalDefaults = {
57
+ autocorrect: 'on',
58
+ fetchpriority: 'auto',
59
+ loading: 'eager',
60
+ popovertargetaction: 'toggle'
61
+ };
62
+
63
+ // Tag-specific default attribute values
64
+ const tagDefaults = {
65
+ area: { shape: 'rect' },
66
+ button: { type: 'submit' },
67
+ form: {
68
+ enctype: 'application/x-www-form-urlencoded',
69
+ method: 'get'
70
+ },
71
+ html: { dir: 'ltr' },
72
+ img: { decoding: 'auto' },
73
+ input: {
74
+ colorspace: 'limited-srgb',
75
+ type: 'text'
76
+ },
77
+ link: { media: 'all' },
78
+ marquee: {
79
+ behavior: 'scroll',
80
+ direction: 'left'
81
+ },
82
+ meta: { media: 'all' },
83
+ source: { media: 'all' },
84
+ style: { media: 'all' },
85
+ textarea: { wrap: 'soft' },
86
+ track: { kind: 'subtitles' }
87
+ };
88
+
89
+ // Script MIME types
90
+
91
+ // https://mathiasbynens.be/demo/javascript-mime-type
92
+ // https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/script
93
+ const executableScriptsMimetypes = new Set([
94
+ 'text/javascript',
95
+ 'text/x-javascript',
96
+ 'text/ecmascript',
97
+ 'text/x-ecmascript',
98
+ 'text/jscript',
99
+ 'application/javascript',
100
+ 'application/x-javascript',
101
+ 'application/ecmascript',
102
+ 'application/x-ecmascript',
103
+ 'module'
104
+ ]);
105
+
106
+ const keepScriptsMimetypes = new Set([
107
+ 'module'
108
+ ]);
109
+
110
+ // Boolean attribute sets
111
+
112
+ const isSimpleBoolean = new Set(['allowfullscreen', 'async', 'autofocus', 'autoplay', 'checked', 'compact', 'controls', 'declare', 'default', 'defaultchecked', 'defaultmuted', 'defaultselected', 'defer', 'disabled', 'enabled', 'formnovalidate', 'hidden', 'indeterminate', 'inert', 'ismap', 'itemscope', 'loop', 'multiple', 'muted', 'nohref', 'noresize', 'noshade', 'novalidate', 'nowrap', 'open', 'pauseonexit', 'readonly', 'required', 'reversed', 'scoped', 'seamless', 'selected', 'sortable', 'truespeed', 'typemustmatch', 'visible']);
113
+
114
+ const isBooleanValue = new Set(['true', 'false']);
115
+
116
+ // Attributes where certain values can be collapsed to just the attribute name;
117
+ // maps each attribute name to the set of values that collapse to the bare attribute:
118
+ // - `crossorigin=""` and `crossorigin="anonymous"` → `crossorigin` (anonymous is the default)
119
+ // - `contenteditable=""` → `contenteditable` (empty string means inherit/true)
120
+ const collapsibleValues = new Map([
121
+ ['crossorigin', new Set(['', 'anonymous'])],
122
+ ['contenteditable', new Set([''])]
123
+ ]);
124
+
125
+ // `srcset` elements
126
+
127
+ const srcsetElements = new Set(['img', 'source']);
128
+
129
+ // JSON script types
130
+
131
+ const jsonScriptTypes = new Set([
132
+ 'application/json',
133
+ 'application/ld+json',
134
+ 'application/manifest+json',
135
+ 'application/vnd.geo+json',
136
+ 'application/problem+json',
137
+ 'application/merge-patch+json',
138
+ 'application/json-patch+json',
139
+ 'importmap',
140
+ 'speculationrules',
141
+ ]);
142
+
143
+ // Tag omission rules and element sets
144
+
145
+ // Tag omission rules from https://html.spec.whatwg.org/multipage/syntax.html#optional-tags with the following extensions:
146
+ // - retain `<body>` if followed by `<noscript>`
147
+ // - `<rb>`, `<rt>`, `<rtc>`, `<rp>` follow HTML Ruby Markup Extensions draft (https://www.w3.org/TR/html-ruby-extensions/)
148
+ // - retain all tags which are adjacent to non-standard HTML tags
149
+
150
+ const optionalStartTags = new Set(['html', 'head', 'body', 'colgroup', 'tbody']);
151
+
152
+ const optionalEndTags = new Set(['html', 'head', 'body', 'li', 'dt', 'dd', 'p', 'rb', 'rt', 'rtc', 'rp', 'optgroup', 'option', 'colgroup', 'caption', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th']);
153
+
154
+ const headerElements = new Set(['meta', 'link', 'script', 'style', 'template', 'noscript']);
155
+
156
+ const descriptionElements = new Set(['dt', 'dd']);
157
+
158
+ const pBlockElements = new Set(['address', 'article', 'aside', 'blockquote', 'details', 'dialog', 'div', 'dl', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'main', 'menu', 'nav', 'ol', 'p', 'pre', 'search', 'section', 'table', 'ul']);
159
+
160
+ const pInlineElements = new Set(['a', 'audio', 'del', 'ins', 'map', 'noscript', 'video']);
161
+
162
+ const rubyEndTagOmission = new Set(['rb', 'rt', 'rtc', 'rp']); // `</rb>`, `</rt>`, `</rp>` can be omitted if followed by `<rb>`, `<rt>`, `<rtc>`, or `<rp>`
163
+
164
+ const rubyRtcEndTagOmission = new Set(['rb', 'rtc']); // `</rtc>` can be omitted if followed by `<rb>` or `<rtc>` (not `<rt>` or `<rp>`)
165
+
166
+ const optionElements = new Set(['option', 'optgroup']);
167
+
168
+ const tableContentElements = new Set(['tbody', 'tfoot']);
169
+
170
+ const tableSectionElements = new Set(['thead', 'tbody', 'tfoot']);
171
+
172
+ const cellElements = new Set(['td', 'th']);
173
+
174
+ const topLevelElements = new Set(['html', 'head', 'body']);
175
+
176
+ const compactElements = new Set(['html', 'body']);
177
+
178
+ const looseElements = new Set(['head', 'colgroup', 'caption']);
179
+
180
+ const trailingElements = new Set(['dt', 'thead']);
181
+
182
+ const htmlElements = new Set(['a', 'abbr', 'acronym', 'address', 'applet', 'area', 'article', 'aside', 'audio', 'b', 'base', 'basefont', 'bdi', 'bdo', 'bgsound', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'command', 'content', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'image', 'img', 'input', 'ins', 'isindex', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'listing', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meta', 'meter', 'multicol', 'nav', 'nobr', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'plaintext', 'pre', 'progress', 'q', 'rb', 'rp', 'rt', 'rtc', 'ruby', 's', 'samp', 'script', 'search', 'section', 'select', 'selectedcontent', 'shadow', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr', 'xmp']);
183
+
184
+ // Special content elements
185
+
186
+ const specialContentElements = new Set(['script', 'style']);
187
+
188
+ // Elements the parser reads as raw text as well, though only `script` and `style` are raw text
189
+ // elements by name—these are HTML’s alone, where `script` and `style` hold text in SVG, too
190
+ // https://html.spec.whatwg.org/multipage/parsing.html#generic-raw-text-element-parsing-algorithm
191
+ //
192
+ // (`noscript`, `noframes`, and `noembed` are raw text, too, but stay markup here: What they
193
+ // hold is markup to the UA that displays it—one without scripting or frames—so minifying it
194
+ // as markup keeps what that UA sees)
195
+ const genericRawTextElements = new Set(['iframe', 'plaintext', 'xmp']);
196
+
197
+ // `plaintext` is the one element among these whose content has no end: The text runs to the
198
+ // end of the document, `</plaintext>` and all, as nothing switches the parser back to markup
199
+ // https://html.spec.whatwg.org/multipage/parsing.html#plaintext-state
200
+ const endlessRawTextElements = new Set(['plaintext']);
201
+
202
+ // Escapable raw text elements, whose content is text rather than markup
203
+ // https://html.spec.whatwg.org/multipage/syntax.html#elements-2
204
+ const escapableRawTextElements = new Set(['textarea', 'title']);
205
+
206
+ // Raw text is read without resolving character references, so its text keeps them—unlike that
207
+ // of `textarea` and `title`, where they are resolved as they are anywhere else
208
+ const rawTextElements = new Set([...specialContentElements, ...genericRawTextElements]);
209
+
210
+ // Exports
211
+
212
+ export {
213
+ // Regex patterns
214
+ RE_WS_START,
215
+ RE_WS_END,
216
+ RE_WS_ONLY,
217
+ RE_WS_NBSP_END,
218
+ RE_ALL_WS_NBSP,
219
+ RE_NBSP_LEADING_GROUP,
220
+ RE_NBSP_LEAD_GROUP,
221
+ RE_NBSP_TRAILING_GROUP,
222
+ RE_NBSP_TRAILING_STRIP,
223
+ RE_EVENT_ATTR_DEFAULT,
224
+ RE_CAN_REMOVE_ATTR_QUOTES,
225
+ RE_TRAILING_SEMICOLON,
226
+ RE_AMP_ENTITY,
227
+ RE_LEGACY_ENTITIES,
228
+ RE_ESCAPE_LT,
229
+ RE_ESCAPE_LT_RAW_TEXT,
230
+ RE_HTML_ENCODING,
231
+ RE_ATTR_WS_CHECK,
232
+ RE_ATTR_WS_COLLAPSE,
233
+ RE_ATTR_WS_TRIM,
234
+ RE_STYLE_ELEMENT,
235
+ RE_EMPTY_ATTRIBUTE,
236
+
237
+ // Inline element sets
238
+ inlineElementsToKeepWhitespaceAround,
239
+ inlineElementsToKeepWhitespaceWithin,
240
+ inlineElementsToKeepWhitespace,
241
+ formControlElements,
242
+
243
+ // Default values
244
+ generalDefaults,
245
+ tagDefaults,
246
+
247
+ // Script/style constants
248
+ executableScriptsMimetypes,
249
+ keepScriptsMimetypes,
250
+ jsonScriptTypes,
251
+
252
+ // Boolean sets
253
+ isSimpleBoolean,
254
+ isBooleanValue,
255
+ collapsibleValues,
256
+
257
+ // Misc
258
+ srcsetElements,
259
+
260
+ // Tag omission rules
261
+ optionalStartTags,
262
+ optionalEndTags,
263
+ headerElements,
264
+ descriptionElements,
265
+ pBlockElements,
266
+ pInlineElements,
267
+ rubyEndTagOmission,
268
+ rubyRtcEndTagOmission,
269
+ optionElements,
270
+ tableContentElements,
271
+ tableSectionElements,
272
+ cellElements,
273
+ topLevelElements,
274
+ compactElements,
275
+ looseElements,
276
+ trailingElements,
277
+ htmlElements,
278
+
279
+ // Special content elements
280
+ specialContentElements,
281
+ genericRawTextElements,
282
+ endlessRawTextElements,
283
+ escapableRawTextElements,
284
+ rawTextElements
285
+ };
@@ -0,0 +1,190 @@
1
+ /**
2
+ * CSS and script content wrapping for minification
3
+ */
4
+
5
+ import {
6
+ jsonScriptTypes
7
+ } from './constants.js';
8
+ import { isExecutableScript } from './attributes.js';
9
+ import { findTagEnd } from './utils.js';
10
+ import { trimWhitespace } from './whitespace.js';
11
+
12
+ /** @import { ProcessedOptions } from './options.js' */
13
+
14
+ // CSS processing
15
+
16
+ // Wrap CSS declarations for inline styles and media queries
17
+ // This ensures proper context for CSS minification
18
+ /**
19
+ * @param {string} text
20
+ * @param {string} [type]
21
+ */
22
+ function wrapCSS(text, type) {
23
+ switch (type) {
24
+ case 'inline':
25
+ return '*{' + text + '}';
26
+ case 'media':
27
+ return '@media ' + text + '{a{top:0}}';
28
+ default:
29
+ return text;
30
+ }
31
+ }
32
+
33
+ /**
34
+ * @param {string} text
35
+ * @param {string} [type]
36
+ */
37
+ function unwrapCSS(text, type) {
38
+ let matches;
39
+ switch (type) {
40
+ case 'inline':
41
+ matches = text.match(/^\*\{([\s\S]*)\}$/);
42
+ break;
43
+ case 'media':
44
+ matches = text.match(/^@media ([\s\S]*?)\s*{[\s\S]*}$/);
45
+ break;
46
+ }
47
+ return matches ? matches[1] ?? text : text;
48
+ }
49
+
50
+ // Script processing
51
+
52
+ // Minify JSON script content, keeping `<` escaped
53
+ /**
54
+ * @param {string} text
55
+ * @param {{continueOnMinifyError?: boolean, log?: Function}} options
56
+ */
57
+ function minifyJson(text, options) {
58
+ try {
59
+ return JSON.stringify(JSON.parse(text)).replace(/</g, '\\u003C');
60
+ }
61
+ catch (err) {
62
+ if (!options.continueOnMinifyError) {
63
+ throw err;
64
+ }
65
+ options.log && options.log(err);
66
+ return text;
67
+ }
68
+ }
69
+
70
+ /** @param {Array<{name: string, value?: string}>} attrs */
71
+ function hasJsonScriptType(attrs) {
72
+ for (const attr of attrs) {
73
+ if (attr.name.toLowerCase() === 'type') {
74
+ const attrValue = trimWhitespace((attr.value || '').split(/;/, 2)[0] ?? '').toLowerCase();
75
+ if (jsonScriptTypes.has(attrValue)) {
76
+ return true;
77
+ }
78
+ }
79
+ }
80
+ return false;
81
+ }
82
+
83
+ /**
84
+ * @param {string} text
85
+ * @param {ProcessedOptions} options
86
+ * @param {Array<{name: string, value?: string | undefined}>} currentAttrs
87
+ * @param {Function} minifyHTML
88
+ */
89
+ async function processScript(text, options, currentAttrs, minifyHTML) {
90
+ for (const attr of currentAttrs) {
91
+ const attrName = attr.name.toLowerCase();
92
+ if (attrName === 'type') {
93
+ const rawValue = attr.value;
94
+ const normalizedValue = trimWhitespace((rawValue || '').split(/;/, 2)[0] ?? '').toLowerCase();
95
+ // Minify JSON script types automatically
96
+ if (jsonScriptTypes.has(normalizedValue)) {
97
+ return minifyJson(text, options);
98
+ }
99
+ // Process custom script types if specified
100
+ if (options.processScripts && rawValue && options.processScripts.indexOf(rawValue) > -1) {
101
+ return await minifyHTML(text, options);
102
+ }
103
+ }
104
+ }
105
+ return text;
106
+ }
107
+
108
+ // A `script` element is walked in three steps rather than matched by one pattern—
109
+ // a pattern spanning the whole element rescans the same text for every candidate
110
+ // tag, which turns markup repeating `<script` or `</script` into a quadratic scan
111
+ const RE_SCRIPT_START = /<script\b/gi;
112
+ // A tag name ends at whitespace, a slash, or the closing bracket, so `</scriptx>` names a
113
+ // different element and leaves the body running, as it does for the parser
114
+ const RE_SCRIPT_END = /<\/script(?=[\s/>])/gi;
115
+ const RE_TYPE_ATTRIBUTE = /(?:^|\s)type\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i;
116
+
117
+ /**
118
+ * Collects the bodies of executable inline scripts, in document order, so they can be
119
+ * minified as one batch ahead of the parse. Duplicates are dropped: The minifier is
120
+ * content-keyed, so the same body only needs dispatching once.
121
+ * @param {string} html
122
+ * @returns {Array<{code: string, isModule: boolean}>}
123
+ */
124
+ function extractScriptBodies(html) {
125
+ /** @type {Array<{code: string, isModule: boolean}>} */
126
+ const bodies = [];
127
+ const seen = new Set();
128
+
129
+ RE_SCRIPT_START.lastIndex = 0;
130
+ let startTag;
131
+ while ((startTag = RE_SCRIPT_START.exec(html))) {
132
+ const tagEnd = findTagEnd(html, RE_SCRIPT_START.lastIndex);
133
+ if (tagEnd === -1) {
134
+ break;
135
+ }
136
+ // Script content is raw text, so the body runs to the first `</script`—
137
+ // no nesting to account for
138
+ RE_SCRIPT_END.lastIndex = tagEnd + 1;
139
+ const endTag = RE_SCRIPT_END.exec(html);
140
+ if (!endTag) {
141
+ break;
142
+ }
143
+ const closeEnd = html.indexOf('>', RE_SCRIPT_END.lastIndex);
144
+ if (closeEnd === -1) {
145
+ break;
146
+ }
147
+ // Resuming past the element is what keeps every character visited once
148
+ RE_SCRIPT_START.lastIndex = closeEnd + 1;
149
+
150
+ const code = html.slice(tagEnd + 1, endTag.index);
151
+ // Whitespace-only and external scripts carry no work the minifier would do
152
+ if (!code.trim()) {
153
+ continue;
154
+ }
155
+
156
+ const typeMatch = RE_TYPE_ATTRIBUTE.exec(html.slice(startTag.index + '<script'.length, tagEnd));
157
+ /** @type {Array<{name: string, value: string}>} */
158
+ const attrs = typeMatch
159
+ ? [{ name: 'type', value: typeMatch[1] ?? typeMatch[2] ?? typeMatch[3] ?? '' }]
160
+ : [];
161
+ if (!isExecutableScript('script', attrs) || hasJsonScriptType(attrs)) {
162
+ continue;
163
+ }
164
+
165
+ // Module and classic scripts minify differently, so identical bodies in the two
166
+ // modes stay separate entries
167
+ const isModule = trimWhitespace((attrs[0]?.value ?? '')).toLowerCase() === 'module';
168
+ const key = (isModule ? 'm|' : '|') + code;
169
+ if (!seen.has(key)) {
170
+ seen.add(key);
171
+ bodies.push({ code, isModule });
172
+ }
173
+ }
174
+
175
+ return bodies;
176
+ }
177
+
178
+ // Exports
179
+
180
+ export {
181
+ // CSS
182
+ wrapCSS,
183
+ unwrapCSS,
184
+
185
+ // Scripts
186
+ minifyJson,
187
+ hasJsonScriptType,
188
+ extractScriptBodies,
189
+ processScript
190
+ };