html.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. // Package html minifies HTML5 following the specifications at http://www.w3.org/TR/html5/syntax.html.
  2. package html
  3. import (
  4. "bytes"
  5. "io"
  6. "github.com/tdewolff/minify/v2"
  7. "github.com/tdewolff/parse/v2"
  8. "github.com/tdewolff/parse/v2/buffer"
  9. "github.com/tdewolff/parse/v2/html"
  10. )
  11. var (
  12. gtBytes = []byte(">")
  13. isBytes = []byte("=")
  14. spaceBytes = []byte(" ")
  15. doctypeBytes = []byte("<!doctype html>")
  16. jsMimeBytes = []byte("application/javascript")
  17. cssMimeBytes = []byte("text/css")
  18. htmlMimeBytes = []byte("text/html")
  19. svgMimeBytes = []byte("image/svg+xml")
  20. formMimeBytes = []byte("application/x-www-form-urlencoded")
  21. mathMimeBytes = []byte("application/mathml+xml")
  22. dataSchemeBytes = []byte("data:")
  23. jsSchemeBytes = []byte("javascript:")
  24. httpBytes = []byte("http")
  25. radioBytes = []byte("radio")
  26. onBytes = []byte("on")
  27. textBytes = []byte("text")
  28. noneBytes = []byte("none")
  29. submitBytes = []byte("submit")
  30. allBytes = []byte("all")
  31. rectBytes = []byte("rect")
  32. dataBytes = []byte("data")
  33. getBytes = []byte("get")
  34. autoBytes = []byte("auto")
  35. oneBytes = []byte("one")
  36. inlineParams = map[string]string{"inline": "1"}
  37. )
  38. ////////////////////////////////////////////////////////////////
  39. var GoTemplateDelims = [2]string{"{{", "}}"}
  40. var HandlebarsTemplateDelims = [2]string{"{{", "}}"}
  41. var MustacheTemplateDelims = [2]string{"{{", "}}"}
  42. var EJSTemplateDelims = [2]string{"<%", "%>"}
  43. var ASPTemplateDelims = [2]string{"<%", "%>"}
  44. var PHPTemplateDelims = [2]string{"<?", "?>"}
  45. // Minifier is an HTML minifier.
  46. type Minifier struct {
  47. KeepComments bool
  48. KeepConditionalComments bool
  49. KeepDefaultAttrVals bool
  50. KeepDocumentTags bool
  51. KeepEndTags bool
  52. KeepQuotes bool
  53. KeepWhitespace bool
  54. TemplateDelims [2]string
  55. }
  56. // Minify minifies HTML data, it reads from r and writes to w.
  57. func Minify(m *minify.M, w io.Writer, r io.Reader, params map[string]string) error {
  58. return (&Minifier{}).Minify(m, w, r, params)
  59. }
  60. // Minify minifies HTML data, it reads from r and writes to w.
  61. func (o *Minifier) Minify(m *minify.M, w io.Writer, r io.Reader, _ map[string]string) error {
  62. var rawTagHash Hash
  63. var rawTagMediatype []byte
  64. omitSpace := true // if true the next leading space is omitted
  65. inPre := false
  66. attrMinifyBuffer := buffer.NewWriter(make([]byte, 0, 64))
  67. attrByteBuffer := make([]byte, 0, 64)
  68. z := parse.NewInput(r)
  69. defer z.Restore()
  70. l := html.NewTemplateLexer(z, o.TemplateDelims)
  71. tb := NewTokenBuffer(z, l)
  72. for {
  73. t := *tb.Shift()
  74. switch t.TokenType {
  75. case html.ErrorToken:
  76. if _, err := w.Write(nil); err != nil {
  77. return err
  78. }
  79. if l.Err() == io.EOF {
  80. return nil
  81. }
  82. return l.Err()
  83. case html.DoctypeToken:
  84. w.Write(doctypeBytes)
  85. case html.CommentToken:
  86. if o.KeepComments {
  87. w.Write(t.Data)
  88. } else if o.KeepConditionalComments && 6 < len(t.Text) && (bytes.HasPrefix(t.Text, []byte("[if ")) || bytes.HasSuffix(t.Text, []byte("[endif]")) || bytes.HasSuffix(t.Text, []byte("[endif]--"))) {
  89. // [if ...] is always 7 or more characters, [endif] is only encountered for downlevel-revealed
  90. // see https://msdn.microsoft.com/en-us/library/ms537512(v=vs.85).aspx#syntax
  91. if bytes.HasPrefix(t.Data, []byte("<!--[if ")) && bytes.HasSuffix(t.Data, []byte("<![endif]-->")) { // downlevel-hidden
  92. begin := bytes.IndexByte(t.Data, '>') + 1
  93. end := len(t.Data) - len("<![endif]-->")
  94. if begin < end {
  95. w.Write(t.Data[:begin])
  96. if err := o.Minify(m, w, buffer.NewReader(t.Data[begin:end]), nil); err != nil {
  97. return minify.UpdateErrorPosition(err, z, t.Offset)
  98. }
  99. w.Write(t.Data[end:])
  100. } else {
  101. w.Write(t.Data) // malformed
  102. }
  103. } else {
  104. w.Write(t.Data) // downlevel-revealed or short downlevel-hidden
  105. }
  106. } else if 1 < len(t.Text) && t.Text[0] == '#' {
  107. // SSI tags
  108. w.Write(t.Data)
  109. }
  110. case html.SvgToken:
  111. if err := m.MinifyMimetype(svgMimeBytes, w, buffer.NewReader(t.Data), nil); err != nil {
  112. if err != minify.ErrNotExist {
  113. return minify.UpdateErrorPosition(err, z, t.Offset)
  114. }
  115. w.Write(t.Data)
  116. }
  117. case html.MathToken:
  118. if err := m.MinifyMimetype(mathMimeBytes, w, buffer.NewReader(t.Data), nil); err != nil {
  119. if err != minify.ErrNotExist {
  120. return minify.UpdateErrorPosition(err, z, t.Offset)
  121. }
  122. w.Write(t.Data)
  123. }
  124. case html.TextToken:
  125. if t.HasTemplate {
  126. w.Write(t.Data)
  127. } else if rawTagHash != 0 {
  128. if rawTagHash == Style || rawTagHash == Script || rawTagHash == Iframe {
  129. var mimetype []byte
  130. var params map[string]string
  131. if rawTagHash == Iframe {
  132. mimetype = htmlMimeBytes
  133. } else if 0 < len(rawTagMediatype) {
  134. mimetype, params = parse.Mediatype(rawTagMediatype)
  135. } else if rawTagHash == Script {
  136. mimetype = jsMimeBytes
  137. } else if rawTagHash == Style {
  138. mimetype = cssMimeBytes
  139. }
  140. if err := m.MinifyMimetype(mimetype, w, buffer.NewReader(t.Data), params); err != nil {
  141. if err != minify.ErrNotExist {
  142. return minify.UpdateErrorPosition(err, z, t.Offset)
  143. }
  144. w.Write(t.Data)
  145. }
  146. } else {
  147. w.Write(t.Data)
  148. }
  149. } else if inPre {
  150. w.Write(t.Data)
  151. } else {
  152. t.Data = parse.ReplaceMultipleWhitespaceAndEntities(t.Data, EntitiesMap, TextRevEntitiesMap)
  153. // whitespace removal; trim left
  154. if omitSpace && parse.IsWhitespace(t.Data[0]) {
  155. t.Data = t.Data[1:]
  156. }
  157. // whitespace removal; trim right
  158. omitSpace = false
  159. if len(t.Data) == 0 {
  160. omitSpace = true
  161. } else if parse.IsWhitespace(t.Data[len(t.Data)-1]) {
  162. omitSpace = true
  163. i := 0
  164. for {
  165. next := tb.Peek(i)
  166. // trim if EOF, text token with leading whitespace or block token
  167. if next.TokenType == html.ErrorToken {
  168. t.Data = t.Data[:len(t.Data)-1]
  169. omitSpace = false
  170. break
  171. } else if next.TokenType == html.TextToken && !parse.IsAllWhitespace(next.Data) {
  172. // stop looking when text encountered
  173. break
  174. } else if next.TokenType == html.StartTagToken || next.TokenType == html.EndTagToken {
  175. if o.KeepWhitespace {
  176. break
  177. }
  178. // remove when followed by a block tag
  179. if next.Traits&blockTag != 0 {
  180. t.Data = t.Data[:len(t.Data)-1]
  181. omitSpace = false
  182. break
  183. } else if next.TokenType == html.StartTagToken {
  184. break
  185. }
  186. }
  187. i++
  188. }
  189. }
  190. w.Write(t.Data)
  191. }
  192. case html.StartTagToken, html.EndTagToken:
  193. rawTagHash = 0
  194. hasAttributes := false
  195. if t.TokenType == html.StartTagToken {
  196. if next := tb.Peek(0); next.TokenType == html.AttributeToken {
  197. hasAttributes = true
  198. }
  199. if t.Traits&rawTag != 0 {
  200. // ignore empty script and style tags
  201. if !hasAttributes && (t.Hash == Script || t.Hash == Style) {
  202. if next := tb.Peek(1); next.TokenType == html.EndTagToken {
  203. tb.Shift()
  204. tb.Shift()
  205. break
  206. }
  207. }
  208. rawTagHash = t.Hash
  209. rawTagMediatype = nil
  210. // do not minify content of <style amp-boilerplate>
  211. if hasAttributes && t.Hash == Style {
  212. if attrs := tb.Attributes(Amp_Boilerplate); attrs[0] != nil {
  213. rawTagHash = 0
  214. }
  215. }
  216. }
  217. } else if t.Hash == Template {
  218. omitSpace = true // EndTagToken
  219. }
  220. if t.Hash == Pre {
  221. inPre = t.TokenType == html.StartTagToken
  222. }
  223. // remove superfluous tags, except for html, head and body tags when KeepDocumentTags is set
  224. if !hasAttributes && (!o.KeepDocumentTags && (t.Hash == Html || t.Hash == Head || t.Hash == Body) || t.Hash == Colgroup) {
  225. break
  226. } else if t.TokenType == html.EndTagToken {
  227. omitEndTag := false
  228. if !o.KeepEndTags {
  229. if t.Hash == Thead || t.Hash == Tbody || t.Hash == Tfoot || t.Hash == Tr || t.Hash == Th ||
  230. t.Hash == Td || t.Hash == Option || t.Hash == Dd || t.Hash == Dt || t.Hash == Li ||
  231. t.Hash == Rb || t.Hash == Rt || t.Hash == Rtc || t.Hash == Rp {
  232. omitEndTag = true // omit end tags
  233. } else if t.Hash == P {
  234. i := 0
  235. for {
  236. next := tb.Peek(i)
  237. i++
  238. // continue if text token is empty or whitespace
  239. if next.TokenType == html.TextToken && parse.IsAllWhitespace(next.Data) {
  240. continue
  241. }
  242. if next.TokenType == html.ErrorToken || next.TokenType == html.EndTagToken && next.Traits&keepPTag == 0 || next.TokenType == html.StartTagToken && next.Traits&omitPTag != 0 {
  243. omitEndTag = true // omit p end tag
  244. }
  245. break
  246. }
  247. } else if t.Hash == Optgroup {
  248. i := 0
  249. for {
  250. next := tb.Peek(i)
  251. i++
  252. // continue if text token
  253. if next.TokenType == html.TextToken {
  254. continue
  255. }
  256. if next.TokenType == html.ErrorToken || next.Hash != Option {
  257. omitEndTag = true // omit optgroup end tag
  258. }
  259. break
  260. }
  261. }
  262. }
  263. if !omitEndTag {
  264. if o.KeepWhitespace || t.Traits&objectTag != 0 {
  265. omitSpace = false
  266. } else if t.Traits&blockTag != 0 {
  267. omitSpace = true // omit spaces after block elements
  268. }
  269. if 3+len(t.Text) < len(t.Data) {
  270. t.Data[2+len(t.Text)] = '>'
  271. t.Data = t.Data[:3+len(t.Text)]
  272. }
  273. w.Write(t.Data)
  274. }
  275. // skip text in select and optgroup tags
  276. if t.Hash == Option || t.Hash == Optgroup {
  277. if next := tb.Peek(0); next.TokenType == html.TextToken {
  278. tb.Shift()
  279. }
  280. }
  281. break
  282. }
  283. if o.KeepWhitespace || t.Traits&objectTag != 0 {
  284. omitSpace = false
  285. } else if t.Traits&blockTag != 0 {
  286. omitSpace = true // omit spaces after block elements
  287. }
  288. w.Write(t.Data)
  289. if hasAttributes {
  290. if t.Hash == Meta {
  291. attrs := tb.Attributes(Content, Http_Equiv, Charset, Name)
  292. if content := attrs[0]; content != nil {
  293. if httpEquiv := attrs[1]; httpEquiv != nil {
  294. httpEquiv.AttrVal = parse.TrimWhitespace(httpEquiv.AttrVal)
  295. if charset := attrs[2]; charset == nil && parse.EqualFold(httpEquiv.AttrVal, []byte("content-type")) {
  296. content.AttrVal = minify.Mediatype(content.AttrVal)
  297. if bytes.Equal(content.AttrVal, []byte("text/html;charset=utf-8")) {
  298. httpEquiv.Text = nil
  299. content.Text = []byte("charset")
  300. content.Hash = Charset
  301. content.AttrVal = []byte("utf-8")
  302. }
  303. }
  304. }
  305. if name := attrs[3]; name != nil {
  306. name.AttrVal = parse.TrimWhitespace(name.AttrVal)
  307. if parse.EqualFold(name.AttrVal, []byte("keywords")) {
  308. content.AttrVal = bytes.ReplaceAll(content.AttrVal, []byte(", "), []byte(","))
  309. } else if parse.EqualFold(name.AttrVal, []byte("viewport")) {
  310. content.AttrVal = bytes.ReplaceAll(content.AttrVal, []byte(" "), []byte(""))
  311. for i := 0; i < len(content.AttrVal); i++ {
  312. if content.AttrVal[i] == '=' && i+2 < len(content.AttrVal) {
  313. i++
  314. if n := parse.Number(content.AttrVal[i:]); 0 < n {
  315. minNum := minify.Number(content.AttrVal[i:i+n], -1)
  316. if len(minNum) < n {
  317. copy(content.AttrVal[i:i+len(minNum)], minNum)
  318. copy(content.AttrVal[i+len(minNum):], content.AttrVal[i+n:])
  319. content.AttrVal = content.AttrVal[:len(content.AttrVal)+len(minNum)-n]
  320. }
  321. i += len(minNum)
  322. }
  323. i-- // mitigate for-loop increase
  324. }
  325. }
  326. }
  327. }
  328. }
  329. } else if t.Hash == Script {
  330. attrs := tb.Attributes(Src, Charset)
  331. if attrs[0] != nil && attrs[1] != nil {
  332. attrs[1].Text = nil
  333. }
  334. } else if t.Hash == Input {
  335. attrs := tb.Attributes(Type, Value)
  336. if t, value := attrs[0], attrs[1]; t != nil && value != nil {
  337. isRadio := parse.EqualFold(t.AttrVal, radioBytes)
  338. if !isRadio && len(value.AttrVal) == 0 {
  339. value.Text = nil
  340. } else if isRadio && parse.EqualFold(value.AttrVal, onBytes) {
  341. value.Text = nil
  342. }
  343. }
  344. } else if t.Hash == A {
  345. attrs := tb.Attributes(Id, Name)
  346. if id, name := attrs[0], attrs[1]; id != nil && name != nil {
  347. if bytes.Equal(id.AttrVal, name.AttrVal) {
  348. name.Text = nil
  349. }
  350. }
  351. }
  352. // write attributes
  353. for {
  354. attr := *tb.Shift()
  355. if attr.TokenType != html.AttributeToken {
  356. break
  357. } else if attr.Text == nil {
  358. continue // removed attribute
  359. } else if attr.HasTemplate {
  360. w.Write(attr.Data)
  361. continue // don't minify attributes that contain templates
  362. }
  363. val := attr.AttrVal
  364. if attr.Traits&trimAttr != 0 {
  365. val = parse.ReplaceMultipleWhitespaceAndEntities(val, EntitiesMap, nil)
  366. val = parse.TrimWhitespace(val)
  367. } else {
  368. val = parse.ReplaceEntities(val, EntitiesMap, nil)
  369. }
  370. if t.Traits != 0 {
  371. if len(val) == 0 && (attr.Hash == Class ||
  372. attr.Hash == Dir ||
  373. attr.Hash == Id ||
  374. attr.Hash == Name ||
  375. attr.Hash == Action && t.Hash == Form) {
  376. continue // omit empty attribute values
  377. }
  378. if rawTagHash != 0 && attr.Hash == Type {
  379. rawTagMediatype = parse.Copy(val)
  380. }
  381. if attr.Hash == Enctype ||
  382. attr.Hash == Formenctype ||
  383. attr.Hash == Accept ||
  384. attr.Hash == Type && (t.Hash == A || t.Hash == Link || t.Hash == Embed || t.Hash == Object || t.Hash == Source || t.Hash == Script) {
  385. val = minify.Mediatype(val)
  386. }
  387. // default attribute values can be omitted
  388. if !o.KeepDefaultAttrVals && (attr.Hash == Type && (t.Hash == Script && jsMimetypes[string(parse.ToLower(parse.Copy(val)))] ||
  389. t.Hash == Style && parse.EqualFold(val, cssMimeBytes) ||
  390. t.Hash == Link && parse.EqualFold(val, cssMimeBytes) ||
  391. t.Hash == Input && parse.EqualFold(val, textBytes) ||
  392. t.Hash == Button && parse.EqualFold(val, submitBytes)) ||
  393. attr.Hash == Method && parse.EqualFold(val, getBytes) ||
  394. attr.Hash == Enctype && parse.EqualFold(val, formMimeBytes) ||
  395. attr.Hash == Colspan && bytes.Equal(val, oneBytes) ||
  396. attr.Hash == Rowspan && bytes.Equal(val, oneBytes) ||
  397. attr.Hash == Shape && parse.EqualFold(val, rectBytes) ||
  398. attr.Hash == Span && bytes.Equal(val, oneBytes) ||
  399. attr.Hash == Media && t.Hash == Style && parse.EqualFold(val, allBytes)) {
  400. continue
  401. }
  402. if attr.Hash == Style {
  403. // CSS minifier for attribute inline code
  404. val = parse.TrimWhitespace(val)
  405. attrMinifyBuffer.Reset()
  406. if err := m.MinifyMimetype(cssMimeBytes, attrMinifyBuffer, buffer.NewReader(val), inlineParams); err == nil {
  407. val = attrMinifyBuffer.Bytes()
  408. } else if err != minify.ErrNotExist {
  409. return minify.UpdateErrorPosition(err, z, attr.Offset)
  410. }
  411. if len(val) == 0 {
  412. continue
  413. }
  414. } else if 2 < len(attr.Text) && attr.Text[0] == 'o' && attr.Text[1] == 'n' {
  415. // JS minifier for attribute inline code
  416. val = parse.TrimWhitespace(val)
  417. if 11 <= len(val) && parse.EqualFold(val[:11], jsSchemeBytes) {
  418. val = val[11:]
  419. }
  420. attrMinifyBuffer.Reset()
  421. if err := m.MinifyMimetype(jsMimeBytes, attrMinifyBuffer, buffer.NewReader(val), inlineParams); err == nil {
  422. val = attrMinifyBuffer.Bytes()
  423. } else if err != minify.ErrNotExist {
  424. return minify.UpdateErrorPosition(err, z, attr.Offset)
  425. }
  426. if len(val) == 0 {
  427. continue
  428. }
  429. } else if attr.Traits&urlAttr != 0 { // anchors are already handled
  430. val = parse.TrimWhitespace(val)
  431. if 5 < len(val) {
  432. if parse.EqualFold(val[:4], httpBytes) {
  433. if val[4] == ':' {
  434. if m.URL != nil && m.URL.Scheme == "http" {
  435. val = val[5:]
  436. } else {
  437. parse.ToLower(val[:4])
  438. }
  439. } else if (val[4] == 's' || val[4] == 'S') && val[5] == ':' {
  440. if m.URL != nil && m.URL.Scheme == "https" {
  441. val = val[6:]
  442. } else {
  443. parse.ToLower(val[:5])
  444. }
  445. }
  446. } else if parse.EqualFold(val[:5], dataSchemeBytes) {
  447. val = minify.DataURI(m, val)
  448. }
  449. }
  450. }
  451. }
  452. w.Write(spaceBytes)
  453. w.Write(attr.Text)
  454. if 0 < len(val) && attr.Traits&booleanAttr == 0 {
  455. w.Write(isBytes)
  456. // use double quotes for RDFa attributes
  457. isXML := attr.Hash == Vocab || attr.Hash == Typeof || attr.Hash == Property || attr.Hash == Resource || attr.Hash == Prefix || attr.Hash == Content || attr.Hash == About || attr.Hash == Rev || attr.Hash == Datatype || attr.Hash == Inlist
  458. // no quotes if possible, else prefer single or double depending on which occurs more often in value
  459. var quote byte
  460. if 0 < len(attr.Data) && (attr.Data[len(attr.Data)-1] == '\'' || attr.Data[len(attr.Data)-1] == '"') {
  461. quote = attr.Data[len(attr.Data)-1]
  462. }
  463. val = html.EscapeAttrVal(&attrByteBuffer, val, quote, o.KeepQuotes, isXML)
  464. w.Write(val)
  465. }
  466. }
  467. } else {
  468. _ = tb.Shift() // StartTagClose
  469. }
  470. w.Write(gtBytes)
  471. // skip text in select and optgroup tags
  472. if t.Hash == Select || t.Hash == Optgroup {
  473. if next := tb.Peek(0); next.TokenType == html.TextToken {
  474. tb.Shift()
  475. }
  476. }
  477. // keep space after phrasing tags (<i>, <span>, ...) FontAwesome etc.
  478. if t.TokenType == html.StartTagToken && t.Traits == normalTag {
  479. if next := tb.Peek(0); next.Hash == t.Hash && next.TokenType == html.EndTagToken {
  480. omitSpace = false
  481. }
  482. }
  483. }
  484. }
  485. }