/**
 * Copyright (c) AXA Assistance France
 *
 * Licensed under the AXA Assistance France License (the "License"); you
 * may not use this file except in compliance with the License.
 * A copy of the License can be found in the LICENSE.md file distributed
 * together with this file.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ module import { Server , RequestListener , createServer } from 'http' ; import { createServer as createHttpsServer } from 'https' ; import { AddressInfo , isIP } from 'net' ; import { assertIsAddressInfo } from './helpers' ; import { HttpServerOptions } from './types' ; /**
 * Provides a restartable wrapper for http.CreateServer().
 */ export class HttpServer { #server : Server ; #isSecured : boolean ; param { RequestListener } requestListener param { HttpServerOptions } options constructor ( requestListener , options ? ) { this . #isSecured = false ; if ( options ?. key && options ?. cert ) { this . #server = createHttpsServer ( options , requestListener ) ; this . #isSecured = true ; } else { this . #server = createServer ( requestListener ) ; } } type { boolean } get listening ( ) : boolean { return this . #server . listening ; } returns { AddressInfo } address ( ) { if ( ! this . listening ) { throw new Error ( 'Server is not started.' ) ; } const address = this . #server . address ( ) ; assertIsAddressInfo ( address ) ; return address ; } param { number } port param { string } host returns { Promise < void > } async start ( port ? , host ? ) { if ( this . listening ) { throw new Error ( 'Server has already been started.' ) ; } return new Promise ( ( resolve , reject ) => { this . #server . listen ( port , host ) . on ( 'listening' , resolve ) . on ( 'error' , reject ) ; } ) ; } returns { Promise } async stop ( ) { if ( ! this . listening ) { throw new Error ( 'Server is not started.' ) ; } return new Promise ( ( resolve , reject ) => { this . #server . close ( ( err ) => { if ( err ) { return reject ( err ) ; } return resolve ( ) ; } ) ; } ) ; } protected buildIssuerUrl ( host , port ) { const url = new URL ( `${ this . #isSecured ? 'https' : 'http' }://localhost:${ port }` ) ; if ( host && ! coversLocalhost ( host ) ) { url . hostname = host . includes ( ':' ) ? `[${ host }]` : host ; } return url . origin ; } } const coversLocalhost = ( address ) => { switch ( isIP ( address ) ) { case 4 : return address === '0.0.0.0' || address . startsWith ( '127.' ) ; case 6 : return address === '::' || address === '::1' ; default : return false ; } } ;