123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363 |
- "use strict";
- var _ = require('../../lodash'), url_parse = require('postman-url-encoder/parser').parse, PropertyBase = require('./property-base').PropertyBase, QueryParam = require('./query-param').QueryParam, PropertyList = require('./property-list').PropertyList, VariableList = require('./variable-list').VariableList, E = '', OBJECT = 'object', STRING = 'string', FUNCTION = 'function', PROTOCOL_HTTPS = 'https', PROTOCOL_HTTP = 'http', HTTPS_PORT = '443', HTTP_PORT = '80', PATH_SEPARATOR = '/', PATH_VARIABLE_IDENTIFIER = ':', PORT_SEPARATOR = ':', DOMAIN_SEPARATOR = '.', PROTOCOL_SEPARATOR = '://', AUTH_SEPARATOR = ':', AUTH_CREDENTIALS_SEPARATOR = '@', QUERY_SEPARATOR = '?', SEARCH_SEPARATOR = '#', DEFAULT_PROTOCOL = PROTOCOL_HTTP + PROTOCOL_SEPARATOR, MATCH_1 = '$1', regexes = {
- trimPath: /^\/((.+))$/,
- splitDomain: /\.(?![^{]*\}{2})/g
- }, Url;
- _.inherit((
- /**
- * Defines a URL.
- *
- * @constructor
- * @extends {PropertyBase}
- * @param {Object|String} options
- */
- Url = function PostmanUrl(options) {
- // this constructor is intended to inherit and as such the super constructor is required to be executed
- Url.super_.apply(this, arguments);
- // create the url properties
- this.update(options);
- }), PropertyBase);
- _.assign(Url.prototype, /** @lends Url.prototype */ {
- /**
- * Set a URL.
- *
- * @draft
- * @param {String|Object} url
- */
- update: function (url) {
- !url && (url = E);
- var parsedUrl = _.isString(url) ? Url.parse(url) : url, auth = parsedUrl.auth, protocol = parsedUrl.protocol, port = parsedUrl.port, path = parsedUrl.path, hash = parsedUrl.hash, host = parsedUrl.host, query = parsedUrl.query, variable = parsedUrl.variable;
- // convert object based query string to array
- // @todo: create a key value parser
- if (query) {
- if (_.isString(query)) {
- query = QueryParam.parse(query);
- }
- if (!_.isArray(query) && _.keys(query).length) {
- query = _.map(_.keys(query), function (key) {
- return {
- key: key,
- value: query[key]
- };
- });
- }
- }
- // backward compatibility with path variables being storing thins with `id`
- if (_.isArray(variable)) {
- variable = _.map(variable, function (v) {
- _.isObject(v) && (v.key = v.key || v.id); // @todo Remove once path variables are deprecated
- return v;
- });
- }
- // expand string path name
- if (_.isString(path)) {
- path && (path = path.replace(regexes.trimPath, MATCH_1)); // remove leading slash for valid path
- // if path is blank string, we set it to undefined, if '/' then single blank string array
- path = path ? (path === PATH_SEPARATOR ? [E] : path.split(PATH_SEPARATOR)) : undefined;
- }
- // expand host string
- _.isString(host) && (host = host.split(regexes.splitDomain));
- _.assign(this, /** @lends Url.prototype */ {
- /**
- * @type {String}
- */
- auth: auth,
- /**
- * @type {String}
- */
- protocol: protocol,
- /**
- * @type {String}
- */
- port: port,
- /**
- * @type {Array<String>}
- */
- path: path,
- /**
- * @type {String}
- */
- hash: hash,
- /**
- * @type {Array<String>}
- */
- host: host,
- /**
- * @type {PropertyList<QueryParam>}
- *
- * @todo consider setting this as undefined in v4 otherwise it's
- * difficult to detect URL like `localhost/?`.
- * currently it's replying upon a single member with empty key.
- */
- query: new PropertyList(QueryParam, this, query || []),
- /**
- * @type {VariableList}
- */
- variables: new VariableList(this, variable || [])
- });
- },
- /**
- * Add query parameters to the URL.
- *
- * @param {Object|String} params Key value pairs to add to the URL.
- */
- addQueryParams: function (params) {
- params = _.isString(params) ? QueryParam.parse(params) : params;
- this.query.populate(params);
- },
- /**
- * Removes query parameters from the URL.
- *
- * @param {Array<QueryParam>|Array<String>|String} params Params should be an array of strings, or an array of
- * actual query parameters, or a string containing the parameter key.
- * @note Input should *not* be a query string.
- */
- removeQueryParams: function (params) {
- params = _.isArray(params) ? _.map(params, function (param) {
- return param.key ? param.key : param;
- }) : [params];
- this.query.remove(function (param) {
- return _.includes(params, param.key);
- });
- },
- /**
- * Unparses a {PostmanUrl} into a string.
- *
- * @deprecated Please use {@link Url#toString} instead of this
- * @returns {string}
- */
- getRaw: function () {
- return this.toString();
- },
- /**
- * Unparses a {PostmanUrl} into a string.
- *
- * @param {Boolean=} forceProtocol - Forces the URL to have a protocol
- * @returns {string}
- */
- toString: function (forceProtocol) {
- var rawUrl = E, protocol = this.protocol, queryString, authString;
- forceProtocol && !protocol && (protocol = DEFAULT_PROTOCOL);
- if (protocol) {
- rawUrl += (_.endsWith(protocol, PROTOCOL_SEPARATOR) ? protocol : protocol + PROTOCOL_SEPARATOR);
- }
- if (this.auth) {
- if (typeof this.auth.user === STRING) {
- authString = this.auth.user;
- }
- if (typeof this.auth.password === STRING) {
- !authString && (authString = E);
- authString += AUTH_SEPARATOR + this.auth.password;
- }
- if (typeof authString === STRING) {
- rawUrl += authString + AUTH_CREDENTIALS_SEPARATOR;
- }
- }
- if (this.host) {
- rawUrl += this.getHost();
- }
- if (typeof _.get(this.port, 'toString') === FUNCTION) {
- rawUrl += PORT_SEPARATOR + this.port.toString();
- }
- if (this.path) {
- rawUrl += this.getPath();
- }
- if (this.query && this.query.count()) {
- queryString = this.getQueryString({ ignoreDisabled: true });
- // either all the params are disabled or a single param is like { key: '' } (http://localhost?)
- // in that case, query separator ? must be included in the raw URL.
- // @todo return undefined or string from getQueryString method to distinguish
- // no params vs empty param.
- if (queryString === E) {
- // check if there's any enabled param, if so, set queryString to empty string
- // otherwise (all disabled), it will be set as undefined
- queryString = this.query.find(function (param) { return !(param && param.disabled); }) && E;
- }
- if (typeof queryString === STRING) {
- rawUrl += QUERY_SEPARATOR + queryString;
- }
- }
- if (typeof this.hash === STRING) {
- rawUrl += SEARCH_SEPARATOR + this.hash;
- }
- return rawUrl;
- },
- /**
- * Returns the request path, with a leading '/'.
- *
- * @param {?Boolean=} [unresolved=false]
- * @returns {string}
- *
- * @note deprecated variant in v3.4:
- * - param {Object} options
- * - param {Object} options.unresolved If set to true, path variables will not be processed
- */
- getPath: function (unresolved) {
- if (typeof unresolved === OBJECT) { // @todo discontinue in v4
- unresolved = unresolved.unresolved;
- }
- // for unresolved case, this is super simple as that is how raw data is stored
- if (unresolved) {
- return PATH_SEPARATOR + this.path.join(PATH_SEPARATOR);
- }
- var self = this, segments;
- segments = _.transform(this.path, function (res, segment) {
- var variable;
- // check if the segment has path variable prefix followed by the variable name.
- if (_.startsWith(segment, PATH_VARIABLE_IDENTIFIER) && segment !== PATH_VARIABLE_IDENTIFIER) {
- variable = self.variables.one(segment.slice(1)); // remove path variable prefix.
- }
- variable = variable && variable.valueOf && variable.valueOf();
- res.push(_.isString(variable) ? variable : segment);
- }, []);
- return PATH_SEPARATOR + segments.join(PATH_SEPARATOR); // add leading slash
- },
- /**
- * Returns the stringified query string for this URL.
- *
- * @param {?Boolean} [encode=false] - Enables URL encoding when processing the query string
- * @returns {String}
- *
- * @deprecated since v3.4.6, drop support for `encode`
- *
- * @note Deprecated variant of this function is as follows:
- * - param {?Object} [options={}]
- * - param {?Boolean} options.encode - Enables URL encoding when processing the query string.
- * - param {?Boolean} options.ignoreDisabled - Prevents disabled query parameters from showing up in the unparsed
- */
- getQueryString: function (encode) {
- if (!this.query.count()) {
- return E;
- }
- if (typeof encode === OBJECT) { // @todo discontinue in v4
- return QueryParam.unparse(this.query.all(), encode);
- }
- return QueryParam.unparse(this.query.all(), { encode: encode });
- },
- /**
- * Returns the complete path, including the query string.
- *
- * @param {?Boolean} [encodeQuery=false] - when set to `true` the query string part will be URL encoded
- *
- * @returns {*|string}
- * @example /something/postman?hi=notbye
- *
- * @deprecated since v3.4.6, drop support for `encodeQuery`
- */
- getPathWithQuery: function (encodeQuery) {
- var path = this.getPath();
- // check count first so that, we can ensure that ba `?` is always appended, even if a blank query string exists
- if (this.query.count()) {
- path += (QUERY_SEPARATOR + this.getQueryString(encodeQuery));
- }
- return path;
- },
- /**
- * Returns the host part of the URL
- *
- * @returns {string}
- */
- getHost: function () {
- if (!this.host) {
- return E;
- }
- return _.isArray(this.host) ? this.host.join(DOMAIN_SEPARATOR) : this.host.toString();
- },
- /**
- * Returns the host *and* port (if any), separated by a ":"
- *
- * @param {?Boolean} [forcePort=false] - forces the port to be added even for the protocol default ones (89, 443)
- * @returns {String}
- *
- * @note deprecated variant since v3.5
- * - param {Object} options
- * - param {Boolean} options.forcePort
- */
- getRemote: function (forcePort) {
- var host = this.getHost(), port = this.port && this.port.toString();
- // @todo remove when v4 is released and this is discontinued
- if (typeof forcePort === OBJECT) {
- forcePort = forcePort.forcePort;
- }
- if (forcePort && !port) { // this (!port) works since it assumes port as a string
- port = this.protocol && (this.protocol === PROTOCOL_HTTPS) ? HTTPS_PORT : HTTP_PORT;
- }
- return port ? (host + PORT_SEPARATOR + port) : host;
- },
- /**
- * Returns a OAuth1.0-a compatible representation of the request URL, also called "Base URL".
- * For details, http://oauth.net/core/1.0a/#anchor13
- *
- * todo: should we ignore the auth parameters of the URL or not? (the standard does not mention them)
- * we currently are.
- *
- * @private
- * @returns {String}
- *
- * @deprecated since v3.5 in favour of getBaseUrl
- * @todo discontinue in v4.0
- */
- getOAuth1BaseUrl: function () {
- var protocol = this.protocol || PROTOCOL_HTTP, port = this.port ? this.port.toString() : undefined, host = ((port === HTTP_PORT ||
- port === HTTPS_PORT ||
- port === undefined) && this.host.join(DOMAIN_SEPARATOR)) || (this.host.join(DOMAIN_SEPARATOR) +
- PORT_SEPARATOR + port), path = this.getPath();
- protocol = (_.endsWith(protocol, PROTOCOL_SEPARATOR) ? protocol : protocol + PROTOCOL_SEPARATOR);
- return protocol.toLowerCase() + host.toLowerCase() + path;
- }
- });
- _.assign(Url, /** @lends Url */ {
- /**
- * Defines the name of this property for internal use.
- * @private
- * @readOnly
- * @type {String}
- */
- _postman_propertyName: 'Url',
- /**
- * Parses a string to a PostmanUrl, decomposing the URL into it's constituent parts,
- * such as path, host, port, etc.
- *
- * @param {String} url
- * @returns {Object}
- */
- parse: function (url) {
- url = url_parse(url);
- var pathVariables, pathVariableKeys = {};
- if (url.auth) {
- url.auth = {
- user: url.auth[0],
- password: url.auth[1]
- };
- }
- if (url.query) {
- url.query = url.query.map(QueryParam.parseSingle);
- }
- // extract path variables
- pathVariables = _.transform(url.path, function (res, segment) {
- // check if the segment has path variable prefix followed by the variable name and
- // the variable is not already added in the list.
- if (_.startsWith(segment, PATH_VARIABLE_IDENTIFIER) &&
- segment !== PATH_VARIABLE_IDENTIFIER &&
- !pathVariableKeys[segment]) {
- pathVariableKeys[segment] = true;
- res.push({ key: segment.slice(1) }); // remove path variable prefix.
- }
- }, []);
- url.variable = pathVariables.length ? pathVariables : undefined;
- return url;
- },
- /**
- * Checks whether an object is a Url
- *
- * @param {*} obj
- * @returns {Boolean}
- */
- isUrl: function (obj) {
- return Boolean(obj) && ((obj instanceof Url) ||
- _.inSuperChain(obj.constructor, '_postman_propertyName', Url._postman_propertyName));
- }
- });
- module.exports = {
- Url: Url
- };
|