84 lines
2.6 KiB
TypeScript
84 lines
2.6 KiB
TypeScript
export class Domain {
|
|
public fullName: string;
|
|
public level1?: string;
|
|
public level2?: string;
|
|
public level3?: string;
|
|
public level4?: string;
|
|
public level5?: string;
|
|
public protocol?: string;
|
|
public zoneName: string;
|
|
// aliases
|
|
public topLevel?: string;
|
|
public domainName?: string;
|
|
public subDomain?: string;
|
|
public port: string;
|
|
public nodeParsedUrl: URL;
|
|
constructor(domainStringArg: string) {
|
|
// lets do the node standard stuff first
|
|
this.protocol = this._protocolRegex(domainStringArg);
|
|
if (!this.protocol) {
|
|
domainStringArg = `https://${domainStringArg}`;
|
|
}
|
|
this.nodeParsedUrl = new URL(domainStringArg);
|
|
this.port = this.nodeParsedUrl.port;
|
|
|
|
// lets do the rest after
|
|
const regexMatches = this._domainRegex(
|
|
domainStringArg.replace(this.nodeParsedUrl.pathname, '')
|
|
);
|
|
[this.level1, this.level2, this.level3, this.level4, this.level5] = regexMatches;
|
|
this.fullName = '';
|
|
for (const localMatch of regexMatches) {
|
|
if (this.fullName === '') {
|
|
this.fullName = localMatch;
|
|
} else {
|
|
this.fullName = localMatch + '.' + this.fullName;
|
|
}
|
|
}
|
|
this.zoneName = [this.level2, this.level1].filter(Boolean).join('.');
|
|
|
|
// aliases
|
|
this.topLevel = this.level1;
|
|
this.domainName = this.level2;
|
|
this.subDomain = this.level3;
|
|
}
|
|
|
|
// helper functions
|
|
|
|
/** */
|
|
private _domainRegex(stringArg: string): string[] {
|
|
const regexString =
|
|
/([a-zA-Z0-9\-\_]*)\.{0,1}([a-zA-Z0-9\-\_]*)\.{0,1}([a-zA-Z0-9\-\_]*)\.{0,1}([a-zA-Z0-9\-\_]*)\.{0,1}([a-zA-Z0-9\-\_]*)\.{0,1}$/;
|
|
const regexMatches = regexString.exec(stringArg);
|
|
if (!regexMatches) {
|
|
return [];
|
|
}
|
|
const reversedMatches = [...regexMatches].reverse(); // make sure we build the domain from top level to subdomain
|
|
reversedMatches.pop(); // pop the last element, which is, since we reversed the Array, the full String of matched elements
|
|
const regexMatchesFiltered = reversedMatches.filter(function (stringArg: string) {
|
|
return stringArg !== '';
|
|
});
|
|
return regexMatchesFiltered;
|
|
}
|
|
|
|
private _protocolRegex(stringArg: string): string | undefined {
|
|
const regexString = /^([a-zA-Z0-9]*):\/\//;
|
|
const regexMatches = regexString.exec(stringArg);
|
|
if (regexMatches) {
|
|
return regexMatches[1];
|
|
} else {
|
|
return undefined;
|
|
}
|
|
}
|
|
|
|
private _portRegex(stringArg: string): string | undefined {
|
|
const regexString = /^([a-zA-Z0-9]*):\/\//;
|
|
const regexMatches = regexString.exec(stringArg);
|
|
if (regexMatches) {
|
|
return regexMatches[1];
|
|
} else {
|
|
return undefined;
|
|
}
|
|
}
|
|
}
|