Files
openapi-clean-arch-gen/src/utils/name-formatter.ts

110 lines
2.1 KiB
TypeScript

/**
* Converts a string to PascalCase, handling spaces, hyphens and underscores.
* Used to derive class names from schema/tag names.
*
* @example
* toPascalCase('Product Format') // 'ProductFormat'
* toPascalCase('user-response') // 'UserResponse'
* toPascalCase('UserSchema') // 'UserSchema'
*/
export function toPascalCase(name: string): string {
if (!name) return name;
return name
.split(/[\s\-_]+/)
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join('');
}
/**
* Converts a string to camelCase, handling spaces, hyphens and underscores.
* Used to derive class filenames and variable names from schema/tag names.
*
* @example
* toCamelCase('Product Format') // 'productFormat'
* toCamelCase('ProductResponse') // 'productResponse'
* toCamelCase('UserSchema') // 'userSchema'
*/
export function toCamelCase(name: string): string {
if (!name) return name;
const pascal = toPascalCase(name);
return pascal.charAt(0).toLowerCase() + pascal.slice(1);
}
const JS_RESERVED_WORDS = new Set([
'abstract',
'arguments',
'await',
'boolean',
'break',
'byte',
'case',
'catch',
'char',
'class',
'const',
'continue',
'debugger',
'default',
'delete',
'do',
'double',
'else',
'enum',
'eval',
'export',
'extends',
'false',
'final',
'finally',
'float',
'for',
'function',
'goto',
'if',
'implements',
'import',
'in',
'instanceof',
'int',
'interface',
'let',
'long',
'native',
'new',
'null',
'package',
'private',
'protected',
'public',
'return',
'short',
'static',
'super',
'switch',
'synchronized',
'this',
'throw',
'throws',
'transient',
'true',
'try',
'typeof',
'undefined',
'var',
'void',
'volatile',
'while',
'with',
'yield'
]);
/** Returns true if the given name is a JS/TS reserved word. */
export function isReservedWord(name: string): boolean {
return JS_RESERVED_WORDS.has(name);
}
/** Prefixes reserved words with `_` to produce a safe identifier. */
export function safePropertyName(name: string): string {
return isReservedWord(name) ? `_${name}` : name;
}