uri.ts 10.8 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

import marshalling = require('vs/base/common/marshalling');
import platform = require('vs/base/common/platform');

// see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
function fixedEncodeURIComponent(str: string): string {
	return encodeURIComponent(str).replace(/[!'()*]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase());
}

/**
 * Uniform Resource Identifier (URI) http://tools.ietf.org/html/rfc3986.
 * This class is a simple parser which creates the basic component paths
 * (http://tools.ietf.org/html/rfc3986#section-3) with minimal validation
 * and encoding.
 *
 *     foo://example.com:8042/over/there?name=ferret#nose
 *       \_/   \______________/\_________/ \_________/ \__/
 *        |           |            |            |        |
 *     scheme     authority       path        query   fragment
 *        |   _____________________|__
 *       / \ /                        \
 *       urn:example:animal:ferret:nose
 *
 *
 */
export default class URI {

	private static _empty = '';
	private static _regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
	private static _driveLetterPath = /^\/[a-zA-z]:/;
	private static _driveLetter = /^[a-zA-z]:/;

	private _scheme: string;
	private _authority: string;
	private _path: string;
	private _query: string;
	private _fragment: string;

	constructor() {
		this._scheme = URI._empty;
		this._authority = URI._empty;
		this._path = URI._empty;
		this._query = URI._empty;
		this._fragment = URI._empty;
	}

	/**
	 * scheme is the 'http' part of 'http://www.msft.com/some/path?query#fragment'.
	 * The part before the first colon.
	 */
	get scheme() {
		return this._scheme;
	}

	/**
	 * authority is the 'www.msft.com' part of 'http://www.msft.com/some/path?query#fragment'.
	 * The part between the first double slashes and the next slash.
	 */
	get authority() {
		return this._authority;
	}

	/**
	 * path is the '/some/path' part of 'http://www.msft.com/some/path?query#fragment'.
	 */
	get path() {
		return this._path;
	}

	/**
	 * query is the 'query' part of 'http://www.msft.com/some/path?query#fragment'.
	 */
	get query() {
		return this._query;
	}

	/**
	 * fragment is the 'fragment' part of 'http://www.msft.com/some/path?query#fragment'.
	 */
	get fragment() {
		return this._fragment;
	}

	// ---- filesystem path -----------------------

	private _fsPath: string;

	/**
P
Pascal Borreli 已提交
94
	 * Returns a string representing the corresponding file system path of this URI.
E
Erich Gamma 已提交
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
	 * Will handle UNC paths and normalize windows drive letters to lower-case. Also
	 * uses the platform specific path separator. Will *not* validate the path for
	 * invalid characters and semantics. Will *not* look at the scheme of this URI.
	 */
	get fsPath() {
		if (!this._fsPath) {
			var value: string;
			if (this._authority && this.scheme === 'file') {
				// unc path: file://shares/c$/far/boo
				value = `//${this._authority}${this._path}`;
			} else if (URI._driveLetterPath.test(this._path)) {
				// windows drive letter: file:///c:/far/boo
				value = this._path[1].toLowerCase() + this._path.substr(2);
			} else {
				// other path
				value = this._path;
			}
			if (platform.isWindows) {
				value = value.replace(/\//g, '\\');
			}
			this._fsPath = value;
		}
		return this._fsPath;
	}

	// ---- modify to new -------------------------

	public with(scheme: string, authority: string, path: string, query: string, fragment: string): URI {
		var ret = new URI();
		ret._scheme = scheme || this.scheme;
		ret._authority = authority || this.authority;
		ret._path = path || this.path;
		ret._query = query || this.query;
		ret._fragment = fragment || this.fragment;
		URI._validate(ret);
		return ret;
	}

	public withScheme(value: string): URI {
		return this.with(value, undefined, undefined, undefined, undefined);
	}

	public withAuthority(value: string): URI {
		return this.with(undefined, value, undefined, undefined, undefined);
	}

	public withPath(value: string): URI {
		return this.with(undefined, undefined, value, undefined, undefined);
	}

	public withQuery(value: string): URI {
		return this.with(undefined, undefined, undefined, value, undefined);
	}

	public withFragment(value: string): URI {
		return this.with(undefined, undefined, undefined, undefined, value);
	}

	// ---- parse & validate ------------------------

	public static parse(value: string): URI {
		var ret = URI._parse(value);
		ret = ret.with(undefined,
			decodeURIComponent(ret.authority),
			decodeURIComponent(ret.path),
			decodeURIComponent(ret.query),
			decodeURIComponent(ret.fragment));

		return ret;
	}

	public static file(path: string): URI {
		path = path.replace(/\\/g, '/');
		path = path.replace(/%/g, '%25');
		path = path.replace(/#/g, '%23');
		path = path.replace(/\?/g, '%3F');
		path = URI._driveLetter.test(path)
			? '/' + path
			: path;

		var ret = URI._parse(path);
		if (ret.scheme || ret.fragment || ret.query) {
			throw new Error();
		}

		ret = ret.with('file', undefined,
			decodeURIComponent(ret.path),
			undefined, undefined);

		return ret;
	}

	private static _parse(value: string): URI {
		var ret = new URI();
		var match = URI._regexp.exec(value);
		if (match) {
			ret._scheme = match[2] || ret._scheme;
			ret._authority = match[4] || ret._authority;
			ret._path = match[5] || ret._path;
			ret._query = match[7] || ret._query;
			ret._fragment = match[9] || ret._fragment;
		};
		URI._validate(ret);
		return ret;
	}

	public static create(scheme?: string, authority?: string, path?: string, query?: string, fragment?: string): URI {
		return new URI().with(scheme, authority, path, query, fragment);
	}

	private static _validate(ret: URI): void {

		// validation
		// path, http://tools.ietf.org/html/rfc3986#section-3.3
		// If a URI contains an authority component, then the path component
		// must either be empty or begin with a slash ("/") character.  If a URI
		// does not contain an authority component, then the path cannot begin
		// with two slash characters ("//").
		if (ret.authority && ret.path && ret.path[0] !== '/') {
			throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character');
		}
		if (!ret.authority && ret.path.indexOf('//') === 0) {
			throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")');
		}
	}

	// ---- printing/externalize ---------------------------

	private _formatted: string;

	public toString(): string {
		if (!this._formatted) {
			var parts: string[] = [];

			if (this._scheme) {
				parts.push(this._scheme);
				parts.push(':');
			}
			if (this._authority || this._scheme === 'file') {
				parts.push('//');
			}
			if (this._authority) {
				var authority = this._authority,
					idx: number;

				authority = authority.toLowerCase();
				idx = authority.indexOf(':');
				if (idx === -1) {
					parts.push(fixedEncodeURIComponent(authority));
				} else {
					parts.push(fixedEncodeURIComponent(authority.substr(0, idx)));
					parts.push(authority.substr(idx));
				}
			}
			if (this._path) {
				// encode every segment of the path
				var path = this._path,
					segments: string[];

				// lower-case win drive letters in /C:/fff
				if (URI._driveLetterPath.test(path)) {
					path = '/' + path[1].toLowerCase() + path.substr(2);
				} else if (URI._driveLetter.test(path)) {
					path = path[0].toLowerCase() + path.substr(1);
				}
				segments = path.split('/');
				for (var i = 0, len = segments.length; i < len; i++) {
					segments[i] = fixedEncodeURIComponent(segments[i]);
				}
				parts.push(segments.join('/'));
			}
			if (this._query) {
				// in http(s) querys often use 'key=value'-pairs and
				// ampersand characters for multiple pairs
				var encoder = /https?/i.test(this.scheme)
					? encodeURI
					: fixedEncodeURIComponent;

				parts.push('?');
				parts.push(encoder(this._query));
			}
			if (this._fragment) {
				parts.push('#');
				parts.push(fixedEncodeURIComponent(this._fragment));
			}
			this._formatted = parts.join('');
		}
		return this._formatted;
	}

	public toJSON(): any {
		return this.toString();
	}

	public _toSerialized(): any {
		// because network.URL extends this class it is important that
		// it can refine/override this method

		return {
			$isURI: true,
			_scheme: this._scheme,
			_authority: this._authority,
			_path: this._path,
			_query: this._query,
			_fragment: this._fragment,
			_fsPath: this._fsPath,
			_formatted: this._formatted
		};
	}

	static _fromSerialized(data: any): URI {
		let result = new URI();
		result._scheme = data._scheme;
		result._authority = data._authority;
		result._path = data._path;
		result._query = data._query;
		result._fragment = data._fragment;
		result._fsPath = data._fsPath;
		result._formatted = data._formatted;
		return result;
	}

	public static isURI(thing: any): thing is URI {
		if (thing instanceof URI) {
			return true;
		}
		if(!thing) {
			return false;
		}
		if (typeof (<URI>thing).scheme !== 'string') {
			return false;
		}
		if (typeof (<URI>thing).authority !== 'string') {
			return false;
		}
		if (typeof (<URI>thing).fsPath !== 'string') {
			return false;
		}
		if (typeof (<URI>thing).query !== 'string') {
			return false;
		}
		if (typeof (<URI>thing).fragment !== 'string') {
			return false;
		}
		if (typeof (<URI>thing).with !== 'function') {
			return false;
		}
		if (typeof (<URI>thing).withScheme !== 'function') {
			return false;
		}
		if (typeof (<URI>thing).withAuthority !== 'function') {
			return false;
		}
		if (typeof (<URI>thing).withPath !== 'function') {
			return false;
		}
		if (typeof (<URI>thing).withQuery !== 'function') {
			return false;
		}
		if (typeof (<URI>thing).withFragment !== 'function') {
			return false;
		}
		if (typeof (<URI>thing).toString !== 'function') {
			return false;
		}
		if (typeof (<URI>thing).toJSON !== 'function') {
			return false;
		}
		return true;
	}
}

interface _ISerializedURI {
	$isURI: boolean;

	_scheme: string;
	_authority: string;
	_path: string;
	_query: string;
	_fragment: string;

	_fsPath: string;
	_formatted: string;
}

marshalling.registerMarshallingContribution({

	canSerialize: (obj:any): boolean => {
		return URI.isURI(obj);
	},

	serialize: (url: URI, serialize: (obj: any) => any): _ISerializedURI => {
		return url._toSerialized();
	},

	canDeserialize: (obj:_ISerializedURI): boolean => {
		return obj.$isURI;
	},

	deserialize: (obj:_ISerializedURI, deserialize:(obj:any)=>any): any => {
		return URI._fromSerialized(obj);
	}
});