UNPKG

aws-cdk-lib

Version:

Version 2 of the AWS Cloud Development Kit library

2 lines (1 loc) 13.9 kB
"use strict";var _a,_b,_c,_d;Object.defineProperty(exports,"__esModule",{value:!0}),exports.Expires=exports.StorageClass=exports.ServerSideEncryption=exports.CacheControl=exports.DeployTimeSubstitutedFile=exports.BucketDeployment=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");var fs=()=>{var tmp=require("fs");return fs=()=>tmp,tmp},case_1=()=>{var tmp=require("case");return case_1=()=>tmp,tmp},constructs_1=()=>{var tmp=require("constructs");return constructs_1=()=>tmp,tmp},source_1=()=>{var tmp=require("./source");return source_1=()=>tmp,tmp},efs=()=>{var tmp=require("../../aws-efs");return efs=()=>tmp,tmp},iam=()=>{var tmp=require("../../aws-iam");return iam=()=>tmp,tmp},lambda=()=>{var tmp=require("../../aws-lambda");return lambda=()=>tmp,tmp},s3=()=>{var tmp=require("../../aws-s3");return s3=()=>tmp,tmp},cdk=()=>{var tmp=require("../../core");return cdk=()=>tmp,tmp},errors_1=()=>{var tmp=require("../../core/lib/errors");return errors_1=()=>tmp,tmp},bucket_deployment_provider_generated_1=()=>{var tmp=require("../../custom-resource-handlers/dist/aws-s3-deployment/bucket-deployment-provider.generated");return bucket_deployment_provider_generated_1=()=>tmp,tmp},lambda_layer_awscli_1=()=>{var tmp=require("../../lambda-layer-awscli");return lambda_layer_awscli_1=()=>tmp,tmp};const CUSTOM_RESOURCE_OWNER_TAG="aws-cdk:cr-owned";class BucketDeployment extends constructs_1().Construct{constructor(scope,id,props){super(scope,id),this.requestDestinationArn=!1;try{jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_deployment_BucketDeploymentProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,BucketDeployment),error}if(props.distributionPaths){if(!props.distribution)throw new(errors_1()).ValidationError("Distribution must be specified if distribution paths are specified",this);if(!cdk().Token.isUnresolved(props.distributionPaths)&&!props.distributionPaths.every(distributionPath=>cdk().Token.isUnresolved(distributionPath)||distributionPath.startsWith("/")))throw new(errors_1()).ValidationError('Distribution paths must start with "/"',this)}if(props.useEfs&&!props.vpc)throw new(errors_1()).ValidationError("Vpc must be specified if useEfs is set",this);this.destinationBucket=props.destinationBucket;const accessPointPath="/lambda";let accessPoint;if(props.useEfs&&props.vpc){const accessMode="0777",fileSystem=this.getOrCreateEfsFileSystem(scope,{vpc:props.vpc,removalPolicy:cdk().RemovalPolicy.DESTROY});accessPoint=fileSystem.addAccessPoint("AccessPoint",{path:accessPointPath,createAcl:{ownerUid:"1001",ownerGid:"1001",permissions:accessMode},posixUser:{uid:"1001",gid:"1001"}}),accessPoint.node.addDependency(fileSystem.mountTargetsAvailable)}props.vpc&&this.node.addDependency(props.vpc);const mountPath=`/mnt${accessPointPath}`,handler=new(bucket_deployment_provider_generated_1()).BucketDeploymentSingletonFunction(this,"CustomResourceHandler",{uuid:this.renderSingletonUuid(props.memoryLimit,props.ephemeralStorageSize,props.vpc),layers:[new(lambda_layer_awscli_1()).AwsCliLayer(this,"AwsCliLayer")],environment:{...props.useEfs?{MOUNT_PATH:mountPath}:void 0,AWS_CA_BUNDLE:"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"},lambdaPurpose:"Custom::CDKBucketDeployment",timeout:cdk().Duration.minutes(15),role:props.role,memorySize:props.memoryLimit,ephemeralStorageSize:props.ephemeralStorageSize,vpc:props.vpc,vpcSubnets:props.vpcSubnets,filesystem:accessPoint?lambda().FileSystem.fromEfsAccessPoint(accessPoint,mountPath):void 0,...props.logRetention?{logRetention:props.logRetention}:{},logGroup:props.logGroup}),handlerRole=handler.role;if(!handlerRole)throw new(errors_1()).ValidationError("lambda.SingletonFunction should have created a Role",this);this.handlerRole=handlerRole,this.sources=props.sources.map(source=>source.bind(this,{handlerRole:this.handlerRole})),this.destinationBucket.grantReadWrite(handler),props.accessControl&&this.destinationBucket.grantPutAcl(handler),props.distribution&&handler.addToRolePolicy(new(iam()).PolicyStatement({effect:iam().Effect.ALLOW,actions:["cloudfront:GetInvalidation","cloudfront:CreateInvalidation"],resources:["*"]}));const _this=this;this.node.addValidation({validate(){return _this.sources.some(source=>source.markers)&&props.extract==!1?["Some sources are incompatible with extract=false; sources with deploy-time values (such as 'snsTopic.topicArn') must be extracted."]:[]}});const crUniqueId=`CustomResource${this.renderUniqueId(props.memoryLimit,props.ephemeralStorageSize,props.vpc)}`;this.cr=new(cdk()).CustomResource(this,crUniqueId,{serviceToken:handler.functionArn,resourceType:"Custom::CDKBucketDeployment",properties:{SourceBucketNames:cdk().Lazy.uncachedList({produce:()=>this.sources.map(source=>source.bucket.bucketName)}),SourceObjectKeys:cdk().Lazy.uncachedList({produce:()=>this.sources.map(source=>source.zipObjectKey)}),SourceMarkers:cdk().Lazy.uncachedAny({produce:()=>this.sources.reduce((acc,source)=>(source.markers?acc.push(source.markers):this.sources.length>1&&acc.push({}),acc),[])},{omitEmptyArray:!0}),DestinationBucketName:this.destinationBucket.bucketName,DestinationBucketKeyPrefix:props.destinationKeyPrefix,RetainOnDelete:props.retainOnDelete,Extract:props.extract,Prune:props.prune??!0,Exclude:props.exclude,Include:props.include,UserMetadata:props.metadata?mapUserMetadata(props.metadata):void 0,SystemMetadata:mapSystemMetadata(props),DistributionId:props.distribution?.distributionId,DistributionPaths:props.distributionPaths,SignContent:props.signContent,OutputObjectKeys:props.outputObjectKeys??!0,DestinationBucketArn:cdk().Lazy.string({produce:()=>this.requestDestinationArn?this.destinationBucket.bucketArn:void 0})}});let prefix=props.destinationKeyPrefix?`:${props.destinationKeyPrefix}`:"";prefix+=`:${this.cr.node.addr.slice(-8)}`;const tagKey=CUSTOM_RESOURCE_OWNER_TAG+prefix;if(!cdk().Token.isUnresolved(tagKey)&&tagKey.length>128)throw new(errors_1()).ValidationError('The BucketDeployment construct requires that the "destinationKeyPrefix" be <=104 characters.',this);cdk().Tags.of(this.destinationBucket).add(tagKey,"true")}get deployedBucket(){return this.requestDestinationArn=!0,this._deployedBucket=this._deployedBucket??s3().Bucket.fromBucketAttributes(this,"DestinationBucket",{bucketArn:cdk().Token.asString(this.cr.getAtt("DestinationBucketArn")),region:this.destinationBucket.env.region,account:this.destinationBucket.env.account,isWebsite:this.destinationBucket.isWebsite}),this._deployedBucket}get objectKeys(){return cdk().Token.asList(this.cr.getAtt("SourceObjectKeys"))}addSource(source){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_deployment_ISource(source)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.addSource),error}const config=source.bind(this,{handlerRole:this.handlerRole});this.sources.some(c=>sourceConfigEqual(cdk().Stack.of(this),c,config))||this.sources.push(config)}renderUniqueId(memoryLimit,ephemeralStorageSize,vpc){let uuid="";if(memoryLimit){if(cdk().Token.isUnresolved(memoryLimit))throw new(errors_1()).ValidationError("Can't use tokens when specifying 'memoryLimit' since we use it to identify the singleton custom resource handler.",this);uuid+=`-${memoryLimit.toString()}MiB`}if(ephemeralStorageSize){if(ephemeralStorageSize.isUnresolved())throw new(errors_1()).ValidationError("Can't use tokens when specifying 'ephemeralStorageSize' since we use it to identify the singleton custom resource handler.",this);uuid+=`-${ephemeralStorageSize.toMebibytes().toString()}MiB`}return vpc&&(uuid+=`-${vpc.node.addr}`),uuid}renderSingletonUuid(memoryLimit,ephemeralStorageSize,vpc){let uuid="8693BB64-9689-44B6-9AAF-B0CC9EB8756C";return uuid+=this.renderUniqueId(memoryLimit,ephemeralStorageSize,vpc),uuid}getOrCreateEfsFileSystem(scope,fileSystemProps){const stack=cdk().Stack.of(scope),uuid=`BucketDeploymentEFS-VPC-${fileSystemProps.vpc.node.addr}`;return stack.node.tryFindChild(uuid)??new(efs()).FileSystem(scope,uuid,fileSystemProps)}}exports.BucketDeployment=BucketDeployment,_a=JSII_RTTI_SYMBOL_1,BucketDeployment[_a]={fqn:"aws-cdk-lib.aws_s3_deployment.BucketDeployment",version:"2.185.0"};class DeployTimeSubstitutedFile extends BucketDeployment{constructor(scope,id,props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_deployment_DeployTimeSubstitutedFileProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,DeployTimeSubstitutedFile),error}if(!fs().existsSync(props.source))throw new(errors_1()).ValidationError(`No file found at 'source' path ${props.source}`,scope);let fileData=fs().readFileSync(props.source,"utf-8");fileData=fileData.replace(/{{\s*(\w+)\s*}}/g,function(match,expr){return props.substitutions[expr]??match});const objectKey=props.destinationKey??cdk().FileSystem.fingerprint(props.source),fileSource=source_1().Source.data(objectKey,fileData),fullBucketDeploymentProps={prune:!1,extract:!0,...props,sources:[fileSource],role:props.role};super(scope,id,fullBucketDeploymentProps),this.objectKey=objectKey}get bucket(){return this.deployedBucket}}exports.DeployTimeSubstitutedFile=DeployTimeSubstitutedFile,_b=JSII_RTTI_SYMBOL_1,DeployTimeSubstitutedFile[_b]={fqn:"aws-cdk-lib.aws_s3_deployment.DeployTimeSubstitutedFile",version:"2.185.0"};function mapUserMetadata(metadata){const mapKey=key=>key.toLowerCase();return Object.keys(metadata).reduce((o,key)=>({...o,[mapKey(key)]:metadata[key]}),{})}function mapSystemMetadata(metadata){const res={};return metadata.cacheControl&&(res["cache-control"]=metadata.cacheControl.map(c=>c.value).join(", ")),metadata.expires&&(res.expires=metadata.expires.date.toUTCString()),metadata.contentDisposition&&(res["content-disposition"]=metadata.contentDisposition),metadata.contentEncoding&&(res["content-encoding"]=metadata.contentEncoding),metadata.contentLanguage&&(res["content-language"]=metadata.contentLanguage),metadata.contentType&&(res["content-type"]=metadata.contentType),metadata.serverSideEncryption&&(res.sse=metadata.serverSideEncryption),metadata.storageClass&&(res["storage-class"]=metadata.storageClass),metadata.websiteRedirectLocation&&(res["website-redirect"]=metadata.websiteRedirectLocation),metadata.serverSideEncryptionAwsKmsKeyId&&(res["sse-kms-key-id"]=metadata.serverSideEncryptionAwsKmsKeyId),metadata.serverSideEncryptionCustomerAlgorithm&&(res["sse-c-copy-source"]=metadata.serverSideEncryptionCustomerAlgorithm),metadata.accessControl&&(res.acl=(0,case_1().kebab)(metadata.accessControl.toString())),Object.keys(res).length===0?void 0:res}class CacheControl{static mustRevalidate(){return new CacheControl("must-revalidate")}static noCache(){return new CacheControl("no-cache")}static noTransform(){return new CacheControl("no-transform")}static noStore(){return new CacheControl("no-store")}static mustUnderstand(){return new CacheControl("must-understand")}static setPublic(){return new CacheControl("public")}static setPrivate(){return new CacheControl("private")}static immutable(){return new CacheControl("immutable")}static proxyRevalidate(){return new CacheControl("proxy-revalidate")}static maxAge(t){try{jsiiDeprecationWarnings().aws_cdk_lib_Duration(t)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.maxAge),error}return new CacheControl(`max-age=${t.toSeconds()}`)}static sMaxAge(t){try{jsiiDeprecationWarnings().aws_cdk_lib_Duration(t)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.sMaxAge),error}return new CacheControl(`s-maxage=${t.toSeconds()}`)}static staleWhileRevalidate(t){try{jsiiDeprecationWarnings().aws_cdk_lib_Duration(t)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.staleWhileRevalidate),error}return new CacheControl(`stale-while-revalidate=${t.toSeconds()}`)}static staleIfError(t){try{jsiiDeprecationWarnings().aws_cdk_lib_Duration(t)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.staleIfError),error}return new CacheControl(`stale-if-error=${t.toSeconds()}`)}static fromString(s){return new CacheControl(s)}constructor(value){this.value=value}}exports.CacheControl=CacheControl,_c=JSII_RTTI_SYMBOL_1,CacheControl[_c]={fqn:"aws-cdk-lib.aws_s3_deployment.CacheControl",version:"2.185.0"};var ServerSideEncryption;(function(ServerSideEncryption2){ServerSideEncryption2.AES_256="AES256",ServerSideEncryption2.AWS_KMS="aws:kms",ServerSideEncryption2.AWS_KMS_DSSE="aws:kms:dsse"})(ServerSideEncryption||(exports.ServerSideEncryption=ServerSideEncryption={}));var StorageClass;(function(StorageClass2){StorageClass2.STANDARD="STANDARD",StorageClass2.REDUCED_REDUNDANCY="REDUCED_REDUNDANCY",StorageClass2.STANDARD_IA="STANDARD_IA",StorageClass2.ONEZONE_IA="ONEZONE_IA",StorageClass2.INTELLIGENT_TIERING="INTELLIGENT_TIERING",StorageClass2.GLACIER="GLACIER",StorageClass2.DEEP_ARCHIVE="DEEP_ARCHIVE"})(StorageClass||(exports.StorageClass=StorageClass={}));class Expires{static atDate(d){return new Expires(d.toUTCString())}static atTimestamp(t){return Expires.atDate(new Date(t))}static after(t){return Expires.atDate(new Date(Date.now()+t.toMilliseconds()))}static fromString(s){return new Expires(s)}constructor(value){this.value=value}}exports.Expires=Expires,_d=JSII_RTTI_SYMBOL_1,Expires[_d]={fqn:"aws-cdk-lib.aws_s3_deployment.Expires",version:"2.185.0"};function sourceConfigEqual(stack,a,b){return JSON.stringify(stack.resolve(a.bucket.bucketName))===JSON.stringify(stack.resolve(b.bucket.bucketName))&&a.zipObjectKey===b.zipObjectKey&&a.markers===void 0&&b.markers===void 0}