fork of hey-api/openapi-ts because I need some additional things
1import { ono } from '@jsdevtools/ono';
2
3import type { $RefParserOptions } from './options';
4import type { FileInfo } from './types';
5import { ParserError } from './util/errors';
6import type { PluginResult } from './util/plugins';
7import * as plugins from './util/plugins';
8import { getExtension } from './util/url';
9
10/**
11 * Prepares the file object so we can populate it with data and other values
12 * when it's read and parsed. This "file object" will be passed to all
13 * resolvers and parsers.
14 */
15export function newFile(path: string): FileInfo {
16 let url = path;
17 // Remove the URL fragment, if any
18 const hashIndex = url.indexOf('#');
19 let hash = '';
20 if (hashIndex > -1) {
21 hash = url.substring(hashIndex);
22 url = url.substring(0, hashIndex);
23 }
24 return {
25 extension: getExtension(url),
26 hash,
27 url,
28 } as FileInfo;
29}
30
31/**
32 * Parses the given file's contents, using the configured parser plugins.
33 */
34export async function parseFile(
35 file: FileInfo,
36 options: $RefParserOptions['parse'],
37): Promise<PluginResult> {
38 try {
39 // If none of the parsers are a match for this file, try all of them. This
40 // handles situations where the file is a supported type, just with an
41 // unknown extension.
42 const parsers = [options.json, options.yaml, options.text, options.binary];
43 const filtered = parsers.filter((plugin) => plugin.canHandle(file));
44 return await plugins.run(filtered.length ? filtered : parsers, file);
45 } catch (error: any) {
46 if (error && error.message && error.message.startsWith('Error parsing')) {
47 throw error;
48 }
49
50 if (!error || !('error' in error)) {
51 throw ono.syntax(`Unable to parse ${file.url}`);
52 }
53
54 if (error.error instanceof ParserError) {
55 throw error.error;
56 }
57
58 throw new ParserError(error.error.message, file.url);
59 }
60}