@yuebai008/cli
Version:
Command line interface for rapid qg-minigame development
1 lines • 2.37 kB
JavaScript
function parseScheme(t){const e=t.indexOf("://");if(e<0)return;const s=t.substr(0,e).toLowerCase();return["*","http","https","ftp","chrome","chrome-extension"].includes(s)?{scheme:s,hostPattern:t.substr(e+3)}:void 0}function defaultPort(t){switch(t){case"http":return"80";case"https":return"443";case"ftp":return"25"}}function parseHostAndPort(t,e){const s=t.indexOf("/");if(s>=0){const e=t.substr(s);if("/*"!==e&&"/"!==e)return;t=t.substr(0,s)}if(t.endsWith(":*")&&(t=t.substr(0,t.length-2)),t.endsWith(":"))return;let r;try{r=new URL(t.startsWith("*.")?`http://${t.substr(2)}`:`http://${t}`)}catch{return}if("/"!==r.pathname)return;if(r.hostname.endsWith(".")&&(r.hostname=r.hostname.substr(0,r.hostname.length-1)),"%2A"!==r.hostname&&r.hostname.includes("%2A"))return;const n=defaultPort("http");if(!n)return;const h=t.endsWith(`:${n}`)?n:""===r.port?"*":r.port;if("*"!==h&&!["http","https","ftp"].includes(e))return;return{host:"%2A"!==r.hostname?t.startsWith("*.")?`*.${r.hostname}`:r.hostname:"*",port:h}}export class HostUrlPattern{pattern;static parse(t){if("<all_urls>"===t)return new HostUrlPattern({matchesAll:!0});const e=parseScheme(t);if(!e)return;const{scheme:s,hostPattern:r}=e,n=parseHostAndPort(r,s);if(!n)return;const{host:h,port:a}=n;return new HostUrlPattern({scheme:s,host:h,port:a,matchesAll:!1})}constructor(t){this.pattern=t}get scheme(){return this.pattern.matchesAll?"*":this.pattern.scheme}get host(){return this.pattern.matchesAll?"*":this.pattern.host}get port(){return this.pattern.matchesAll?"*":this.pattern.port}matchesAllUrls(){return this.pattern.matchesAll}matchesUrl(t){let e;try{e=new URL(t)}catch{return!1}if(this.matchesAllUrls())return!0;const s=e.protocol.substr(0,e.protocol.length-1),r=e.port||defaultPort(s);return this.matchesScheme(s)&&this.matchesHost(e.hostname)&&(!r||this.matchesPort(r))}matchesScheme(t){return!!this.pattern.matchesAll||("*"===this.pattern.scheme?"http"===t||"https"===t:this.pattern.scheme===t)}matchesHost(t){if(this.pattern.matchesAll)return!0;if("*"===this.pattern.host)return!0;let e=new URL(`http://${t}`).hostname;return e.endsWith(".")&&(e=e.substr(0,e.length-1)),this.pattern.host.startsWith("*.")?e===this.pattern.host.substr(2)||e.endsWith(this.pattern.host.substr(1)):this.pattern.host===e}matchesPort(t){return!!this.pattern.matchesAll||("*"===this.pattern.port||this.pattern.port===t)}}