fork of hey-api/openapi-ts because I need some additional things
at feat/skip-token 79 lines 2.6 kB view raw
1import type { GetPointerPriorityFn, MatchPointerToGroupFn } from '../graph'; 2 3export const irTopLevelKinds = [ 4 'operation', 5 'parameter', 6 'requestBody', 7 'schema', 8 'server', 9 'webhook', 10] as const; 11 12export type IrTopLevelKind = (typeof irTopLevelKinds)[number]; 13 14/** 15 * Checks if a pointer matches a known top-level IR component (schema, parameter, etc) and returns match info. 16 * 17 * @param pointer - The IR pointer string (e.g. '#/components/schemas/Foo') 18 * @param kind - (Optional) The component kind to check 19 * @returns { matched: true, kind: IrTopLevelKind } | { matched: false } - Whether it matched, and the matched kind if so 20 */ 21export const matchIrPointerToGroup: MatchPointerToGroupFn<IrTopLevelKind> = (pointer, kind) => { 22 const patterns: Record<IrTopLevelKind, RegExp> = { 23 operation: /^#\/paths\/[^/]+\/(get|put|post|delete|options|head|patch|trace)$/, 24 parameter: /^#\/components\/parameters\/[^/]+$/, 25 requestBody: /^#\/components\/requestBodies\/[^/]+$/, 26 schema: /^#\/components\/schemas\/[^/]+$/, 27 server: /^#\/servers\/(\d+|[^/]+)$/, 28 webhook: /^#\/webhooks\/[^/]+\/(get|put|post|delete|options|head|patch|trace)$/, 29 }; 30 if (kind) { 31 return patterns[kind].test(pointer) ? { kind, matched: true } : { matched: false }; 32 } 33 for (const key of Object.keys(patterns)) { 34 const kind = key as IrTopLevelKind; 35 if (patterns[kind].test(pointer)) { 36 return { kind, matched: true }; 37 } 38 } 39 return { matched: false }; 40}; 41 42// default grouping preference (earlier groups emitted first when safe) 43export const preferGroups = [ 44 'server', 45 'schema', 46 'parameter', 47 'requestBody', 48 'operation', 49 'webhook', 50] satisfies ReadonlyArray<IrTopLevelKind>; 51 52type KindPriority = Record<IrTopLevelKind, number>; 53 54// default group priority (lower = earlier) 55// built from `preferGroups` so the priority order stays in sync with the prefer-groups array. 56const kindPriority: KindPriority = (() => { 57 const partial: Partial<KindPriority> = {}; 58 for (let i = 0; i < preferGroups.length; i++) { 59 const k = preferGroups[i]; 60 if (k) partial[k] = i; 61 } 62 // Ensure all known kinds exist in the map (fall back to a high index). 63 for (const k of irTopLevelKinds) { 64 if (partial[k] === undefined) { 65 partial[k] = preferGroups.length; 66 } 67 } 68 return partial as KindPriority; 69})(); 70 71const defaultPriority = 10; 72 73export const getIrPointerPriority: GetPointerPriorityFn = (pointer) => { 74 const result = matchIrPointerToGroup(pointer); 75 if (result.matched) { 76 return kindPriority[result.kind] ?? defaultPriority; 77 } 78 return defaultPriority; 79};