muddle/contracts/typegen/minify.ts
2026-10-23 08:53:07 -04:00

45 lines
1.4 KiB
TypeScript

/** Flattens an intersection into one object type. */
export type Minify<T> = T extends (...args: never[]) => unknown
? T
: { [K in keyof T]: T[K] } & {};
/** Alias of {@link Minify}, kept for readability in generated output. */
export type Simplify<T> = Minify<T>;
/** Makes every property of `T` readonly, recursively. */
export type DeepReadonly<T> = T extends (...args: never[]) => unknown
? T
: T extends readonly (infer U)[]
? readonly DeepReadonly<U>[]
: T extends object
? { readonly [K in keyof T]: DeepReadonly<T[K]> }
: T;
/** Removes `null` and `undefined` from a union. */
export type Defined<T> = Exclude<T, null | undefined>;
/** Marks the selected keys of `T` as optional. */
export type WithOptional<T, K extends keyof T> = Omit<T, K> &
Partial<Pick<T, K>>;
/** Marks the selected keys of `T` as required. */
export type WithRequired<T, K extends keyof T> = Omit<T, K> &
Required<Pick<T, K>>;
export function compactTypeSource(source: string): string {
const arrow = source.replace(/=>/g, "__ARROW__");
return arrow
.replace(/\s+/g, " ")
.replace(/\s*([|&=<>?:,()[\]{}])\s*/g, "$1")
.replace(/;\s*$/, "")
.trim()
.replace(/__ARROW__/g, "=>");
}
export function indent(source: string, depth = 1): string {
const pad = " ".repeat(depth);
return source
.split("\n")
.map((line) => (line.length > 0 ? pad + line : line))
.join("\n");
}