Skip to content

Commit

Permalink
refactor: exports extras and missed things (#635)
Browse files Browse the repository at this point in the history
  • Loading branch information
magicmatatjahu authored Oct 4, 2022
1 parent add289e commit 73bd4fb
Show file tree
Hide file tree
Showing 8 changed files with 65 additions and 14 deletions.
7 changes: 4 additions & 3 deletions src/from.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { readFile } from 'fs/promises';
import { readFile } from 'fs';
import { promisify } from 'util';

import type { RequestInit } from 'node-fetch';
import type { Parser } from './parser';
Expand Down Expand Up @@ -29,9 +30,9 @@ export function fromURL(parser: Parser, source: string, options?: RequestInit):
};
}

export function fromFile(parser: Parser, source: string, options?: Parameters<typeof readFile>[1]): FromResult {
export function fromFile(parser: Parser, source: string, options?: Parameters<typeof readFile.__promisify__>[1]): FromResult {
async function readFileFn(): Promise<Input> {
return (await readFile(source, options)).toString();
return (await promisify(readFile)(source, options)).toString();
}

return {
Expand Down
7 changes: 5 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import { DiagnosticSeverity } from '@stoplight/types';

import { Parser } from './parser';

export * from './models';

export { Parser };
export { stringify, unstringify } from './stringify';
export { fromURL, fromFile } from './from';
export { createAsyncAPIDocument, toAsyncAPIDocument, isAsyncAPIDocument } from './document';

export { AsyncAPIDocument as OldAsyncAPIDocument } from './old-api/asyncapi';
export { convertToOldAPI } from './old-api/converter';
export * from './old-api';

export { DiagnosticSeverity };
export type { AsyncAPISemver, Input, Diagnostic, SchemaValidateResult } from './types';
export type { ValidateOptions, ValidateOutput } from './validate';
export type { ParseOptions, ParseOutput } from './parse';
Expand Down
22 changes: 22 additions & 0 deletions src/old-api/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
export { convertToOldAPI } from './converter';

export { AsyncAPIDocument as OldAsyncAPIDocument } from './asyncapi';
export { Base as OldBase } from './base';
export { ChannelParameter as OldChannelParameter } from './channel-parameter';
export { Channel as OldChannel } from './channel';
export { Components as OldComponents } from './components';
export { Contact as OldContact } from './contact';
export { CorrelationId as OldCorrelationId } from './correlation-id';
export { ExternalDocs as OldExternalDocs } from './external-docs';
export { License as OldLicense } from './license';
export { MessageTrait as OldMessageTrait } from './message-trait';
export { Message as OldMessage } from './message';
export { OAuthFlow as OldOAuthFlow } from './oauth-flow';
export { OperationTrait as OldOperationTrait } from './operation-trait';
export { Operation as OldOperation } from './operation';
export { Schema as OldSchema } from './schema';
export { SecurityRequirement as OldSecurityRequirement } from './security-requirement';
export { SecurityScheme as OldSecurityScheme } from './security-scheme';
export { ServerVariable as OldServerVariable } from './server-variable';
export { Server as OldServer } from './server';
export { Tag as OldTag } from './tag';
11 changes: 8 additions & 3 deletions src/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,17 @@ import { createDetailedAsyncAPI, mergePatch, setExtension } from './utils';

import { xParserSpecParsed } from './constants';

import type { Spectral } from '@stoplight/spectral-core';
import type { Spectral, Document } from '@stoplight/spectral-core';
import type { Parser } from './parser';
import type { ValidateOptions } from './validate';
import type { Input, Diagnostic } from './types';

export interface ParseOutput {
document: AsyncAPIDocumentInterface | undefined;
diagnostics: Diagnostic[];
diagnostics: Diagnostic[];
extras?: {
document: Document;
}
}

export interface ParseOptions {
Expand All @@ -33,11 +36,12 @@ const defaultOptions: ParseOptions = {

export async function parse(parser: Parser, spectral: Spectral, asyncapi: Input, options: ParseOptions = {}): Promise<ParseOutput> {
options = mergePatch<ParseOptions>(defaultOptions, options);
const { validated, diagnostics } = await validate(spectral, asyncapi, { ...options.validateOptions, source: options.source });
const { validated, diagnostics, extras } = await validate(spectral, asyncapi, { ...options.validateOptions, source: options.source });
if (validated === undefined) {
return {
document: undefined,
diagnostics,
extras: undefined
};
}

Expand All @@ -52,5 +56,6 @@ export async function parse(parser: Parser, spectral: Spectral, asyncapi: Input,
return {
document,
diagnostics,
extras,
};
}
4 changes: 0 additions & 4 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,6 @@ export function normalizeInput(asyncapi: string | MaybeAsyncAPI): string {
return JSON.stringify(asyncapi, undefined, 2);
}

export function unfreezeObject(data: unknown) {
return JSON.parse(JSON.stringify(data));
}

export function hasErrorDiagnostic(diagnostics: ISpectralDiagnostic[]): boolean {
return diagnostics.some(diagnostic => diagnostic.severity === DiagnosticSeverity.Error);
}
Expand Down
9 changes: 7 additions & 2 deletions src/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type { Input, Diagnostic } from './types';
export interface ValidateOptions extends IRunOpts {
source?: string;
allowedSeverity?: {
error?: boolean;
warning?: boolean;
info?: boolean;
hint?: boolean;
Expand All @@ -18,10 +19,14 @@ export interface ValidateOptions extends IRunOpts {
export interface ValidateOutput {
validated: unknown;
diagnostics: Diagnostic[];
extras: {
document: Document,
}
}

const defaultOptions: ValidateOptions = {
allowedSeverity: {
error: false,
warning: true,
info: true,
hint: true,
Expand All @@ -37,13 +42,13 @@ export async function validate(spectral: Spectral, asyncapi: Input, options: Val
let { resolved: validated, results } = await spectral.runWithResolved(document);

if (
hasErrorDiagnostic(results) ||
(!allowedSeverity?.error && hasErrorDiagnostic(results)) ||
(!allowedSeverity?.warning && hasWarningDiagnostic(results)) ||
(!allowedSeverity?.info && hasInfoDiagnostic(results)) ||
(!allowedSeverity?.hint && hasHintDiagnostic(results))
) {
validated = undefined;
}

return { validated, diagnostics: results };
return { validated, diagnostics: results, extras: { document: document as Document } };
}
18 changes: 18 additions & 0 deletions test/parse.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { Document } from '@stoplight/spectral-core';

import { AsyncAPIDocumentV2 } from '../src/models';
import { Parser } from '../src/parser';

Expand Down Expand Up @@ -33,6 +35,22 @@ describe('parse()', function() {
expect(diagnostics.length > 0).toEqual(true);
});

it('should return extras', async function() {
const documentRaw = {
asyncapi: '2.0.0',
info: {
title: 'Valid AsyncApi document',
version: '1.0',
},
channels: {}
};
const { document, diagnostics, extras } = await parser.parse(documentRaw);

expect(document).toBeInstanceOf(AsyncAPIDocumentV2);
expect(extras?.document).toBeInstanceOf(Document);
expect(diagnostics.length > 0).toEqual(true);
});

it('should preserve references', async function() {
const documentRaw = {
asyncapi: '2.0.0',
Expand Down
1 change: 1 addition & 0 deletions webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ module.exports = {
fallback: {
fs: false,
path: false,
util: false,
buffer: require.resolve('buffer/'),
}
},
Expand Down

0 comments on commit 73bd4fb

Please sign in to comment.