Uri.js 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319
  1. /* This file is automatically rebuilt by the Cesium build process. */
  2. import { c as createCommonjsModule, a as commonjsGlobal } from './_commonjsHelpers-3aae1032.js';
  3. var punycode = createCommonjsModule(function (module, exports) {
  4. (function(root) {
  5. /** Detect free variables */
  6. var freeExports = exports &&
  7. !exports.nodeType && exports;
  8. var freeModule = module &&
  9. !module.nodeType && module;
  10. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal;
  11. if (
  12. freeGlobal.global === freeGlobal ||
  13. freeGlobal.window === freeGlobal ||
  14. freeGlobal.self === freeGlobal
  15. ) {
  16. root = freeGlobal;
  17. }
  18. /**
  19. * The `punycode` object.
  20. * @name punycode
  21. * @type Object
  22. */
  23. var punycode,
  24. /** Highest positive signed 32-bit float value */
  25. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  26. /** Bootstring parameters */
  27. base = 36,
  28. tMin = 1,
  29. tMax = 26,
  30. skew = 38,
  31. damp = 700,
  32. initialBias = 72,
  33. initialN = 128, // 0x80
  34. delimiter = '-', // '\x2D'
  35. /** Regular expressions */
  36. regexPunycode = /^xn--/,
  37. regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
  38. regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
  39. /** Error messages */
  40. errors = {
  41. 'overflow': 'Overflow: input needs wider integers to process',
  42. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  43. 'invalid-input': 'Invalid input'
  44. },
  45. /** Convenience shortcuts */
  46. baseMinusTMin = base - tMin,
  47. floor = Math.floor,
  48. stringFromCharCode = String.fromCharCode,
  49. /** Temporary variable */
  50. key;
  51. /*--------------------------------------------------------------------------*/
  52. /**
  53. * A generic error utility function.
  54. * @private
  55. * @param {String} type The error type.
  56. * @returns {Error} Throws a `RangeError` with the applicable error message.
  57. */
  58. function error(type) {
  59. throw new RangeError(errors[type]);
  60. }
  61. /**
  62. * A generic `Array#map` utility function.
  63. * @private
  64. * @param {Array} array The array to iterate over.
  65. * @param {Function} callback The function that gets called for every array
  66. * item.
  67. * @returns {Array} A new array of values returned by the callback function.
  68. */
  69. function map(array, fn) {
  70. var length = array.length;
  71. var result = [];
  72. while (length--) {
  73. result[length] = fn(array[length]);
  74. }
  75. return result;
  76. }
  77. /**
  78. * A simple `Array#map`-like wrapper to work with domain name strings or email
  79. * addresses.
  80. * @private
  81. * @param {String} domain The domain name or email address.
  82. * @param {Function} callback The function that gets called for every
  83. * character.
  84. * @returns {Array} A new string of characters returned by the callback
  85. * function.
  86. */
  87. function mapDomain(string, fn) {
  88. var parts = string.split('@');
  89. var result = '';
  90. if (parts.length > 1) {
  91. // In email addresses, only the domain name should be punycoded. Leave
  92. // the local part (i.e. everything up to `@`) intact.
  93. result = parts[0] + '@';
  94. string = parts[1];
  95. }
  96. // Avoid `split(regex)` for IE8 compatibility. See #17.
  97. string = string.replace(regexSeparators, '\x2E');
  98. var labels = string.split('.');
  99. var encoded = map(labels, fn).join('.');
  100. return result + encoded;
  101. }
  102. /**
  103. * Creates an array containing the numeric code points of each Unicode
  104. * character in the string. While JavaScript uses UCS-2 internally,
  105. * this function will convert a pair of surrogate halves (each of which
  106. * UCS-2 exposes as separate characters) into a single code point,
  107. * matching UTF-16.
  108. * @see `punycode.ucs2.encode`
  109. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  110. * @memberOf punycode.ucs2
  111. * @name decode
  112. * @param {String} string The Unicode input string (UCS-2).
  113. * @returns {Array} The new array of code points.
  114. */
  115. function ucs2decode(string) {
  116. var output = [],
  117. counter = 0,
  118. length = string.length,
  119. value,
  120. extra;
  121. while (counter < length) {
  122. value = string.charCodeAt(counter++);
  123. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  124. // high surrogate, and there is a next character
  125. extra = string.charCodeAt(counter++);
  126. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  127. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  128. } else {
  129. // unmatched surrogate; only append this code unit, in case the next
  130. // code unit is the high surrogate of a surrogate pair
  131. output.push(value);
  132. counter--;
  133. }
  134. } else {
  135. output.push(value);
  136. }
  137. }
  138. return output;
  139. }
  140. /**
  141. * Creates a string based on an array of numeric code points.
  142. * @see `punycode.ucs2.decode`
  143. * @memberOf punycode.ucs2
  144. * @name encode
  145. * @param {Array} codePoints The array of numeric code points.
  146. * @returns {String} The new Unicode string (UCS-2).
  147. */
  148. function ucs2encode(array) {
  149. return map(array, function(value) {
  150. var output = '';
  151. if (value > 0xFFFF) {
  152. value -= 0x10000;
  153. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  154. value = 0xDC00 | value & 0x3FF;
  155. }
  156. output += stringFromCharCode(value);
  157. return output;
  158. }).join('');
  159. }
  160. /**
  161. * Converts a basic code point into a digit/integer.
  162. * @see `digitToBasic()`
  163. * @private
  164. * @param {Number} codePoint The basic numeric code point value.
  165. * @returns {Number} The numeric value of a basic code point (for use in
  166. * representing integers) in the range `0` to `base - 1`, or `base` if
  167. * the code point does not represent a value.
  168. */
  169. function basicToDigit(codePoint) {
  170. if (codePoint - 48 < 10) {
  171. return codePoint - 22;
  172. }
  173. if (codePoint - 65 < 26) {
  174. return codePoint - 65;
  175. }
  176. if (codePoint - 97 < 26) {
  177. return codePoint - 97;
  178. }
  179. return base;
  180. }
  181. /**
  182. * Converts a digit/integer into a basic code point.
  183. * @see `basicToDigit()`
  184. * @private
  185. * @param {Number} digit The numeric value of a basic code point.
  186. * @returns {Number} The basic code point whose value (when used for
  187. * representing integers) is `digit`, which needs to be in the range
  188. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  189. * used; else, the lowercase form is used. The behavior is undefined
  190. * if `flag` is non-zero and `digit` has no uppercase form.
  191. */
  192. function digitToBasic(digit, flag) {
  193. // 0..25 map to ASCII a..z or A..Z
  194. // 26..35 map to ASCII 0..9
  195. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  196. }
  197. /**
  198. * Bias adaptation function as per section 3.4 of RFC 3492.
  199. * https://tools.ietf.org/html/rfc3492#section-3.4
  200. * @private
  201. */
  202. function adapt(delta, numPoints, firstTime) {
  203. var k = 0;
  204. delta = firstTime ? floor(delta / damp) : delta >> 1;
  205. delta += floor(delta / numPoints);
  206. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  207. delta = floor(delta / baseMinusTMin);
  208. }
  209. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  210. }
  211. /**
  212. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  213. * symbols.
  214. * @memberOf punycode
  215. * @param {String} input The Punycode string of ASCII-only symbols.
  216. * @returns {String} The resulting string of Unicode symbols.
  217. */
  218. function decode(input) {
  219. // Don't use UCS-2
  220. var output = [],
  221. inputLength = input.length,
  222. out,
  223. i = 0,
  224. n = initialN,
  225. bias = initialBias,
  226. basic,
  227. j,
  228. index,
  229. oldi,
  230. w,
  231. k,
  232. digit,
  233. t,
  234. /** Cached calculation results */
  235. baseMinusT;
  236. // Handle the basic code points: let `basic` be the number of input code
  237. // points before the last delimiter, or `0` if there is none, then copy
  238. // the first basic code points to the output.
  239. basic = input.lastIndexOf(delimiter);
  240. if (basic < 0) {
  241. basic = 0;
  242. }
  243. for (j = 0; j < basic; ++j) {
  244. // if it's not a basic code point
  245. if (input.charCodeAt(j) >= 0x80) {
  246. error('not-basic');
  247. }
  248. output.push(input.charCodeAt(j));
  249. }
  250. // Main decoding loop: start just after the last delimiter if any basic code
  251. // points were copied; start at the beginning otherwise.
  252. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  253. // `index` is the index of the next character to be consumed.
  254. // Decode a generalized variable-length integer into `delta`,
  255. // which gets added to `i`. The overflow checking is easier
  256. // if we increase `i` as we go, then subtract off its starting
  257. // value at the end to obtain `delta`.
  258. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  259. if (index >= inputLength) {
  260. error('invalid-input');
  261. }
  262. digit = basicToDigit(input.charCodeAt(index++));
  263. if (digit >= base || digit > floor((maxInt - i) / w)) {
  264. error('overflow');
  265. }
  266. i += digit * w;
  267. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  268. if (digit < t) {
  269. break;
  270. }
  271. baseMinusT = base - t;
  272. if (w > floor(maxInt / baseMinusT)) {
  273. error('overflow');
  274. }
  275. w *= baseMinusT;
  276. }
  277. out = output.length + 1;
  278. bias = adapt(i - oldi, out, oldi == 0);
  279. // `i` was supposed to wrap around from `out` to `0`,
  280. // incrementing `n` each time, so we'll fix that now:
  281. if (floor(i / out) > maxInt - n) {
  282. error('overflow');
  283. }
  284. n += floor(i / out);
  285. i %= out;
  286. // Insert `n` at position `i` of the output
  287. output.splice(i++, 0, n);
  288. }
  289. return ucs2encode(output);
  290. }
  291. /**
  292. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  293. * Punycode string of ASCII-only symbols.
  294. * @memberOf punycode
  295. * @param {String} input The string of Unicode symbols.
  296. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  297. */
  298. function encode(input) {
  299. var n,
  300. delta,
  301. handledCPCount,
  302. basicLength,
  303. bias,
  304. j,
  305. m,
  306. q,
  307. k,
  308. t,
  309. currentValue,
  310. output = [],
  311. /** `inputLength` will hold the number of code points in `input`. */
  312. inputLength,
  313. /** Cached calculation results */
  314. handledCPCountPlusOne,
  315. baseMinusT,
  316. qMinusT;
  317. // Convert the input in UCS-2 to Unicode
  318. input = ucs2decode(input);
  319. // Cache the length
  320. inputLength = input.length;
  321. // Initialize the state
  322. n = initialN;
  323. delta = 0;
  324. bias = initialBias;
  325. // Handle the basic code points
  326. for (j = 0; j < inputLength; ++j) {
  327. currentValue = input[j];
  328. if (currentValue < 0x80) {
  329. output.push(stringFromCharCode(currentValue));
  330. }
  331. }
  332. handledCPCount = basicLength = output.length;
  333. // `handledCPCount` is the number of code points that have been handled;
  334. // `basicLength` is the number of basic code points.
  335. // Finish the basic string - if it is not empty - with a delimiter
  336. if (basicLength) {
  337. output.push(delimiter);
  338. }
  339. // Main encoding loop:
  340. while (handledCPCount < inputLength) {
  341. // All non-basic code points < n have been handled already. Find the next
  342. // larger one:
  343. for (m = maxInt, j = 0; j < inputLength; ++j) {
  344. currentValue = input[j];
  345. if (currentValue >= n && currentValue < m) {
  346. m = currentValue;
  347. }
  348. }
  349. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  350. // but guard against overflow
  351. handledCPCountPlusOne = handledCPCount + 1;
  352. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  353. error('overflow');
  354. }
  355. delta += (m - n) * handledCPCountPlusOne;
  356. n = m;
  357. for (j = 0; j < inputLength; ++j) {
  358. currentValue = input[j];
  359. if (currentValue < n && ++delta > maxInt) {
  360. error('overflow');
  361. }
  362. if (currentValue == n) {
  363. // Represent delta as a generalized variable-length integer
  364. for (q = delta, k = base; /* no condition */; k += base) {
  365. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  366. if (q < t) {
  367. break;
  368. }
  369. qMinusT = q - t;
  370. baseMinusT = base - t;
  371. output.push(
  372. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  373. );
  374. q = floor(qMinusT / baseMinusT);
  375. }
  376. output.push(stringFromCharCode(digitToBasic(q, 0)));
  377. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  378. delta = 0;
  379. ++handledCPCount;
  380. }
  381. }
  382. ++delta;
  383. ++n;
  384. }
  385. return output.join('');
  386. }
  387. /**
  388. * Converts a Punycode string representing a domain name or an email address
  389. * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
  390. * it doesn't matter if you call it on a string that has already been
  391. * converted to Unicode.
  392. * @memberOf punycode
  393. * @param {String} input The Punycoded domain name or email address to
  394. * convert to Unicode.
  395. * @returns {String} The Unicode representation of the given Punycode
  396. * string.
  397. */
  398. function toUnicode(input) {
  399. return mapDomain(input, function(string) {
  400. return regexPunycode.test(string)
  401. ? decode(string.slice(4).toLowerCase())
  402. : string;
  403. });
  404. }
  405. /**
  406. * Converts a Unicode string representing a domain name or an email address to
  407. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  408. * i.e. it doesn't matter if you call it with a domain that's already in
  409. * ASCII.
  410. * @memberOf punycode
  411. * @param {String} input The domain name or email address to convert, as a
  412. * Unicode string.
  413. * @returns {String} The Punycode representation of the given domain name or
  414. * email address.
  415. */
  416. function toASCII(input) {
  417. return mapDomain(input, function(string) {
  418. return regexNonASCII.test(string)
  419. ? 'xn--' + encode(string)
  420. : string;
  421. });
  422. }
  423. /*--------------------------------------------------------------------------*/
  424. /** Define the public API */
  425. punycode = {
  426. /**
  427. * A string representing the current Punycode.js version number.
  428. * @memberOf punycode
  429. * @type String
  430. */
  431. 'version': '1.3.2',
  432. /**
  433. * An object of methods to convert from JavaScript's internal character
  434. * representation (UCS-2) to Unicode code points, and back.
  435. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  436. * @memberOf punycode
  437. * @type Object
  438. */
  439. 'ucs2': {
  440. 'decode': ucs2decode,
  441. 'encode': ucs2encode
  442. },
  443. 'decode': decode,
  444. 'encode': encode,
  445. 'toASCII': toASCII,
  446. 'toUnicode': toUnicode
  447. };
  448. /** Expose `punycode` */
  449. // Some AMD build optimizers, like r.js, check for specific condition patterns
  450. // like the following:
  451. if (freeExports && freeModule) {
  452. if (module.exports == freeExports) {
  453. // in Node.js, io.js, or RingoJS v0.8.0+
  454. freeModule.exports = punycode;
  455. } else {
  456. // in Narwhal or RingoJS v0.7.0-
  457. for (key in punycode) {
  458. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  459. }
  460. }
  461. } else {
  462. // in Rhino or a web browser
  463. root.punycode = punycode;
  464. }
  465. }(commonjsGlobal));
  466. });
  467. var IPv6 = createCommonjsModule(function (module) {
  468. /*!
  469. * URI.js - Mutating URLs
  470. * IPv6 Support
  471. *
  472. * Version: 1.19.11
  473. *
  474. * Author: Rodney Rehm
  475. * Web: http://medialize.github.io/URI.js/
  476. *
  477. * Licensed under
  478. * MIT License http://www.opensource.org/licenses/mit-license
  479. *
  480. */
  481. (function (root, factory) {
  482. // https://github.com/umdjs/umd/blob/master/returnExports.js
  483. if (module.exports) {
  484. // Node
  485. module.exports = factory();
  486. } else {
  487. // Browser globals (root is window)
  488. root.IPv6 = factory(root);
  489. }
  490. }(commonjsGlobal, function (root) {
  491. /*
  492. var _in = "fe80:0000:0000:0000:0204:61ff:fe9d:f156";
  493. var _out = IPv6.best(_in);
  494. var _expected = "fe80::204:61ff:fe9d:f156";
  495. console.log(_in, _out, _expected, _out === _expected);
  496. */
  497. // save current IPv6 variable, if any
  498. var _IPv6 = root && root.IPv6;
  499. function bestPresentation(address) {
  500. // based on:
  501. // Javascript to test an IPv6 address for proper format, and to
  502. // present the "best text representation" according to IETF Draft RFC at
  503. // http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04
  504. // 8 Feb 2010 Rich Brown, Dartware, LLC
  505. // Please feel free to use this code as long as you provide a link to
  506. // http://www.intermapper.com
  507. // http://intermapper.com/support/tools/IPV6-Validator.aspx
  508. // http://download.dartware.com/thirdparty/ipv6validator.js
  509. var _address = address.toLowerCase();
  510. var segments = _address.split(':');
  511. var length = segments.length;
  512. var total = 8;
  513. // trim colons (:: or ::a:b:c… or …a:b:c::)
  514. if (segments[0] === '' && segments[1] === '' && segments[2] === '') {
  515. // must have been ::
  516. // remove first two items
  517. segments.shift();
  518. segments.shift();
  519. } else if (segments[0] === '' && segments[1] === '') {
  520. // must have been ::xxxx
  521. // remove the first item
  522. segments.shift();
  523. } else if (segments[length - 1] === '' && segments[length - 2] === '') {
  524. // must have been xxxx::
  525. segments.pop();
  526. }
  527. length = segments.length;
  528. // adjust total segments for IPv4 trailer
  529. if (segments[length - 1].indexOf('.') !== -1) {
  530. // found a "." which means IPv4
  531. total = 7;
  532. }
  533. // fill empty segments them with "0000"
  534. var pos;
  535. for (pos = 0; pos < length; pos++) {
  536. if (segments[pos] === '') {
  537. break;
  538. }
  539. }
  540. if (pos < total) {
  541. segments.splice(pos, 1, '0000');
  542. while (segments.length < total) {
  543. segments.splice(pos, 0, '0000');
  544. }
  545. }
  546. // strip leading zeros
  547. var _segments;
  548. for (var i = 0; i < total; i++) {
  549. _segments = segments[i].split('');
  550. for (var j = 0; j < 3 ; j++) {
  551. if (_segments[0] === '0' && _segments.length > 1) {
  552. _segments.splice(0,1);
  553. } else {
  554. break;
  555. }
  556. }
  557. segments[i] = _segments.join('');
  558. }
  559. // find longest sequence of zeroes and coalesce them into one segment
  560. var best = -1;
  561. var _best = 0;
  562. var _current = 0;
  563. var current = -1;
  564. var inzeroes = false;
  565. // i; already declared
  566. for (i = 0; i < total; i++) {
  567. if (inzeroes) {
  568. if (segments[i] === '0') {
  569. _current += 1;
  570. } else {
  571. inzeroes = false;
  572. if (_current > _best) {
  573. best = current;
  574. _best = _current;
  575. }
  576. }
  577. } else {
  578. if (segments[i] === '0') {
  579. inzeroes = true;
  580. current = i;
  581. _current = 1;
  582. }
  583. }
  584. }
  585. if (_current > _best) {
  586. best = current;
  587. _best = _current;
  588. }
  589. if (_best > 1) {
  590. segments.splice(best, _best, '');
  591. }
  592. length = segments.length;
  593. // assemble remaining segments
  594. var result = '';
  595. if (segments[0] === '') {
  596. result = ':';
  597. }
  598. for (i = 0; i < length; i++) {
  599. result += segments[i];
  600. if (i === length - 1) {
  601. break;
  602. }
  603. result += ':';
  604. }
  605. if (segments[length - 1] === '') {
  606. result += ':';
  607. }
  608. return result;
  609. }
  610. function noConflict() {
  611. /*jshint validthis: true */
  612. if (root.IPv6 === this) {
  613. root.IPv6 = _IPv6;
  614. }
  615. return this;
  616. }
  617. return {
  618. best: bestPresentation,
  619. noConflict: noConflict
  620. };
  621. }));
  622. });
  623. var SecondLevelDomains = createCommonjsModule(function (module) {
  624. /*!
  625. * URI.js - Mutating URLs
  626. * Second Level Domain (SLD) Support
  627. *
  628. * Version: 1.19.11
  629. *
  630. * Author: Rodney Rehm
  631. * Web: http://medialize.github.io/URI.js/
  632. *
  633. * Licensed under
  634. * MIT License http://www.opensource.org/licenses/mit-license
  635. *
  636. */
  637. (function (root, factory) {
  638. // https://github.com/umdjs/umd/blob/master/returnExports.js
  639. if (module.exports) {
  640. // Node
  641. module.exports = factory();
  642. } else {
  643. // Browser globals (root is window)
  644. root.SecondLevelDomains = factory(root);
  645. }
  646. }(commonjsGlobal, function (root) {
  647. // save current SecondLevelDomains variable, if any
  648. var _SecondLevelDomains = root && root.SecondLevelDomains;
  649. var SLD = {
  650. // list of known Second Level Domains
  651. // converted list of SLDs from https://github.com/gavingmiller/second-level-domains
  652. // ----
  653. // publicsuffix.org is more current and actually used by a couple of browsers internally.
  654. // downside is it also contains domains like "dyndns.org" - which is fine for the security
  655. // issues browser have to deal with (SOP for cookies, etc) - but is way overboard for URI.js
  656. // ----
  657. list: {
  658. 'ac':' com gov mil net org ',
  659. 'ae':' ac co gov mil name net org pro sch ',
  660. 'af':' com edu gov net org ',
  661. 'al':' com edu gov mil net org ',
  662. 'ao':' co ed gv it og pb ',
  663. 'ar':' com edu gob gov int mil net org tur ',
  664. 'at':' ac co gv or ',
  665. 'au':' asn com csiro edu gov id net org ',
  666. 'ba':' co com edu gov mil net org rs unbi unmo unsa untz unze ',
  667. 'bb':' biz co com edu gov info net org store tv ',
  668. 'bh':' biz cc com edu gov info net org ',
  669. 'bn':' com edu gov net org ',
  670. 'bo':' com edu gob gov int mil net org tv ',
  671. 'br':' adm adv agr am arq art ato b bio blog bmd cim cng cnt com coop ecn edu eng esp etc eti far flog fm fnd fot fst g12 ggf gov imb ind inf jor jus lel mat med mil mus net nom not ntr odo org ppg pro psc psi qsl rec slg srv tmp trd tur tv vet vlog wiki zlg ',
  672. 'bs':' com edu gov net org ',
  673. 'bz':' du et om ov rg ',
  674. 'ca':' ab bc mb nb nf nl ns nt nu on pe qc sk yk ',
  675. 'ck':' biz co edu gen gov info net org ',
  676. 'cn':' ac ah bj com cq edu fj gd gov gs gx gz ha hb he hi hl hn jl js jx ln mil net nm nx org qh sc sd sh sn sx tj tw xj xz yn zj ',
  677. 'co':' com edu gov mil net nom org ',
  678. 'cr':' ac c co ed fi go or sa ',
  679. 'cy':' ac biz com ekloges gov ltd name net org parliament press pro tm ',
  680. 'do':' art com edu gob gov mil net org sld web ',
  681. 'dz':' art asso com edu gov net org pol ',
  682. 'ec':' com edu fin gov info med mil net org pro ',
  683. 'eg':' com edu eun gov mil name net org sci ',
  684. 'er':' com edu gov ind mil net org rochest w ',
  685. 'es':' com edu gob nom org ',
  686. 'et':' biz com edu gov info name net org ',
  687. 'fj':' ac biz com info mil name net org pro ',
  688. 'fk':' ac co gov net nom org ',
  689. 'fr':' asso com f gouv nom prd presse tm ',
  690. 'gg':' co net org ',
  691. 'gh':' com edu gov mil org ',
  692. 'gn':' ac com gov net org ',
  693. 'gr':' com edu gov mil net org ',
  694. 'gt':' com edu gob ind mil net org ',
  695. 'gu':' com edu gov net org ',
  696. 'hk':' com edu gov idv net org ',
  697. 'hu':' 2000 agrar bolt casino city co erotica erotika film forum games hotel info ingatlan jogasz konyvelo lakas media news org priv reklam sex shop sport suli szex tm tozsde utazas video ',
  698. 'id':' ac co go mil net or sch web ',
  699. 'il':' ac co gov idf k12 muni net org ',
  700. 'in':' ac co edu ernet firm gen gov i ind mil net nic org res ',
  701. 'iq':' com edu gov i mil net org ',
  702. 'ir':' ac co dnssec gov i id net org sch ',
  703. 'it':' edu gov ',
  704. 'je':' co net org ',
  705. 'jo':' com edu gov mil name net org sch ',
  706. 'jp':' ac ad co ed go gr lg ne or ',
  707. 'ke':' ac co go info me mobi ne or sc ',
  708. 'kh':' com edu gov mil net org per ',
  709. 'ki':' biz com de edu gov info mob net org tel ',
  710. 'km':' asso com coop edu gouv k medecin mil nom notaires pharmaciens presse tm veterinaire ',
  711. 'kn':' edu gov net org ',
  712. 'kr':' ac busan chungbuk chungnam co daegu daejeon es gangwon go gwangju gyeongbuk gyeonggi gyeongnam hs incheon jeju jeonbuk jeonnam k kg mil ms ne or pe re sc seoul ulsan ',
  713. 'kw':' com edu gov net org ',
  714. 'ky':' com edu gov net org ',
  715. 'kz':' com edu gov mil net org ',
  716. 'lb':' com edu gov net org ',
  717. 'lk':' assn com edu gov grp hotel int ltd net ngo org sch soc web ',
  718. 'lr':' com edu gov net org ',
  719. 'lv':' asn com conf edu gov id mil net org ',
  720. 'ly':' com edu gov id med net org plc sch ',
  721. 'ma':' ac co gov m net org press ',
  722. 'mc':' asso tm ',
  723. 'me':' ac co edu gov its net org priv ',
  724. 'mg':' com edu gov mil nom org prd tm ',
  725. 'mk':' com edu gov inf name net org pro ',
  726. 'ml':' com edu gov net org presse ',
  727. 'mn':' edu gov org ',
  728. 'mo':' com edu gov net org ',
  729. 'mt':' com edu gov net org ',
  730. 'mv':' aero biz com coop edu gov info int mil museum name net org pro ',
  731. 'mw':' ac co com coop edu gov int museum net org ',
  732. 'mx':' com edu gob net org ',
  733. 'my':' com edu gov mil name net org sch ',
  734. 'nf':' arts com firm info net other per rec store web ',
  735. 'ng':' biz com edu gov mil mobi name net org sch ',
  736. 'ni':' ac co com edu gob mil net nom org ',
  737. 'np':' com edu gov mil net org ',
  738. 'nr':' biz com edu gov info net org ',
  739. 'om':' ac biz co com edu gov med mil museum net org pro sch ',
  740. 'pe':' com edu gob mil net nom org sld ',
  741. 'ph':' com edu gov i mil net ngo org ',
  742. 'pk':' biz com edu fam gob gok gon gop gos gov net org web ',
  743. 'pl':' art bialystok biz com edu gda gdansk gorzow gov info katowice krakow lodz lublin mil net ngo olsztyn org poznan pwr radom slupsk szczecin torun warszawa waw wroc wroclaw zgora ',
  744. 'pr':' ac biz com edu est gov info isla name net org pro prof ',
  745. 'ps':' com edu gov net org plo sec ',
  746. 'pw':' belau co ed go ne or ',
  747. 'ro':' arts com firm info nom nt org rec store tm www ',
  748. 'rs':' ac co edu gov in org ',
  749. 'sb':' com edu gov net org ',
  750. 'sc':' com edu gov net org ',
  751. 'sh':' co com edu gov net nom org ',
  752. 'sl':' com edu gov net org ',
  753. 'st':' co com consulado edu embaixada gov mil net org principe saotome store ',
  754. 'sv':' com edu gob org red ',
  755. 'sz':' ac co org ',
  756. 'tr':' av bbs bel biz com dr edu gen gov info k12 name net org pol tel tsk tv web ',
  757. 'tt':' aero biz cat co com coop edu gov info int jobs mil mobi museum name net org pro tel travel ',
  758. 'tw':' club com ebiz edu game gov idv mil net org ',
  759. 'mu':' ac co com gov net or org ',
  760. 'mz':' ac co edu gov org ',
  761. 'na':' co com ',
  762. 'nz':' ac co cri geek gen govt health iwi maori mil net org parliament school ',
  763. 'pa':' abo ac com edu gob ing med net nom org sld ',
  764. 'pt':' com edu gov int net nome org publ ',
  765. 'py':' com edu gov mil net org ',
  766. 'qa':' com edu gov mil net org ',
  767. 're':' asso com nom ',
  768. 'ru':' ac adygeya altai amur arkhangelsk astrakhan bashkiria belgorod bir bryansk buryatia cbg chel chelyabinsk chita chukotka chuvashia com dagestan e-burg edu gov grozny int irkutsk ivanovo izhevsk jar joshkar-ola kalmykia kaluga kamchatka karelia kazan kchr kemerovo khabarovsk khakassia khv kirov koenig komi kostroma kranoyarsk kuban kurgan kursk lipetsk magadan mari mari-el marine mil mordovia mosreg msk murmansk nalchik net nnov nov novosibirsk nsk omsk orenburg org oryol penza perm pp pskov ptz rnd ryazan sakhalin samara saratov simbirsk smolensk spb stavropol stv surgut tambov tatarstan tom tomsk tsaritsyn tsk tula tuva tver tyumen udm udmurtia ulan-ude vladikavkaz vladimir vladivostok volgograd vologda voronezh vrn vyatka yakutia yamal yekaterinburg yuzhno-sakhalinsk ',
  769. 'rw':' ac co com edu gouv gov int mil net ',
  770. 'sa':' com edu gov med net org pub sch ',
  771. 'sd':' com edu gov info med net org tv ',
  772. 'se':' a ac b bd c d e f g h i k l m n o org p parti pp press r s t tm u w x y z ',
  773. 'sg':' com edu gov idn net org per ',
  774. 'sn':' art com edu gouv org perso univ ',
  775. 'sy':' com edu gov mil net news org ',
  776. 'th':' ac co go in mi net or ',
  777. 'tj':' ac biz co com edu go gov info int mil name net nic org test web ',
  778. 'tn':' agrinet com defense edunet ens fin gov ind info intl mincom nat net org perso rnrt rns rnu tourism ',
  779. 'tz':' ac co go ne or ',
  780. 'ua':' biz cherkassy chernigov chernovtsy ck cn co com crimea cv dn dnepropetrovsk donetsk dp edu gov if in ivano-frankivsk kh kharkov kherson khmelnitskiy kiev kirovograd km kr ks kv lg lugansk lutsk lviv me mk net nikolaev od odessa org pl poltava pp rovno rv sebastopol sumy te ternopil uzhgorod vinnica vn zaporizhzhe zhitomir zp zt ',
  781. 'ug':' ac co go ne or org sc ',
  782. 'uk':' ac bl british-library co cym gov govt icnet jet lea ltd me mil mod national-library-scotland nel net nhs nic nls org orgn parliament plc police sch scot soc ',
  783. 'us':' dni fed isa kids nsn ',
  784. 'uy':' com edu gub mil net org ',
  785. 've':' co com edu gob info mil net org web ',
  786. 'vi':' co com k12 net org ',
  787. 'vn':' ac biz com edu gov health info int name net org pro ',
  788. 'ye':' co com gov ltd me net org plc ',
  789. 'yu':' ac co edu gov org ',
  790. 'za':' ac agric alt bourse city co cybernet db edu gov grondar iaccess imt inca landesign law mil net ngo nis nom olivetti org pix school tm web ',
  791. 'zm':' ac co com edu gov net org sch ',
  792. // https://en.wikipedia.org/wiki/CentralNic#Second-level_domains
  793. 'com': 'ar br cn de eu gb gr hu jpn kr no qc ru sa se uk us uy za ',
  794. 'net': 'gb jp se uk ',
  795. 'org': 'ae',
  796. 'de': 'com '
  797. },
  798. // gorhill 2013-10-25: Using indexOf() instead Regexp(). Significant boost
  799. // in both performance and memory footprint. No initialization required.
  800. // http://jsperf.com/uri-js-sld-regex-vs-binary-search/4
  801. // Following methods use lastIndexOf() rather than array.split() in order
  802. // to avoid any memory allocations.
  803. has: function(domain) {
  804. var tldOffset = domain.lastIndexOf('.');
  805. if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {
  806. return false;
  807. }
  808. var sldOffset = domain.lastIndexOf('.', tldOffset-1);
  809. if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) {
  810. return false;
  811. }
  812. var sldList = SLD.list[domain.slice(tldOffset+1)];
  813. if (!sldList) {
  814. return false;
  815. }
  816. return sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') >= 0;
  817. },
  818. is: function(domain) {
  819. var tldOffset = domain.lastIndexOf('.');
  820. if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {
  821. return false;
  822. }
  823. var sldOffset = domain.lastIndexOf('.', tldOffset-1);
  824. if (sldOffset >= 0) {
  825. return false;
  826. }
  827. var sldList = SLD.list[domain.slice(tldOffset+1)];
  828. if (!sldList) {
  829. return false;
  830. }
  831. return sldList.indexOf(' ' + domain.slice(0, tldOffset) + ' ') >= 0;
  832. },
  833. get: function(domain) {
  834. var tldOffset = domain.lastIndexOf('.');
  835. if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {
  836. return null;
  837. }
  838. var sldOffset = domain.lastIndexOf('.', tldOffset-1);
  839. if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) {
  840. return null;
  841. }
  842. var sldList = SLD.list[domain.slice(tldOffset+1)];
  843. if (!sldList) {
  844. return null;
  845. }
  846. if (sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') < 0) {
  847. return null;
  848. }
  849. return domain.slice(sldOffset+1);
  850. },
  851. noConflict: function(){
  852. if (root.SecondLevelDomains === this) {
  853. root.SecondLevelDomains = _SecondLevelDomains;
  854. }
  855. return this;
  856. }
  857. };
  858. return SLD;
  859. }));
  860. });
  861. var URI = createCommonjsModule(function (module) {
  862. /*!
  863. * URI.js - Mutating URLs
  864. *
  865. * Version: 1.19.11
  866. *
  867. * Author: Rodney Rehm
  868. * Web: http://medialize.github.io/URI.js/
  869. *
  870. * Licensed under
  871. * MIT License http://www.opensource.org/licenses/mit-license
  872. *
  873. */
  874. (function (root, factory) {
  875. // https://github.com/umdjs/umd/blob/master/returnExports.js
  876. if (module.exports) {
  877. // Node
  878. module.exports = factory(punycode, IPv6, SecondLevelDomains);
  879. } else {
  880. // Browser globals (root is window)
  881. root.URI = factory(root.punycode, root.IPv6, root.SecondLevelDomains, root);
  882. }
  883. }(commonjsGlobal, function (punycode, IPv6, SLD, root) {
  884. /*global location, escape, unescape */
  885. // FIXME: v2.0.0 renamce non-camelCase properties to uppercase
  886. /*jshint camelcase: false */
  887. // save current URI variable, if any
  888. var _URI = root && root.URI;
  889. function URI(url, base) {
  890. var _urlSupplied = arguments.length >= 1;
  891. var _baseSupplied = arguments.length >= 2;
  892. // Allow instantiation without the 'new' keyword
  893. if (!(this instanceof URI)) {
  894. if (_urlSupplied) {
  895. if (_baseSupplied) {
  896. return new URI(url, base);
  897. }
  898. return new URI(url);
  899. }
  900. return new URI();
  901. }
  902. if (url === undefined) {
  903. if (_urlSupplied) {
  904. throw new TypeError('undefined is not a valid argument for URI');
  905. }
  906. if (typeof location !== 'undefined') {
  907. url = location.href + '';
  908. } else {
  909. url = '';
  910. }
  911. }
  912. if (url === null) {
  913. if (_urlSupplied) {
  914. throw new TypeError('null is not a valid argument for URI');
  915. }
  916. }
  917. this.href(url);
  918. // resolve to base according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#constructor
  919. if (base !== undefined) {
  920. return this.absoluteTo(base);
  921. }
  922. return this;
  923. }
  924. function isInteger(value) {
  925. return /^[0-9]+$/.test(value);
  926. }
  927. URI.version = '1.19.11';
  928. var p = URI.prototype;
  929. var hasOwn = Object.prototype.hasOwnProperty;
  930. function escapeRegEx(string) {
  931. // https://github.com/medialize/URI.js/commit/85ac21783c11f8ccab06106dba9735a31a86924d#commitcomment-821963
  932. return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
  933. }
  934. function getType(value) {
  935. // IE8 doesn't return [Object Undefined] but [Object Object] for undefined value
  936. if (value === undefined) {
  937. return 'Undefined';
  938. }
  939. return String(Object.prototype.toString.call(value)).slice(8, -1);
  940. }
  941. function isArray(obj) {
  942. return getType(obj) === 'Array';
  943. }
  944. function filterArrayValues(data, value) {
  945. var lookup = {};
  946. var i, length;
  947. if (getType(value) === 'RegExp') {
  948. lookup = null;
  949. } else if (isArray(value)) {
  950. for (i = 0, length = value.length; i < length; i++) {
  951. lookup[value[i]] = true;
  952. }
  953. } else {
  954. lookup[value] = true;
  955. }
  956. for (i = 0, length = data.length; i < length; i++) {
  957. /*jshint laxbreak: true */
  958. var _match = lookup && lookup[data[i]] !== undefined
  959. || !lookup && value.test(data[i]);
  960. /*jshint laxbreak: false */
  961. if (_match) {
  962. data.splice(i, 1);
  963. length--;
  964. i--;
  965. }
  966. }
  967. return data;
  968. }
  969. function arrayContains(list, value) {
  970. var i, length;
  971. // value may be string, number, array, regexp
  972. if (isArray(value)) {
  973. // Note: this can be optimized to O(n) (instead of current O(m * n))
  974. for (i = 0, length = value.length; i < length; i++) {
  975. if (!arrayContains(list, value[i])) {
  976. return false;
  977. }
  978. }
  979. return true;
  980. }
  981. var _type = getType(value);
  982. for (i = 0, length = list.length; i < length; i++) {
  983. if (_type === 'RegExp') {
  984. if (typeof list[i] === 'string' && list[i].match(value)) {
  985. return true;
  986. }
  987. } else if (list[i] === value) {
  988. return true;
  989. }
  990. }
  991. return false;
  992. }
  993. function arraysEqual(one, two) {
  994. if (!isArray(one) || !isArray(two)) {
  995. return false;
  996. }
  997. // arrays can't be equal if they have different amount of content
  998. if (one.length !== two.length) {
  999. return false;
  1000. }
  1001. one.sort();
  1002. two.sort();
  1003. for (var i = 0, l = one.length; i < l; i++) {
  1004. if (one[i] !== two[i]) {
  1005. return false;
  1006. }
  1007. }
  1008. return true;
  1009. }
  1010. function trimSlashes(text) {
  1011. var trim_expression = /^\/+|\/+$/g;
  1012. return text.replace(trim_expression, '');
  1013. }
  1014. URI._parts = function() {
  1015. return {
  1016. protocol: null,
  1017. username: null,
  1018. password: null,
  1019. hostname: null,
  1020. urn: null,
  1021. port: null,
  1022. path: null,
  1023. query: null,
  1024. fragment: null,
  1025. // state
  1026. preventInvalidHostname: URI.preventInvalidHostname,
  1027. duplicateQueryParameters: URI.duplicateQueryParameters,
  1028. escapeQuerySpace: URI.escapeQuerySpace
  1029. };
  1030. };
  1031. // state: throw on invalid hostname
  1032. // see https://github.com/medialize/URI.js/pull/345
  1033. // and https://github.com/medialize/URI.js/issues/354
  1034. URI.preventInvalidHostname = false;
  1035. // state: allow duplicate query parameters (a=1&a=1)
  1036. URI.duplicateQueryParameters = false;
  1037. // state: replaces + with %20 (space in query strings)
  1038. URI.escapeQuerySpace = true;
  1039. // static properties
  1040. URI.protocol_expression = /^[a-z][a-z0-9.+-]*$/i;
  1041. URI.idn_expression = /[^a-z0-9\._-]/i;
  1042. URI.punycode_expression = /(xn--)/i;
  1043. // well, 333.444.555.666 matches, but it sure ain't no IPv4 - do we care?
  1044. URI.ip4_expression = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
  1045. // credits to Rich Brown
  1046. // source: http://forums.intermapper.com/viewtopic.php?p=1096#1096
  1047. // specification: http://www.ietf.org/rfc/rfc4291.txt
  1048. URI.ip6_expression = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/;
  1049. // expression used is "gruber revised" (@gruber v2) determined to be the
  1050. // best solution in a regex-golf we did a couple of ages ago at
  1051. // * http://mathiasbynens.be/demo/url-regex
  1052. // * http://rodneyrehm.de/t/url-regex.html
  1053. URI.find_uri_expression = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/ig;
  1054. URI.findUri = {
  1055. // valid "scheme://" or "www."
  1056. start: /\b(?:([a-z][a-z0-9.+-]*:\/\/)|www\.)/gi,
  1057. // everything up to the next whitespace
  1058. end: /[\s\r\n]|$/,
  1059. // trim trailing punctuation captured by end RegExp
  1060. trim: /[`!()\[\]{};:'".,<>?«»“”„‘’]+$/,
  1061. // balanced parens inclusion (), [], {}, <>
  1062. parens: /(\([^\)]*\)|\[[^\]]*\]|\{[^}]*\}|<[^>]*>)/g,
  1063. };
  1064. URI.leading_whitespace_expression = /^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;
  1065. // https://infra.spec.whatwg.org/#ascii-tab-or-newline
  1066. URI.ascii_tab_whitespace = /[\u0009\u000A\u000D]+/g;
  1067. // http://www.iana.org/assignments/uri-schemes.html
  1068. // http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports
  1069. URI.defaultPorts = {
  1070. http: '80',
  1071. https: '443',
  1072. ftp: '21',
  1073. gopher: '70',
  1074. ws: '80',
  1075. wss: '443'
  1076. };
  1077. // list of protocols which always require a hostname
  1078. URI.hostProtocols = [
  1079. 'http',
  1080. 'https'
  1081. ];
  1082. // allowed hostname characters according to RFC 3986
  1083. // ALPHA DIGIT "-" "." "_" "~" "!" "$" "&" "'" "(" ")" "*" "+" "," ";" "=" %encoded
  1084. // I've never seen a (non-IDN) hostname other than: ALPHA DIGIT . - _
  1085. URI.invalid_hostname_characters = /[^a-zA-Z0-9\.\-:_]/;
  1086. // map DOM Elements to their URI attribute
  1087. URI.domAttributes = {
  1088. 'a': 'href',
  1089. 'blockquote': 'cite',
  1090. 'link': 'href',
  1091. 'base': 'href',
  1092. 'script': 'src',
  1093. 'form': 'action',
  1094. 'img': 'src',
  1095. 'area': 'href',
  1096. 'iframe': 'src',
  1097. 'embed': 'src',
  1098. 'source': 'src',
  1099. 'track': 'src',
  1100. 'input': 'src', // but only if type="image"
  1101. 'audio': 'src',
  1102. 'video': 'src'
  1103. };
  1104. URI.getDomAttribute = function(node) {
  1105. if (!node || !node.nodeName) {
  1106. return undefined;
  1107. }
  1108. var nodeName = node.nodeName.toLowerCase();
  1109. // <input> should only expose src for type="image"
  1110. if (nodeName === 'input' && node.type !== 'image') {
  1111. return undefined;
  1112. }
  1113. return URI.domAttributes[nodeName];
  1114. };
  1115. function escapeForDumbFirefox36(value) {
  1116. // https://github.com/medialize/URI.js/issues/91
  1117. return escape(value);
  1118. }
  1119. // encoding / decoding according to RFC3986
  1120. function strictEncodeURIComponent(string) {
  1121. // see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent
  1122. return encodeURIComponent(string)
  1123. .replace(/[!'()*]/g, escapeForDumbFirefox36)
  1124. .replace(/\*/g, '%2A');
  1125. }
  1126. URI.encode = strictEncodeURIComponent;
  1127. URI.decode = decodeURIComponent;
  1128. URI.iso8859 = function() {
  1129. URI.encode = escape;
  1130. URI.decode = unescape;
  1131. };
  1132. URI.unicode = function() {
  1133. URI.encode = strictEncodeURIComponent;
  1134. URI.decode = decodeURIComponent;
  1135. };
  1136. URI.characters = {
  1137. pathname: {
  1138. encode: {
  1139. // RFC3986 2.1: For consistency, URI producers and normalizers should
  1140. // use uppercase hexadecimal digits for all percent-encodings.
  1141. expression: /%(24|26|2B|2C|3B|3D|3A|40)/ig,
  1142. map: {
  1143. // -._~!'()*
  1144. '%24': '$',
  1145. '%26': '&',
  1146. '%2B': '+',
  1147. '%2C': ',',
  1148. '%3B': ';',
  1149. '%3D': '=',
  1150. '%3A': ':',
  1151. '%40': '@'
  1152. }
  1153. },
  1154. decode: {
  1155. expression: /[\/\?#]/g,
  1156. map: {
  1157. '/': '%2F',
  1158. '?': '%3F',
  1159. '#': '%23'
  1160. }
  1161. }
  1162. },
  1163. reserved: {
  1164. encode: {
  1165. // RFC3986 2.1: For consistency, URI producers and normalizers should
  1166. // use uppercase hexadecimal digits for all percent-encodings.
  1167. expression: /%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/ig,
  1168. map: {
  1169. // gen-delims
  1170. '%3A': ':',
  1171. '%2F': '/',
  1172. '%3F': '?',
  1173. '%23': '#',
  1174. '%5B': '[',
  1175. '%5D': ']',
  1176. '%40': '@',
  1177. // sub-delims
  1178. '%21': '!',
  1179. '%24': '$',
  1180. '%26': '&',
  1181. '%27': '\'',
  1182. '%28': '(',
  1183. '%29': ')',
  1184. '%2A': '*',
  1185. '%2B': '+',
  1186. '%2C': ',',
  1187. '%3B': ';',
  1188. '%3D': '='
  1189. }
  1190. }
  1191. },
  1192. urnpath: {
  1193. // The characters under `encode` are the characters called out by RFC 2141 as being acceptable
  1194. // for usage in a URN. RFC2141 also calls out "-", ".", and "_" as acceptable characters, but
  1195. // these aren't encoded by encodeURIComponent, so we don't have to call them out here. Also
  1196. // note that the colon character is not featured in the encoding map; this is because URI.js
  1197. // gives the colons in URNs semantic meaning as the delimiters of path segements, and so it
  1198. // should not appear unencoded in a segment itself.
  1199. // See also the note above about RFC3986 and capitalalized hex digits.
  1200. encode: {
  1201. expression: /%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/ig,
  1202. map: {
  1203. '%21': '!',
  1204. '%24': '$',
  1205. '%27': '\'',
  1206. '%28': '(',
  1207. '%29': ')',
  1208. '%2A': '*',
  1209. '%2B': '+',
  1210. '%2C': ',',
  1211. '%3B': ';',
  1212. '%3D': '=',
  1213. '%40': '@'
  1214. }
  1215. },
  1216. // These characters are the characters called out by RFC2141 as "reserved" characters that
  1217. // should never appear in a URN, plus the colon character (see note above).
  1218. decode: {
  1219. expression: /[\/\?#:]/g,
  1220. map: {
  1221. '/': '%2F',
  1222. '?': '%3F',
  1223. '#': '%23',
  1224. ':': '%3A'
  1225. }
  1226. }
  1227. }
  1228. };
  1229. URI.encodeQuery = function(string, escapeQuerySpace) {
  1230. var escaped = URI.encode(string + '');
  1231. if (escapeQuerySpace === undefined) {
  1232. escapeQuerySpace = URI.escapeQuerySpace;
  1233. }
  1234. return escapeQuerySpace ? escaped.replace(/%20/g, '+') : escaped;
  1235. };
  1236. URI.decodeQuery = function(string, escapeQuerySpace) {
  1237. string += '';
  1238. if (escapeQuerySpace === undefined) {
  1239. escapeQuerySpace = URI.escapeQuerySpace;
  1240. }
  1241. try {
  1242. return URI.decode(escapeQuerySpace ? string.replace(/\+/g, '%20') : string);
  1243. } catch(e) {
  1244. // we're not going to mess with weird encodings,
  1245. // give up and return the undecoded original string
  1246. // see https://github.com/medialize/URI.js/issues/87
  1247. // see https://github.com/medialize/URI.js/issues/92
  1248. return string;
  1249. }
  1250. };
  1251. // generate encode/decode path functions
  1252. var _parts = {'encode':'encode', 'decode':'decode'};
  1253. var _part;
  1254. var generateAccessor = function(_group, _part) {
  1255. return function(string) {
  1256. try {
  1257. return URI[_part](string + '').replace(URI.characters[_group][_part].expression, function(c) {
  1258. return URI.characters[_group][_part].map[c];
  1259. });
  1260. } catch (e) {
  1261. // we're not going to mess with weird encodings,
  1262. // give up and return the undecoded original string
  1263. // see https://github.com/medialize/URI.js/issues/87
  1264. // see https://github.com/medialize/URI.js/issues/92
  1265. return string;
  1266. }
  1267. };
  1268. };
  1269. for (_part in _parts) {
  1270. URI[_part + 'PathSegment'] = generateAccessor('pathname', _parts[_part]);
  1271. URI[_part + 'UrnPathSegment'] = generateAccessor('urnpath', _parts[_part]);
  1272. }
  1273. var generateSegmentedPathFunction = function(_sep, _codingFuncName, _innerCodingFuncName) {
  1274. return function(string) {
  1275. // Why pass in names of functions, rather than the function objects themselves? The
  1276. // definitions of some functions (but in particular, URI.decode) will occasionally change due
  1277. // to URI.js having ISO8859 and Unicode modes. Passing in the name and getting it will ensure
  1278. // that the functions we use here are "fresh".
  1279. var actualCodingFunc;
  1280. if (!_innerCodingFuncName) {
  1281. actualCodingFunc = URI[_codingFuncName];
  1282. } else {
  1283. actualCodingFunc = function(string) {
  1284. return URI[_codingFuncName](URI[_innerCodingFuncName](string));
  1285. };
  1286. }
  1287. var segments = (string + '').split(_sep);
  1288. for (var i = 0, length = segments.length; i < length; i++) {
  1289. segments[i] = actualCodingFunc(segments[i]);
  1290. }
  1291. return segments.join(_sep);
  1292. };
  1293. };
  1294. // This takes place outside the above loop because we don't want, e.g., encodeUrnPath functions.
  1295. URI.decodePath = generateSegmentedPathFunction('/', 'decodePathSegment');
  1296. URI.decodeUrnPath = generateSegmentedPathFunction(':', 'decodeUrnPathSegment');
  1297. URI.recodePath = generateSegmentedPathFunction('/', 'encodePathSegment', 'decode');
  1298. URI.recodeUrnPath = generateSegmentedPathFunction(':', 'encodeUrnPathSegment', 'decode');
  1299. URI.encodeReserved = generateAccessor('reserved', 'encode');
  1300. URI.parse = function(string, parts) {
  1301. var pos;
  1302. if (!parts) {
  1303. parts = {
  1304. preventInvalidHostname: URI.preventInvalidHostname
  1305. };
  1306. }
  1307. string = string.replace(URI.leading_whitespace_expression, '');
  1308. // https://infra.spec.whatwg.org/#ascii-tab-or-newline
  1309. string = string.replace(URI.ascii_tab_whitespace, '');
  1310. // [protocol"://"[username[":"password]"@"]hostname[":"port]"/"?][path]["?"querystring]["#"fragment]
  1311. // extract fragment
  1312. pos = string.indexOf('#');
  1313. if (pos > -1) {
  1314. // escaping?
  1315. parts.fragment = string.substring(pos + 1) || null;
  1316. string = string.substring(0, pos);
  1317. }
  1318. // extract query
  1319. pos = string.indexOf('?');
  1320. if (pos > -1) {
  1321. // escaping?
  1322. parts.query = string.substring(pos + 1) || null;
  1323. string = string.substring(0, pos);
  1324. }
  1325. // slashes and backslashes have lost all meaning for the web protocols (https, http, wss, ws)
  1326. string = string.replace(/^(https?|ftp|wss?)?:+[/\\]*/i, '$1://');
  1327. // slashes and backslashes have lost all meaning for scheme relative URLs
  1328. string = string.replace(/^[/\\]{2,}/i, '//');
  1329. // extract protocol
  1330. if (string.substring(0, 2) === '//') {
  1331. // relative-scheme
  1332. parts.protocol = null;
  1333. string = string.substring(2);
  1334. // extract "user:pass@host:port"
  1335. string = URI.parseAuthority(string, parts);
  1336. } else {
  1337. pos = string.indexOf(':');
  1338. if (pos > -1) {
  1339. parts.protocol = string.substring(0, pos) || null;
  1340. if (parts.protocol && !parts.protocol.match(URI.protocol_expression)) {
  1341. // : may be within the path
  1342. parts.protocol = undefined;
  1343. } else if (string.substring(pos + 1, pos + 3).replace(/\\/g, '/') === '//') {
  1344. string = string.substring(pos + 3);
  1345. // extract "user:pass@host:port"
  1346. string = URI.parseAuthority(string, parts);
  1347. } else {
  1348. string = string.substring(pos + 1);
  1349. parts.urn = true;
  1350. }
  1351. }
  1352. }
  1353. // what's left must be the path
  1354. parts.path = string;
  1355. // and we're done
  1356. return parts;
  1357. };
  1358. URI.parseHost = function(string, parts) {
  1359. if (!string) {
  1360. string = '';
  1361. }
  1362. // Copy chrome, IE, opera backslash-handling behavior.
  1363. // Back slashes before the query string get converted to forward slashes
  1364. // See: https://github.com/joyent/node/blob/386fd24f49b0e9d1a8a076592a404168faeecc34/lib/url.js#L115-L124
  1365. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  1366. // https://github.com/medialize/URI.js/pull/233
  1367. string = string.replace(/\\/g, '/');
  1368. // extract host:port
  1369. var pos = string.indexOf('/');
  1370. var bracketPos;
  1371. var t;
  1372. if (pos === -1) {
  1373. pos = string.length;
  1374. }
  1375. if (string.charAt(0) === '[') {
  1376. // IPv6 host - http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04#section-6
  1377. // I claim most client software breaks on IPv6 anyways. To simplify things, URI only accepts
  1378. // IPv6+port in the format [2001:db8::1]:80 (for the time being)
  1379. bracketPos = string.indexOf(']');
  1380. parts.hostname = string.substring(1, bracketPos) || null;
  1381. parts.port = string.substring(bracketPos + 2, pos) || null;
  1382. if (parts.port === '/') {
  1383. parts.port = null;
  1384. }
  1385. } else {
  1386. var firstColon = string.indexOf(':');
  1387. var firstSlash = string.indexOf('/');
  1388. var nextColon = string.indexOf(':', firstColon + 1);
  1389. if (nextColon !== -1 && (firstSlash === -1 || nextColon < firstSlash)) {
  1390. // IPv6 host contains multiple colons - but no port
  1391. // this notation is actually not allowed by RFC 3986, but we're a liberal parser
  1392. parts.hostname = string.substring(0, pos) || null;
  1393. parts.port = null;
  1394. } else {
  1395. t = string.substring(0, pos).split(':');
  1396. parts.hostname = t[0] || null;
  1397. parts.port = t[1] || null;
  1398. }
  1399. }
  1400. if (parts.hostname && string.substring(pos).charAt(0) !== '/') {
  1401. pos++;
  1402. string = '/' + string;
  1403. }
  1404. if (parts.preventInvalidHostname) {
  1405. URI.ensureValidHostname(parts.hostname, parts.protocol);
  1406. }
  1407. if (parts.port) {
  1408. URI.ensureValidPort(parts.port);
  1409. }
  1410. return string.substring(pos) || '/';
  1411. };
  1412. URI.parseAuthority = function(string, parts) {
  1413. string = URI.parseUserinfo(string, parts);
  1414. return URI.parseHost(string, parts);
  1415. };
  1416. URI.parseUserinfo = function(string, parts) {
  1417. // extract username:password
  1418. var _string = string;
  1419. var firstBackSlash = string.indexOf('\\');
  1420. if (firstBackSlash !== -1) {
  1421. string = string.replace(/\\/g, '/');
  1422. }
  1423. var firstSlash = string.indexOf('/');
  1424. var pos = string.lastIndexOf('@', firstSlash > -1 ? firstSlash : string.length - 1);
  1425. var t;
  1426. // authority@ must come before /path or \path
  1427. if (pos > -1 && (firstSlash === -1 || pos < firstSlash)) {
  1428. t = string.substring(0, pos).split(':');
  1429. parts.username = t[0] ? URI.decode(t[0]) : null;
  1430. t.shift();
  1431. parts.password = t[0] ? URI.decode(t.join(':')) : null;
  1432. string = _string.substring(pos + 1);
  1433. } else {
  1434. parts.username = null;
  1435. parts.password = null;
  1436. }
  1437. return string;
  1438. };
  1439. URI.parseQuery = function(string, escapeQuerySpace) {
  1440. if (!string) {
  1441. return {};
  1442. }
  1443. // throw out the funky business - "?"[name"="value"&"]+
  1444. string = string.replace(/&+/g, '&').replace(/^\?*&*|&+$/g, '');
  1445. if (!string) {
  1446. return {};
  1447. }
  1448. var items = {};
  1449. var splits = string.split('&');
  1450. var length = splits.length;
  1451. var v, name, value;
  1452. for (var i = 0; i < length; i++) {
  1453. v = splits[i].split('=');
  1454. name = URI.decodeQuery(v.shift(), escapeQuerySpace);
  1455. // no "=" is null according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#collect-url-parameters
  1456. value = v.length ? URI.decodeQuery(v.join('='), escapeQuerySpace) : null;
  1457. if (name === '__proto__') {
  1458. // ignore attempt at exploiting JavaScript internals
  1459. continue;
  1460. } else if (hasOwn.call(items, name)) {
  1461. if (typeof items[name] === 'string' || items[name] === null) {
  1462. items[name] = [items[name]];
  1463. }
  1464. items[name].push(value);
  1465. } else {
  1466. items[name] = value;
  1467. }
  1468. }
  1469. return items;
  1470. };
  1471. URI.build = function(parts) {
  1472. var t = '';
  1473. var requireAbsolutePath = false;
  1474. if (parts.protocol) {
  1475. t += parts.protocol + ':';
  1476. }
  1477. if (!parts.urn && (t || parts.hostname)) {
  1478. t += '//';
  1479. requireAbsolutePath = true;
  1480. }
  1481. t += (URI.buildAuthority(parts) || '');
  1482. if (typeof parts.path === 'string') {
  1483. if (parts.path.charAt(0) !== '/' && requireAbsolutePath) {
  1484. t += '/';
  1485. }
  1486. t += parts.path;
  1487. }
  1488. if (typeof parts.query === 'string' && parts.query) {
  1489. t += '?' + parts.query;
  1490. }
  1491. if (typeof parts.fragment === 'string' && parts.fragment) {
  1492. t += '#' + parts.fragment;
  1493. }
  1494. return t;
  1495. };
  1496. URI.buildHost = function(parts) {
  1497. var t = '';
  1498. if (!parts.hostname) {
  1499. return '';
  1500. } else if (URI.ip6_expression.test(parts.hostname)) {
  1501. t += '[' + parts.hostname + ']';
  1502. } else {
  1503. t += parts.hostname;
  1504. }
  1505. if (parts.port) {
  1506. t += ':' + parts.port;
  1507. }
  1508. return t;
  1509. };
  1510. URI.buildAuthority = function(parts) {
  1511. return URI.buildUserinfo(parts) + URI.buildHost(parts);
  1512. };
  1513. URI.buildUserinfo = function(parts) {
  1514. var t = '';
  1515. if (parts.username) {
  1516. t += URI.encode(parts.username);
  1517. }
  1518. if (parts.password) {
  1519. t += ':' + URI.encode(parts.password);
  1520. }
  1521. if (t) {
  1522. t += '@';
  1523. }
  1524. return t;
  1525. };
  1526. URI.buildQuery = function(data, duplicateQueryParameters, escapeQuerySpace) {
  1527. // according to http://tools.ietf.org/html/rfc3986 or http://labs.apache.org/webarch/uri/rfc/rfc3986.html
  1528. // being »-._~!$&'()*+,;=:@/?« %HEX and alnum are allowed
  1529. // the RFC explicitly states ?/foo being a valid use case, no mention of parameter syntax!
  1530. // URI.js treats the query string as being application/x-www-form-urlencoded
  1531. // see http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type
  1532. var t = '';
  1533. var unique, key, i, length;
  1534. for (key in data) {
  1535. if (key === '__proto__') {
  1536. // ignore attempt at exploiting JavaScript internals
  1537. continue;
  1538. } else if (hasOwn.call(data, key)) {
  1539. if (isArray(data[key])) {
  1540. unique = {};
  1541. for (i = 0, length = data[key].length; i < length; i++) {
  1542. if (data[key][i] !== undefined && unique[data[key][i] + ''] === undefined) {
  1543. t += '&' + URI.buildQueryParameter(key, data[key][i], escapeQuerySpace);
  1544. if (duplicateQueryParameters !== true) {
  1545. unique[data[key][i] + ''] = true;
  1546. }
  1547. }
  1548. }
  1549. } else if (data[key] !== undefined) {
  1550. t += '&' + URI.buildQueryParameter(key, data[key], escapeQuerySpace);
  1551. }
  1552. }
  1553. }
  1554. return t.substring(1);
  1555. };
  1556. URI.buildQueryParameter = function(name, value, escapeQuerySpace) {
  1557. // http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type -- application/x-www-form-urlencoded
  1558. // don't append "=" for null values, according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#url-parameter-serialization
  1559. return URI.encodeQuery(name, escapeQuerySpace) + (value !== null ? '=' + URI.encodeQuery(value, escapeQuerySpace) : '');
  1560. };
  1561. URI.addQuery = function(data, name, value) {
  1562. if (typeof name === 'object') {
  1563. for (var key in name) {
  1564. if (hasOwn.call(name, key)) {
  1565. URI.addQuery(data, key, name[key]);
  1566. }
  1567. }
  1568. } else if (typeof name === 'string') {
  1569. if (data[name] === undefined) {
  1570. data[name] = value;
  1571. return;
  1572. } else if (typeof data[name] === 'string') {
  1573. data[name] = [data[name]];
  1574. }
  1575. if (!isArray(value)) {
  1576. value = [value];
  1577. }
  1578. data[name] = (data[name] || []).concat(value);
  1579. } else {
  1580. throw new TypeError('URI.addQuery() accepts an object, string as the name parameter');
  1581. }
  1582. };
  1583. URI.setQuery = function(data, name, value) {
  1584. if (typeof name === 'object') {
  1585. for (var key in name) {
  1586. if (hasOwn.call(name, key)) {
  1587. URI.setQuery(data, key, name[key]);
  1588. }
  1589. }
  1590. } else if (typeof name === 'string') {
  1591. data[name] = value === undefined ? null : value;
  1592. } else {
  1593. throw new TypeError('URI.setQuery() accepts an object, string as the name parameter');
  1594. }
  1595. };
  1596. URI.removeQuery = function(data, name, value) {
  1597. var i, length, key;
  1598. if (isArray(name)) {
  1599. for (i = 0, length = name.length; i < length; i++) {
  1600. data[name[i]] = undefined;
  1601. }
  1602. } else if (getType(name) === 'RegExp') {
  1603. for (key in data) {
  1604. if (name.test(key)) {
  1605. data[key] = undefined;
  1606. }
  1607. }
  1608. } else if (typeof name === 'object') {
  1609. for (key in name) {
  1610. if (hasOwn.call(name, key)) {
  1611. URI.removeQuery(data, key, name[key]);
  1612. }
  1613. }
  1614. } else if (typeof name === 'string') {
  1615. if (value !== undefined) {
  1616. if (getType(value) === 'RegExp') {
  1617. if (!isArray(data[name]) && value.test(data[name])) {
  1618. data[name] = undefined;
  1619. } else {
  1620. data[name] = filterArrayValues(data[name], value);
  1621. }
  1622. } else if (data[name] === String(value) && (!isArray(value) || value.length === 1)) {
  1623. data[name] = undefined;
  1624. } else if (isArray(data[name])) {
  1625. data[name] = filterArrayValues(data[name], value);
  1626. }
  1627. } else {
  1628. data[name] = undefined;
  1629. }
  1630. } else {
  1631. throw new TypeError('URI.removeQuery() accepts an object, string, RegExp as the first parameter');
  1632. }
  1633. };
  1634. URI.hasQuery = function(data, name, value, withinArray) {
  1635. switch (getType(name)) {
  1636. case 'String':
  1637. // Nothing to do here
  1638. break;
  1639. case 'RegExp':
  1640. for (var key in data) {
  1641. if (hasOwn.call(data, key)) {
  1642. if (name.test(key) && (value === undefined || URI.hasQuery(data, key, value))) {
  1643. return true;
  1644. }
  1645. }
  1646. }
  1647. return false;
  1648. case 'Object':
  1649. for (var _key in name) {
  1650. if (hasOwn.call(name, _key)) {
  1651. if (!URI.hasQuery(data, _key, name[_key])) {
  1652. return false;
  1653. }
  1654. }
  1655. }
  1656. return true;
  1657. default:
  1658. throw new TypeError('URI.hasQuery() accepts a string, regular expression or object as the name parameter');
  1659. }
  1660. switch (getType(value)) {
  1661. case 'Undefined':
  1662. // true if exists (but may be empty)
  1663. return name in data; // data[name] !== undefined;
  1664. case 'Boolean':
  1665. // true if exists and non-empty
  1666. var _booly = Boolean(isArray(data[name]) ? data[name].length : data[name]);
  1667. return value === _booly;
  1668. case 'Function':
  1669. // allow complex comparison
  1670. return !!value(data[name], name, data);
  1671. case 'Array':
  1672. if (!isArray(data[name])) {
  1673. return false;
  1674. }
  1675. var op = withinArray ? arrayContains : arraysEqual;
  1676. return op(data[name], value);
  1677. case 'RegExp':
  1678. if (!isArray(data[name])) {
  1679. return Boolean(data[name] && data[name].match(value));
  1680. }
  1681. if (!withinArray) {
  1682. return false;
  1683. }
  1684. return arrayContains(data[name], value);
  1685. case 'Number':
  1686. value = String(value);
  1687. /* falls through */
  1688. case 'String':
  1689. if (!isArray(data[name])) {
  1690. return data[name] === value;
  1691. }
  1692. if (!withinArray) {
  1693. return false;
  1694. }
  1695. return arrayContains(data[name], value);
  1696. default:
  1697. throw new TypeError('URI.hasQuery() accepts undefined, boolean, string, number, RegExp, Function as the value parameter');
  1698. }
  1699. };
  1700. URI.joinPaths = function() {
  1701. var input = [];
  1702. var segments = [];
  1703. var nonEmptySegments = 0;
  1704. for (var i = 0; i < arguments.length; i++) {
  1705. var url = new URI(arguments[i]);
  1706. input.push(url);
  1707. var _segments = url.segment();
  1708. for (var s = 0; s < _segments.length; s++) {
  1709. if (typeof _segments[s] === 'string') {
  1710. segments.push(_segments[s]);
  1711. }
  1712. if (_segments[s]) {
  1713. nonEmptySegments++;
  1714. }
  1715. }
  1716. }
  1717. if (!segments.length || !nonEmptySegments) {
  1718. return new URI('');
  1719. }
  1720. var uri = new URI('').segment(segments);
  1721. if (input[0].path() === '' || input[0].path().slice(0, 1) === '/') {
  1722. uri.path('/' + uri.path());
  1723. }
  1724. return uri.normalize();
  1725. };
  1726. URI.commonPath = function(one, two) {
  1727. var length = Math.min(one.length, two.length);
  1728. var pos;
  1729. // find first non-matching character
  1730. for (pos = 0; pos < length; pos++) {
  1731. if (one.charAt(pos) !== two.charAt(pos)) {
  1732. pos--;
  1733. break;
  1734. }
  1735. }
  1736. if (pos < 1) {
  1737. return one.charAt(0) === two.charAt(0) && one.charAt(0) === '/' ? '/' : '';
  1738. }
  1739. // revert to last /
  1740. if (one.charAt(pos) !== '/' || two.charAt(pos) !== '/') {
  1741. pos = one.substring(0, pos).lastIndexOf('/');
  1742. }
  1743. return one.substring(0, pos + 1);
  1744. };
  1745. URI.withinString = function(string, callback, options) {
  1746. options || (options = {});
  1747. var _start = options.start || URI.findUri.start;
  1748. var _end = options.end || URI.findUri.end;
  1749. var _trim = options.trim || URI.findUri.trim;
  1750. var _parens = options.parens || URI.findUri.parens;
  1751. var _attributeOpen = /[a-z0-9-]=["']?$/i;
  1752. _start.lastIndex = 0;
  1753. while (true) {
  1754. var match = _start.exec(string);
  1755. if (!match) {
  1756. break;
  1757. }
  1758. var start = match.index;
  1759. if (options.ignoreHtml) {
  1760. // attribut(e=["']?$)
  1761. var attributeOpen = string.slice(Math.max(start - 3, 0), start);
  1762. if (attributeOpen && _attributeOpen.test(attributeOpen)) {
  1763. continue;
  1764. }
  1765. }
  1766. var end = start + string.slice(start).search(_end);
  1767. var slice = string.slice(start, end);
  1768. // make sure we include well balanced parens
  1769. var parensEnd = -1;
  1770. while (true) {
  1771. var parensMatch = _parens.exec(slice);
  1772. if (!parensMatch) {
  1773. break;
  1774. }
  1775. var parensMatchEnd = parensMatch.index + parensMatch[0].length;
  1776. parensEnd = Math.max(parensEnd, parensMatchEnd);
  1777. }
  1778. if (parensEnd > -1) {
  1779. slice = slice.slice(0, parensEnd) + slice.slice(parensEnd).replace(_trim, '');
  1780. } else {
  1781. slice = slice.replace(_trim, '');
  1782. }
  1783. if (slice.length <= match[0].length) {
  1784. // the extract only contains the starting marker of a URI,
  1785. // e.g. "www" or "http://"
  1786. continue;
  1787. }
  1788. if (options.ignore && options.ignore.test(slice)) {
  1789. continue;
  1790. }
  1791. end = start + slice.length;
  1792. var result = callback(slice, start, end, string);
  1793. if (result === undefined) {
  1794. _start.lastIndex = end;
  1795. continue;
  1796. }
  1797. result = String(result);
  1798. string = string.slice(0, start) + result + string.slice(end);
  1799. _start.lastIndex = start + result.length;
  1800. }
  1801. _start.lastIndex = 0;
  1802. return string;
  1803. };
  1804. URI.ensureValidHostname = function(v, protocol) {
  1805. // Theoretically URIs allow percent-encoding in Hostnames (according to RFC 3986)
  1806. // they are not part of DNS and therefore ignored by URI.js
  1807. var hasHostname = !!v; // not null and not an empty string
  1808. var hasProtocol = !!protocol;
  1809. var rejectEmptyHostname = false;
  1810. if (hasProtocol) {
  1811. rejectEmptyHostname = arrayContains(URI.hostProtocols, protocol);
  1812. }
  1813. if (rejectEmptyHostname && !hasHostname) {
  1814. throw new TypeError('Hostname cannot be empty, if protocol is ' + protocol);
  1815. } else if (v && v.match(URI.invalid_hostname_characters)) {
  1816. // test punycode
  1817. if (!punycode) {
  1818. throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_] and Punycode.js is not available');
  1819. }
  1820. if (punycode.toASCII(v).match(URI.invalid_hostname_characters)) {
  1821. throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_]');
  1822. }
  1823. }
  1824. };
  1825. URI.ensureValidPort = function (v) {
  1826. if (!v) {
  1827. return;
  1828. }
  1829. var port = Number(v);
  1830. if (isInteger(port) && (port > 0) && (port < 65536)) {
  1831. return;
  1832. }
  1833. throw new TypeError('Port "' + v + '" is not a valid port');
  1834. };
  1835. // noConflict
  1836. URI.noConflict = function(removeAll) {
  1837. if (removeAll) {
  1838. var unconflicted = {
  1839. URI: this.noConflict()
  1840. };
  1841. if (root.URITemplate && typeof root.URITemplate.noConflict === 'function') {
  1842. unconflicted.URITemplate = root.URITemplate.noConflict();
  1843. }
  1844. if (root.IPv6 && typeof root.IPv6.noConflict === 'function') {
  1845. unconflicted.IPv6 = root.IPv6.noConflict();
  1846. }
  1847. if (root.SecondLevelDomains && typeof root.SecondLevelDomains.noConflict === 'function') {
  1848. unconflicted.SecondLevelDomains = root.SecondLevelDomains.noConflict();
  1849. }
  1850. return unconflicted;
  1851. } else if (root.URI === this) {
  1852. root.URI = _URI;
  1853. }
  1854. return this;
  1855. };
  1856. p.build = function(deferBuild) {
  1857. if (deferBuild === true) {
  1858. this._deferred_build = true;
  1859. } else if (deferBuild === undefined || this._deferred_build) {
  1860. this._string = URI.build(this._parts);
  1861. this._deferred_build = false;
  1862. }
  1863. return this;
  1864. };
  1865. p.clone = function() {
  1866. return new URI(this);
  1867. };
  1868. p.valueOf = p.toString = function() {
  1869. return this.build(false)._string;
  1870. };
  1871. function generateSimpleAccessor(_part){
  1872. return function(v, build) {
  1873. if (v === undefined) {
  1874. return this._parts[_part] || '';
  1875. } else {
  1876. this._parts[_part] = v || null;
  1877. this.build(!build);
  1878. return this;
  1879. }
  1880. };
  1881. }
  1882. function generatePrefixAccessor(_part, _key){
  1883. return function(v, build) {
  1884. if (v === undefined) {
  1885. return this._parts[_part] || '';
  1886. } else {
  1887. if (v !== null) {
  1888. v = v + '';
  1889. if (v.charAt(0) === _key) {
  1890. v = v.substring(1);
  1891. }
  1892. }
  1893. this._parts[_part] = v;
  1894. this.build(!build);
  1895. return this;
  1896. }
  1897. };
  1898. }
  1899. p.protocol = generateSimpleAccessor('protocol');
  1900. p.username = generateSimpleAccessor('username');
  1901. p.password = generateSimpleAccessor('password');
  1902. p.hostname = generateSimpleAccessor('hostname');
  1903. p.port = generateSimpleAccessor('port');
  1904. p.query = generatePrefixAccessor('query', '?');
  1905. p.fragment = generatePrefixAccessor('fragment', '#');
  1906. p.search = function(v, build) {
  1907. var t = this.query(v, build);
  1908. return typeof t === 'string' && t.length ? ('?' + t) : t;
  1909. };
  1910. p.hash = function(v, build) {
  1911. var t = this.fragment(v, build);
  1912. return typeof t === 'string' && t.length ? ('#' + t) : t;
  1913. };
  1914. p.pathname = function(v, build) {
  1915. if (v === undefined || v === true) {
  1916. var res = this._parts.path || (this._parts.hostname ? '/' : '');
  1917. return v ? (this._parts.urn ? URI.decodeUrnPath : URI.decodePath)(res) : res;
  1918. } else {
  1919. if (this._parts.urn) {
  1920. this._parts.path = v ? URI.recodeUrnPath(v) : '';
  1921. } else {
  1922. this._parts.path = v ? URI.recodePath(v) : '/';
  1923. }
  1924. this.build(!build);
  1925. return this;
  1926. }
  1927. };
  1928. p.path = p.pathname;
  1929. p.href = function(href, build) {
  1930. var key;
  1931. if (href === undefined) {
  1932. return this.toString();
  1933. }
  1934. this._string = '';
  1935. this._parts = URI._parts();
  1936. var _URI = href instanceof URI;
  1937. var _object = typeof href === 'object' && (href.hostname || href.path || href.pathname);
  1938. if (href.nodeName) {
  1939. var attribute = URI.getDomAttribute(href);
  1940. href = href[attribute] || '';
  1941. _object = false;
  1942. }
  1943. // window.location is reported to be an object, but it's not the sort
  1944. // of object we're looking for:
  1945. // * location.protocol ends with a colon
  1946. // * location.query != object.search
  1947. // * location.hash != object.fragment
  1948. // simply serializing the unknown object should do the trick
  1949. // (for location, not for everything...)
  1950. if (!_URI && _object && href.pathname !== undefined) {
  1951. href = href.toString();
  1952. }
  1953. if (typeof href === 'string' || href instanceof String) {
  1954. this._parts = URI.parse(String(href), this._parts);
  1955. } else if (_URI || _object) {
  1956. var src = _URI ? href._parts : href;
  1957. for (key in src) {
  1958. if (key === 'query') { continue; }
  1959. if (hasOwn.call(this._parts, key)) {
  1960. this._parts[key] = src[key];
  1961. }
  1962. }
  1963. if (src.query) {
  1964. this.query(src.query, false);
  1965. }
  1966. } else {
  1967. throw new TypeError('invalid input');
  1968. }
  1969. this.build(!build);
  1970. return this;
  1971. };
  1972. // identification accessors
  1973. p.is = function(what) {
  1974. var ip = false;
  1975. var ip4 = false;
  1976. var ip6 = false;
  1977. var name = false;
  1978. var sld = false;
  1979. var idn = false;
  1980. var punycode = false;
  1981. var relative = !this._parts.urn;
  1982. if (this._parts.hostname) {
  1983. relative = false;
  1984. ip4 = URI.ip4_expression.test(this._parts.hostname);
  1985. ip6 = URI.ip6_expression.test(this._parts.hostname);
  1986. ip = ip4 || ip6;
  1987. name = !ip;
  1988. sld = name && SLD && SLD.has(this._parts.hostname);
  1989. idn = name && URI.idn_expression.test(this._parts.hostname);
  1990. punycode = name && URI.punycode_expression.test(this._parts.hostname);
  1991. }
  1992. switch (what.toLowerCase()) {
  1993. case 'relative':
  1994. return relative;
  1995. case 'absolute':
  1996. return !relative;
  1997. // hostname identification
  1998. case 'domain':
  1999. case 'name':
  2000. return name;
  2001. case 'sld':
  2002. return sld;
  2003. case 'ip':
  2004. return ip;
  2005. case 'ip4':
  2006. case 'ipv4':
  2007. case 'inet4':
  2008. return ip4;
  2009. case 'ip6':
  2010. case 'ipv6':
  2011. case 'inet6':
  2012. return ip6;
  2013. case 'idn':
  2014. return idn;
  2015. case 'url':
  2016. return !this._parts.urn;
  2017. case 'urn':
  2018. return !!this._parts.urn;
  2019. case 'punycode':
  2020. return punycode;
  2021. }
  2022. return null;
  2023. };
  2024. // component specific input validation
  2025. var _protocol = p.protocol;
  2026. var _port = p.port;
  2027. var _hostname = p.hostname;
  2028. p.protocol = function(v, build) {
  2029. if (v) {
  2030. // accept trailing ://
  2031. v = v.replace(/:(\/\/)?$/, '');
  2032. if (!v.match(URI.protocol_expression)) {
  2033. throw new TypeError('Protocol "' + v + '" contains characters other than [A-Z0-9.+-] or doesn\'t start with [A-Z]');
  2034. }
  2035. }
  2036. return _protocol.call(this, v, build);
  2037. };
  2038. p.scheme = p.protocol;
  2039. p.port = function(v, build) {
  2040. if (this._parts.urn) {
  2041. return v === undefined ? '' : this;
  2042. }
  2043. if (v !== undefined) {
  2044. if (v === 0) {
  2045. v = null;
  2046. }
  2047. if (v) {
  2048. v += '';
  2049. if (v.charAt(0) === ':') {
  2050. v = v.substring(1);
  2051. }
  2052. URI.ensureValidPort(v);
  2053. }
  2054. }
  2055. return _port.call(this, v, build);
  2056. };
  2057. p.hostname = function(v, build) {
  2058. if (this._parts.urn) {
  2059. return v === undefined ? '' : this;
  2060. }
  2061. if (v !== undefined) {
  2062. var x = { preventInvalidHostname: this._parts.preventInvalidHostname };
  2063. var res = URI.parseHost(v, x);
  2064. if (res !== '/') {
  2065. throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
  2066. }
  2067. v = x.hostname;
  2068. if (this._parts.preventInvalidHostname) {
  2069. URI.ensureValidHostname(v, this._parts.protocol);
  2070. }
  2071. }
  2072. return _hostname.call(this, v, build);
  2073. };
  2074. // compound accessors
  2075. p.origin = function(v, build) {
  2076. if (this._parts.urn) {
  2077. return v === undefined ? '' : this;
  2078. }
  2079. if (v === undefined) {
  2080. var protocol = this.protocol();
  2081. var authority = this.authority();
  2082. if (!authority) {
  2083. return '';
  2084. }
  2085. return (protocol ? protocol + '://' : '') + this.authority();
  2086. } else {
  2087. var origin = URI(v);
  2088. this
  2089. .protocol(origin.protocol())
  2090. .authority(origin.authority())
  2091. .build(!build);
  2092. return this;
  2093. }
  2094. };
  2095. p.host = function(v, build) {
  2096. if (this._parts.urn) {
  2097. return v === undefined ? '' : this;
  2098. }
  2099. if (v === undefined) {
  2100. return this._parts.hostname ? URI.buildHost(this._parts) : '';
  2101. } else {
  2102. var res = URI.parseHost(v, this._parts);
  2103. if (res !== '/') {
  2104. throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
  2105. }
  2106. this.build(!build);
  2107. return this;
  2108. }
  2109. };
  2110. p.authority = function(v, build) {
  2111. if (this._parts.urn) {
  2112. return v === undefined ? '' : this;
  2113. }
  2114. if (v === undefined) {
  2115. return this._parts.hostname ? URI.buildAuthority(this._parts) : '';
  2116. } else {
  2117. var res = URI.parseAuthority(v, this._parts);
  2118. if (res !== '/') {
  2119. throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
  2120. }
  2121. this.build(!build);
  2122. return this;
  2123. }
  2124. };
  2125. p.userinfo = function(v, build) {
  2126. if (this._parts.urn) {
  2127. return v === undefined ? '' : this;
  2128. }
  2129. if (v === undefined) {
  2130. var t = URI.buildUserinfo(this._parts);
  2131. return t ? t.substring(0, t.length -1) : t;
  2132. } else {
  2133. if (v[v.length-1] !== '@') {
  2134. v += '@';
  2135. }
  2136. URI.parseUserinfo(v, this._parts);
  2137. this.build(!build);
  2138. return this;
  2139. }
  2140. };
  2141. p.resource = function(v, build) {
  2142. var parts;
  2143. if (v === undefined) {
  2144. return this.path() + this.search() + this.hash();
  2145. }
  2146. parts = URI.parse(v);
  2147. this._parts.path = parts.path;
  2148. this._parts.query = parts.query;
  2149. this._parts.fragment = parts.fragment;
  2150. this.build(!build);
  2151. return this;
  2152. };
  2153. // fraction accessors
  2154. p.subdomain = function(v, build) {
  2155. if (this._parts.urn) {
  2156. return v === undefined ? '' : this;
  2157. }
  2158. // convenience, return "www" from "www.example.org"
  2159. if (v === undefined) {
  2160. if (!this._parts.hostname || this.is('IP')) {
  2161. return '';
  2162. }
  2163. // grab domain and add another segment
  2164. var end = this._parts.hostname.length - this.domain().length - 1;
  2165. return this._parts.hostname.substring(0, end) || '';
  2166. } else {
  2167. var e = this._parts.hostname.length - this.domain().length;
  2168. var sub = this._parts.hostname.substring(0, e);
  2169. var replace = new RegExp('^' + escapeRegEx(sub));
  2170. if (v && v.charAt(v.length - 1) !== '.') {
  2171. v += '.';
  2172. }
  2173. if (v.indexOf(':') !== -1) {
  2174. throw new TypeError('Domains cannot contain colons');
  2175. }
  2176. if (v) {
  2177. URI.ensureValidHostname(v, this._parts.protocol);
  2178. }
  2179. this._parts.hostname = this._parts.hostname.replace(replace, v);
  2180. this.build(!build);
  2181. return this;
  2182. }
  2183. };
  2184. p.domain = function(v, build) {
  2185. if (this._parts.urn) {
  2186. return v === undefined ? '' : this;
  2187. }
  2188. if (typeof v === 'boolean') {
  2189. build = v;
  2190. v = undefined;
  2191. }
  2192. // convenience, return "example.org" from "www.example.org"
  2193. if (v === undefined) {
  2194. if (!this._parts.hostname || this.is('IP')) {
  2195. return '';
  2196. }
  2197. // if hostname consists of 1 or 2 segments, it must be the domain
  2198. var t = this._parts.hostname.match(/\./g);
  2199. if (t && t.length < 2) {
  2200. return this._parts.hostname;
  2201. }
  2202. // grab tld and add another segment
  2203. var end = this._parts.hostname.length - this.tld(build).length - 1;
  2204. end = this._parts.hostname.lastIndexOf('.', end -1) + 1;
  2205. return this._parts.hostname.substring(end) || '';
  2206. } else {
  2207. if (!v) {
  2208. throw new TypeError('cannot set domain empty');
  2209. }
  2210. if (v.indexOf(':') !== -1) {
  2211. throw new TypeError('Domains cannot contain colons');
  2212. }
  2213. URI.ensureValidHostname(v, this._parts.protocol);
  2214. if (!this._parts.hostname || this.is('IP')) {
  2215. this._parts.hostname = v;
  2216. } else {
  2217. var replace = new RegExp(escapeRegEx(this.domain()) + '$');
  2218. this._parts.hostname = this._parts.hostname.replace(replace, v);
  2219. }
  2220. this.build(!build);
  2221. return this;
  2222. }
  2223. };
  2224. p.tld = function(v, build) {
  2225. if (this._parts.urn) {
  2226. return v === undefined ? '' : this;
  2227. }
  2228. if (typeof v === 'boolean') {
  2229. build = v;
  2230. v = undefined;
  2231. }
  2232. // return "org" from "www.example.org"
  2233. if (v === undefined) {
  2234. if (!this._parts.hostname || this.is('IP')) {
  2235. return '';
  2236. }
  2237. var pos = this._parts.hostname.lastIndexOf('.');
  2238. var tld = this._parts.hostname.substring(pos + 1);
  2239. if (build !== true && SLD && SLD.list[tld.toLowerCase()]) {
  2240. return SLD.get(this._parts.hostname) || tld;
  2241. }
  2242. return tld;
  2243. } else {
  2244. var replace;
  2245. if (!v) {
  2246. throw new TypeError('cannot set TLD empty');
  2247. } else if (v.match(/[^a-zA-Z0-9-]/)) {
  2248. if (SLD && SLD.is(v)) {
  2249. replace = new RegExp(escapeRegEx(this.tld()) + '$');
  2250. this._parts.hostname = this._parts.hostname.replace(replace, v);
  2251. } else {
  2252. throw new TypeError('TLD "' + v + '" contains characters other than [A-Z0-9]');
  2253. }
  2254. } else if (!this._parts.hostname || this.is('IP')) {
  2255. throw new ReferenceError('cannot set TLD on non-domain host');
  2256. } else {
  2257. replace = new RegExp(escapeRegEx(this.tld()) + '$');
  2258. this._parts.hostname = this._parts.hostname.replace(replace, v);
  2259. }
  2260. this.build(!build);
  2261. return this;
  2262. }
  2263. };
  2264. p.directory = function(v, build) {
  2265. if (this._parts.urn) {
  2266. return v === undefined ? '' : this;
  2267. }
  2268. if (v === undefined || v === true) {
  2269. if (!this._parts.path && !this._parts.hostname) {
  2270. return '';
  2271. }
  2272. if (this._parts.path === '/') {
  2273. return '/';
  2274. }
  2275. var end = this._parts.path.length - this.filename().length - 1;
  2276. var res = this._parts.path.substring(0, end) || (this._parts.hostname ? '/' : '');
  2277. return v ? URI.decodePath(res) : res;
  2278. } else {
  2279. var e = this._parts.path.length - this.filename().length;
  2280. var directory = this._parts.path.substring(0, e);
  2281. var replace = new RegExp('^' + escapeRegEx(directory));
  2282. // fully qualifier directories begin with a slash
  2283. if (!this.is('relative')) {
  2284. if (!v) {
  2285. v = '/';
  2286. }
  2287. if (v.charAt(0) !== '/') {
  2288. v = '/' + v;
  2289. }
  2290. }
  2291. // directories always end with a slash
  2292. if (v && v.charAt(v.length - 1) !== '/') {
  2293. v += '/';
  2294. }
  2295. v = URI.recodePath(v);
  2296. this._parts.path = this._parts.path.replace(replace, v);
  2297. this.build(!build);
  2298. return this;
  2299. }
  2300. };
  2301. p.filename = function(v, build) {
  2302. if (this._parts.urn) {
  2303. return v === undefined ? '' : this;
  2304. }
  2305. if (typeof v !== 'string') {
  2306. if (!this._parts.path || this._parts.path === '/') {
  2307. return '';
  2308. }
  2309. var pos = this._parts.path.lastIndexOf('/');
  2310. var res = this._parts.path.substring(pos+1);
  2311. return v ? URI.decodePathSegment(res) : res;
  2312. } else {
  2313. var mutatedDirectory = false;
  2314. if (v.charAt(0) === '/') {
  2315. v = v.substring(1);
  2316. }
  2317. if (v.match(/\.?\//)) {
  2318. mutatedDirectory = true;
  2319. }
  2320. var replace = new RegExp(escapeRegEx(this.filename()) + '$');
  2321. v = URI.recodePath(v);
  2322. this._parts.path = this._parts.path.replace(replace, v);
  2323. if (mutatedDirectory) {
  2324. this.normalizePath(build);
  2325. } else {
  2326. this.build(!build);
  2327. }
  2328. return this;
  2329. }
  2330. };
  2331. p.suffix = function(v, build) {
  2332. if (this._parts.urn) {
  2333. return v === undefined ? '' : this;
  2334. }
  2335. if (v === undefined || v === true) {
  2336. if (!this._parts.path || this._parts.path === '/') {
  2337. return '';
  2338. }
  2339. var filename = this.filename();
  2340. var pos = filename.lastIndexOf('.');
  2341. var s, res;
  2342. if (pos === -1) {
  2343. return '';
  2344. }
  2345. // suffix may only contain alnum characters (yup, I made this up.)
  2346. s = filename.substring(pos+1);
  2347. res = (/^[a-z0-9%]+$/i).test(s) ? s : '';
  2348. return v ? URI.decodePathSegment(res) : res;
  2349. } else {
  2350. if (v.charAt(0) === '.') {
  2351. v = v.substring(1);
  2352. }
  2353. var suffix = this.suffix();
  2354. var replace;
  2355. if (!suffix) {
  2356. if (!v) {
  2357. return this;
  2358. }
  2359. this._parts.path += '.' + URI.recodePath(v);
  2360. } else if (!v) {
  2361. replace = new RegExp(escapeRegEx('.' + suffix) + '$');
  2362. } else {
  2363. replace = new RegExp(escapeRegEx(suffix) + '$');
  2364. }
  2365. if (replace) {
  2366. v = URI.recodePath(v);
  2367. this._parts.path = this._parts.path.replace(replace, v);
  2368. }
  2369. this.build(!build);
  2370. return this;
  2371. }
  2372. };
  2373. p.segment = function(segment, v, build) {
  2374. var separator = this._parts.urn ? ':' : '/';
  2375. var path = this.path();
  2376. var absolute = path.substring(0, 1) === '/';
  2377. var segments = path.split(separator);
  2378. if (segment !== undefined && typeof segment !== 'number') {
  2379. build = v;
  2380. v = segment;
  2381. segment = undefined;
  2382. }
  2383. if (segment !== undefined && typeof segment !== 'number') {
  2384. throw new Error('Bad segment "' + segment + '", must be 0-based integer');
  2385. }
  2386. if (absolute) {
  2387. segments.shift();
  2388. }
  2389. if (segment < 0) {
  2390. // allow negative indexes to address from the end
  2391. segment = Math.max(segments.length + segment, 0);
  2392. }
  2393. if (v === undefined) {
  2394. /*jshint laxbreak: true */
  2395. return segment === undefined
  2396. ? segments
  2397. : segments[segment];
  2398. /*jshint laxbreak: false */
  2399. } else if (segment === null || segments[segment] === undefined) {
  2400. if (isArray(v)) {
  2401. segments = [];
  2402. // collapse empty elements within array
  2403. for (var i=0, l=v.length; i < l; i++) {
  2404. if (!v[i].length && (!segments.length || !segments[segments.length -1].length)) {
  2405. continue;
  2406. }
  2407. if (segments.length && !segments[segments.length -1].length) {
  2408. segments.pop();
  2409. }
  2410. segments.push(trimSlashes(v[i]));
  2411. }
  2412. } else if (v || typeof v === 'string') {
  2413. v = trimSlashes(v);
  2414. if (segments[segments.length -1] === '') {
  2415. // empty trailing elements have to be overwritten
  2416. // to prevent results such as /foo//bar
  2417. segments[segments.length -1] = v;
  2418. } else {
  2419. segments.push(v);
  2420. }
  2421. }
  2422. } else {
  2423. if (v) {
  2424. segments[segment] = trimSlashes(v);
  2425. } else {
  2426. segments.splice(segment, 1);
  2427. }
  2428. }
  2429. if (absolute) {
  2430. segments.unshift('');
  2431. }
  2432. return this.path(segments.join(separator), build);
  2433. };
  2434. p.segmentCoded = function(segment, v, build) {
  2435. var segments, i, l;
  2436. if (typeof segment !== 'number') {
  2437. build = v;
  2438. v = segment;
  2439. segment = undefined;
  2440. }
  2441. if (v === undefined) {
  2442. segments = this.segment(segment, v, build);
  2443. if (!isArray(segments)) {
  2444. segments = segments !== undefined ? URI.decode(segments) : undefined;
  2445. } else {
  2446. for (i = 0, l = segments.length; i < l; i++) {
  2447. segments[i] = URI.decode(segments[i]);
  2448. }
  2449. }
  2450. return segments;
  2451. }
  2452. if (!isArray(v)) {
  2453. v = (typeof v === 'string' || v instanceof String) ? URI.encode(v) : v;
  2454. } else {
  2455. for (i = 0, l = v.length; i < l; i++) {
  2456. v[i] = URI.encode(v[i]);
  2457. }
  2458. }
  2459. return this.segment(segment, v, build);
  2460. };
  2461. // mutating query string
  2462. var q = p.query;
  2463. p.query = function(v, build) {
  2464. if (v === true) {
  2465. return URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
  2466. } else if (typeof v === 'function') {
  2467. var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
  2468. var result = v.call(this, data);
  2469. this._parts.query = URI.buildQuery(result || data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
  2470. this.build(!build);
  2471. return this;
  2472. } else if (v !== undefined && typeof v !== 'string') {
  2473. this._parts.query = URI.buildQuery(v, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
  2474. this.build(!build);
  2475. return this;
  2476. } else {
  2477. return q.call(this, v, build);
  2478. }
  2479. };
  2480. p.setQuery = function(name, value, build) {
  2481. var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
  2482. if (typeof name === 'string' || name instanceof String) {
  2483. data[name] = value !== undefined ? value : null;
  2484. } else if (typeof name === 'object') {
  2485. for (var key in name) {
  2486. if (hasOwn.call(name, key)) {
  2487. data[key] = name[key];
  2488. }
  2489. }
  2490. } else {
  2491. throw new TypeError('URI.addQuery() accepts an object, string as the name parameter');
  2492. }
  2493. this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
  2494. if (typeof name !== 'string') {
  2495. build = value;
  2496. }
  2497. this.build(!build);
  2498. return this;
  2499. };
  2500. p.addQuery = function(name, value, build) {
  2501. var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
  2502. URI.addQuery(data, name, value === undefined ? null : value);
  2503. this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
  2504. if (typeof name !== 'string') {
  2505. build = value;
  2506. }
  2507. this.build(!build);
  2508. return this;
  2509. };
  2510. p.removeQuery = function(name, value, build) {
  2511. var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
  2512. URI.removeQuery(data, name, value);
  2513. this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
  2514. if (typeof name !== 'string') {
  2515. build = value;
  2516. }
  2517. this.build(!build);
  2518. return this;
  2519. };
  2520. p.hasQuery = function(name, value, withinArray) {
  2521. var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
  2522. return URI.hasQuery(data, name, value, withinArray);
  2523. };
  2524. p.setSearch = p.setQuery;
  2525. p.addSearch = p.addQuery;
  2526. p.removeSearch = p.removeQuery;
  2527. p.hasSearch = p.hasQuery;
  2528. // sanitizing URLs
  2529. p.normalize = function() {
  2530. if (this._parts.urn) {
  2531. return this
  2532. .normalizeProtocol(false)
  2533. .normalizePath(false)
  2534. .normalizeQuery(false)
  2535. .normalizeFragment(false)
  2536. .build();
  2537. }
  2538. return this
  2539. .normalizeProtocol(false)
  2540. .normalizeHostname(false)
  2541. .normalizePort(false)
  2542. .normalizePath(false)
  2543. .normalizeQuery(false)
  2544. .normalizeFragment(false)
  2545. .build();
  2546. };
  2547. p.normalizeProtocol = function(build) {
  2548. if (typeof this._parts.protocol === 'string') {
  2549. this._parts.protocol = this._parts.protocol.toLowerCase();
  2550. this.build(!build);
  2551. }
  2552. return this;
  2553. };
  2554. p.normalizeHostname = function(build) {
  2555. if (this._parts.hostname) {
  2556. if (this.is('IDN') && punycode) {
  2557. this._parts.hostname = punycode.toASCII(this._parts.hostname);
  2558. } else if (this.is('IPv6') && IPv6) {
  2559. this._parts.hostname = IPv6.best(this._parts.hostname);
  2560. }
  2561. this._parts.hostname = this._parts.hostname.toLowerCase();
  2562. this.build(!build);
  2563. }
  2564. return this;
  2565. };
  2566. p.normalizePort = function(build) {
  2567. // remove port of it's the protocol's default
  2568. if (typeof this._parts.protocol === 'string' && this._parts.port === URI.defaultPorts[this._parts.protocol]) {
  2569. this._parts.port = null;
  2570. this.build(!build);
  2571. }
  2572. return this;
  2573. };
  2574. p.normalizePath = function(build) {
  2575. var _path = this._parts.path;
  2576. if (!_path) {
  2577. return this;
  2578. }
  2579. if (this._parts.urn) {
  2580. this._parts.path = URI.recodeUrnPath(this._parts.path);
  2581. this.build(!build);
  2582. return this;
  2583. }
  2584. if (this._parts.path === '/') {
  2585. return this;
  2586. }
  2587. _path = URI.recodePath(_path);
  2588. var _was_relative;
  2589. var _leadingParents = '';
  2590. var _parent, _pos;
  2591. // handle relative paths
  2592. if (_path.charAt(0) !== '/') {
  2593. _was_relative = true;
  2594. _path = '/' + _path;
  2595. }
  2596. // handle relative files (as opposed to directories)
  2597. if (_path.slice(-3) === '/..' || _path.slice(-2) === '/.') {
  2598. _path += '/';
  2599. }
  2600. // resolve simples
  2601. _path = _path
  2602. .replace(/(\/(\.\/)+)|(\/\.$)/g, '/')
  2603. .replace(/\/{2,}/g, '/');
  2604. // remember leading parents
  2605. if (_was_relative) {
  2606. _leadingParents = _path.substring(1).match(/^(\.\.\/)+/) || '';
  2607. if (_leadingParents) {
  2608. _leadingParents = _leadingParents[0];
  2609. }
  2610. }
  2611. // resolve parents
  2612. while (true) {
  2613. _parent = _path.search(/\/\.\.(\/|$)/);
  2614. if (_parent === -1) {
  2615. // no more ../ to resolve
  2616. break;
  2617. } else if (_parent === 0) {
  2618. // top level cannot be relative, skip it
  2619. _path = _path.substring(3);
  2620. continue;
  2621. }
  2622. _pos = _path.substring(0, _parent).lastIndexOf('/');
  2623. if (_pos === -1) {
  2624. _pos = _parent;
  2625. }
  2626. _path = _path.substring(0, _pos) + _path.substring(_parent + 3);
  2627. }
  2628. // revert to relative
  2629. if (_was_relative && this.is('relative')) {
  2630. _path = _leadingParents + _path.substring(1);
  2631. }
  2632. this._parts.path = _path;
  2633. this.build(!build);
  2634. return this;
  2635. };
  2636. p.normalizePathname = p.normalizePath;
  2637. p.normalizeQuery = function(build) {
  2638. if (typeof this._parts.query === 'string') {
  2639. if (!this._parts.query.length) {
  2640. this._parts.query = null;
  2641. } else {
  2642. this.query(URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace));
  2643. }
  2644. this.build(!build);
  2645. }
  2646. return this;
  2647. };
  2648. p.normalizeFragment = function(build) {
  2649. if (!this._parts.fragment) {
  2650. this._parts.fragment = null;
  2651. this.build(!build);
  2652. }
  2653. return this;
  2654. };
  2655. p.normalizeSearch = p.normalizeQuery;
  2656. p.normalizeHash = p.normalizeFragment;
  2657. p.iso8859 = function() {
  2658. // expect unicode input, iso8859 output
  2659. var e = URI.encode;
  2660. var d = URI.decode;
  2661. URI.encode = escape;
  2662. URI.decode = decodeURIComponent;
  2663. try {
  2664. this.normalize();
  2665. } finally {
  2666. URI.encode = e;
  2667. URI.decode = d;
  2668. }
  2669. return this;
  2670. };
  2671. p.unicode = function() {
  2672. // expect iso8859 input, unicode output
  2673. var e = URI.encode;
  2674. var d = URI.decode;
  2675. URI.encode = strictEncodeURIComponent;
  2676. URI.decode = unescape;
  2677. try {
  2678. this.normalize();
  2679. } finally {
  2680. URI.encode = e;
  2681. URI.decode = d;
  2682. }
  2683. return this;
  2684. };
  2685. p.readable = function() {
  2686. var uri = this.clone();
  2687. // removing username, password, because they shouldn't be displayed according to RFC 3986
  2688. uri.username('').password('').normalize();
  2689. var t = '';
  2690. if (uri._parts.protocol) {
  2691. t += uri._parts.protocol + '://';
  2692. }
  2693. if (uri._parts.hostname) {
  2694. if (uri.is('punycode') && punycode) {
  2695. t += punycode.toUnicode(uri._parts.hostname);
  2696. if (uri._parts.port) {
  2697. t += ':' + uri._parts.port;
  2698. }
  2699. } else {
  2700. t += uri.host();
  2701. }
  2702. }
  2703. if (uri._parts.hostname && uri._parts.path && uri._parts.path.charAt(0) !== '/') {
  2704. t += '/';
  2705. }
  2706. t += uri.path(true);
  2707. if (uri._parts.query) {
  2708. var q = '';
  2709. for (var i = 0, qp = uri._parts.query.split('&'), l = qp.length; i < l; i++) {
  2710. var kv = (qp[i] || '').split('=');
  2711. q += '&' + URI.decodeQuery(kv[0], this._parts.escapeQuerySpace)
  2712. .replace(/&/g, '%26');
  2713. if (kv[1] !== undefined) {
  2714. q += '=' + URI.decodeQuery(kv[1], this._parts.escapeQuerySpace)
  2715. .replace(/&/g, '%26');
  2716. }
  2717. }
  2718. t += '?' + q.substring(1);
  2719. }
  2720. t += URI.decodeQuery(uri.hash(), true);
  2721. return t;
  2722. };
  2723. // resolving relative and absolute URLs
  2724. p.absoluteTo = function(base) {
  2725. var resolved = this.clone();
  2726. var properties = ['protocol', 'username', 'password', 'hostname', 'port'];
  2727. var basedir, i, p;
  2728. if (this._parts.urn) {
  2729. throw new Error('URNs do not have any generally defined hierarchical components');
  2730. }
  2731. if (!(base instanceof URI)) {
  2732. base = new URI(base);
  2733. }
  2734. if (resolved._parts.protocol) {
  2735. // Directly returns even if this._parts.hostname is empty.
  2736. return resolved;
  2737. } else {
  2738. resolved._parts.protocol = base._parts.protocol;
  2739. }
  2740. if (this._parts.hostname) {
  2741. return resolved;
  2742. }
  2743. for (i = 0; (p = properties[i]); i++) {
  2744. resolved._parts[p] = base._parts[p];
  2745. }
  2746. if (!resolved._parts.path) {
  2747. resolved._parts.path = base._parts.path;
  2748. if (!resolved._parts.query) {
  2749. resolved._parts.query = base._parts.query;
  2750. }
  2751. } else {
  2752. if (resolved._parts.path.substring(-2) === '..') {
  2753. resolved._parts.path += '/';
  2754. }
  2755. if (resolved.path().charAt(0) !== '/') {
  2756. basedir = base.directory();
  2757. basedir = basedir ? basedir : base.path().indexOf('/') === 0 ? '/' : '';
  2758. resolved._parts.path = (basedir ? (basedir + '/') : '') + resolved._parts.path;
  2759. resolved.normalizePath();
  2760. }
  2761. }
  2762. resolved.build();
  2763. return resolved;
  2764. };
  2765. p.relativeTo = function(base) {
  2766. var relative = this.clone().normalize();
  2767. var relativeParts, baseParts, common, relativePath, basePath;
  2768. if (relative._parts.urn) {
  2769. throw new Error('URNs do not have any generally defined hierarchical components');
  2770. }
  2771. base = new URI(base).normalize();
  2772. relativeParts = relative._parts;
  2773. baseParts = base._parts;
  2774. relativePath = relative.path();
  2775. basePath = base.path();
  2776. if (relativePath.charAt(0) !== '/') {
  2777. throw new Error('URI is already relative');
  2778. }
  2779. if (basePath.charAt(0) !== '/') {
  2780. throw new Error('Cannot calculate a URI relative to another relative URI');
  2781. }
  2782. if (relativeParts.protocol === baseParts.protocol) {
  2783. relativeParts.protocol = null;
  2784. }
  2785. if (relativeParts.username !== baseParts.username || relativeParts.password !== baseParts.password) {
  2786. return relative.build();
  2787. }
  2788. if (relativeParts.protocol !== null || relativeParts.username !== null || relativeParts.password !== null) {
  2789. return relative.build();
  2790. }
  2791. if (relativeParts.hostname === baseParts.hostname && relativeParts.port === baseParts.port) {
  2792. relativeParts.hostname = null;
  2793. relativeParts.port = null;
  2794. } else {
  2795. return relative.build();
  2796. }
  2797. if (relativePath === basePath) {
  2798. relativeParts.path = '';
  2799. return relative.build();
  2800. }
  2801. // determine common sub path
  2802. common = URI.commonPath(relativePath, basePath);
  2803. // If the paths have nothing in common, return a relative URL with the absolute path.
  2804. if (!common) {
  2805. return relative.build();
  2806. }
  2807. var parents = baseParts.path
  2808. .substring(common.length)
  2809. .replace(/[^\/]*$/, '')
  2810. .replace(/.*?\//g, '../');
  2811. relativeParts.path = (parents + relativeParts.path.substring(common.length)) || './';
  2812. return relative.build();
  2813. };
  2814. // comparing URIs
  2815. p.equals = function(uri) {
  2816. var one = this.clone();
  2817. var two = new URI(uri);
  2818. var one_map = {};
  2819. var two_map = {};
  2820. var checked = {};
  2821. var one_query, two_query, key;
  2822. one.normalize();
  2823. two.normalize();
  2824. // exact match
  2825. if (one.toString() === two.toString()) {
  2826. return true;
  2827. }
  2828. // extract query string
  2829. one_query = one.query();
  2830. two_query = two.query();
  2831. one.query('');
  2832. two.query('');
  2833. // definitely not equal if not even non-query parts match
  2834. if (one.toString() !== two.toString()) {
  2835. return false;
  2836. }
  2837. // query parameters have the same length, even if they're permuted
  2838. if (one_query.length !== two_query.length) {
  2839. return false;
  2840. }
  2841. one_map = URI.parseQuery(one_query, this._parts.escapeQuerySpace);
  2842. two_map = URI.parseQuery(two_query, this._parts.escapeQuerySpace);
  2843. for (key in one_map) {
  2844. if (hasOwn.call(one_map, key)) {
  2845. if (!isArray(one_map[key])) {
  2846. if (one_map[key] !== two_map[key]) {
  2847. return false;
  2848. }
  2849. } else if (!arraysEqual(one_map[key], two_map[key])) {
  2850. return false;
  2851. }
  2852. checked[key] = true;
  2853. }
  2854. }
  2855. for (key in two_map) {
  2856. if (hasOwn.call(two_map, key)) {
  2857. if (!checked[key]) {
  2858. // two contains a parameter not present in one
  2859. return false;
  2860. }
  2861. }
  2862. }
  2863. return true;
  2864. };
  2865. // state
  2866. p.preventInvalidHostname = function(v) {
  2867. this._parts.preventInvalidHostname = !!v;
  2868. return this;
  2869. };
  2870. p.duplicateQueryParameters = function(v) {
  2871. this._parts.duplicateQueryParameters = !!v;
  2872. return this;
  2873. };
  2874. p.escapeQuerySpace = function(v) {
  2875. this._parts.escapeQuerySpace = !!v;
  2876. return this;
  2877. };
  2878. return URI;
  2879. }));
  2880. });
  2881. export { URI as default };