@@ -250,7 +250,50 @@ export class TCVB {
250250 private m_arrOperations : TcvbOperation [ ] = [ ] ;
251251
252252 constructor ( tcStrContent : string ) {
253- this . parse ( tcStrContent ) ;
253+ try {
254+ this . parse ( tcStrContent ) ;
255+ } catch ( error ) {
256+ const fixedContent = TCVB . autoFixTCVBContent ( tcStrContent ) ;
257+ this . parse ( fixedContent ) ;
258+ }
259+ }
260+
261+ public static autoFixTCVBContent ( original : string ) : string {
262+ let content = original ;
263+
264+ // Remove leading spaces before ## directives
265+ content = content . replace ( / ^ ( \s + ) # # / gm, '##' ) ;
266+
267+ // Close unclosed code blocks, inspired by the file-ending reference regex
268+ content = content . replace ( / ( ` ` ` [ ^ \n ] * \n [ \s \S ] * ?) (? = ^ # # | \n # # E N D _ T C V B | (? ! [ \s \S ] ) ) / gm, '$1\n```' ) ;
269+
270+ // Ensure END_TCVB is present
271+ if ( ! / ^ # # \s * E N D _ T C V B \s * $ / m. test ( content ) ) {
272+ content += '\n## END_TCVB' ;
273+ }
274+
275+ // Fix GLOBAL-REPLACE operations
276+ content = content . replace (
277+ / # # O P E R A T I O N : G L O B A L - R E P L A C E \n ( [ \s \S ] * ?) (? = \n # # O P E R A T I O N : | \n # # F I L E : | \n # # E N D _ T C V B | $ ) / g,
278+ ( match ) => {
279+ const hasOldContent = / # # O L D _ C O N T E N T / . test ( match ) ;
280+ const hasNewContent = / # # N E W _ C O N T E N T / . test ( match ) ;
281+
282+ if ( ! hasOldContent && hasNewContent ) {
283+ // Convert to CREATE if only NEW_CONTENT is present
284+ const newContentMatch = match . match ( / # # N E W _ C O N T E N T \n ` ` ` ( [ \s \S ] * ?) ` ` ` / ) ;
285+ const newContentCode = newContentMatch ? newContentMatch [ 1 ] : '' ;
286+ return `## OPERATION:CREATE\n\`\`\`\n${ newContentCode } \n\`\`\`` ;
287+ } else if ( hasOldContent && ! hasNewContent ) {
288+ // Add empty NEW_CONTENT if only OLD_CONTENT is present
289+ return match + '\n## NEW_CONTENT\n```\n```' ;
290+ }
291+ // Return unchanged if both are present or both are missing (assuming minimal valid structure)
292+ return match ;
293+ }
294+ ) ;
295+
296+ return content ;
254297 }
255298
256299 private parse ( tcStrContent : string ) : void {
0 commit comments