UNPKG

@kontent-ai/model-generator

Version:

This utility generates strongly-typed models for Delivery JS SDK, Migration toolkit or just general scripting to improve the experience when referencing Kontent.ai related objects.

71 lines 2.82 kB
import { createHash } from "node:crypto"; import { P, match } from "ts-pattern"; export function mapFilename(resolver, options) { return (item, addExtension) => { return ((options?.prefix ? options.prefix : "") + addExtensionToFilename(resolveCase(match(resolver) .returnType() .with(P.instanceOf(Function), (resolver) => resolver(item, addExtension)) .otherwise(() => item.codename), "kebabCase") + (options?.suffix ? options.suffix : ""), addExtension)); }; } export function mapName(resolver, caseType, options) { return (item) => (options?.prefix ? options.prefix : "") + resolveCase(match(resolver) .returnType() .with(P.instanceOf(Function), (resolver) => resolver(item)) .otherwise(() => item.name), caseType) + (options?.suffix ? options.suffix : ""); } export function resolveCase(text, resolverType) { return match(resolverType) .returnType() .with("camelCase", () => toCamelCase(text)) .with("pascalCase", () => toPascalCase(text)) .with("kebabCase", () => toKebabCase(text)) .exhaustive(); } export function resolvePropertyName(value) { const propertyName = toCamelCase(value); if (propertyName.length === 0) { // to prevent empty string being used as property name, use hash return getPropertyStringHash(value); } return prefixWithUnderscoreWhenStartsWithNonAlpha(propertyName); } function addExtensionToFilename(filename, addExtension) { return `${filename}${addExtension ? ".ts" : ""}`; } function toPascalCase(text) { return prefixWithUnderscoreWhenStartsWithNonAlpha(toSafeStringCode(text .replace(/[_-]+/g, " ") .replace(/(?:^\w|[A-Z]|\b\w|\s+|\d\w)/g, (match) => match.toUpperCase()) .replace(/\s+/g, ""), false)); } function toKebabCase(text) { const matchResult = text.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g); if (!matchResult) { throw new Error(`Failed to convert text to kebab case: ${text}`); } return matchResult.join("-").toLowerCase(); } function toCamelCase(text) { return toPascalCase(text).replace(/^\w/, (s) => s.toLowerCase()); } function getPropertyStringHash(text) { const hash = createHash("sha256"); hash.update(text); return `_${hash.digest("hex")}`.slice(0, 10); } function toSafeStringCode(text, allowHyphen) { const replaceWith = ""; const pattern = allowHyphen ? /[^a-zA-Z0-9_-]/g : /[^a-zA-Z0-9_]/g; return text.replace(pattern, replaceWith); } function prefixWithUnderscoreWhenStartsWithNonAlpha(text) { if (/^[^a-zA-Z-]/.test(text)) { return `_${text.replace(/^_+/, "")}`; } return text; } //# sourceMappingURL=resolvers.js.map