import { Construct } from 'constructs' ; import * as logs from "aws-cdk-lib/aws-logs" ; import * as apig from "aws-cdk-lib/aws-apigateway" ; export interface AccessLogProps extends apig . CfnStage . AccessLogSettingProperty { retention ? : keyof typeof logs . RetentionDays ; } export type AccessLogData = { logGroup : logs . LogGroup | undefined ; format : apig . AccessLogFormat ; destination : apig . LogGroupLogDestination ; } ; export function buildAccessLogData ( scope , accessLog ) { if ( accessLog === false ) { return ; } let logGroup ; let destination ; if ( accessLog && ( accessLog as AccessLogProps ) . destinationArn ) { const destinationArn = ( accessLog as AccessLogProps ) . destinationArn as string ; const destinationLogGroup = logs . LogGroup . fromLogGroupArn ( scope , "LogGroup" , destinationArn ) ; destination = new apig . LogGroupLogDestination ( destinationLogGroup ) ; } else { const retention = ( accessLog && ( accessLog as AccessLogProps ) . retention ) || "INFINITE" ; const retentionValue = logs . RetentionDays [ retention ] ; if ( ! retentionValue ) { throw new Error ( `Invalid access log retention value "${ retention }".` ) ; } logGroup = new logs . LogGroup ( scope , "LogGroup" , { retention : retentionValue , } ) ; destination = new apig . LogGroupLogDestination ( logGroup ) ; } let format ; if ( accessLog && ( accessLog as AccessLogProps ) . format ) { format = ( accessLog as AccessLogProps ) . format as string ; } else if ( typeof accessLog === "string" ) { format = accessLog ; } else { format = "{" + [ `"requestTime":"$context.requestTime"` , `"requestId":"$context.requestId"` , `"httpMethod":"$context.httpMethod"` , `"path":"$context.path"` , `"resourcePath":"$context.resourcePath"` , `"status":$context.status` , `"responseLatency":$context.responseLatency` , `"xrayTraceId":"$context.xrayTraceId"` , `"integrationRequestId":"$context.integration.requestId"` , `"functionResponseStatus":"$context.integration.status"` , `"integrationLatency":"$context.integration.latency"` , `"integrationServiceStatus":"$context.integration.integrationStatus"` , `"ip":"$context.identity.sourceIp"` , `"userAgent":"$context.identity.userAgent"` , `"principalId":"$context.authorizer.principalId"` , ] . join ( "," ) + "}" ; } const accessLogData = { logGroup , format : apig . AccessLogFormat . custom ( format ) , destination , } ; return accessLogData ; } export function cleanupLogGroupName ( str ) { return str . replace ( /[^.\-_/#A-Za-z0-9]/g , "" ) ; }