10
10
* OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions
11
11
* and limitations under the License.
12
12
*/
13
+ import { createHash } from 'crypto' ;
13
14
import * as cdk from 'aws-cdk-lib' ;
14
15
import { IConstruct } from 'constructs' ;
15
16
import { CfnNagSuppressRule } from '../../patterns/gen-ai/aws-rag-appsync-stepfn-kendra/types' ;
@@ -76,6 +77,12 @@ export interface GeneratePhysicalNameV2Options extends cdk.UniqueResourceNameOpt
76
77
* @default false
77
78
*/
78
79
lower ?: boolean ;
80
+
81
+ /**
82
+ * This object is hashed for uniqueness and can force a destroy instead of a replace.
83
+ * @default : undefined
84
+ */
85
+ destroyCreate ?: any ;
79
86
}
80
87
/**
81
88
* @internal This is an internal core function and should not be called directly by Solutions Constructs clients.
@@ -102,20 +109,36 @@ export function generatePhysicalNameV2(
102
109
*/
103
110
options ?: GeneratePhysicalNameV2Options ,
104
111
) : string {
112
+ function objectToHash ( obj : any ) : string {
113
+ // Nothing to hash if undefined
114
+ if ( obj === undefined ) { return '' ; }
115
+
116
+ // Convert the object to a JSON string
117
+ const jsonString = JSON . stringify ( obj ) ;
118
+
119
+ // Create a SHA-256 hash
120
+ const hash = createHash ( 'sha256' ) ;
121
+
122
+ // Update the hash with the JSON string and get the digest in hexadecimal format
123
+ // Shorten it (modeled after seven characters like git commit hash shortening)
124
+ return hash . update ( jsonString ) . digest ( 'hex' ) . slice ( 0 , 7 ) ;
125
+ }
105
126
const {
106
127
maxLength = 256 ,
107
128
lower = false ,
108
129
separator = '' ,
109
130
allowedSpecialCharacters = undefined ,
131
+ destroyCreate = undefined ,
110
132
} = options ?? { } ;
111
- if ( maxLength < ( prefix + separator ) . length ) {
133
+ const hash = objectToHash ( destroyCreate ) ;
134
+ if ( maxLength < ( prefix + hash + separator ) . length ) {
112
135
throw new Error ( 'The prefix is longer than the maximum length.' ) ;
113
136
}
114
137
const uniqueName = cdk . Names . uniqueResourceName (
115
138
scope ,
116
- { maxLength : maxLength - ( prefix + separator ) . length , separator, allowedSpecialCharacters } ,
139
+ { maxLength : maxLength - ( prefix + hash + separator ) . length , separator, allowedSpecialCharacters } ,
117
140
) ;
118
- const name = `${ prefix } ${ separator } ${ uniqueName } ` ;
141
+ const name = `${ prefix } ${ hash } ${ separator } ${ uniqueName } ` ;
119
142
if ( name . length > maxLength ) {
120
143
throw new Error ( `The generated name is longer than the maximum length of ${ maxLength } ` ) ;
121
144
}
0 commit comments