chore: prettier all

This commit is contained in:
Roman Hotsiy
2020-07-06 23:31:28 +03:00
parent 779afde99b
commit a4090f534a
30 changed files with 95 additions and 78 deletions

View File

@@ -1,9 +1,8 @@
import { readdirSync, statSync, existsSync } from 'fs';
import { spawnSync } from 'child_process';
import {join} from 'path';
import { join } from 'path';
import { toMatchSpecificSnapshot, addSerializer } from './specific-snapshot';
expect.extend({
toMatchExtendedSpecificSnapshot(received, snapshotFile) {
return toMatchSpecificSnapshot.call(this, received + 1, snapshotFile);
@@ -27,19 +26,19 @@ describe('E2E', () => {
cwd: testPath,
env: {
...process.env,
'NODE_ENV': 'test',
'NO_COLOR': 'TRUE',
}
NODE_ENV: 'test',
NO_COLOR: 'TRUE',
},
});
const out = r.stdout.toString('utf-8');
const err = r.stderr.toString('utf-8')
const err = r.stderr.toString('utf-8');
const result = `${out}\n${err}`
const result = `${out}\n${err}`;
it(file, () => {
// we need this cause TS types not actually allows to 'extend'
(expect(result) as any).toMatchSpecificSnapshot(join(testPath, 'snapshot.js'));
})
});
}
});

View File

@@ -1,7 +1,6 @@
const { SnapshotState, toMatchSnapshot, addSerializer } = require('jest-snapshot');
const path = require('path');
const snapshotsStateMap = new Map();
let commonSnapshotState;
@@ -28,7 +27,6 @@ function toMatchSpecificSnapshot(received, snapshotFile, ...rest) {
expect.extend({ toMatchSpecificSnapshot });
function getAbsolutePathToSnapshot(testPath, snapshotFile) {
return path.isAbsolute(snapshotFile)
? snapshotFile
@@ -36,7 +34,7 @@ function getAbsolutePathToSnapshot(testPath, snapshotFile) {
}
afterAll(() => {
snapshotsStateMap.forEach(snapshotState => {
snapshotsStateMap.forEach((snapshotState) => {
const uncheckedCount = snapshotState.getUncheckedCount();
if (uncheckedCount) {

View File

@@ -41,7 +41,7 @@ export const decorators = {
'inject-x-stats': () => {
return {
Info(info) {
info['x-stats'] = {test: 1}
info['x-stats'] = { test: 1 };
},
};
},

View File

@@ -29,7 +29,7 @@ export function replaceSourceWithRef(results: NormalizedReportMessage[], cwd?: s
...mapped.from,
source: cwd
? path.relative(cwd, mapped.from.source.absoluteRef)
: mapped.from.source.absoluteRef as any,
: (mapped.from.source.absoluteRef as any),
};
}
return mapped;

View File

@@ -99,7 +99,10 @@ yargs // eslint-disable-line
});
}
const elapsed = process.env.NODE_ENV === 'test' ? '<test>ms': `in ${Math.ceil(performance.now() - startedAt)}ms`;
const elapsed =
process.env.NODE_ENV === 'test'
? '<test>ms'
: `in ${Math.ceil(performance.now() - startedAt)}ms`;
process.stderr.write(gray(`${entryPoint}: validated in ${elapsed}\n\n`));
} catch (e) {
totals.errors++;
@@ -421,7 +424,10 @@ function pluralize(label: string, num: number) {
return num === 1 ? `${label}` : `${label}s`;
}
export function getFallbackEntryPointsOrExit(argsEntrypoints: string[] | undefined, config: Config) {
export function getFallbackEntryPointsOrExit(
argsEntrypoints: string[] | undefined,
config: Config,
) {
let res = argsEntrypoints;
if (
(!argsEntrypoints || !argsEntrypoints.length) &&
@@ -445,15 +451,17 @@ function printUnusedWarnings(config: LintConfig) {
const { preprocessors, rules, decorators } = config.getUnusedRules();
if (rules.length) {
process.stderr.write(
yellow(`[WARNING] Unused rules found in ${blue(config.configFile || '')}: ${rules.join(', ')}.\n`),
yellow(
`[WARNING] Unused rules found in ${blue(config.configFile || '')}: ${rules.join(', ')}.\n`,
),
);
}
if (preprocessors.length) {
process.stderr.write(
yellow(
`[WARNING] Unused preprocessors found in ${blue(config.configFile || '')}: ${preprocessors.join(
', ',
)}.\n`,
`[WARNING] Unused preprocessors found in ${blue(
config.configFile || '',
)}: ${preprocessors.join(', ')}.\n`,
),
);
}

View File

@@ -7,7 +7,7 @@ import { getFallbackEntryPointsOrExit, getTotals } from '../cli';
import startPreviewServer from './preview-server/preview-server';
export async function previewDocs(argv: {
port: number,
port: number;
useCommunityEdition?: boolean;
config?: string;
entrypoint: string;
@@ -48,7 +48,7 @@ export async function previewDocs(argv: {
process.stdout.write(
fileTotals.errors === 0
? `Created a bundle for ${entrypoint} ${
fileTotals.warnings > 0 ? 'with warnings' : 'successfully'
fileTotals.warnings > 0 ? 'with warnings' : 'successfully'
}\n`
: colorette.yellow(
`Created a bundle for ${entrypoint} with errors. Docs may be broken or not accurate\n`,

View File

@@ -40,4 +40,4 @@
socket.destroy();
});
}
}());
})();

View File

@@ -87,7 +87,7 @@ export default async function startPreviewServer(
}[request.url || ''] ||
path.resolve(htmlTemplate ? path.dirname(htmlTemplate) : process.cwd(), `.${request.url}`);
const extname = String(path.extname(filePath)).toLowerCase() as keyof (typeof mimeTypes);
const extname = String(path.extname(filePath)).toLowerCase() as keyof typeof mimeTypes;
const contentType = mimeTypes[extname] || 'application/octet-stream';
try {

View File

@@ -31,7 +31,7 @@ export function respondWithGzip(
code = 200,
) {
let compressedStream;
const acceptEncoding = request.headers['accept-encoding'] as string || '';
const acceptEncoding = (request.headers['accept-encoding'] as string) || '';
if (acceptEncoding.match(/\bdeflate\b/)) {
response.writeHead(code, { ...headers, 'content-encoding': 'deflate' });
compressedStream = zlib.createDeflate();

View File

@@ -43,5 +43,5 @@ export default {
'no-example-value-and-externalValue': 'error',
'no-unused-components': 'error',
'no-undefined-server-variable': 'error',
}
},
} as LintRawConfig;

View File

@@ -380,7 +380,7 @@ export class Config {
this.resolve = {
http: {
headers: rawConfig?.resolve?.http?.headers ?? [],
customFetch: undefined
customFetch: undefined,
},
};
}

View File

@@ -46,5 +46,5 @@ export default {
'no-example-value-and-externalValue': 'error',
'no-unused-components': 'warn',
'no-undefined-server-variable': 'warn',
}
},
} as LintRawConfig;

View File

@@ -1,5 +1,14 @@
import * as path from 'path';
import { options as colorOptions, gray, blue, bgRed, bgYellow, black, yellow, red } from 'colorette';
import {
options as colorOptions,
gray,
blue,
bgRed,
bgYellow,
black,
yellow,
red,
} from 'colorette';
import {
NormalizedReportMessage,

View File

@@ -1,4 +1,4 @@
export type { Oas3Rule, OasRule, Oas3Preprocessor, OasPreprocessor} from './visitors';
export type { Oas3Rule, OasRule, Oas3Preprocessor, OasPreprocessor } from './visitors';
export type { NodeType } from './types/index';
export type {
Config,

View File

@@ -24,11 +24,11 @@ export class Location {
}
key() {
return { ...this, reportOnKey: true }
return { ...this, reportOnKey: true };
}
get absolutePointer() {
return this.source.absoluteRef + (this.pointer === '#/' ? '' : this.pointer)
return this.source.absoluteRef + (this.pointer === '#/' ? '' : this.pointer);
}
}
@@ -45,7 +45,7 @@ export function parseRef(ref: string): { uri: string | null; pointer: string[] }
const [uri, pointer] = ref.split('#/');
return {
uri: uri || null,
pointer: pointer ? pointer.split('/').map(escapePointer).filter(Boolean) : []
pointer: pointer ? pointer.split('/').map(escapePointer).filter(Boolean) : [],
};
}
@@ -67,11 +67,13 @@ export function isAbsoluteUrl(ref: string) {
return ref.startsWith('http://') || ref.startsWith('https://');
}
export function isMappingRef(mapping: string ) {
export function isMappingRef(mapping: string) {
// TODO: proper detection of mapping refs
return mapping.startsWith('#') ||
mapping.startsWith('https://') ||
mapping.startsWith('./') ||
mapping.startsWith('../') ||
mapping.indexOf('/') > -1
return (
mapping.startsWith('#') ||
mapping.startsWith('https://') ||
mapping.startsWith('./') ||
mapping.startsWith('../') ||
mapping.indexOf('/') > -1
);
}

View File

@@ -24,7 +24,7 @@ function getAjv(resolve: ResolveFn<any>, disallowAdditionalProperties: boolean)
validateSchema: false,
defaultAdditionalProperties: !disallowAdditionalProperties,
loadSchemaSync(base: string, $ref: string, id: string) {
const resolvedRef = resolve({$ref}, base.replace(/#$/, ''));
const resolvedRef = resolve({ $ref }, base.replace(/#$/, ''));
if (!resolvedRef || !resolvedRef.location) return undefined;
return { id, ...resolvedRef.node };
},

View File

@@ -1,7 +1,7 @@
import { Oas3Rule, Oas2Rule } from '../../visitors';
import { missingRequiredField } from '../utils';
export const InfoContact: (Oas3Rule | Oas2Rule) = () => {
export const InfoContact: Oas3Rule | Oas2Rule = () => {
return {
Info(info, { report, location }) {
if (!info.contact) {

View File

@@ -1,7 +1,7 @@
import { Oas3Rule, Oas2Rule } from '../../visitors';
import { validateDefinedAndNonEmpty } from '../utils';
export const InfoDescription: (Oas3Rule | Oas2Rule) = () => {
export const InfoDescription: Oas3Rule | Oas2Rule = () => {
return {
Info(info, ctx) {
validateDefinedAndNonEmpty('description', info, ctx);

View File

@@ -4,7 +4,7 @@ import { Oas2Schema } from '../../typings/swagger';
import { Oas3Schema } from '../../typings/openapi';
import { UserContext } from '../../walk';
export const NoEnumTypeMismatch: (Oas3Rule | Oas2Rule) = () => {
export const NoEnumTypeMismatch: Oas3Rule | Oas2Rule = () => {
return {
Schema(schema: Oas2Schema | Oas3Schema, { report, location }: UserContext) {
if (schema.enum && schema.type) {

View File

@@ -62,7 +62,7 @@ export const OasSpec: Oas3Rule | Oas2Rule = () => {
}
if (propSchema.referenceable && isRef(propValue)) {
propValue = resolve(propValue).node
propValue = resolve(propValue).node;
}
if (propSchema.enum) {

View File

@@ -9,11 +9,11 @@ export const NoUnresolvedRefs: Oas3Rule = () => {
leave(_, { report, location }, resolved) {
if (resolved.node !== undefined) return;
reportUnresolvedRef(resolved, report, location);
}
},
},
DiscriminatorMapping(mapping, { report, resolve, location }) {
for (const mappingName of Object.keys(mapping)) {
const resolved = resolve({ $ref: mapping[mappingName] } );
const resolved = resolve({ $ref: mapping[mappingName] });
if (resolved.node !== undefined) return;
console.log(mapping[mappingName], location.absolutePointer);

View File

@@ -1,5 +1,5 @@
import { outdent } from "outdent";
import { validateDoc } from "./utils";
import { outdent } from 'outdent';
import { validateDoc } from './utils';
describe('OpenAPI Schema 2.0', () => {
it('should not report of a valid GET operation object', async () => {

View File

@@ -1,5 +1,5 @@
import { outdent } from "outdent";
import { validateDoc } from "./utils";
import { outdent } from 'outdent';
import { validateDoc } from './utils';
it('should not report if summary field is valid', async () => {
const source = outdent`

View File

@@ -1,10 +1,10 @@
import { outdent } from "outdent";
import { outdent } from 'outdent';
import { parseYamlToDocument, replaceSourceWithRef } from "../../../../__tests__/utils";
import { parseYamlToDocument, replaceSourceWithRef } from '../../../../__tests__/utils';
import { validateDocument } from "../../../../validate";
import { LintConfig } from "../../../..";
import { BaseResolver } from "../../../../resolve";
import { validateDocument } from '../../../../validate';
import { LintConfig } from '../../../..';
import { BaseResolver } from '../../../../resolve';
describe('Referenceable scalars', () => {
it('should not report $ref description', async () => {
@@ -18,7 +18,7 @@ describe('Referenceable scalars', () => {
$ref: fixtures/description.md
paths: {}
`,
__dirname+ '/foobar.yaml',
__dirname + '/foobar.yaml',
);
const results = await validateDocument({
@@ -27,7 +27,7 @@ describe('Referenceable scalars', () => {
config: new LintConfig({
extends: [],
rules: {
'spec': 'error',
spec: 'error',
},
}),
});

View File

@@ -35,7 +35,7 @@ export const ValidContentExamples: Oas3Rule = (opts) => {
location.child('schema'),
dataLoc.pointer,
resolve,
disallowAdditionalProperties
disallowAdditionalProperties,
);
if (!valid) {
for (let error of errors) {

View File

@@ -3,15 +3,15 @@ import { Oas3Rule } from '../../visitors';
export const NoUndefinedServerVariable: Oas3Rule = () => {
return {
Server(server, { report, location }) {
const urlVariables = server.url.match(/{[^}]+}/g)?.map(e => e.slice(1, e.length - 1)) || [];
const definedVariables = server?.variables && Object.keys(server.variables) || [];
const urlVariables = server.url.match(/{[^}]+}/g)?.map((e) => e.slice(1, e.length - 1)) || [];
const definedVariables = (server?.variables && Object.keys(server.variables)) || [];
for (const serverVar of urlVariables) {
if (!definedVariables.includes(serverVar)) {
report({
message: `The \`${serverVar}\` variable is not defined in the \`variables\` objects.`,
location: location.child(['url'])
})
location: location.child(['url']),
});
}
}
@@ -21,9 +21,9 @@ export const NoUndefinedServerVariable: Oas3Rule = () => {
message: `The \`${definedServerVar}\` variable is not used in the server's \`url\` field.`,
location: location.child(['variables', definedServerVar]).key(),
from: location.child('url'),
})
});
}
}
}
},
};
};

View File

@@ -109,14 +109,13 @@ export function normalizeTypes(
return {
...type,
directResolveAs: resolveType(type.directResolveAs),
}
};
} else {
return type;
}
}
}
export function isNamedType(
t: NormalizedNodeType | NormalizedScalarSchema | null | undefined,
): t is NormalizedNodeType {

View File

@@ -178,7 +178,6 @@ export interface Oas2Responses {
[code: string]: Oas2Response;
}
export type Oas2Header = Oas2Items & { description?: 'string' };
export interface Oas2Response {

View File

@@ -45,7 +45,6 @@ import {
Oas2SecurityScheme,
} from './typings/swagger';
import { NormalizedNodeType } from './types';
import { Stack } from './utils';
import { UserContext, ResolveResult, MessageSeverity } from './walk';

View File

@@ -228,7 +228,7 @@ export function walkDocument<T>(opts: {
// visit in order from type-tree first
const props = Object.keys(type.properties);
if (type.additionalProperties) {
props.push(...Object.keys(resolvedNode).filter(k => !props.includes(k)));
props.push(...Object.keys(resolvedNode).filter((k) => !props.includes(k)));
}
for (const propName of props) {
let value = resolvedNode[propName];
@@ -251,7 +251,6 @@ export function walkDocument<T>(opts: {
walkNode(value, propType, newLocation.child([propName]), resolvedNode, propName);
}
}
}
@@ -357,7 +356,12 @@ export function walkDocument<T>(opts: {
return { location: newLocation, node, error };
}
function reportFn(ruleId: string, severity: MessageSeverity, location: Location, opts: ReportMessage) {
function reportFn(
ruleId: string,
severity: MessageSeverity,
location: Location,
opts: ReportMessage,
) {
const loc = opts.location
? Array.isArray(opts.location)
? opts.location