Skip to content

Instantly share code, notes, and snippets.

@mrgrain
Created October 28, 2022 14:26
Show Gist options
  • Save mrgrain/aaf256695c53e71db9764342116343cf to your computer and use it in GitHub Desktop.
Save mrgrain/aaf256695c53e71db9764342116343cf to your computer and use it in GitHub Desktop.
import {
DefaultStackSynthesizer,
FileAssetLocation,
FileAssetSource,
} from 'aws-cdk-lib';
import { DefaultStackSynthesizerProps } from 'aws-cdk-lib/core/lib/stack-synthesizers/default-synthesizer';
import * as path from 'path';
export interface FileAssetSynthesizerProps
extends DefaultStackSynthesizerProps {}
const cdkLibRoot = path.dirname(require.resolve('aws-cdk-lib'));
export class FileAssetSynthesizer extends DefaultStackSynthesizer {
constructor(props: FileAssetSynthesizerProps = {}) {
super(props);
}
addFileAsset(asset: FileAssetSource): FileAssetLocation {
const assetDirName = asset.fileName && path.dirname(asset.fileName);
if (!isSubDir(assetDirName, cdkLibRoot) && assetDirName !== '.') {
throw new Error(
`Asset ${asset.fileName} cannot be used. Only assets from the CDK construct library are supported.`
);
}
return super.addFileAsset(asset);
}
}
function isSubDir(dir: string | undefined, parent: string): boolean {
if (!dir) return false;
const path = require('path');
const relative = path.relative(parent, dir);
return relative && !relative.startsWith('..') && !path.isAbsolute(relative);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment