aws-cdk-lib
Version:
Version 2 of the AWS Cloud Development Kit library
2 lines (1 loc) • 1.86 kB
JavaScript
Object.defineProperty(exports,"__esModule",{value:!0}),exports.makeUniqueResourceName=makeUniqueResourceName;var md5_1=()=>{var tmp=require("./md5");return md5_1=()=>tmp,tmp};const HIDDEN_FROM_HUMAN_ID="Resource",HIDDEN_ID="Default",PATH_SEP="/",MAX_LEN=256,HASH_LEN=8;function makeUniqueResourceName(components,options){const maxLength=options.maxLength??256,separator=options.separator??"",prefix=options.prefix??"";if(components=components.filter(x=>x!==HIDDEN_ID),components.length===0)throw new Error("Unable to calculate a unique resource name for an empty set of components");if(components.length===1){const topLevelResource=prefix+removeNonAllowedSpecialCharacters(components[0],separator,options.allowedSpecialCharacters);if(topLevelResource.length<=maxLength)return topLevelResource}const hash=pathHash(components),human=prefix+removeDupes(components).filter(pathElement=>pathElement!==HIDDEN_FROM_HUMAN_ID).map(pathElement=>removeNonAllowedSpecialCharacters(pathElement,separator,options.allowedSpecialCharacters)).filter(pathElement=>pathElement).join(separator).concat(separator),maxhumanLength=maxLength-HASH_LEN;return human.length>maxhumanLength?`${splitInMiddle(human,maxhumanLength)}${hash}`:`${human}${hash}`}function pathHash(path){return(0,md5_1().md5hash)(path.join(PATH_SEP)).slice(0,HASH_LEN).toUpperCase()}function removeNonAllowedSpecialCharacters(s,_separator,allowedSpecialCharacters){const pattern=allowedSpecialCharacters?`[^A-Za-z0-9${allowedSpecialCharacters}]`:"[^A-Za-z0-9]",regex=new RegExp(pattern,"g");return s.replace(regex,"")}function removeDupes(path){const ret=new Array;for(const component of path)(ret.length===0||!ret[ret.length-1].endsWith(component))&&ret.push(component);return ret}function splitInMiddle(s,maxLength=MAX_LEN-HASH_LEN){const half=maxLength/2;return s.slice(0,half)+s.slice(-half)}
;