wangzhibo
2026-05-09 53418655c061ac26f66058253f39200aced1ab1d
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
94
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
/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */
 
import {
    createClientConfigurationError,
    ClientConfigurationErrorCodes,
} from "../error/ClientConfigurationError.js";
import { StringUtils } from "../utils/StringUtils.js";
import { IUri } from "./IUri.js";
import * as Constants from "../utils/Constants.js";
 
/**
 * Url object class which can perform various transformations on url strings.
 */
export class UrlString {
    // internal url string field
    private _urlString: string;
    public get urlString(): string {
        return this._urlString;
    }
 
    constructor(url: string) {
        this._urlString = url;
        if (!this._urlString) {
            // Throws error if url is empty
            throw createClientConfigurationError(
                ClientConfigurationErrorCodes.urlEmptyError
            );
        }
 
        if (!url.includes("#")) {
            this._urlString = UrlString.canonicalizeUri(url);
        }
    }
 
    /**
     * Ensure urls are lower case and end with a / character.
     * @param url
     */
    static canonicalizeUri(url: string): string {
        if (url) {
            let lowerCaseUrl = url.toLowerCase();
 
            if (StringUtils.endsWith(lowerCaseUrl, "?")) {
                lowerCaseUrl = lowerCaseUrl.slice(0, -1);
            } else if (StringUtils.endsWith(lowerCaseUrl, "?/")) {
                lowerCaseUrl = lowerCaseUrl.slice(0, -2);
            }
 
            if (!StringUtils.endsWith(lowerCaseUrl, "/")) {
                lowerCaseUrl += "/";
            }
 
            return lowerCaseUrl;
        }
 
        return url;
    }
 
    /**
     * Throws if urlString passed is not a valid authority URI string.
     */
    validateAsUri(): void {
        // Attempts to parse url for uri components
        let components;
        try {
            components = this.getUrlComponents();
        } catch (e) {
            throw createClientConfigurationError(
                ClientConfigurationErrorCodes.urlParseError
            );
        }
 
        // Throw error if URI or path segments are not parseable.
        if (!components.HostNameAndPort || !components.PathSegments) {
            throw createClientConfigurationError(
                ClientConfigurationErrorCodes.urlParseError
            );
        }
 
        // Throw error if uri is insecure.
        if (
            !components.Protocol ||
            components.Protocol.toLowerCase() !== "https:"
        ) {
            throw createClientConfigurationError(
                ClientConfigurationErrorCodes.authorityUriInsecure
            );
        }
    }
 
    /**
     * Given a url and a query string return the url with provided query string appended
     * @param url
     * @param queryString
     */
    static appendQueryString(url: string, queryString: string): string {
        if (!queryString) {
            return url;
        }
 
        return url.indexOf("?") < 0
            ? `${url}?${queryString}`
            : `${url}&${queryString}`;
    }
 
    /**
     * Returns a url with the hash removed
     * @param url
     */
    static removeHashFromUrl(url: string): string {
        return UrlString.canonicalizeUri(url.split("#")[0]);
    }
 
    /**
     * Given a url like https://a:b/common/d?e=f#g, and a tenantId, returns https://a:b/tenantId/d
     * @param href The url
     * @param tenantId The tenant id to replace
     */
    replaceTenantPath(tenantId: string): UrlString {
        const urlObject = this.getUrlComponents();
        const pathArray = urlObject.PathSegments;
        if (
            tenantId &&
            pathArray.length !== 0 &&
            (pathArray[0] === Constants.AADAuthority.COMMON ||
                pathArray[0] === Constants.AADAuthority.ORGANIZATIONS)
        ) {
            pathArray[0] = tenantId;
        }
        return UrlString.constructAuthorityUriFromObject(urlObject);
    }
 
    /**
     * Parses out the components from a url string.
     * @returns An object with the various components. Please cache this value insted of calling this multiple times on the same url.
     */
    getUrlComponents(): IUri {
        // https://gist.github.com/curtisz/11139b2cfcaef4a261e0
        const regEx = RegExp(
            "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?"
        );
 
        // If url string does not match regEx, we throw an error
        const match = this.urlString.match(regEx);
        if (!match) {
            throw createClientConfigurationError(
                ClientConfigurationErrorCodes.urlParseError
            );
        }
 
        // Url component object
        const urlComponents = {
            Protocol: match[1],
            HostNameAndPort: match[4],
            AbsolutePath: match[5],
            QueryString: match[7],
        } as IUri;
 
        let pathSegments = urlComponents.AbsolutePath.split("/");
        pathSegments = pathSegments.filter((val) => val && val.length > 0); // remove empty elements
        urlComponents.PathSegments = pathSegments;
 
        if (
            urlComponents.QueryString &&
            urlComponents.QueryString.endsWith("/")
        ) {
            urlComponents.QueryString = urlComponents.QueryString.substring(
                0,
                urlComponents.QueryString.length - 1
            );
        }
        return urlComponents;
    }
 
    static getDomainFromUrl(url: string): string {
        const regEx = RegExp("^([^:/?#]+://)?([^/?#]*)");
 
        const match = url.match(regEx);
 
        if (!match) {
            throw createClientConfigurationError(
                ClientConfigurationErrorCodes.urlParseError
            );
        }
 
        return match[2];
    }
 
    static getAbsoluteUrl(relativeUrl: string, baseUrl: string): string {
        if (relativeUrl[0] === Constants.FORWARD_SLASH) {
            const url = new UrlString(baseUrl);
            const baseComponents = url.getUrlComponents();
 
            return (
                baseComponents.Protocol +
                "//" +
                baseComponents.HostNameAndPort +
                relativeUrl
            );
        }
 
        return relativeUrl;
    }
 
    static constructAuthorityUriFromObject(urlObject: IUri): UrlString {
        return new UrlString(
            urlObject.Protocol +
                "//" +
                urlObject.HostNameAndPort +
                "/" +
                urlObject.PathSegments.join("/")
        );
    }
}