Refactored to use maps for the bulk of the operations, build out functions for building entire endpoint schema

This commit is contained in:
Luke Hagar
2024-02-06 21:54:41 -06:00
parent 949602623c
commit bf89ea8705
7 changed files with 1524 additions and 162 deletions

View File

@@ -68,7 +68,7 @@ export type NumberType = {
export type ObjectType = { export type ObjectType = {
type: 'object'; type: 'object';
properties?: { [key: string]: Output }; properties: { [key: string]: Output };
additionalProperties?: boolean; additionalProperties?: boolean;
example?: object; example?: object;
}; };
@@ -126,45 +126,62 @@ export function convertNumber(number: number, config: Config) {
return output; return output;
} }
const isObject = (item: Output): item is ObjectType => {
return item.type === 'object';
};
const isArray = (item: Output): item is ArrayType => {
return item.type === 'array';
};
const isObjectOrArray = (item: Output): item is ObjectType | ArrayType => {
return isObject(item) || isArray(item);
};
export function convertArray(array: unknown[], config: Config) { export function convertArray(array: unknown[], config: Config) {
const output: ArrayType = { type: 'array' }; const output: ArrayType = { type: 'array' };
const items: Output[] = []; const outputItems: Output[] = [];
const items: unknown[] = [];
const exampleArray = []; const exampleArray = [];
let schema = {}; const schema = new Map<string, unknown>();
for (const entry of array) { for (const entry of array) {
if (config.allowOneOf) { if (config.allowOneOf) {
const map = convertObject(entry, config); const objectMap = convertObject(entry, config);
if ( if (
!items.some( !outputItems.some(
(item) => (item) =>
(item.type === map.type && item.format === map.format && item.type !== 'object') || (item.type === objectMap.type &&
(item.type === 'object' && !isObjectOrArray(item) &&
JSON.stringify(Object.keys(item.properties).sort()) === !isObjectOrArray(objectMap) &&
JSON.stringify(Object.keys(map.properties).sort())) item.format === objectMap.format) ||
(isObject(item) &&
isObject(objectMap) &&
Object.keys(item.properties).sort() === Object.keys(objectMap.properties).sort())
) )
) { ) {
items.push(map); outputItems.push(objectMap);
exampleArray.push(entry); exampleArray.push(entry);
} }
} else { } else {
items.push(entry); items.push(entry);
if (typeof entry === 'object' && !Array.isArray(entry)) { if (typeof entry === 'object' && !Array.isArray(entry) && entry !== null) {
for (const prop in entry) { for (const prop in entry) {
schema[prop] = entry[prop]; // @ts-expect-error we are looping through self supplied object keys determined at runtime
schema.set(prop, entry[prop]);
} }
} }
} }
} }
if (config.allowOneOf) { if (config.allowOneOf) {
if (items.length > 1) { if (outputItems.length > 1) {
output.items = { oneOf: [...items] }; output.items = { oneOf: [...outputItems] };
} else { } else {
output.items = items[0]; output.items = outputItems[0];
} }
} else { } else {
if (Object.keys(schema).length > 0) { if (schema.size > 0) {
exampleArray.push(schema); exampleArray.push(Object.fromEntries(schema.entries()));
output.items = convertObject(schema, config); output.items = convertObject(schema, config);
} else { } else {
exampleArray.push(items[0]); exampleArray.push(items[0]);
@@ -193,7 +210,7 @@ export function convertString(string: string, config: Config) {
return output; return output;
} }
export function convertObject(input: any, config: Config) { export function convertObject(input: unknown, config: Config) {
if (input === null) { if (input === null) {
return { type: config.nullType, format: 'nullable' } as NullableType; return { type: config.nullType, format: 'nullable' } as NullableType;
} else if (typeof input === 'number') { } else if (typeof input === 'number') {
@@ -201,12 +218,13 @@ export function convertObject(input: any, config: Config) {
} else if (Array.isArray(input)) { } else if (Array.isArray(input)) {
return convertArray(input, config); return convertArray(input, config);
} else if (typeof input === 'object') { } else if (typeof input === 'object') {
const output: ObjectType = { type: 'object' }; const output: ObjectType = { type: 'object', properties: {} };
const outputObj: any = {}; const outputObj: Map<string, Output> = new Map();
for (const prop in input) { for (const prop in input) {
outputObj[prop] = convertObject(input[prop], config); // @ts-expect-error we are looping through self supplied object keys determined at runtime
outputObj.set(prop, convertObject(input[prop], config));
} }
output.properties = outputObj; output.properties = Object.fromEntries(outputObj.entries());
return output; return output;
} else if (typeof input === 'string') { } else if (typeof input === 'string') {
return convertString(input, config); return convertString(input, config);
@@ -229,3 +247,32 @@ export function convertJSONToOAS(input: string, config: Config) {
export function convertObjectToOAS(input: object, config: Config) { export function convertObjectToOAS(input: object, config: Config) {
return convertObject(input, config); return convertObject(input, config);
} }
const ignoredWords = [
'the',
'a',
'an',
'of',
'to',
'in',
'for',
'with',
'on',
'at',
'from',
'by',
'and'
];
// convert Get Server Preferences to getServerPreferences
export function convertSummaryToOperationId(summary: string) {
const firstChar = summary.slice(0, 1).toLowerCase();
const rest = summary
.split(' ')
.map((entry) => entry.slice(0, 1).toUpperCase() + entry.slice(1))
.filter((entry) => !ignoredWords.includes(entry.toLowerCase()))
.join('')
.slice(1);
return firstChar + rest;
}

512
src/lib/status.ts Normal file
View File

@@ -0,0 +1,512 @@
export type StatusCode = {
code: string;
phrase: string;
description: string;
spec_title: string;
spec_href: string;
};
export function sortByCode(a: StatusCode, b: StatusCode) {
if (Number(a.code[0]) !== Number(b.code[0])) {
return Number(a.code[0]) - Number(b.code[0]);
}
if (a.code[1] === 'x') {
return -1;
}
if (b.code[1] === 'x') {
return 1;
}
return Number(a.code) - Number(b.code);
}
export const status_codes = [
{
code: '1xx',
phrase: '**Informational**',
description:
'"indicates an interim response for communicating connection status or request progress prior to completing the requested action and sending a final response." ~ [sure](http://www.urbandictionary.com/define.php?term=sure)',
spec_title: 'RFC7231#6.2',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.2'
},
{
code: '100',
phrase: 'Continue',
description:
'"indicates that the initial part of a request has been received and has not yet been rejected by the server."',
spec_title: 'RFC7231#6.2.1',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.2.1'
},
{
code: '101',
phrase: 'Switching Protocols',
description:
'"indicates that the server understands and is willing to comply with the client\'s request, via the Upgrade header field, for a change in the application protocol being used on this connection."',
spec_title: 'RFC7231#6.2.2',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.2.2'
},
{
code: '2xx',
phrase: '**Successful**',
description:
'"indicates that the client\'s request was successfully received, understood, and accepted." ~ [cool](https://twitter.com/DanaDanger/status/183316183494311936)',
spec_title: 'RFC7231#6.3',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.3'
},
{
code: '200',
phrase: 'OK',
description: '"indicates that the request has succeeded."',
spec_title: 'RFC7231#6.3.1',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.3.1'
},
{
code: '201',
phrase: 'Created',
description:
'"indicates that the request has been fulfilled and has resulted in one or more new resources being created."',
spec_title: 'RFC7231#6.3.2',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.3.2'
},
{
code: '202',
phrase: 'Accepted',
description:
'"indicates that the request has been accepted for processing, but the processing has not been completed."',
spec_title: 'RFC7231#6.3.3',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.3.3'
},
{
code: '203',
phrase: 'Non-Authoritative Information',
description:
'"indicates that the request was successful but the enclosed payload has been modified from that of the origin server\'s 200 (OK) response by a transforming proxy."',
spec_title: 'RFC7231#6.3.4',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.3.4'
},
{
code: '204',
phrase: 'No Content',
description:
'"indicates that the server has successfully fulfilled the request and that there is no additional content to send in the response payload body."',
spec_title: 'RFC7231#6.3.5',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.3.5'
},
{
code: '205',
phrase: 'Reset Content',
description:
'"indicates that the server has fulfilled the request and desires that the user agent reset the "document view", which caused the request to be sent, to its original state as received from the origin server."',
spec_title: 'RFC7231#6.3.6',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.3.6'
},
{
code: '206',
phrase: 'Partial Content',
description:
'"indicates that the server is successfully fulfilling a range request for the target resource by transferring one or more parts of the selected representation that correspond to the satisfiable ranges found in the requests\'s Range header field."',
spec_title: 'RFC7233#4.1',
spec_href: 'https://tools.ietf.org/html/rfc7233#section-4.1'
},
{
code: '3xx',
phrase: '**Redirection**',
description:
'"indicates that further action needs to be taken by the user agent in order to fulfill the request." ~ [ask that dude over there](https://twitter.com/DanaDanger/status/183316183494311936)',
spec_title: 'RFC7231#6.4',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.4'
},
{
code: '300',
phrase: 'Multiple Choices',
description:
'"indicates that the target resource has more than one representation, each with its own more specific identifier, and information about the alternatives is being provided so that the user (or user agent) can select a preferred representation by redirecting its request to one or more of those identifiers."',
spec_title: 'RFC7231#6.4.1',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.4.1'
},
{
code: '301',
phrase: 'Moved Permanently',
description:
'"indicates that the target resource has been assigned a new permanent URI and any future references to this resource ought to use one of the enclosed URIs."',
spec_title: 'RFC7231#6.4.2',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.4.2'
},
{
code: '302',
phrase: 'Found',
description: '"indicates that the target resource resides temporarily under a different URI."',
spec_title: 'RFC7231#6.4.3',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.4.3'
},
{
code: '303',
phrase: 'See Other',
description:
'"indicates that the server is redirecting the user agent to a different resource, as indicated by a URI in the Location header field, that is intended to provide an indirect response to the original request."',
spec_title: 'RFC7231#6.4.4',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.4.4'
},
{
code: '304',
phrase: 'Not Modified',
description:
'"indicates that a conditional GET request has been received and would have resulted in a 200 (OK) response if it were not for the fact that the condition has evaluated to false."',
spec_title: 'RFC7232#4.1',
spec_href: 'https://tools.ietf.org/html/rfc7232#section-4.1'
},
{
code: '305',
phrase: 'Use Proxy',
description: '*deprecated*',
spec_title: 'RFC7231#6.4.5',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.4.5'
},
{
code: '307',
phrase: 'Temporary Redirect',
description:
'"indicates that the target resource resides temporarily under a different URI and the user agent MUST NOT change the request method if it performs an automatic redirection to that URI."',
spec_title: 'RFC7231#6.4.7',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.4.7'
},
{
code: '4xx',
phrase: '**Client Error**',
description:
'"indicates that the client seems to have erred." ~ [*you* fucked up](https://twitter.com/DanaDanger/status/183316183494311936)',
spec_title: 'RFC7231#6.5',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.5'
},
{
code: '400',
phrase: 'Bad Request',
description:
'"indicates that the server cannot or will not process the request because the received syntax is invalid, nonsensical, or exceeds some limitation on what the server is willing to process."',
spec_title: 'RFC7231#6.5.1',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.5.1'
},
{
code: '401',
phrase: 'Unauthorized',
description:
'"indicates that the request has not been applied because it lacks valid authentication credentials for the target resource."',
spec_title: 'RFC7235#6.3.1',
spec_href: 'https://tools.ietf.org/html/rfc7235#section-3.1'
},
{
code: '402',
phrase: 'Payment Required',
description: '*reserved*',
spec_title: 'RFC7231#6.5.2',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.5.2'
},
{
code: '403',
phrase: 'Forbidden',
description: '"indicates that the server understood the request but refuses to authorize it."',
spec_title: 'RFC7231#6.5.3',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.5.3'
},
{
code: '404',
phrase: 'Not Found',
description:
'"indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists."',
spec_title: 'RFC7231#6.5.4',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.5.4'
},
{
code: '405',
phrase: 'Method Not Allowed',
description:
'"indicates that the method specified in the request-line is known by the origin server but not supported by the target resource."',
spec_title: 'RFC7231#6.5.5',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.5.5'
},
{
code: '406',
phrase: 'Not Acceptable',
description:
'"indicates that the target resource does not have a current representation that would be acceptable to the user agent, according to the proactive negotiation header fields received in the request, and the server is unwilling to supply a default representation."',
spec_title: 'RFC7231#6.5.6',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.5.6'
},
{
code: '407',
phrase: 'Proxy Authentication Required',
description:
'"is similar to 401 (Unauthorized), but indicates that the client needs to authenticate itself in order to use a proxy."',
spec_title: 'RFC7235#3.2',
spec_href: 'https://tools.ietf.org/html/rfc7235#section-3.2'
},
{
code: '408',
phrase: 'Request Timeout',
description:
'"indicates that the server did not receive a complete request message within the time that it was prepared to wait."',
spec_title: 'RFC7231#6.5.7',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.5.7'
},
{
code: '409',
phrase: 'Conflict',
description:
'"indicates that the request could not be completed due to a conflict with the current state of the resource."',
spec_title: 'RFC7231#6.5.8',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.5.8'
},
{
code: '410',
phrase: 'Gone',
description:
'"indicates that access to the target resource is no longer available at the origin server and that this condition is likely to be permanent."',
spec_title: 'RFC7231#6.5.9',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.5.9'
},
{
code: '411',
phrase: 'Length Required',
description:
'"indicates that the server refuses to accept the request without a defined Content-Length."',
spec_title: 'RFC7231#6.5.10',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.5.10'
},
{
code: '412',
phrase: 'Precondition Failed',
description:
'"indicates that one or more preconditions given in the request header fields evaluated to false when tested on the server."',
spec_title: 'RFC7232#4.2',
spec_href: 'https://tools.ietf.org/html/rfc7232#section-4.2'
},
{
code: '413',
phrase: 'Payload Too Large',
description:
'"indicates that the server is refusing to process a request because the request payload is larger than the server is willing or able to process."',
spec_title: 'RFC7231#6.5.11',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.5.11'
},
{
code: '414',
phrase: 'URI Too Long',
description:
'"indicates that the server is refusing to service the request because the request-target is longer than the server is willing to interpret."',
spec_title: 'RFC7231#6.5.12',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.5.12'
},
{
code: '415',
phrase: 'Unsupported Media Type',
description:
'"indicates that the origin server is refusing to service the request because the payload is in a format not supported by the target resource for this method."',
spec_title: 'RFC7231#6.5.13',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.5.13'
},
{
code: '416',
phrase: 'Range Not Satisfiable',
description:
'"indicates that none of the ranges in the request\'s Range header field overlap the current extent of the selected resource or that the set of ranges requested has been rejected due to invalid ranges or an excessive request of small or overlapping ranges."',
spec_title: 'RFC7233#4.4',
spec_href: 'https://tools.ietf.org/html/rfc7233#section-4.4'
},
{
code: '417',
phrase: 'Expectation Failed',
description:
'"indicates that the expectation given in the request\'s Expect header field could not be met by at least one of the inbound servers."',
spec_title: 'RFC7231#6.5.14',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.5.14'
},
{
code: '418',
phrase: "I'm a teapot",
description:
'"Any attempt to brew coffee with a teapot should result in the error code 418 I\'m a teapot."',
spec_title: 'RFC2324#2.3.1',
spec_href: 'https://tools.ietf.org/html/rfc2324#section-2.3.1'
},
{
code: '426',
phrase: 'Upgrade Required',
description:
'"indicates that the server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol."',
spec_title: 'RFC7231#6.5.15',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.5.15'
},
{
code: '5xx',
phrase: '**Server Error**',
description:
'"indicates that the server is aware that it has erred or is incapable of performing the requested method." ~ [*we* fucked up](https://twitter.com/DanaDanger/status/183316183494311936)',
spec_title: 'RFC7231#6.6',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.6'
},
{
code: '500',
phrase: 'Internal Server Error',
description:
'"indicates that the server encountered an unexpected condition that prevented it from fulfilling the request."',
spec_title: 'RFC7231#6.6.1',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.6.1'
},
{
code: '501',
phrase: 'Not Implemented',
description:
'"indicates that the server does not support the functionality required to fulfill the request."',
spec_title: 'RFC7231#6.6.2',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.6.2'
},
{
code: '502',
phrase: 'Bad Gateway',
description:
'"indicates that the server, while acting as a gateway or proxy, received an invalid response from an inbound server it accessed while attempting to fulfill the request."',
spec_title: 'RFC7231#6.6.3',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.6.3'
},
{
code: '503',
phrase: 'Service Unavailable',
description:
'"indicates that the server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay."',
spec_title: 'RFC7231#6.6.4',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.6.4'
},
{
code: '504',
phrase: 'Gateway Time-out',
description:
'"indicates that the server, while acting as a gateway or proxy, did not receive a timely response from an upstream server it needed to access in order to complete the request."',
spec_title: 'RFC7231#6.6.5',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.6.5'
},
{
code: '505',
phrase: 'HTTP Version Not Supported',
description:
'"indicates that the server does not support, or refuses to support, the protocol version that was used in the request message."',
spec_title: 'RFC7231#6.6.6',
spec_href: 'https://tools.ietf.org/html/rfc7231#section-6.6.6'
},
{
code: '102',
phrase: 'Processing',
description:
'"is an interim response used to inform the client that the server has accepted the complete request, but has not yet completed it."',
spec_title: 'RFC5218#10.1',
spec_href: 'https://tools.ietf.org/html/rfc2518#section-10.1'
},
{
code: '207',
phrase: 'Multi-Status',
description: '"provides status for multiple independent operations."',
spec_title: 'RFC5218#10.2',
spec_href: 'https://tools.ietf.org/html/rfc2518#section-10.2'
},
{
code: '226',
phrase: 'IM Used',
description:
'"The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance."',
spec_title: 'RFC3229#10.4.1',
spec_href: 'https://tools.ietf.org/html/rfc3229#section-10.4.1'
},
{
code: '308',
phrase: 'Permanent Redirect',
description:
'"The target resource has been assigned a new permanent URI and any future references to this resource outght to use one of the enclosed URIs. [...] This status code is similar to 301 Moved Permanently (Section 7.3.2 of rfc7231), except that it does not allow rewriting the request method from POST to GET."',
spec_title: 'RFC7538',
spec_href: 'https://tools.ietf.org/html/rfc7538'
},
{
code: '422',
phrase: 'Unprocessable Entity',
description:
'"means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions."',
spec_title: 'RFC5218#10.3',
spec_href: 'https://tools.ietf.org/html/rfc2518#section-10.3'
},
{
code: '423',
phrase: 'Locked',
description: '"means the source or destination resource of a method is locked."',
spec_title: 'RFC5218#10.4',
spec_href: 'https://tools.ietf.org/html/rfc2518#section-10.4'
},
{
code: '424',
phrase: 'Failed Dependency',
description:
'"means that the method could not be performed on the resource because the requested action depended on another action and that action failed."',
spec_title: 'RFC5218#10.5',
spec_href: 'https://tools.ietf.org/html/rfc2518#section-10.5'
},
{
code: '428',
phrase: 'Precondition Required',
description: '"indicates that the origin server requires the request to be conditional."',
spec_title: 'RFC6585#3',
spec_href: 'https://tools.ietf.org/html/rfc6585#section-3'
},
{
code: '429',
phrase: 'Too Many Requests',
description:
'"indicates that the user has sent too many requests in a given amount of time ("rate limiting")."',
spec_title: 'RFC6585#4',
spec_href: 'https://tools.ietf.org/html/rfc6585#section-4'
},
{
code: '431',
phrase: 'Request Header Fields Too Large',
description:
'"indicates that the server is unwilling to process the request because its header fields are too large."',
spec_title: 'RFC6585#5',
spec_href: 'https://tools.ietf.org/html/rfc6585#section-5'
},
{
code: '451',
phrase: 'Unavailable For Legal Reasons',
description:
'"This status code indicates that the server is denying access to the resource in response to a legal demand."',
spec_title: 'draft-ietf-httpbis-legally-restricted-status',
spec_href: 'https://tools.ietf.org/html/draft-ietf-httpbis-legally-restricted-status'
},
{
code: '506',
phrase: 'Variant Also Negotiates',
description:
'"indicates that the server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process."',
spec_title: 'RFC2295#8.1',
spec_href: 'https://tools.ietf.org/html/rfc2295#section-8.1'
},
{
code: '507',
phrase: 'Insufficient Storage',
description:
'"means the method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request."',
spec_title: 'RFC5218#10.6',
spec_href: 'https://tools.ietf.org/html/rfc2518#section-10.6'
},
{
code: '511',
phrase: 'Network Authentication Required',
description: '"indicates that the client needs to authenticate to gain network access."',
spec_title: 'RFC6585#6',
spec_href: 'https://tools.ietf.org/html/rfc6585#section-6'
},
{
code: '7xx',
phrase: '**Developer Error**',
description: '[err](http://www.urbandictionary.com/define.php?term=err)',
spec_title: '7xx-rfc',
spec_href: 'http://documentup.com/joho/7XX-rfc'
}
];

View File

@@ -1,6 +1,5 @@
import type { Writable } from 'svelte/store'; import { writable, type Writable } from 'svelte/store';
import type { Config } from './converter'; import type { Config } from './converter';
import { localStorageStore } from '@skeletonlabs/skeleton';
const localConfig: Config = { const localConfig: Config = {
allowIntegers: true, allowIntegers: true,
@@ -9,5 +8,5 @@ const localConfig: Config = {
allowOneOf: false allowOneOf: false
}; };
export const config: Writable<Config> = localStorageStore('config', localConfig); export const config: Writable<Config> = writable(localConfig);
export const yamlOut: Writable<boolean> = localStorageStore('yaml', true); export const yamlOut: Writable<boolean> = writable(true);

View File

@@ -1,7 +1,24 @@
<script lang="ts"> <script lang="ts">
import { config, yamlOut } from '$lib/store'; import { arrow, autoUpdate, computePosition, flip, offset, shift } from '@floating-ui/dom';
import { AppBar, AppShell, RadioGroup, RadioItem } from '@skeletonlabs/skeleton'; import { AppBar, AppShell, storeHighlightJs } from '@skeletonlabs/skeleton';
import { storePopup } from '@skeletonlabs/skeleton';
storePopup.set({ computePosition, autoUpdate, offset, shift, flip, arrow });
import 'highlight.js/styles/github-dark.css';
import '../app.postcss'; import '../app.postcss';
import hljs from 'highlight.js/lib/core';
// Import each language module you require
import json from 'highlight.js/lib/languages/json';
import yaml from 'highlight.js/lib/languages/yaml';
// Register each imported language module
hljs.registerLanguage('yaml', yaml);
hljs.registerLanguage('json', json);
storeHighlightJs.set(hljs);
</script> </script>
<!-- App Shell --> <!-- App Shell -->
@@ -13,58 +30,6 @@
<strong class="text-xl">OpenAPI Definition Generator</strong> <strong class="text-xl">OpenAPI Definition Generator</strong>
</svelte:fragment> </svelte:fragment>
<div class="flex flex-row flex-wrap justify-center gap-8">
<label class="label text-sm">
Convert null values to
<select bind:value={$config.nullType} class="select" id="nullType">
<option value="string" selected>String</option>
<option value="number">Number</option>
<option value="integer">Integer</option>
<option value="boolean">Boolean</option>
</select>
</label>
<div class="flex flex-col justify-center text-sm">
<RadioGroup>
<RadioItem padding="px-2" bind:group={$yamlOut} name="justify" value={true}>
YAML
</RadioItem>
<RadioItem padding="px-2" bind:group={$yamlOut} name="justify" value={false}>
JSON
</RadioItem>
</RadioGroup>
</div>
<div class="flex flex-row justify-center gap-6">
<label class="flex items-center space-x-2 text-sm">
<input
bind:checked={$config.includeExamples}
class="checkbox"
type="checkbox"
id="requestExamples"
/>
<p>Add values as examples</p>
</label>
<label class="flex items-center space-x-2 text-sm">
<input
bind:checked={$config.allowIntegers}
class="checkbox"
type="checkbox"
id="allowInts"
/>
<p>Allow integer types</p>
</label>
<label class="flex items-center space-x-2 text-sm">
<input
bind:checked={$config.allowOneOf}
class="checkbox"
type="checkbox"
id="allowOneOf"
/>
<p>Allow array oneOf</p>
</label>
</div>
</div>
<svelte:fragment slot="trail"> <svelte:fragment slot="trail">
<div class="flex flex-row flex-wrap justify-between gap-4"> <div class="flex flex-row flex-wrap justify-between gap-4">
<a <a

View File

@@ -1,82 +1,216 @@
<script lang="ts"> <script lang="ts">
import { example, convertObjectToOAS, type Config } from '$lib/converter'; import {
import { clipboard } from '@skeletonlabs/skeleton'; convertObjectToOAS,
import { onMount } from 'svelte'; example,
import { stringify } from 'yaml'; type Config,
import { JSONEditor } from 'svelte-jsoneditor'; convertSummaryToOperationId
} from '$lib/converter';
import { sortByCode, status_codes } from '$lib/status';
import { config, yamlOut } from '$lib/store'; import { config, yamlOut } from '$lib/store';
import { CodeBlock, InputChip, RadioGroup, RadioItem } from '@skeletonlabs/skeleton';
import { JSONEditor, isJSONContent, isTextContent, type Content } from 'svelte-jsoneditor';
import { writable, type Writable } from 'svelte/store';
import { stringify } from 'yaml';
const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'];
let content: { text?: string; json?: object } = {
text: undefined, // can be used to pass a stringified JSON document instead
json: example
};
let outSwagger: string = ''; let outSwagger: string = '';
let path: string = '';
let method: string = methods[0];
let summary: string = '';
let description: string = '';
let status: string = '200';
let tags: string[] = ['things'];
onMount(() => { const content: Writable<Content> = writable({
let tempJSON = localStorage.getItem('inputJSON'); json: example
if (tempJSON !== null && tempJSON !== '') {
content.json = JSON.parse(tempJSON);
} else {
content.json = example;
}
}); });
function format(value: object, yamlOut: boolean) { function format(value: object, yamlOut: boolean) {
if (yamlOut) { if (yamlOut) {
return stringify(value, { aliasDuplicateObjects: false }); return stringify(value, { aliasDuplicateObjects: false });
} else { } else {
return JSON.stringify(value, null, '\t'); return JSON.stringify(value, null, 4);
} }
} }
function run( function run(
content: { text?: string; json?: object | undefined }, content: Content,
config: Config, config: Config,
yamlOut: boolean yamlOut: boolean,
method: string,
status: string,
path: string,
summary: string,
description: string,
tags: string[]
) { ) {
if (content.json !== undefined && content.text !== undefined) return; console.log(content, yamlOut);
let data;
if (content.text !== undefined) { let outJsonContent = {};
data = JSON.parse(content.text);
} else if (content.json !== undefined) { if (isTextContent(content) && content.text) {
data = content.json; outJsonContent = convertObjectToOAS(JSON.parse(content.text), config);
} else if (isJSONContent(content) && content.json) {
outJsonContent = convertObjectToOAS(content.json, config);
} }
outSwagger = format(convertObjectToOAS(data, config), yamlOut); outSwagger = format(
{
[path]: {
[method.toLowerCase()]: {
tags,
summary,
description,
operationId: convertSummaryToOperationId(summary),
responses: { [status]: { content: { 'application/json': { schema: outJsonContent } } } }
}
}
},
yamlOut
);
} }
$: run(content, $config, $yamlOut); $: run($content, $config, $yamlOut, method, status, path, summary, description, tags);
</script> </script>
<div class="flex flex-row justify-between px-2 gap-2 overflow-hidden"> <div class="flex flex-row p-1 gap-1">
<div class="grow max-w-[50%]"> <div class="grow max-w-[50%]">
<p class="text-center py-2"> <div class="card overflow-hidden">
Input all of your JSON formatted Data, Typically API response bodies <p class="text-center pt-2">Input you API call details here</p>
</p> <div class="flex flex-row gap-4 justify-center py-6">
<div class="card my-json-editor jse-theme-dark overflow-hidden h-[85vh]"> <div class="flex flex-col gap-2 max-w-md text-sm">
<JSONEditor onChange={() => run(content, $config, $yamlOut)} bind:content /> <label class="label flex flex-col">
<span>Path</span>
<input
type="text"
class="input px-3 py-1 min-w-0"
placeholder={`/get/the/thing`}
bind:value={path}
/>
</label>
<label class="label flex flex-col">
<span>Summary</span>
<input
type="text"
class="input px-3 py-1"
placeholder={`Get a thing`}
bind:value={summary}
/>
</label>
<label class="label flex flex-col">
<span>Description</span>
<textarea
class="textarea px-2 py-1 h-[92px]"
placeholder="This endpoint gets a thing"
bind:value={description}
/>
</label>
<label class="label flex flex-col">
<span>Status Code</span>
<select class="select" bind:value={status}>
{#each status_codes.sort(sortByCode) as code}
<option value={code.code}>
{code.code} - {code.description
.replaceAll(`"`, ``)
.slice(0, code.description.indexOf('~'))
.replaceAll(`~`, ``)
.trim()}
</option>
{/each}
</select>
</label>
</div>
<div class="flex flex-col flex-wrap justify-center gap-3 text-sm">
<InputChip
class="h-[92px] w-[214px] overflow-auto"
bind:value={tags}
name="tags"
placeholder="Enter the operations tags..."
/>
<div class="flex flex-col justify-center">
<label class="label flex flex-col">
<span>Convert null values to</span>
<select bind:value={$config.nullType} class="select p-1" id="nullType">
<option value="string" selected>String</option>
<option value="number">Number</option>
<option value="integer">Integer</option>
<option value="boolean">Boolean</option>
</select>
</label>
</div>
<div class="flex flex-col justify-center">
<label for="output-format" class="label flex flex-col">
<span class="text-center">Output format</span>
<RadioGroup>
<RadioItem padding="px-2" bind:group={$yamlOut} name="justify" value={true}>
YAML
</RadioItem>
<RadioItem padding="px-2" bind:group={$yamlOut} name="justify" value={false}>
JSON
</RadioItem>
</RadioGroup>
</label>
</div>
<div class="flex flex-col justify-center gap-1 py-1">
<label class="flex items-center space-x-2">
<input
bind:checked={$config.includeExamples}
class="checkbox"
type="checkbox"
id="requestExamples"
/>
<span>Add values as examples</span>
</label>
<label class="flex items-center space-x-2">
<input
bind:checked={$config.allowIntegers}
class="checkbox"
type="checkbox"
id="allowInts"
/>
<span>Allow integer types</span>
</label>
<label class="flex items-center space-x-2">
<input
bind:checked={$config.allowOneOf}
class="checkbox"
type="checkbox"
id="allowOneOf"
/>
<span>Allow array oneOf</span>
</label>
</div>
</div>
</div>
<div class="jse-theme-dark h-[500px]">
<JSONEditor
onChange={() =>
run($content, $config, $yamlOut, method, status, path, summary, description, tags)}
bind:content={$content}
/>
</div>
</div> </div>
</div> </div>
<div class="grow max-w-[50%]"> <div class="grow max-w-[50%]">
<p class="text-center py-2"> <div class="card">
And here is that JSON Response formatted as a {$yamlOut === true ? 'YAML' : 'JSON'} OpenAPI Specification <p class="text-center p-2">
</p> And here is that JSON Response formatted as a {$yamlOut === true ? 'YAML' : 'JSON'} OpenAPI Specification
<div class="card relative h-[85vh]"> </p>
<textarea <div class="">
readonly <CodeBlock lineNumbers code={outSwagger} language={$yamlOut === true ? 'YAML' : 'JSON'} />
id="Swagger" </div>
class="textarea p-4 h-full"
placeholder="Here is your Swagger"
bind:value={outSwagger}
/>
<button class="btn variant-filled-primary absolute top-4 right-4" use:clipboard={outSwagger}>
Copy
</button>
</div> </div>
</div> </div>
</div> </div>
<style> <style>
/* load one or multiple themes */ /* load one or multiple themes */
@import 'svelte-jsoneditor/themes/jse-theme-dark.css'; @import 'svelte-jsoneditor/themes/jse-theme-dark.css';
</style> </style>

View File

@@ -1,6 +1,23 @@
import { sentrySvelteKit } from '@sentry/sveltekit';
import { sveltekit } from '@sveltejs/kit/vite'; import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite'; import { defineConfig } from 'vite';
import { purgeCss } from 'vite-plugin-tailwind-purgecss';
export default defineConfig({ export default defineConfig({
plugins: [sveltekit()] plugins: [
sentrySvelteKit({
sourceMapsUploadOptions: {
org: 'sentry',
project: 'oas-def-gen',
url: 'https://sentry.plygrnd.org/'
}
}),
sveltekit(),
purgeCss({
safelist: {
// any selectors that begin with "hljs-" will not be purged
greedy: [/^hljs-/]
}
})
]
}); });

756
yarn.lock

File diff suppressed because it is too large Load Diff