UNPKG

@kubb/core

Version:

Core functionality for Kubb's plugin-based code generation system, providing the foundation for transforming OpenAPI specifications.

1 lines 13.2 kB
{"version":3,"file":"utils.cjs","names":["#buffer","#items","#orderItems","#addParams","camelCase","item","path","timeout"],"sources":["../src/utils/buildJSDoc.ts","../src/utils/Cache.ts","../src/utils/FunctionParams.ts","../src/utils/getNestedAccessor.ts","../src/utils/promise.ts","../src/utils/renderTemplate.ts","../src/utils/resolveModuleSource.ts","../src/utils/timeout.ts"],"sourcesContent":["/**\n * Builds a JSDoc comment block with custom indentation.\n * @param comments - Array of comment strings to include in the JSDoc block\n * @param options - Configuration options for formatting\n * @returns Formatted JSDoc string or fallback string if no comments\n */\nexport function buildJSDoc(\n comments: Array<string>,\n options: {\n /**\n * String to use for indenting each line of the JSDoc comment\n * @default ' * ' (3 spaces + asterisk + space)\n */\n indent?: string\n /**\n * String to append after the closing JSDoc tag\n * @default '\\n ' (newline + 2 spaces)\n */\n suffix?: string\n /**\n * String to return when there are no comments\n * @default ' ' (2 spaces)\n */\n fallback?: string\n } = {},\n): string {\n const { indent = ' * ', suffix = '\\n ', fallback = ' ' } = options\n\n if (comments.length === 0) {\n return fallback\n }\n\n return `/**\\n${comments.map((c) => `${indent}${c}`).join('\\n')}\\n */${suffix}`\n}\n","export class Cache<T> {\n #buffer = new Map<string, T>()\n\n async get(key: string): Promise<T | null> {\n return this.#buffer.get(key) ?? null\n }\n\n async set(key: string, value: T): Promise<void> {\n this.#buffer.set(key, value)\n }\n\n async delete(key: string): Promise<void> {\n this.#buffer.delete(key)\n }\n\n async clear(): Promise<void> {\n this.#buffer.clear()\n }\n\n async keys(): Promise<string[]> {\n return [...this.#buffer.keys()]\n }\n\n async values(): Promise<T[]> {\n return [...this.#buffer.values()]\n }\n\n async flush(): Promise<void> {\n // No-op for base cache\n }\n}\n","import { orderBy } from 'natural-orderby'\n\nimport { camelCase } from '../transformers/casing.ts'\n\ntype FunctionParamsASTWithoutType = {\n name?: string\n type?: string\n /**\n * @default true\n */\n required?: boolean\n /**\n * @default true\n */\n enabled?: boolean\n default?: string\n}\n\ntype FunctionParamsASTWithType = {\n name?: never\n type: string\n /**\n * @default true\n */\n required?: boolean\n /**\n * @default true\n */\n enabled?: boolean\n default?: string\n}\n/**\n * @deprecated\n */\nexport type FunctionParamsAST = FunctionParamsASTWithoutType | FunctionParamsASTWithType\n\n/**\n * @deprecated\n */\nexport class FunctionParams {\n #items: Array<FunctionParamsAST | FunctionParamsAST[]> = []\n constructor() {\n return this\n }\n\n get items(): FunctionParamsAST[] {\n return this.#items.flat()\n }\n\n add(item: FunctionParamsAST | Array<FunctionParamsAST | FunctionParamsAST[] | undefined> | undefined): FunctionParams {\n if (!item) {\n return this\n }\n\n if (Array.isArray(item)) {\n item.filter(Boolean).forEach((it) => {\n this.#items.push(it)\n })\n return this\n }\n this.#items.push(item)\n\n return this\n }\n static #orderItems(items: Array<FunctionParamsAST | FunctionParamsAST[]>) {\n return orderBy(\n items.filter(Boolean),\n [\n (v) => {\n if (Array.isArray(v)) {\n return undefined\n }\n return !v.default\n },\n (v) => {\n if (Array.isArray(v)) {\n return undefined\n }\n return v.required ?? true\n },\n ],\n ['desc', 'desc'],\n )\n }\n\n static #addParams(acc: string[], item: FunctionParamsAST) {\n const { enabled = true, name, type, required = true, ...rest } = item\n\n if (!enabled) {\n return acc\n }\n\n if (!name) {\n // when name is not se we will use TypeScript generics\n acc.push(`${type}${rest.default ? ` = ${rest.default}` : ''}`)\n\n return acc\n }\n // TODO check whey we still need the camelcase here\n const parameterName = name.startsWith('{') ? name : camelCase(name)\n\n if (type) {\n if (required) {\n acc.push(`${parameterName}: ${type}${rest.default ? ` = ${rest.default}` : ''}`)\n } else {\n acc.push(`${parameterName}?: ${type}`)\n }\n } else {\n acc.push(`${parameterName}`)\n }\n\n return acc\n }\n\n static toObject(items: FunctionParamsAST[]): FunctionParamsAST {\n let type: string[] = []\n let name: string[] = []\n\n const enabled = items.every((item) => item.enabled) ? items.at(0)?.enabled : true\n const required = items.every((item) => item.required) ?? true\n\n items.forEach((item) => {\n name = FunctionParams.#addParams(name, { ...item, type: undefined })\n if (items.some((item) => item.type)) {\n type = FunctionParams.#addParams(type, item)\n }\n })\n\n return {\n name: `{ ${name.join(', ')} }`,\n type: type.length ? `{ ${type.join('; ')} }` : undefined,\n enabled,\n required,\n }\n }\n\n toObject(): FunctionParamsAST {\n const items = FunctionParams.#orderItems(this.#items).flat()\n\n return FunctionParams.toObject(items)\n }\n\n static toString(items: (FunctionParamsAST | FunctionParamsAST[])[]): string {\n const sortedData = FunctionParams.#orderItems(items)\n\n return sortedData\n .reduce((acc, item) => {\n if (Array.isArray(item)) {\n if (item.length <= 0) {\n return acc\n }\n const subItems = FunctionParams.#orderItems(item) as FunctionParamsAST[]\n const objectItem = FunctionParams.toObject(subItems)\n\n return FunctionParams.#addParams(acc, objectItem)\n }\n\n return FunctionParams.#addParams(acc, item)\n }, [] as string[])\n .join(', ')\n }\n\n toString(): string {\n const items = FunctionParams.#orderItems(this.#items)\n\n return FunctionParams.toString(items)\n }\n}\n","/**\n * Converts a param path (string with dot notation or array of strings) to a JavaScript accessor expression.\n * @param param - The param path, e.g., 'pagination.next.id' or ['pagination', 'next', 'id']\n * @param accessor - The base accessor, e.g., 'lastPage' or 'firstPage'\n * @returns A JavaScript accessor expression, e.g., \"lastPage?.['pagination']?.['next']?.['id']\", or undefined if param is empty\n *\n * @example\n * ```ts\n * getNestedAccessor('pagination.next.id', 'lastPage')\n * // returns: \"lastPage?.['pagination']?.['next']?.['id']\"\n *\n * getNestedAccessor(['pagination', 'next', 'id'], 'lastPage')\n * // returns: \"lastPage?.['pagination']?.['next']?.['id']\"\n *\n * getNestedAccessor('', 'lastPage')\n * // returns: undefined\n * ```\n */\nexport function getNestedAccessor(param: string | string[], accessor: string): string | undefined {\n const parts = Array.isArray(param) ? param : param.split('.')\n if (parts.length === 0 || (parts.length === 1 && parts[0] === '')) {\n return undefined\n }\n return parts.reduce((acc, part) => `${acc}?.['${part}']`, accessor)\n}\n","import type { PossiblePromise } from './types.ts'\n\nexport function isPromise<T>(result: PossiblePromise<T>): result is Promise<T> {\n return !!result && typeof (result as Promise<unknown>)?.then === 'function'\n}\n\nexport function isPromiseFulfilledResult<T = unknown>(result: PromiseSettledResult<unknown>): result is PromiseFulfilledResult<T> {\n return result.status === 'fulfilled'\n}\n\nexport function isPromiseRejectedResult<T>(result: PromiseSettledResult<unknown>): result is Omit<PromiseRejectedResult, 'reason'> & { reason: T } {\n return result.status === 'rejected'\n}\n","export function renderTemplate<TData extends Record<string, unknown> = Record<string, unknown>>(template: string, data: TData | undefined = undefined): string {\n if (!data || !Object.keys(data).length) {\n return template.replace(/{{(.*?)}}/g, '')\n }\n\n const matches = template.match(/{{(.*?)}}/g)\n\n return (\n matches?.reduce((prev, curr) => {\n const index = curr.split(/{{|}}/).filter(Boolean)[0]?.trim()\n if (index === undefined) {\n return prev\n }\n const value = data[index]\n\n if (value === undefined) {\n return prev\n }\n\n return prev\n .replace(curr, () => {\n if (typeof value === 'boolean') {\n return `${value.toString()}` || 'false'\n }\n\n return (value as string) || ''\n })\n .trim()\n }, template) || ''\n )\n}\n","import { readFileSync } from 'node:fs'\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport createJiti from 'jiti'\n\nexport function resolveModuleSource(pkgName: string) {\n const parentURL = import.meta.url\n const jiti = createJiti(parentURL)\n\n const resolved = jiti.esmResolve(pkgName, parentURL)\n const filePath = resolved.startsWith('file:') ? fileURLToPath(resolved) : resolved\n const source = readFileSync(filePath, { encoding: 'utf-8' })\n const ext = path.extname(filePath)\n return { path: filePath, source, ext } as const\n}\n","export async function timeout(ms: number): Promise<unknown> {\n return new Promise((resolve) => {\n const timeout = setTimeout(() => {\n resolve(timeout)\n }, ms)\n }).then((timeout) => {\n clearTimeout(timeout as NodeJS.Timeout)\n\n return true\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAMA,SAAgB,WACd,UACA,UAgBI,EAAE,EACE;CAC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