Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(rulesets): use aliases in ruleset #2018

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/core/src/meta/ruleset.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"formats": {
"$ref": "shared#formats"
},
"shorthands": true,
"extends": {
"oneOf": [
{
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/ruleset/mergers/rulesets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export function mergeRulesets(left: MergeableRuleset, right: MergeableRuleset, i
...right,
};

if ('extends' in ruleset && 'extends' in ruleset) {
if ('extends' in ruleset) {
const rightExtensions = getExtensions(ruleset.extends);
(ruleset as Omit<RulesetDefinition, 'extends'> & { extends: RulesetExtendsDefinition }).extends = [
...(Array.isArray(ruleset.extends) ? ruleset.extends : [ruleset.extends]).filter(
Expand Down
73 changes: 45 additions & 28 deletions packages/core/src/ruleset/ruleset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,14 @@ export type StringifiedRuleset = {

export class Ruleset {
public readonly id = SEED++;

protected readonly extends: Ruleset[] | null;
public readonly formats = new FormatsSet();
public readonly overrides: RulesetOverridesDefinition | null;
public readonly aliases: RulesetAliasesDefinition | null;
public readonly hasComplexAliases: boolean;
public readonly rules: Record<string, Rule>;
public readonly definition: RulesetDefinition;

public readonly shorthands: Record<string, string> | null;
protected readonly extends: Ruleset[] | null;
readonly #context: RulesetContext & { severity: FileRulesetSeverityDefinition };

constructor(readonly maybeDefinition: unknown, context?: RulesetContext) {
Expand All @@ -65,7 +64,6 @@ export class Ruleset {
}

this.definition = definition;

this.#context = {
severity: 'recommended',
...context,
Expand Down Expand Up @@ -149,12 +147,21 @@ export class Ruleset {
}

this.rules = this.#getRules();
this.shorthands = this.#getJsonPathShorthands();
}

get source(): string | null {
return this.#context.source ?? null;
}

public get parserOptions(): ParserOptions {
return { ...DEFAULT_PARSER_OPTIONS, ...this.definition.parserOptions };
}

public static isDefaultRulesetFile(uri: string): boolean {
return DEFAULT_RULESET_FILE.test(uri);
}

public fromSource(source: string | null): Ruleset {
if (this.overrides === null) {
return this;
Expand Down Expand Up @@ -259,6 +266,40 @@ export class Ruleset {
return ruleset;
}

public toJSON(): Omit<StringifiedRuleset, 'extends' | 'rules'> & {
extends: Ruleset['extends'];
rules: Ruleset['rules'];
} {
return {
id: this.id,
extends: this.extends,
source: this.source,
aliases: this.aliases,
formats: this.formats.size === 0 ? null : this.formats,
rules: this.rules,
overrides: this.overrides,
parserOptions: this.parserOptions,
};
}

#getJsonPathShorthands(): Record<string, string> {
const shorthands = {};

if (this.extends !== null && this.extends.length > 0) {
for (const extendedRuleset of this.extends) {
if (extendedRuleset === this || extendedRuleset.shorthands === null) continue;
for (const [name, value] of Object.entries(extendedRuleset.shorthands)) {
shorthands[name] = value;
}
}
}

return {
...this.definition.shorthands,
...shorthands,
};
}

#getRules(): Record<string, Rule> {
const rules: Record<string, Rule> = {};

Expand Down Expand Up @@ -300,28 +341,4 @@ export class Ruleset {

return rules;
}

public get parserOptions(): ParserOptions {
return { ...DEFAULT_PARSER_OPTIONS, ...this.definition.parserOptions };
}

public static isDefaultRulesetFile(uri: string): boolean {
return DEFAULT_RULESET_FILE.test(uri);
}

public toJSON(): Omit<StringifiedRuleset, 'extends' | 'rules'> & {
extends: Ruleset['extends'];
rules: Ruleset['rules'];
} {
return {
id: this.id,
extends: this.extends,
source: this.source,
aliases: this.aliases,
formats: this.formats.size === 0 ? null : this.formats,
rules: this.rules,
overrides: this.overrides,
parserOptions: this.parserOptions,
};
}
}
1 change: 1 addition & 0 deletions packages/core/src/ruleset/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ export type RulesetDefinition = Readonly<
parserOptions?: Partial<ParserOptions>;
overrides?: RulesetOverridesDefinition;
aliases?: RulesetAliasesDefinition;
shorthands?: Record<string, string>;
} & Readonly<
| {
overrides: RulesetOverridesDefinition;
Expand Down
17 changes: 14 additions & 3 deletions packages/core/src/runner/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,16 @@ export class Runner {
const unresolvedJsonPaths = Object.keys(callbacks.unresolved);

if (resolvedJsonPaths.length > 0) {
execute(runnerContext.documentInventory.resolved, callbacks.resolved, resolvedJsonPaths);
execute(runnerContext.documentInventory.resolved, callbacks.resolved, resolvedJsonPaths, ruleset.shorthands);
}

if (unresolvedJsonPaths.length > 0) {
execute(runnerContext.documentInventory.unresolved, callbacks.unresolved, unresolvedJsonPaths);
execute(
runnerContext.documentInventory.unresolved,
callbacks.unresolved,
unresolvedJsonPaths,
ruleset.shorthands,
);
}

this.runtime.emit('beforeTeardown');
Expand All @@ -83,7 +88,12 @@ export class Runner {
}
}

function execute(input: unknown, callbacks: Record<string, Callback[]>, jsonPathExpressions: string[]): void {
function execute(
input: unknown,
callbacks: Record<string, Callback[]>,
jsonPathExpressions: string[],
customShorthands: Record<string, string> | null,
): void {
if (!isPlainObject(input) && !Array.isArray(input)) {
for (const cb of callbacks.$ ?? []) {
cb({
Expand All @@ -96,6 +106,7 @@ function execute(input: unknown, callbacks: Record<string, Callback[]>, jsonPath
}

const nimma = new Nimma(jsonPathExpressions, {
customShorthands,
fallback: jsonPathPlus,
unsafe: false,
output: 'auto',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,11 @@ testRule('oas2-parameter-description', [
],
},
},
parameters: {
limit: {
description: 'This is how it works.',
},
},
},
errors: [],
},
Expand Down
9 changes: 9 additions & 0 deletions packages/rulesets/src/oas/functions/oasExample.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,11 @@ function* getMediaValidationItems(
}
}

function isSubschema(givenPath: JsonPath) {
// todo: add more
return givenPath.length > 1 && !['properties', 'items', 'contains'].includes(String(givenPath[givenPath.length - 1]));
}

function* getSchemaValidationItems(
fields: string[],
targetVal: Record<string, unknown>,
Expand All @@ -103,6 +108,10 @@ function* getSchemaValidationItems(
continue;
}

if (!isSubschema(givenPath)) {
continue;
}

yield {
value: targetVal[field],
path: [...givenPath, field],
Expand Down
2 changes: 2 additions & 0 deletions packages/rulesets/src/oas/functions/oasSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ export default createRulesetFunction<unknown, Options>(
},
},
function oasSchema(targetVal, opts, context) {
if (targetVal === void 0) return;

const formats = context.document.formats;

let { schema } = opts;
Expand Down
117 changes: 105 additions & 12 deletions packages/rulesets/src/oas/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,112 @@ import {

export { ruleset as default };

const shorthands: Record<string, string> = {
schema: [
...[
'not',
'if',
'then',
'else',
'unevaluatedProperties',
'additionalProperties',
'propertyNames',
'items',
'unevaluatedItems',
].map(k => `scope.path[scope.path.length - 1] === '${k}'`),
...['prefixItems', 'items', 'allOf', 'oneOf', 'anyOf'].map(
k => `scope.path[scope.path.length - 2] === '${k}' && Number.isInteger(scope.path[scope.path.length - 1])`,
),
...['patternProperties', 'properties'].map(k => `scope.path[scope.path.length - 2] === '${k}'`),
].join(' || '),
};

const ruleset = {
documentationUrl: 'https://meta.stoplight.io/docs/spectral/docs/reference/openapi-rules.md',
formats: [oas2, oas3, oas3_0, oas3_1],
aliases: {
PathItem: ['$.paths[*]'],
ResponsesObject: {
targets: [
{ formats: [oas2], given: ['$.responses', '#OperationObject.responses'] },
{ formats: [oas3], given: ['$.components.responses', '#OperationObject.responses'] },
],
},
ResponseObject: ['#ResponsesObject[*]'], // [(@ && !@.$ref)]
ParametersDefinitionsObject: {
targets: [
{ formats: [oas2], given: ['$.parameters'] },
{ formats: [oas3], given: ['$.components.parameters'] },
],
},
ParametersObject: {
targets: [
{ formats: [oas2], given: ['#PathItem.parameters', '#OperationObject.parameters'] },
{
formats: [oas3],
given: ['#PathItem.parameters', '#OperationObject.parameters'],
},
],
},
ParameterObject: {
targets: [
{ formats: [oas2], given: ['#ParametersDefinitionsObject[*]', '#ParametersObject[*]'] }, // ?(@ && !@.$ref)
{
formats: [oas3],
given: ['#ParametersDefinitionsObject[*]', '#ParametersObject[*]'], // [?(@ && !@.$ref)]
},
],
},
EncodingObject: ['#MediaTypeObject.encoding'],
MediaTypeObject: ['#RequestBodyObject.content', '#ParameterObject.content', '#ResponseObject.content'],
HeadersObject: {
targets: [
{ formats: [oas2], given: ['#ResponseObject.headers'] },
{
formats: [oas3],
given: ['$.components.headers', '#EncodingObject.headers', '#ResponseObject.headers'],
},
],
},
HeaderObject: {
targets: [
{ formats: [oas2], given: ['#ResponseObject.headers[*]'] },
{
formats: [oas3],
given: ['#HeadersObject[*]'], // ?(@ && !$.ref)
},
],
},
RequestBodyObject: ['#OperationObject.requestBody', '$.components.requestBodies[*]'],
OperationObject: ['#PathItem[get,put,post,delete,options,head,patch,trace]'],
SchemaObject: {
targets: [
{
formats: [oas2],
given: [
'#MediaTypeObject.schema',
'#MediaTypeObject.schema..@@schema()',
'#ParameterObject.schema',
'#ParameterObject.schema..@@schema()',
'$.definitions[*]',
'$.definitions[*]..@@schema()',
],
},
{
formats: [oas3],
given: [
'#MediaTypeObject.schema',
'#MediaTypeObject.schema..@@schema()',
'#ParameterObject.schema',
'#ParameterObject.schema..@@schema()',
'$.components.schemas[*]',
'$.components.schemas[*]..@@schema()',
],
},
],
},
},
shorthands,
rules: {
'operation-success-response': {
description: 'Operation must have at least one "2xx" or "3xx" response.',
Expand Down Expand Up @@ -123,7 +222,7 @@ const ruleset = {
severity: 'warn',
recommended: true,
message: '{{error}}',
given: ["$..[?(@property !== 'properties' && @ && @.enum)]"],
given: ['#SchemaObject'],
then: {
field: 'enum',
function: oasSchema,
Expand Down Expand Up @@ -440,7 +539,7 @@ const ruleset = {
description: 'Parameter objects must have "description".',
recommended: false,
formats: [oas2],
given: '$..parameters[?(@ && @.in)]',
given: '#ParameterObject',
type: 'style',
then: {
field: 'description',
Expand Down Expand Up @@ -575,11 +674,9 @@ const ruleset = {
type: 'style',
given: [
'$.components.examples[*]',
'$.paths[*][*]..content[*].examples[*]',
'$.paths[*][*]..parameters[*].examples[*]',
'$.components.parameters[*].examples[*]',
'$.paths[*][*]..headers[*].examples[*]',
'$.components.headers[*].examples[*]',
'#MediaTypeObject.examples[*]',
'#ParameterObject.examples[*]',
'#HeaderObject.examples[*]',
],
then: {
function: xor,
Expand Down Expand Up @@ -608,11 +705,7 @@ const ruleset = {
recommended: false,
formats: [oas3],
type: 'style',
given: [
'#PathItem.parameters[?(@ && @.in)]',
'#OperationObject.parameters[?(@ && @.in)]',
'$.components.parameters[?(@ && @.in)]',
],
given: '#ParameterObject',
then: {
field: 'description',
function: truthy,
Expand Down