string-punycode-to-ascii.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. 'use strict';
  2. // based on https://github.com/bestiejs/punycode.js/blob/master/punycode.js
  3. var global = require('../internals/global');
  4. var uncurryThis = require('../internals/function-uncurry-this');
  5. var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
  6. var base = 36;
  7. var tMin = 1;
  8. var tMax = 26;
  9. var skew = 38;
  10. var damp = 700;
  11. var initialBias = 72;
  12. var initialN = 128; // 0x80
  13. var delimiter = '-'; // '\x2D'
  14. var regexNonASCII = /[^\0-\u007E]/; // non-ASCII chars
  15. var regexSeparators = /[.\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
  16. var OVERFLOW_ERROR = 'Overflow: input needs wider integers to process';
  17. var baseMinusTMin = base - tMin;
  18. var RangeError = global.RangeError;
  19. var exec = uncurryThis(regexSeparators.exec);
  20. var floor = Math.floor;
  21. var fromCharCode = String.fromCharCode;
  22. var charCodeAt = uncurryThis(''.charCodeAt);
  23. var join = uncurryThis([].join);
  24. var push = uncurryThis([].push);
  25. var replace = uncurryThis(''.replace);
  26. var split = uncurryThis(''.split);
  27. var toLowerCase = uncurryThis(''.toLowerCase);
  28. /**
  29. * Creates an array containing the numeric code points of each Unicode
  30. * character in the string. While JavaScript uses UCS-2 internally,
  31. * this function will convert a pair of surrogate halves (each of which
  32. * UCS-2 exposes as separate characters) into a single code point,
  33. * matching UTF-16.
  34. */
  35. var ucs2decode = function (string) {
  36. var output = [];
  37. var counter = 0;
  38. var length = string.length;
  39. while (counter < length) {
  40. var value = charCodeAt(string, counter++);
  41. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  42. // It's a high surrogate, and there is a next character.
  43. var extra = charCodeAt(string, counter++);
  44. if ((extra & 0xFC00) == 0xDC00) { // Low surrogate.
  45. push(output, ((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  46. } else {
  47. // It's an unmatched surrogate; only append this code unit, in case the
  48. // next code unit is the high surrogate of a surrogate pair.
  49. push(output, value);
  50. counter--;
  51. }
  52. } else {
  53. push(output, value);
  54. }
  55. }
  56. return output;
  57. };
  58. /**
  59. * Converts a digit/integer into a basic code point.
  60. */
  61. var digitToBasic = function (digit) {
  62. // 0..25 map to ASCII a..z or A..Z
  63. // 26..35 map to ASCII 0..9
  64. return digit + 22 + 75 * (digit < 26);
  65. };
  66. /**
  67. * Bias adaptation function as per section 3.4 of RFC 3492.
  68. * https://tools.ietf.org/html/rfc3492#section-3.4
  69. */
  70. var adapt = function (delta, numPoints, firstTime) {
  71. var k = 0;
  72. delta = firstTime ? floor(delta / damp) : delta >> 1;
  73. delta += floor(delta / numPoints);
  74. while (delta > baseMinusTMin * tMax >> 1) {
  75. delta = floor(delta / baseMinusTMin);
  76. k += base;
  77. }
  78. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  79. };
  80. /**
  81. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  82. * Punycode string of ASCII-only symbols.
  83. */
  84. var encode = function (input) {
  85. var output = [];
  86. // Convert the input in UCS-2 to an array of Unicode code points.
  87. input = ucs2decode(input);
  88. // Cache the length.
  89. var inputLength = input.length;
  90. // Initialize the state.
  91. var n = initialN;
  92. var delta = 0;
  93. var bias = initialBias;
  94. var i, currentValue;
  95. // Handle the basic code points.
  96. for (i = 0; i < input.length; i++) {
  97. currentValue = input[i];
  98. if (currentValue < 0x80) {
  99. push(output, fromCharCode(currentValue));
  100. }
  101. }
  102. var basicLength = output.length; // number of basic code points.
  103. var handledCPCount = basicLength; // number of code points that have been handled;
  104. // Finish the basic string with a delimiter unless it's empty.
  105. if (basicLength) {
  106. push(output, delimiter);
  107. }
  108. // Main encoding loop:
  109. while (handledCPCount < inputLength) {
  110. // All non-basic code points < n have been handled already. Find the next larger one:
  111. var m = maxInt;
  112. for (i = 0; i < input.length; i++) {
  113. currentValue = input[i];
  114. if (currentValue >= n && currentValue < m) {
  115. m = currentValue;
  116. }
  117. }
  118. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>, but guard against overflow.
  119. var handledCPCountPlusOne = handledCPCount + 1;
  120. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  121. throw RangeError(OVERFLOW_ERROR);
  122. }
  123. delta += (m - n) * handledCPCountPlusOne;
  124. n = m;
  125. for (i = 0; i < input.length; i++) {
  126. currentValue = input[i];
  127. if (currentValue < n && ++delta > maxInt) {
  128. throw RangeError(OVERFLOW_ERROR);
  129. }
  130. if (currentValue == n) {
  131. // Represent delta as a generalized variable-length integer.
  132. var q = delta;
  133. var k = base;
  134. while (true) {
  135. var t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  136. if (q < t) break;
  137. var qMinusT = q - t;
  138. var baseMinusT = base - t;
  139. push(output, fromCharCode(digitToBasic(t + qMinusT % baseMinusT)));
  140. q = floor(qMinusT / baseMinusT);
  141. k += base;
  142. }
  143. push(output, fromCharCode(digitToBasic(q)));
  144. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  145. delta = 0;
  146. handledCPCount++;
  147. }
  148. }
  149. delta++;
  150. n++;
  151. }
  152. return join(output, '');
  153. };
  154. module.exports = function (input) {
  155. var encoded = [];
  156. var labels = split(replace(toLowerCase(input), regexSeparators, '\u002E'), '.');
  157. var i, label;
  158. for (i = 0; i < labels.length; i++) {
  159. label = labels[i];
  160. push(encoded, exec(regexNonASCII, label) ? 'xn--' + encode(label) : label);
  161. }
  162. return join(encoded, '.');
  163. };