@nocobase/plugin-workflow-mailer 2.4.0-alpha.1 → 2.4.0-alpha.11

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 (187) hide show
  1. package/dist/externalVersion.js +6 -6
  2. package/dist/node_modules/joi/dist/joi-browser.min.js +1 -1
  3. package/dist/node_modules/joi/lib/index.js +1 -1
  4. package/dist/node_modules/joi/lib/messages.js +35 -6
  5. package/dist/node_modules/joi/lib/types/keys.js +18 -1
  6. package/dist/node_modules/joi/lib/types/link.js +18 -2
  7. package/dist/node_modules/joi/lib/types/string.js +2 -2
  8. package/dist/node_modules/joi/package.json +1 -1
  9. package/dist/node_modules/nodemailer/dist/cjs/addressparser/index.d.ts +59 -0
  10. package/dist/node_modules/nodemailer/dist/cjs/addressparser/index.js +790 -0
  11. package/dist/node_modules/nodemailer/dist/cjs/base64/index.d.ts +36 -0
  12. package/dist/node_modules/nodemailer/dist/cjs/base64/index.js +119 -0
  13. package/dist/node_modules/nodemailer/dist/cjs/dkim/index.d.ts +52 -0
  14. package/dist/node_modules/nodemailer/dist/cjs/dkim/index.js +228 -0
  15. package/dist/node_modules/nodemailer/dist/cjs/dkim/message-parser.d.ts +48 -0
  16. package/dist/node_modules/nodemailer/dist/cjs/dkim/message-parser.js +180 -0
  17. package/dist/node_modules/nodemailer/dist/cjs/dkim/relaxed-body.d.ts +36 -0
  18. package/dist/node_modules/nodemailer/dist/cjs/dkim/relaxed-body.js +148 -0
  19. package/dist/node_modules/nodemailer/dist/cjs/dkim/sign.d.ts +52 -0
  20. package/dist/node_modules/nodemailer/dist/cjs/dkim/sign.js +165 -0
  21. package/dist/node_modules/nodemailer/dist/cjs/errors.d.ts +96 -0
  22. package/dist/node_modules/nodemailer/dist/cjs/errors.js +70 -0
  23. package/dist/node_modules/nodemailer/dist/cjs/fetch/cookies.d.ts +107 -0
  24. package/dist/node_modules/nodemailer/dist/cjs/fetch/cookies.js +282 -0
  25. package/dist/node_modules/nodemailer/dist/cjs/fetch/index.d.ts +65 -0
  26. package/dist/node_modules/nodemailer/dist/cjs/fetch/index.js +384 -0
  27. package/dist/node_modules/nodemailer/dist/cjs/json-transport/index.d.ts +64 -0
  28. package/dist/node_modules/nodemailer/dist/cjs/json-transport/index.js +99 -0
  29. package/dist/node_modules/nodemailer/dist/cjs/mail-composer/index.d.ts +174 -0
  30. package/dist/node_modules/nodemailer/dist/cjs/mail-composer/index.js +613 -0
  31. package/dist/node_modules/nodemailer/dist/cjs/mailer/index.d.ts +237 -0
  32. package/dist/node_modules/nodemailer/dist/cjs/mailer/index.js +415 -0
  33. package/dist/node_modules/nodemailer/dist/cjs/mailer/mail-message.d.ts +97 -0
  34. package/dist/node_modules/nodemailer/dist/cjs/mailer/mail-message.js +342 -0
  35. package/dist/node_modules/nodemailer/dist/cjs/mime-funcs/index.d.ts +161 -0
  36. package/dist/node_modules/nodemailer/dist/cjs/mime-funcs/index.js +787 -0
  37. package/dist/node_modules/nodemailer/dist/cjs/mime-funcs/mime-types.d.ts +2 -0
  38. package/dist/node_modules/nodemailer/dist/cjs/mime-funcs/mime-types.js +2103 -0
  39. package/dist/node_modules/nodemailer/dist/cjs/mime-node/index.d.ts +333 -0
  40. package/dist/node_modules/nodemailer/dist/cjs/mime-node/index.js +1493 -0
  41. package/dist/node_modules/nodemailer/dist/cjs/mime-node/last-newline.d.ts +5 -0
  42. package/dist/node_modules/nodemailer/dist/cjs/mime-node/last-newline.js +32 -0
  43. package/dist/node_modules/nodemailer/dist/cjs/mime-node/le-unix.d.ts +9 -0
  44. package/dist/node_modules/nodemailer/dist/cjs/mime-node/le-unix.js +40 -0
  45. package/dist/node_modules/nodemailer/dist/cjs/mime-node/le-windows.d.ts +10 -0
  46. package/dist/node_modules/nodemailer/dist/cjs/mime-node/le-windows.js +47 -0
  47. package/dist/node_modules/nodemailer/dist/cjs/nodemailer.d.ts +124 -0
  48. package/dist/node_modules/nodemailer/dist/cjs/nodemailer.js +1 -0
  49. package/dist/node_modules/nodemailer/dist/cjs/package-info.d.ts +3 -0
  50. package/dist/node_modules/nodemailer/dist/cjs/package-info.js +7 -0
  51. package/dist/node_modules/nodemailer/dist/cjs/package.json +3 -0
  52. package/dist/node_modules/nodemailer/dist/cjs/punycode/index.d.ts +73 -0
  53. package/dist/node_modules/nodemailer/{lib → dist/cjs}/punycode/index.js +63 -112
  54. package/dist/node_modules/nodemailer/dist/cjs/qp/index.d.ts +32 -0
  55. package/dist/node_modules/nodemailer/dist/cjs/qp/index.js +207 -0
  56. package/dist/node_modules/nodemailer/dist/cjs/sendmail-transport/index.d.ts +69 -0
  57. package/dist/node_modules/nodemailer/dist/cjs/sendmail-transport/index.js +210 -0
  58. package/dist/node_modules/nodemailer/dist/cjs/ses-transport/index.d.ts +112 -0
  59. package/dist/node_modules/nodemailer/dist/cjs/ses-transport/index.js +252 -0
  60. package/dist/node_modules/nodemailer/dist/cjs/shared/index.d.ts +260 -0
  61. package/dist/node_modules/nodemailer/dist/cjs/shared/index.js +680 -0
  62. package/dist/node_modules/nodemailer/dist/cjs/shared/objects.d.ts +23 -0
  63. package/dist/node_modules/nodemailer/dist/cjs/shared/objects.js +43 -0
  64. package/dist/node_modules/nodemailer/dist/cjs/shared/url.d.ts +21 -0
  65. package/dist/node_modules/nodemailer/dist/cjs/shared/url.js +255 -0
  66. package/dist/node_modules/nodemailer/dist/cjs/smtp-connection/data-stream.d.ts +15 -0
  67. package/dist/node_modules/nodemailer/dist/cjs/smtp-connection/data-stream.js +108 -0
  68. package/dist/node_modules/nodemailer/dist/cjs/smtp-connection/http-proxy-client.d.ts +47 -0
  69. package/dist/node_modules/nodemailer/dist/cjs/smtp-connection/http-proxy-client.js +189 -0
  70. package/dist/node_modules/nodemailer/dist/cjs/smtp-connection/index.d.ts +416 -0
  71. package/dist/node_modules/nodemailer/dist/cjs/smtp-connection/index.js +1837 -0
  72. package/dist/node_modules/nodemailer/dist/cjs/smtp-pool/index.d.ts +133 -0
  73. package/dist/node_modules/nodemailer/dist/cjs/smtp-pool/index.js +569 -0
  74. package/dist/node_modules/nodemailer/dist/cjs/smtp-pool/pool-resource.d.ts +62 -0
  75. package/dist/node_modules/nodemailer/dist/cjs/smtp-pool/pool-resource.js +257 -0
  76. package/dist/node_modules/nodemailer/dist/cjs/smtp-transport/index.d.ts +156 -0
  77. package/dist/node_modules/nodemailer/dist/cjs/smtp-transport/index.js +371 -0
  78. package/dist/node_modules/nodemailer/dist/cjs/stream-transport/index.d.ts +65 -0
  79. package/dist/node_modules/nodemailer/dist/cjs/stream-transport/index.js +146 -0
  80. package/dist/node_modules/nodemailer/dist/cjs/well-known/index.d.ts +35 -0
  81. package/dist/node_modules/nodemailer/dist/cjs/well-known/index.js +41 -0
  82. package/dist/node_modules/nodemailer/dist/cjs/well-known/services.d.ts +2 -0
  83. package/dist/node_modules/nodemailer/dist/cjs/well-known/services.js +674 -0
  84. package/dist/node_modules/nodemailer/dist/cjs/xoauth2/index.d.ts +201 -0
  85. package/dist/node_modules/nodemailer/dist/cjs/xoauth2/index.js +426 -0
  86. package/dist/node_modules/nodemailer/dist/esm/addressparser/index.d.ts +59 -0
  87. package/dist/node_modules/nodemailer/dist/esm/addressparser/index.js +786 -0
  88. package/dist/node_modules/nodemailer/dist/esm/base64/index.d.ts +36 -0
  89. package/dist/node_modules/nodemailer/{lib → dist/esm}/base64/index.js +39 -68
  90. package/dist/node_modules/nodemailer/dist/esm/dkim/index.d.ts +52 -0
  91. package/dist/node_modules/nodemailer/{lib → dist/esm}/dkim/index.js +62 -92
  92. package/dist/node_modules/nodemailer/dist/esm/dkim/message-parser.d.ts +48 -0
  93. package/dist/node_modules/nodemailer/dist/esm/dkim/message-parser.js +176 -0
  94. package/dist/node_modules/nodemailer/dist/esm/dkim/relaxed-body.d.ts +36 -0
  95. package/dist/node_modules/nodemailer/dist/esm/dkim/relaxed-body.js +141 -0
  96. package/dist/node_modules/nodemailer/dist/esm/dkim/sign.d.ts +52 -0
  97. package/dist/node_modules/nodemailer/dist/esm/dkim/sign.js +125 -0
  98. package/dist/node_modules/nodemailer/dist/esm/errors.d.ts +96 -0
  99. package/dist/node_modules/nodemailer/dist/esm/errors.js +67 -0
  100. package/dist/node_modules/nodemailer/dist/esm/fetch/cookies.d.ts +107 -0
  101. package/dist/node_modules/nodemailer/dist/esm/fetch/cookies.js +242 -0
  102. package/dist/node_modules/nodemailer/dist/esm/fetch/index.d.ts +65 -0
  103. package/dist/node_modules/nodemailer/dist/esm/fetch/index.js +344 -0
  104. package/dist/node_modules/nodemailer/dist/esm/json-transport/index.d.ts +64 -0
  105. package/dist/node_modules/nodemailer/dist/esm/json-transport/index.js +62 -0
  106. package/dist/node_modules/nodemailer/dist/esm/mail-composer/index.d.ts +174 -0
  107. package/dist/node_modules/nodemailer/{lib → dist/esm}/mail-composer/index.js +283 -275
  108. package/dist/node_modules/nodemailer/dist/esm/mailer/index.d.ts +237 -0
  109. package/dist/node_modules/nodemailer/{lib → dist/esm}/mailer/index.js +151 -205
  110. package/dist/node_modules/nodemailer/dist/esm/mailer/mail-message.d.ts +97 -0
  111. package/dist/node_modules/nodemailer/{lib → dist/esm}/mailer/mail-message.js +111 -125
  112. package/dist/node_modules/nodemailer/dist/esm/mime-funcs/index.d.ts +161 -0
  113. package/dist/node_modules/nodemailer/dist/esm/mime-funcs/index.js +738 -0
  114. package/dist/node_modules/nodemailer/dist/esm/mime-funcs/mime-types.d.ts +2 -0
  115. package/dist/node_modules/nodemailer/{lib → dist/esm}/mime-funcs/mime-types.js +43 -49
  116. package/dist/node_modules/nodemailer/dist/esm/mime-node/index.d.ts +333 -0
  117. package/dist/node_modules/nodemailer/{lib → dist/esm}/mime-node/index.js +576 -437
  118. package/dist/node_modules/nodemailer/dist/esm/mime-node/last-newline.d.ts +5 -0
  119. package/dist/node_modules/nodemailer/{lib → dist/esm}/mime-node/last-newline.js +4 -10
  120. package/dist/node_modules/nodemailer/dist/esm/mime-node/le-unix.d.ts +9 -0
  121. package/dist/node_modules/nodemailer/{lib → dist/esm}/mime-node/le-unix.js +7 -15
  122. package/dist/node_modules/nodemailer/dist/esm/mime-node/le-windows.d.ts +10 -0
  123. package/dist/node_modules/nodemailer/{lib → dist/esm}/mime-node/le-windows.js +6 -16
  124. package/dist/node_modules/nodemailer/dist/esm/nodemailer.d.ts +124 -0
  125. package/dist/node_modules/nodemailer/dist/esm/nodemailer.js +166 -0
  126. package/dist/node_modules/nodemailer/dist/esm/package-info.d.ts +3 -0
  127. package/dist/node_modules/nodemailer/dist/esm/package-info.js +4 -0
  128. package/dist/node_modules/nodemailer/dist/esm/package.json +3 -0
  129. package/dist/node_modules/nodemailer/dist/esm/punycode/index.d.ts +73 -0
  130. package/dist/node_modules/nodemailer/dist/esm/punycode/index.js +405 -0
  131. package/dist/node_modules/nodemailer/dist/esm/qp/index.d.ts +32 -0
  132. package/dist/node_modules/nodemailer/{lib → dist/esm}/qp/index.js +59 -77
  133. package/dist/node_modules/nodemailer/dist/esm/sendmail-transport/index.d.ts +69 -0
  134. package/dist/node_modules/nodemailer/dist/esm/sendmail-transport/index.js +170 -0
  135. package/dist/node_modules/nodemailer/dist/esm/ses-transport/index.d.ts +112 -0
  136. package/dist/node_modules/nodemailer/dist/esm/ses-transport/index.js +212 -0
  137. package/dist/node_modules/nodemailer/dist/esm/shared/index.d.ts +260 -0
  138. package/dist/node_modules/nodemailer/dist/esm/shared/index.js +631 -0
  139. package/dist/node_modules/nodemailer/dist/esm/shared/objects.d.ts +23 -0
  140. package/dist/node_modules/nodemailer/dist/esm/shared/objects.js +38 -0
  141. package/dist/node_modules/nodemailer/dist/esm/shared/url.d.ts +21 -0
  142. package/dist/node_modules/nodemailer/dist/esm/shared/url.js +214 -0
  143. package/dist/node_modules/nodemailer/dist/esm/smtp-connection/data-stream.d.ts +15 -0
  144. package/dist/node_modules/nodemailer/dist/esm/smtp-connection/data-stream.js +103 -0
  145. package/dist/node_modules/nodemailer/dist/esm/smtp-connection/http-proxy-client.d.ts +47 -0
  146. package/dist/node_modules/nodemailer/dist/esm/smtp-connection/http-proxy-client.js +149 -0
  147. package/dist/node_modules/nodemailer/dist/esm/smtp-connection/index.d.ts +416 -0
  148. package/dist/node_modules/nodemailer/dist/esm/smtp-connection/index.js +1797 -0
  149. package/dist/node_modules/nodemailer/dist/esm/smtp-pool/index.d.ts +133 -0
  150. package/dist/node_modules/nodemailer/{lib → dist/esm}/smtp-pool/index.js +195 -314
  151. package/dist/node_modules/nodemailer/dist/esm/smtp-pool/pool-resource.d.ts +62 -0
  152. package/dist/node_modules/nodemailer/{lib → dist/esm}/smtp-pool/pool-resource.js +70 -107
  153. package/dist/node_modules/nodemailer/dist/esm/smtp-transport/index.d.ts +156 -0
  154. package/dist/node_modules/nodemailer/dist/esm/smtp-transport/index.js +331 -0
  155. package/dist/node_modules/nodemailer/dist/esm/stream-transport/index.d.ts +65 -0
  156. package/dist/node_modules/nodemailer/dist/esm/stream-transport/index.js +106 -0
  157. package/dist/node_modules/nodemailer/dist/esm/well-known/index.d.ts +35 -0
  158. package/dist/node_modules/nodemailer/{lib → dist/esm}/well-known/index.js +12 -23
  159. package/dist/node_modules/nodemailer/dist/esm/well-known/services.d.ts +2 -0
  160. package/dist/node_modules/nodemailer/dist/esm/well-known/services.js +671 -0
  161. package/dist/node_modules/nodemailer/dist/esm/xoauth2/index.d.ts +201 -0
  162. package/dist/node_modules/nodemailer/dist/esm/xoauth2/index.js +386 -0
  163. package/dist/node_modules/nodemailer/dist/well-known/services.json +640 -0
  164. package/dist/node_modules/nodemailer/package.json +1 -1
  165. package/package.json +4 -4
  166. package/dist/node_modules/nodemailer/.gitattributes +0 -6
  167. package/dist/node_modules/nodemailer/.ncurc.js +0 -7
  168. package/dist/node_modules/nodemailer/.prettierrc.js +0 -8
  169. package/dist/node_modules/nodemailer/lib/addressparser/index.js +0 -313
  170. package/dist/node_modules/nodemailer/lib/dkim/message-parser.js +0 -155
  171. package/dist/node_modules/nodemailer/lib/dkim/relaxed-body.js +0 -154
  172. package/dist/node_modules/nodemailer/lib/dkim/sign.js +0 -117
  173. package/dist/node_modules/nodemailer/lib/fetch/cookies.js +0 -281
  174. package/dist/node_modules/nodemailer/lib/fetch/index.js +0 -274
  175. package/dist/node_modules/nodemailer/lib/json-transport/index.js +0 -82
  176. package/dist/node_modules/nodemailer/lib/mime-funcs/index.js +0 -625
  177. package/dist/node_modules/nodemailer/lib/nodemailer.js +0 -1
  178. package/dist/node_modules/nodemailer/lib/sendmail-transport/index.js +0 -210
  179. package/dist/node_modules/nodemailer/lib/ses-transport/index.js +0 -349
  180. package/dist/node_modules/nodemailer/lib/shared/index.js +0 -688
  181. package/dist/node_modules/nodemailer/lib/smtp-connection/data-stream.js +0 -108
  182. package/dist/node_modules/nodemailer/lib/smtp-connection/http-proxy-client.js +0 -143
  183. package/dist/node_modules/nodemailer/lib/smtp-connection/index.js +0 -1825
  184. package/dist/node_modules/nodemailer/lib/smtp-transport/index.js +0 -416
  185. package/dist/node_modules/nodemailer/lib/stream-transport/index.js +0 -135
  186. package/dist/node_modules/nodemailer/lib/well-known/services.json +0 -343
  187. package/dist/node_modules/nodemailer/lib/xoauth2/index.js +0 -376
@@ -0,0 +1,738 @@
1
+ /* eslint no-control-regex:0 */
2
+ import * as base64 from '../base64/index.js';
3
+ import * as qp from '../qp/index.js';
4
+ import * as mimeTypes from './mime-types.js';
5
+ import { isProtoKey } from '../shared/objects.js';
6
+ /**
7
+ * Checks if a value is plaintext string (uses only printable 7bit chars)
8
+ *
9
+ * When isParam is set the value is destined for a header parameter, so HT, CR and LF
10
+ * are not plaintext either: a header parameter has no way to carry them. HT is a valid
11
+ * fold point, so folding and unfolding a header would rewrite it as a space, and CR/LF
12
+ * cannot appear in a header value at all. DEL is neither a token character nor qtext,
13
+ * so it can not be carried bare or quoted. Such values have to go through the rfc2231
14
+ * parameter continuation encoding instead, the same way a quote already does.
15
+ *
16
+ * @param value String to be tested
17
+ * @param [isParam] Set to true if the value is a header parameter value
18
+ * @returns true if it is a plaintext string
19
+ */
20
+ export function isPlainText(value, isParam) {
21
+ const re = isParam ? /[\x00-\x1f\x7f"\u0080-\uFFFF]/ : /[\x00-\x08\x0b\x0c\x0e-\x1f\u0080-\uFFFF]/;
22
+ return typeof value === 'string' && !re.test(value);
23
+ }
24
+ /**
25
+ * Wraps a value into a quoted-string. Inside one a quote would end the string early
26
+ * and a backslash would escape whatever follows it, so both go out as quoted-pairs.
27
+ *
28
+ * @param value String to be quoted
29
+ * @returns The value as a quoted-string, quotes included
30
+ */
31
+ export function quoteString(value) {
32
+ return '"' + (value || '').toString().replace(/["\\]/g, '\\$&') + '"';
33
+ }
34
+ /**
35
+ * Checks if a multi line string containes lines longer than the selected value.
36
+ *
37
+ * Useful when detecting if a mail message needs any processing at all:
38
+ * if only plaintext characters are used and lines are short, then there is
39
+ * no need to encode the values in any way. If the value is plaintext but has
40
+ * longer lines then allowed, then use format=flowed
41
+ *
42
+ * @param str Multi line string to check
43
+ * @param lineLength Max line length to check for
44
+ * @returns Returns true if there is at least one line longer than lineLength chars
45
+ */
46
+ export function hasLongerLines(str, lineLength) {
47
+ if (str.length > 128 * 1024) {
48
+ // do not test strings longer than 128kB
49
+ return true;
50
+ }
51
+ return new RegExp('^.{' + (lineLength + 1) + ',}', 'm').test(str);
52
+ }
53
+ /**
54
+ * Encodes a string or an Buffer to an UTF-8 MIME Word (rfc2047)
55
+ *
56
+ * @param data String to be encoded
57
+ * @param mimeWordEncoding='Q' Encoding for the mime word, either Q or B
58
+ * @param [maxLength=0] If set, split mime words into several chunks if needed
59
+ * @return Single or several mime words joined together
60
+ */
61
+ export function encodeWord(data, mimeWordEncoding, maxLength) {
62
+ mimeWordEncoding = (mimeWordEncoding || 'Q').toString().toUpperCase().trim().charAt(0);
63
+ maxLength = maxLength || 0;
64
+ let encodedStr;
65
+ const toCharset = 'UTF-8';
66
+ if (maxLength && maxLength > 7 + toCharset.length) {
67
+ maxLength -= 7 + toCharset.length;
68
+ }
69
+ if (mimeWordEncoding === 'Q') {
70
+ // https://tools.ietf.org/html/rfc2047#section-5 rule (3)
71
+ encodedStr = qp.encode(data).replace(/[^a-z0-9!*+\-/=]/gi, chr => {
72
+ const ord = chr.charCodeAt(0).toString(16).toUpperCase();
73
+ if (chr === ' ') {
74
+ return '_';
75
+ }
76
+ return '=' + (ord.length === 1 ? '0' + ord : ord);
77
+ });
78
+ }
79
+ else if (mimeWordEncoding === 'B') {
80
+ // the chunking loop below splits raw text and base64 encodes each part, so a
81
+ // Buffer goes in as its UTF-8 string: handing it the base64 of the whole input
82
+ // would encode the encoding itself and decode back to base64 text
83
+ encodedStr = typeof data === 'string' ? data : data.toString('utf-8');
84
+ maxLength = maxLength ? Math.max(3, ((maxLength - (maxLength % 4)) / 4) * 3) : 0;
85
+ }
86
+ if (maxLength && (mimeWordEncoding !== 'B' ? encodedStr : base64.encode(data)).length > maxLength) {
87
+ if (mimeWordEncoding === 'Q') {
88
+ encodedStr = splitMimeEncodedString(encodedStr, maxLength).join('?= =?' + toCharset + '?' + mimeWordEncoding + '?');
89
+ }
90
+ else {
91
+ // RFC2047 6.3 (2) states that encoded-word must include an integral number of characters, so no chopping unicode sequences
92
+ const parts = [];
93
+ let lpart = '';
94
+ for (let i = 0, len = encodedStr.length; i < len; i++) {
95
+ let chr = encodedStr.charAt(i);
96
+ if (/[\ud800-\udbff]/.test(chr) && /[\udc00-\udfff]/.test(encodedStr.charAt(i + 1))) {
97
+ // leading surrogate, so add the trailing surrogate as well
98
+ // an unpaired one must not swallow the next unit, that would destroy
99
+ // a valid pair following it
100
+ chr += encodedStr.charAt(++i);
101
+ }
102
+ // check if we can add this character to the existing string
103
+ // without breaking byte length limit
104
+ if (Buffer.byteLength(lpart + chr) <= maxLength || i === 0) {
105
+ lpart += chr;
106
+ }
107
+ else {
108
+ // we hit the length limit, so push the existing string and start over
109
+ parts.push(base64.encode(lpart));
110
+ lpart = chr;
111
+ }
112
+ }
113
+ if (lpart) {
114
+ parts.push(base64.encode(lpart));
115
+ }
116
+ if (parts.length > 1) {
117
+ encodedStr = parts.join('?= =?' + toCharset + '?' + mimeWordEncoding + '?');
118
+ }
119
+ else {
120
+ encodedStr = parts.join('');
121
+ }
122
+ }
123
+ }
124
+ else if (mimeWordEncoding === 'B') {
125
+ encodedStr = base64.encode(data);
126
+ }
127
+ return '=?' + toCharset + '?' + mimeWordEncoding + '?' + encodedStr + (encodedStr.substr(-2) === '?=' ? '' : '?=');
128
+ }
129
+ /**
130
+ * Finds word sequences with non ascii text and converts these to mime words
131
+ *
132
+ * @param value String to be encoded
133
+ * @param mimeWordEncoding='Q' Encoding for the mime word, either Q or B
134
+ * @param [maxLength=0] If set, split mime words into several chunks if needed
135
+ * @param [encodeAll=false] If true and the value needs encoding then encodes entire string, not just the smallest match
136
+ * @return String with possible mime words
137
+ */
138
+ export function encodeWords(value, mimeWordEncoding, maxLength, encodeAll) {
139
+ maxLength = maxLength || 0;
140
+ // find first word with a non-printable ascii or special symbol in it
141
+ const firstMatch = value.match(/(?:^|\s)([^\s]*["\u0080-\uFFFF])/);
142
+ if (!firstMatch) {
143
+ return value;
144
+ }
145
+ if (encodeAll) {
146
+ // if it is requested to encode everything or the string contains something that resebles encoded word, then encode everything
147
+ return encodeWord(value, mimeWordEncoding, maxLength);
148
+ }
149
+ // find the last word with a non-printable ascii in it
150
+ const lastMatch = value.match(/(["\u0080-\uFFFF][^\s]*)[^"\u0080-\uFFFF]*$/);
151
+ if (!lastMatch) {
152
+ // should not happen
153
+ return value;
154
+ }
155
+ const startIndex = firstMatch.index +
156
+ (firstMatch[0].match(/[^\s]/) || {
157
+ index: 0
158
+ }).index;
159
+ const endIndex = lastMatch.index + (lastMatch[1] || '').length;
160
+ return ((startIndex ? value.substr(0, startIndex) : '') +
161
+ encodeWord(value.substring(startIndex, endIndex), mimeWordEncoding || 'Q', maxLength) +
162
+ (endIndex < value.length ? value.substr(endIndex) : ''));
163
+ }
164
+ /**
165
+ * Joins parsed header value together as 'value; param1=value1; param2=value2'
166
+ * PS: We are following RFC 822 for the list of special characters that we need to keep in quotes.
167
+ * Refer: https://www.w3.org/Protocols/rfc1341/4_Content-Type.html
168
+ * @param structured Parsed header value
169
+ * @return joined header value
170
+ */
171
+ export function buildHeaderValue(structured) {
172
+ const paramsArray = [];
173
+ Object.keys(structured.params || {}).forEach(key => {
174
+ // filename might include unicode characters so it is a special case
175
+ // other values probably do not
176
+ const value = structured.params[key];
177
+ // a parameter name is a token too and it is emitted without any quoting around it
178
+ const param = key.replace(/[\x00-\x1f\x7f]/g, '');
179
+ if (!isPlainText(value, true) || value.length >= 75) {
180
+ buildHeaderParam(param, value, 50).forEach(encodedParam => {
181
+ if (!/[\s"\\;:/=(),<>@[\]?]|^[-']|'$/.test(encodedParam.value) || encodedParam.key.substr(-1) === '*') {
182
+ paramsArray.push(encodedParam.key + '=' + encodedParam.value);
183
+ }
184
+ else {
185
+ paramsArray.push(encodedParam.key + '=' + JSON.stringify(encodedParam.value));
186
+ }
187
+ });
188
+ }
189
+ else if (!value.length || /[\s'"\\;:/=(),<>@[\]?]|^-/.test(value)) {
190
+ // a parameter value is a token or a quoted-string and a token is never empty, so
191
+ // a valueless parameter such as the 'flag' of 'multipart/mixed; flag; boundary=b'
192
+ // goes out as 'flag=""' rather than as the 'flag=' that parses as neither
193
+ paramsArray.push(param + '=' + JSON.stringify(value));
194
+ }
195
+ else {
196
+ paramsArray.push(param + '=' + value);
197
+ }
198
+ });
199
+ // the value ahead of the parameters is a token, it has no way to carry a control
200
+ // char or DEL and there is no quoting construct around it to escape one into
201
+ const value = typeof structured.value === 'string' ? structured.value.replace(/[\x00-\x1f\x7f]/g, '') : structured.value;
202
+ return value + (paramsArray.length ? '; ' + paramsArray.join('; ') : '');
203
+ }
204
+ /**
205
+ * Encodes a string or an Buffer to an UTF-8 Parameter Value Continuation encoding (rfc2231)
206
+ * Useful for splitting long parameter values.
207
+ *
208
+ * For example
209
+ * title="unicode string"
210
+ * becomes
211
+ * title*0*=utf-8''unicode
212
+ * title*1*=%20string
213
+ *
214
+ * @param key Parameter name the generated keys are built from, for example title
215
+ * @param data String to be encoded
216
+ * @param [maxLength=50] Max length for generated chunks
217
+ * @return A list of encoded keys and headers
218
+ */
219
+ export function buildHeaderParam(key, data, maxLength) {
220
+ const list = [];
221
+ let encodedStr = typeof data === 'string' ? data : (data || '').toString();
222
+ let chr;
223
+ let line;
224
+ let startPos = 0;
225
+ let i, len;
226
+ maxLength = maxLength || 50;
227
+ // process ascii only text
228
+ if (isPlainText(data, true)) {
229
+ // check if conversion is even needed
230
+ if (encodedStr.length <= maxLength) {
231
+ return [
232
+ {
233
+ key,
234
+ value: encodedStr
235
+ }
236
+ ];
237
+ }
238
+ encodedStr = encodedStr.replace(new RegExp('.{' + maxLength + '}', 'g'), str => {
239
+ list.push({
240
+ line: str
241
+ });
242
+ return '';
243
+ });
244
+ if (encodedStr) {
245
+ list.push({
246
+ line: encodedStr
247
+ });
248
+ }
249
+ }
250
+ else {
251
+ if (/[\uD800-\uDBFF]/.test(encodedStr)) {
252
+ // string containts surrogate pairs, so normalize it to an array of bytes
253
+ const encodedStrArr = [];
254
+ for (i = 0, len = encodedStr.length; i < len; i++) {
255
+ chr = encodedStr.charAt(i);
256
+ if (/[\ud800-\udbff]/.test(chr) && /[\udc00-\udfff]/.test(encodedStr.charAt(i + 1))) {
257
+ // an unpaired leading surrogate must not consume the next unit, that
258
+ // would tear apart a valid pair following it
259
+ chr += encodedStr.charAt(i + 1);
260
+ encodedStrArr.push(chr);
261
+ i++;
262
+ }
263
+ else {
264
+ encodedStrArr.push(chr);
265
+ }
266
+ }
267
+ encodedStr = encodedStrArr;
268
+ }
269
+ // first line includes the charset and language info and needs to be encoded
270
+ // even if it does not contain any unicode characters
271
+ line = "utf-8''";
272
+ let encoded = true;
273
+ startPos = 0;
274
+ // process text with unicode or special chars
275
+ for (i = 0, len = encodedStr.length; i < len; i++) {
276
+ chr = encodedStr[i];
277
+ if (encoded) {
278
+ chr = safeEncodeURIComponent(chr);
279
+ }
280
+ else {
281
+ // try to urlencode current char
282
+ chr = chr === ' ' ? chr : safeEncodeURIComponent(chr);
283
+ // By default it is not required to encode a line, the need
284
+ // only appears when the string contains unicode or special chars
285
+ // in this case we start processing the line over and encode all chars
286
+ if (chr !== encodedStr[i]) {
287
+ // Check if it is even possible to add the encoded char to the line
288
+ // If not, there is no reason to use this line, just push it to the list
289
+ // and start a new line with the char that needs encoding
290
+ if ((safeEncodeURIComponent(line) + chr).length >= maxLength) {
291
+ list.push({
292
+ line,
293
+ encoded
294
+ });
295
+ // the line we start here holds an encoded char, so it has to be
296
+ // flagged as one. otherwise it gets an unstarred continuation key
297
+ // and a receiver reads the percent escapes as literal text
298
+ line = '';
299
+ encoded = true;
300
+ }
301
+ else {
302
+ encoded = true;
303
+ i = startPos;
304
+ line = '';
305
+ continue;
306
+ }
307
+ }
308
+ }
309
+ // if the line is already too long, push it to the list and start a new one
310
+ if ((line + chr).length >= maxLength) {
311
+ list.push({
312
+ line,
313
+ encoded
314
+ });
315
+ line = chr = encodedStr[i] === ' ' ? ' ' : safeEncodeURIComponent(encodedStr[i]);
316
+ if (chr === encodedStr[i]) {
317
+ encoded = false;
318
+ startPos = i - 1;
319
+ }
320
+ else {
321
+ encoded = true;
322
+ }
323
+ }
324
+ else {
325
+ line += chr;
326
+ }
327
+ }
328
+ if (line) {
329
+ list.push({
330
+ line,
331
+ encoded
332
+ });
333
+ }
334
+ }
335
+ return list.map((item, i) => ({
336
+ // encoded lines: {name}*{part}*
337
+ // unencoded lines: {name}*{part}
338
+ // if any line needs to be encoded then the first line (part==0) is always encoded
339
+ key: key + '*' + i + (item.encoded ? '*' : ''),
340
+ value: item.line
341
+ }));
342
+ }
343
+ /**
344
+ * An RFC 2045 token: printable ASCII without SPACE, the control characters, DEL and the
345
+ * tspecials. A charset name is one, and the name a continuation carries is written into
346
+ * the encoded word the parameter value becomes, so it is checked against this before it
347
+ * goes in. Whitespace used to come off it only because the value was trimmed first.
348
+ */
349
+ const TOKEN = /^[^\x00-\x20\x7f()<>@,;:\\"/[\]?=]+$/;
350
+ /**
351
+ * Whether a string can be a header parameter name.
352
+ *
353
+ * A parameter name is a token, so it is never empty. A "__proto__" name would target the
354
+ * prototype chain of the params object instead of an own property of it and read back as
355
+ * Object.prototype, so it is no name either.
356
+ *
357
+ * @param name Candidate parameter name, already lowercased
358
+ * @return true when the name can be used
359
+ */
360
+ function _isParamName(name) {
361
+ return !!name && !isProtoKey(name);
362
+ }
363
+ /**
364
+ * Parses a header value with key=value arguments into a structured
365
+ * object.
366
+ *
367
+ * parseHeaderValue('content-type: text/plain; CHARSET='UTF-8'') ->
368
+ * {
369
+ * 'value': 'text/plain',
370
+ * 'params': {
371
+ * 'charset': 'UTF-8'
372
+ * }
373
+ * }
374
+ *
375
+ * @param str Header value
376
+ * @return Header value as a parsed structure
377
+ */
378
+ export function parseHeaderValue(str) {
379
+ const response = {
380
+ value: '',
381
+ params: {}
382
+ };
383
+ // A duplicated parameter resolves to its first occurrence, the way a duplicated header
384
+ // does. Letting the last one win disagrees with the receivers that take the first, and
385
+ // the two readings of 'boundary="b"; boundary="c"' name different delimiters. The
386
+ // continuation join below is the only writer of the name it builds, so it tests the
387
+ // name with _isParamName directly rather than taking that rule along from here.
388
+ const setParam = (name, value) => {
389
+ name = name.toLowerCase();
390
+ if (_isParamName(name) && !Object.prototype.hasOwnProperty.call(response.params, name)) {
391
+ response.params[name] = value;
392
+ }
393
+ };
394
+ let key = false;
395
+ let value = '';
396
+ let stage = 'value';
397
+ let quote = false;
398
+ let escaped = false;
399
+ let chr;
400
+ // Whitespace seen outside a quoted string is held back until a significant character
401
+ // follows it, so the whitespace around a value is dropped without trimming spaces the
402
+ // sender quoted on purpose. Trimming the stored value instead loses the trailing space
403
+ // of 'filename*0="Annual Report "', which the next continuation section is appended to.
404
+ let pendingSpace = '';
405
+ let quoteClosed = false;
406
+ // Whitespace ahead of the first character of a value is padding and is dropped, the
407
+ // whitespace between two characters of it is content
408
+ const flushSpace = () => {
409
+ if (value.length) {
410
+ value += pendingSpace;
411
+ }
412
+ pendingSpace = '';
413
+ };
414
+ const addChr = (c) => {
415
+ flushSpace();
416
+ value += c;
417
+ };
418
+ const takeValue = () => {
419
+ const taken = value;
420
+ value = '';
421
+ pendingSpace = '';
422
+ quoteClosed = false;
423
+ return taken;
424
+ };
425
+ const storeValue = () => {
426
+ const taken = takeValue();
427
+ if (key === false) {
428
+ response.value = taken;
429
+ }
430
+ else {
431
+ setParam(key, taken);
432
+ }
433
+ };
434
+ // A parameter name with no '=' is a valueless parameter, not the start of the next one.
435
+ // Without this the name keeps growing across the ';' and swallows whatever follows, which
436
+ // is how 'multipart/mixed; flag; boundary="AAA"' lost its boundary to a parameter named
437
+ // 'flag; boundary' and left the node declaring the generated boundary beside the asked
438
+ // for one, so a receiver reading the first of the two found no delimiter it matched.
439
+ const storeEmptyKey = () => {
440
+ setParam(takeValue().trim(), '');
441
+ };
442
+ for (let i = 0, len = str.length; i < len; i++) {
443
+ chr = str.charAt(i);
444
+ if (stage === 'key') {
445
+ if (chr === '=') {
446
+ key = takeValue().trim();
447
+ stage = 'value';
448
+ continue;
449
+ }
450
+ if (chr === ';') {
451
+ storeEmptyKey();
452
+ continue;
453
+ }
454
+ value += chr;
455
+ }
456
+ else {
457
+ if (quoteClosed && chr !== ';') {
458
+ // Nothing behind a closed quoted string reaches the value. RFC 2045 says a
459
+ // parameter value is a token or a quoted string and not both, so what follows
460
+ // one is junk and only the ';' that ends the parameter still counts. Tested
461
+ // ahead of the branches rather than beside the append at the foot of them,
462
+ // where each branch above was a way around it: a second '"' reopened quoting
463
+ // and swallowed the rest of the header, so 'boundary="AAA" "; boundary=BBB"'
464
+ // read as a single boundary of 'AAA ', and the junk of
465
+ // 'boundary="AAA" (unterminated comment' still joined the declared boundary
466
+ // through the escape branch. quoteClosed is only ever set while no quote is
467
+ // open, and this is what keeps one from being opened afterwards.
468
+ escaped = false;
469
+ continue;
470
+ }
471
+ if (escaped) {
472
+ addChr(chr);
473
+ }
474
+ else if (quote && chr === '\\') {
475
+ // a backslash only escapes inside a quoted string, everywhere else it is an
476
+ // ordinary character. Treating it as an escape turns the parameter value
477
+ // 'C:\Users\me\report.txt' into 'C:Usersmereport.txt'
478
+ escaped = true;
479
+ continue;
480
+ }
481
+ else if (quote && chr === quote) {
482
+ quote = false;
483
+ quoteClosed = true;
484
+ }
485
+ else if (!quote && chr === '"') {
486
+ quote = chr;
487
+ flushSpace();
488
+ }
489
+ else if (!quote && chr === ';') {
490
+ storeValue();
491
+ stage = 'key';
492
+ }
493
+ else if (!quote && (chr === ' ' || chr === '\t')) {
494
+ pendingSpace += chr;
495
+ }
496
+ else {
497
+ addChr(chr);
498
+ }
499
+ escaped = false;
500
+ }
501
+ }
502
+ if (stage === 'value') {
503
+ storeValue();
504
+ }
505
+ else {
506
+ // a key with no value, as in 'Header-Key: somevalue; key=value; emptykey'
507
+ storeEmptyKey();
508
+ }
509
+ // handle parameter value continuations
510
+ // https://tools.ietf.org/html/rfc2231#section-3
511
+ // Sections are collected in a list and ordered below rather than written into an array
512
+ // at their own section number. An index write makes the array as long as the number the
513
+ // header asked for, and the join that follows walks all of it, so the 55 byte value
514
+ // "attachment; filename*0*=utf-8''a; filename*4000000000=b" held a core for over two
515
+ // minutes.
516
+ const continuations = new Map();
517
+ Object.keys(response.params).forEach(key => {
518
+ const match = key.match(/(\*(\d+)|\*(\d+)\*|\*)$/);
519
+ if (!match) {
520
+ // not a continuation parameter, there is nothing to join
521
+ return;
522
+ }
523
+ const actualKey = key.substr(0, match.index);
524
+ const nr = Number(match[2] || match[3]) || 0;
525
+ // RFC 2231 section 4.1: only a section whose name ends in '*' is percent encoded
526
+ const encoded = match[0].substr(-1) === '*';
527
+ // remove the old reference
528
+ let value = response.params[key];
529
+ delete response.params[key];
530
+ if (!_isParamName(actualKey)) {
531
+ // the joined value can not be written back under this name. It is empty when the
532
+ // continuation suffix was all there was of it, as in the bare '*' of 'text/plain; a;*'
533
+ return;
534
+ }
535
+ let continuation = continuations.get(actualKey);
536
+ if (!continuation) {
537
+ continuation = { charset: false, sections: [] };
538
+ continuations.set(actualKey, continuation);
539
+ }
540
+ const charsetMatch = nr === 0 && encoded ? value.match(/^([^']*)'[^']*'(.*)$/) : null;
541
+ if (charsetMatch) {
542
+ // the charset is a token, and anything else named as one is no charset a consumer
543
+ // could resolve, so it reads as the unnamed case rather than being carried into
544
+ // the encoded word below. A "\r\n" of a prefix would otherwise reach a consumer
545
+ // of the parsed value as the charset of a word that no decoder can act on
546
+ continuation.charset = TOKEN.test(charsetMatch[1]) ? charsetMatch[1] : 'iso-8859-1';
547
+ value = charsetMatch[2];
548
+ }
549
+ continuation.sections.push({ nr, value, encoded });
550
+ });
551
+ // concatenate split rfc2231 strings and convert encoded strings to mime encoded words
552
+ continuations.forEach((continuation, key) => {
553
+ if (Object.prototype.hasOwnProperty.call(response.params, key)) {
554
+ // The same name was also given as a plain parameter, which the starred keys were
555
+ // just deleted from around, so this write would be the only one in the function
556
+ // to override a name already taken. 'filename=plain.txt; filename*0=evil.txt'
557
+ // resolves to the plain parameter either way round, so the reading does not come
558
+ // down to which of the two spellings the sender put first
559
+ return;
560
+ }
561
+ continuation.sections.sort((a, b) => a.nr - b.nr);
562
+ if (!continuation.charset) {
563
+ // nothing said which charset the percent escapes of an encoded section are in,
564
+ // so every section is passed on as the text it already is
565
+ response.params[key] = continuation.sections.map(section => section.value).join('');
566
+ return;
567
+ }
568
+ // convert "%AB" to "=?charset?Q?=AB?="
569
+ response.params[key] = '=?' + continuation.charset + '?Q?' + continuation.sections.map(_encodeContinuationSection).join('') + '?=';
570
+ });
571
+ return response;
572
+ }
573
+ /**
574
+ * Renders one parameter value continuation section as the payload of a Q encoded word.
575
+ *
576
+ * A section whose name ends in '*' is percent encoded and its escapes carry the bytes of
577
+ * the value, so they only have to be rewritten into the "=AB" spelling a Q encoded word
578
+ * uses. A section without the '*' is literal text (RFC 2231 section 4.1), so its '%' is a
579
+ * '%' and is escaped along with the characters a Q encoded word can not carry bare.
580
+ * Decoding a literal section invents bytes that never appeared on the wire: it is how the
581
+ * value 'filename*0*=utf-8''safe; filename*1=%2F..%2F..%2Fetc%2Fpasswd' was emitted as a
582
+ * filename every receiving client reads back as 'safe/../../etc/passwd'.
583
+ *
584
+ * @param section One collected continuation section
585
+ * @return The section as Q encoded word payload
586
+ */
587
+ function _encodeContinuationSection(section) {
588
+ const specials = section.encoded ? /[=?_\s]/g : /[=?_\s%]/g;
589
+ return (section.value
590
+ // fix invalidly encoded chars
591
+ .replace(specials, s => {
592
+ const c = s.charCodeAt(0).toString(16);
593
+ if (s === ' ') {
594
+ return '_';
595
+ }
596
+ return '%' + (c.length < 2 ? '0' : '') + c;
597
+ })
598
+ // change from urlencoding to percent encoding
599
+ .replace(/%/g, '='));
600
+ }
601
+ /**
602
+ * Returns file extension for a content type string. If no suitable extensions
603
+ * are found, 'bin' is used as the default extension
604
+ *
605
+ * @param mimeType Content type to be checked for
606
+ * @return File extension
607
+ */
608
+ export function detectExtension(mimeType) {
609
+ return mimeTypes.detectExtension(mimeType);
610
+ }
611
+ /**
612
+ * Returns content type for a file extension. If no suitable content types
613
+ * are found, 'application/octet-stream' is used as the default content type
614
+ *
615
+ * @param extension Extension to be checked for
616
+ * @return File extension
617
+ */
618
+ export function detectMimeType(extension) {
619
+ return mimeTypes.detectMimeType(extension);
620
+ }
621
+ /**
622
+ * Folds long lines, useful for folding header lines (afterSpace=false) and
623
+ * flowed text (afterSpace=true)
624
+ *
625
+ * @param str String to be folded
626
+ * @param [lineLength=76] Maximum length of a line
627
+ * @param afterSpace If true, leave a space in th end of a line
628
+ * @return String with folded lines
629
+ */
630
+ export function foldLines(str, lineLength, afterSpace) {
631
+ str = (str || '').toString();
632
+ lineLength = lineLength || 76;
633
+ let pos = 0;
634
+ const len = str.length;
635
+ let result = '';
636
+ let line, match;
637
+ while (pos < len) {
638
+ line = str.substr(pos, lineLength);
639
+ if (line.length < lineLength) {
640
+ result += line;
641
+ break;
642
+ }
643
+ if ((match = line.match(/^[^\n\r]*(\r?\n|\r)/))) {
644
+ line = match[0];
645
+ result += line;
646
+ pos += line.length;
647
+ continue;
648
+ }
649
+ else if ((match = line.match(/(\s+)[^\s]*$/)) && match[0].length - (afterSpace ? (match[1] || '').length : 0) < line.length) {
650
+ line = line.substr(0, line.length - (match[0].length - (afterSpace ? (match[1] || '').length : 0)));
651
+ }
652
+ else if ((match = str.substr(pos + line.length).match(/^[^\s]+(\s*)/))) {
653
+ line = line + match[0].substr(0, match[0].length - (!afterSpace ? (match[1] || '').length : 0));
654
+ }
655
+ result += line;
656
+ pos += line.length;
657
+ if (pos < len) {
658
+ result += '\r\n';
659
+ }
660
+ }
661
+ return result;
662
+ }
663
+ /**
664
+ * Splits a mime encoded string. Needed for dividing mime words into smaller chunks
665
+ *
666
+ * @param str Mime encoded string to be split up
667
+ * @param maxlen Maximum length of characters for one part (minimum 12)
668
+ * @return Split string
669
+ */
670
+ export function splitMimeEncodedString(str, maxlen) {
671
+ const lines = [];
672
+ let curLine, fallbackLine, match, chr, done;
673
+ // require at least 12 symbols to fit possible 4 octet UTF-8 sequences
674
+ maxlen = Math.max(maxlen || 0, 12);
675
+ while (str.length) {
676
+ curLine = str.substr(0, maxlen);
677
+ // move incomplete escaped char back to main
678
+ if ((match = curLine.match(/[=][0-9A-F]?$/i))) {
679
+ curLine = curLine.substr(0, match.index);
680
+ }
681
+ // Malformed input (a run of stray UTF-8 continuation bytes) has no split point
682
+ // that keeps a character sequence whole, so the loop below walks back to an
683
+ // empty line looking for one. Keep the widest chunk that at least does not cut
684
+ // a "=XX" escape in half, so the part stays a decodable encoded word.
685
+ fallbackLine = curLine.length ? curLine : str.substr(0, maxlen);
686
+ done = false;
687
+ while (!done && curLine.length) {
688
+ done = true;
689
+ // check if not middle of a unicode char sequence
690
+ if ((match = str.substr(curLine.length).match(/^[=]([0-9A-F]{2})/i))) {
691
+ chr = parseInt(match[1], 16);
692
+ // invalid sequence, move one char back anc recheck
693
+ if (chr < 0xc2 && chr > 0x7f) {
694
+ curLine = curLine.substr(0, curLine.length - 3);
695
+ done = false;
696
+ }
697
+ }
698
+ }
699
+ if (!curLine.length) {
700
+ curLine = fallbackLine;
701
+ }
702
+ lines.push(curLine);
703
+ str = str.substr(curLine.length);
704
+ }
705
+ return lines;
706
+ }
707
+ export function encodeURICharComponent(chr) {
708
+ let res = '';
709
+ let ord = chr.charCodeAt(0).toString(16).toUpperCase();
710
+ if (ord.length % 2) {
711
+ ord = '0' + ord;
712
+ }
713
+ if (ord.length > 2) {
714
+ for (let i = 0, len = ord.length / 2; i < len; i++) {
715
+ res += '%' + ord.substr(i, 2);
716
+ }
717
+ }
718
+ else {
719
+ res += '%' + ord;
720
+ }
721
+ return res;
722
+ }
723
+ export function safeEncodeURIComponent(str) {
724
+ str = (str || '').toString();
725
+ try {
726
+ // might throw if we try to encode invalid sequences, eg. partial emoji
727
+ str = encodeURIComponent(str);
728
+ }
729
+ catch (_E) {
730
+ // an unpaired surrogate has no utf-8 representation, so run the value through a
731
+ // utf-8 roundtrip to get the same U+FFFD every other encoder here produces and
732
+ // retry. the value must never come back unencoded, it goes into a header parameter
733
+ // where a bare quote or semicolon would break it out into a parameter of its own
734
+ str = encodeURIComponent(Buffer.from(str, 'utf-8').toString('utf-8'));
735
+ }
736
+ // ensure chars that are not handled by encodeURICompent are converted as well
737
+ return str.replace(/[\x00-\x1F *'()<>@,;:\\"[\]?=\u007F-\uFFFF]/g, chr => encodeURICharComponent(chr));
738
+ }