2 * Library for simple URI parsing and manipulation. Requires jQuery.
4 * Do not expect full RFC 3986 compliance. Intended to be minimal, but featureful.
5 * The use cases we have in mind are constructing 'next page' or 'previous page' URLs,
6 * detecting whether we need to use cross-domain proxies for an API, constructing
7 * simple URL-based API calls, etc.
9 * Intended to compress very well if you use a JS-parsing minifier.
11 * Dependencies: mw, jQuery
15 * var uri = new mw.Uri( 'http://foo.com/mysite/mypage.php?quux=2' );
17 * if ( uri.host == 'foo.com' ) {
18 * uri.host = 'www.foo.com';
19 * uri.extend( { bar: 1 } );
21 * $( 'a#id1' ).attr( 'href', uri );
22 * // anchor with id 'id1' now links to http://foo.com/mysite/mypage.php?bar=1&quux=2
24 * $( 'a#id2' ).attr( 'href', uri.clone().extend( { bar: 3, pif: 'paf' } ) );
25 * // anchor with id 'id2' now links to http://foo.com/mysite/mypage.php?bar=3&quux=2&pif=paf
28 * Parsing here is regex based, so may not work on all URIs, but is good enough for most.
31 * 'http://usr:pwd@www.test.com:81/dir/dir.2/index.htm?q1=0&&test1&test2=&test3=value+%28escaped%29&r=1&r=2#top':
32 * The returned object will have the following properties:
39 * path '/dir/dir.2/index.htm'
44 * test3: 'value (escaped)'
49 * n.b. 'password' is not technically allowed for HTTP URIs, but it is possible with other
51 * You can modify the properties directly. Then use the toString() method to extract the
52 * full URI string again.
54 * Parsing based on parseUri 1.2.2 (c) Steven Levithan <stevenlevithan.com> MIT License
55 * http://stevenlevithan.com/demo/parseuri/js/
62 * Function that's useful when constructing the URI string -- we frequently encounter the pattern of
63 * having to add something to the URI as we go, but only if it's present, and to include a character before or after if so.
64 * @param {String} to prepend, if value not empty
65 * @param {String} value to include, if not empty
66 * @param {String} to append, if value not empty
67 * @param {Boolean} raw -- if true, do not URI encode
70 function cat( pre
, val
, post
, raw
) {
71 if ( val
=== undefined || val
=== null || val
=== '' ) {
74 return pre
+ ( raw
? val
: mw
.Uri
.encode( val
) ) + post
;
78 // Regular expressions to parse many common URIs.
80 strict
: /^(?:([^:\/?#]+):)?(?:\/\/(?:(?:([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)?((?:[^?#\/]*\/)*[^?#]*)(?:\?([^#]*))?(?:#(.*))?/,
81 loose
: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?(?:(?:([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?((?:\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?[^?#\/]*)(?:\?([^#]*))?(?:#(.*))?/
84 // The order here matches the order of captured matches in the above parser regexes.
89 'host', // www.test.com
91 'path', // /dir/dir.2/index.htm
92 'query', // q1=0&&test1&test2=value (will become { q1: 0, test1: '', test2: 'value' } )
98 * We use a factory to inject a document location, for relative URLs, including protocol-relative URLs.
99 * so the library is still testable & purely functional.
101 mw
.UriRelative = function( documentLocation
) {
104 * Constructs URI object. Throws error if arguments are illegal/impossible, or otherwise don't parse.
106 * @param {!Object|String} URI string, or an Object with appropriate properties (especially another URI object to clone). Object must have non-blank 'protocol', 'host', and 'path' properties.
107 * @param {Boolean} strict mode (when parsing a string)
109 function Uri( uri
, strictMode
) {
110 strictMode
= !!strictMode
;
111 if ( uri
!== undefined && uri
!== null || uri
!== '' ) {
112 if ( typeof uri
=== 'string' ) {
113 this._parse( uri
, strictMode
);
114 } else if ( typeof uri
=== 'object' ) {
116 $.each( properties
, function( i
, property
) {
117 _this
[property
] = uri
[property
];
119 if ( this.query
=== undefined ) {
125 // protocol-relative URLs
126 if ( !this.protocol
) {
127 this.protocol
= defaultProtocol
;
130 if ( !( this.protocol
&& this.host
&& this.path
) ) {
131 throw new Error( 'Bad constructor arguments' );
136 * Standard encodeURIComponent, with extra stuff to make all browsers work similarly and more compliant with RFC 3986
137 * Similar to rawurlencode from PHP and our JS library mw.util.rawurlencode, but we also replace space with a +
138 * @param {String} string
139 * @return {String} encoded for URI
141 Uri
.encode = function( s
) {
142 return encodeURIComponent( s
)
143 .replace( /!/g, '%21').replace( /'/g, '%27').replace( /\(/g, '%28')
144 .replace( /\)/g, '%29').replace( /\*/g, '%2A
')
145 .replace( /%20/g, '+' );
149 * Standard decodeURIComponent, with '+' to space
150 * @param {String} string encoded for URI
151 * @return {String} decoded string
153 Uri.decode = function( s ) {
154 return decodeURIComponent( s ).replace( /\+/g, ' ' );
160 * Parse a string and set our properties accordingly.
161 * @param {String} URI
162 * @param {Boolean} strictness
163 * @return {Boolean} success
165 _parse: function( str, strictMode ) {
166 var matches = parser[ strictMode ? 'strict
' : 'loose
' ].exec( str );
168 $.each( properties, function( i, property ) {
169 uri[ property ] = matches[ i+1 ];
172 // uri.query starts out as the query string; we will parse it into key-val pairs then make
173 // that object the "query" property.
174 // we overwrite query in uri way to make cloning easier, it can use the same list of properties.
176 // using replace to iterate over a string
178 uri.query.replace( /(?:^|&)([^&=]*)(?:(=)([^&]*))?/g, function ($0, $1, $2, $3) {
180 var k = Uri.decode( $1 );
181 var v = ( $2 === '' || $2 === undefined ) ? null : Uri.decode( $3 );
182 if ( typeof q[ k ] === 'string
' ) {
185 if ( typeof q[ k ] === 'object
' ) {
197 * Returns user and password portion of a URI.
200 getUserInfo: function() {
201 return cat( '', this.user, cat( ':', this.password, '' ) );
205 * Gets host and port portion of a URI.
208 getHostPort: function() {
209 return this.host + cat( ':', this.port, '' );
213 * Returns the userInfo and host and port portion of the URI.
214 * In most real-world URLs, this is simply the hostname, but it is more general.
217 getAuthority: function() {
218 return cat( '', this.getUserInfo(), '@' ) + this.getHostPort();
222 * Returns the query arguments of the URL, encoded into a string
223 * Does not preserve the order of arguments passed into the URI. Does handle escaping.
226 getQueryString: function() {
228 $.each( this.query, function( key, val ) {
229 var k = Uri.encode( key );
230 var vals = val === null ? [ null ] : $.makeArray( val );
231 $.each( vals, function( i, v ) {
232 args.push( k + ( v === null ? '' : '=' + Uri.encode( v ) ) );
235 return args.join( '&' );
239 * Returns everything after the authority section of the URI
242 getRelativePath: function() {
243 return this.path + cat( '?', this.getQueryString(), '', true ) + cat( '#', this.fragment, '' );
247 * Gets the entire URI string. May not be precisely the same as input due to order of query arguments.
248 * @return {String} the URI string
250 toString: function() {
251 return this.protocol + '://' + this.getAuthority() + this.getRelativePath();
256 * @return {Object} new URI object with same properties
259 return new Uri( this );
263 * Extend the query -- supply query parameters to override or add to ours
264 * @param {Object} query parameters in key-val form to override or add
265 * @return {Object} this URI object
267 extend: function( parameters
) {
268 $.extend( this.query
, parameters
);
273 var defaultProtocol
= ( new Uri( documentLocation
) ).protocol
;
278 // if we are running in a browser, inject the current document location, for relative URLs
279 if ( document
&& document
.location
&& document
.location
.href
) {
280 mw
.Uri
= mw
.UriRelative( document
.location
.href
);
283 } )( jQuery
, mediaWiki
);