Skip to content

Commit

Permalink
fix: respect hostname when opening url (#40)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe committed Sep 26, 2022
1 parent a5e84cd commit d1e985d
Showing 1 changed file with 14 additions and 9 deletions.
23 changes: 14 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,12 @@ export interface ShowURLOptions {
}

export interface Listener {
url: string,
address: { },
server: Server | HTTPServer,
https: false | Certificate,
close: () => Promise<void>,
open: () => Promise<void>,
url: string
address: any
server: Server | HTTPServer
https: false | Certificate
close: () => Promise<void>
open: () => Promise<void>
showURL: (options?: Pick<ListenOptions, 'baseURL'>) => void
}

Expand Down Expand Up @@ -83,7 +83,12 @@ export async function listen (handle: RequestListener, opts: Partial<ListenOptio
let server: Server | HTTPServer

let addr: { proto: 'http' | 'https', addr: string, port: number } | null
const getURL = (host?: string, baseURL?: string) => `${addr!.proto}://${host || opts.hostname || addr!.addr}:${addr!.port}${baseURL || opts.baseURL}`
const getURL = (host?: string, baseURL?: string) => {
const anyV4 = addr?.addr === '0.0.0.0'
const anyV6 = addr?.addr === '[::]'

return `${addr!.proto}://${host || opts.hostname || (anyV4 || anyV6 ? 'localhost' : addr!.addr)}:${addr!.port}${baseURL || opts.baseURL}`
}

let https: Listener['https'] = false
if (opts.https) {
Expand Down Expand Up @@ -115,7 +120,7 @@ export async function listen (handle: RequestListener, opts: Partial<ListenOptio

if (opts.clipboard) {
const clipboardy = await import('clipboardy').then(r => r.default || r)
await clipboardy.write(getURL('localhost')).catch(() => { opts.clipboard = false })
await clipboardy.write(getURL()).catch(() => { opts.clipboard = false })
}

const showURL = (options?: ShowURLOptions) => {
Expand Down Expand Up @@ -143,7 +148,7 @@ export async function listen (handle: RequestListener, opts: Partial<ListenOptio
}

const _open = async () => {
await open(getURL('localhost')).catch(() => { })
await open(getURL()).catch(() => {})
}
if (opts.open) {
await _open()
Expand Down

0 comments on commit d1e985d

Please sign in to comment.