fork of hey-api/openapi-ts because I need some additional things
at feat/skip-token 94 lines 2.3 kB view raw
1import type { Input } from '../../config/input/types'; 2 3// Regular expression to match Hey API Registry input formats: 4// - {organization}/{project}?{queryParams} 5const registryRegExp = /^([\w-]+)\/([\w-]+)(?:\?([\w=&.-]*))?$/; 6 7export const heyApiRegistryBaseUrl = 'https://get.heyapi.dev'; 8 9/** 10 * Creates a full Hey API Registry URL. 11 * 12 * @param organization - Hey API organization slug 13 * @param project - Hey API project slug 14 * @param queryParams - Optional query parameters 15 * @returns The full Hey API registry URL. 16 */ 17export function getRegistryUrl( 18 organization: string, 19 project: string, 20 queryParams?: string, 21): string { 22 return `${heyApiRegistryBaseUrl}/${organization}/${project}${queryParams ? `?${queryParams}` : ''}`; 23} 24 25export type Parsed = { 26 organization: string; 27 project: string; 28 queryParams?: string; 29}; 30 31/** 32 * Parses a Hey API input string and extracts components. 33 * 34 * @param input - Hey API configuration input 35 * @returns Parsed Hey API input components 36 * @throws Error if the input format is invalid 37 */ 38export function parseShorthand( 39 input: Input & { 40 path: string; 41 }, 42): Parsed { 43 let organization = input.organization; 44 let project = input.project; 45 let queryParams: string | undefined; 46 47 if (input.path) { 48 const match = input.path.match(registryRegExp); 49 50 if (!match) { 51 throw new Error( 52 `Invalid Hey API shorthand format. Expected "organization/project?queryParams" or "organization/project", received: ${input.path}`, 53 ); 54 } 55 56 organization = match[1]; 57 project = match[2]; 58 queryParams = match[3]; 59 } 60 61 if (!organization) { 62 throw new Error('The Hey API organization cannot be empty.'); 63 } 64 65 if (!project) { 66 throw new Error('The Hey API project cannot be empty.'); 67 } 68 69 const result: Parsed = { 70 organization, 71 project, 72 queryParams, 73 }; 74 75 return result; 76} 77 78/** 79 * Transforms a Hey API shorthand string to the corresponding API URL. 80 * 81 * @param input - Hey API configuration input 82 * @returns The Hey API Registry URL 83 */ 84export function inputToHeyApiPath( 85 input: Input & { 86 path: string; 87 }, 88): Partial<Input> { 89 const parsed = parseShorthand(input); 90 return { 91 path: getRegistryUrl(parsed.organization, parsed.project, parsed.queryParams), 92 registry: 'hey-api', 93 }; 94}