UNPKG

@scalar/oas-utils

Version:

Open API spec and Yaml handling utilities

96 lines (93 loc) 2.78 kB
import { parse, stringify } from 'yaml'; /** Yaml handling with optional safeparse */ const yaml = { /** Parse and throw if the return value is not an object */ parse: (val) => { const yamlObject = parse(val); if (typeof yamlObject !== 'object') { throw Error('Invalid YAML object'); } return yamlObject; }, /** Parse and return a fallback on failure */ parseSafe(val, fallback) { try { return yaml.parse(val); } catch (err) { return typeof fallback === 'function' ? fallback(err) : fallback; } }, stringify, }; /** JSON handling with optional safeparse */ const json = { /** Parse and throw if the return value is not an object */ parse: (val) => { const jsonObject = JSON.parse(val); if (typeof jsonObject !== 'object') { throw Error('Invalid JSON object'); } return jsonObject; }, /** Parse and return a fallback on failure */ parseSafe(val, fallback) { try { return json.parse(val); } catch (err) { return typeof fallback === 'function' ? fallback(err) : fallback; } }, stringify: (val) => JSON.stringify(val), }; /** * Check if value is a valid JSON string */ const isJsonString = (value) => { if (typeof value !== 'string') { return false; } return !!json.parseSafe(value, false); }; /** * This helper is used to transform the content of the swagger file to JSON, even it was YAML. */ const transformToJson = (value) => { // Try json, then fallback to yaml, then fallback to string return JSON.stringify(json.parseSafe(value, yaml.parseSafe(value, value))); }; /** Validates a JSON string if provided. Otherwise returns the raw YAML */ function formatJsonOrYamlString(value) { // If we don't start with a bracket assume yaml const trimmed = value.trim(); if (trimmed[0] !== '{' && trimmed[0] !== '[') { return value; } try { // JSON return JSON.stringify(JSON.parse(value), null, 2); } catch { // YAML return value; } } /** Parse JSON or YAML into an object */ const parseJsonOrYaml = (value) => { if (typeof value !== 'string') { return value; } const jsonObject = json.parseSafe(value, null); if (jsonObject) { return jsonObject; } // Value is probably supposed to be JSON. Throw if (value.length > 0 && ['{', '['].includes(value[0] ?? '')) { throw Error('Invalid JSON or YAML'); } return yaml.parseSafe(value, (err) => { throw Error(err); }); }; export { formatJsonOrYamlString, isJsonString, json, parseJsonOrYaml, transformToJson, yaml };