Skip to content
Open
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
5 changes: 3 additions & 2 deletions docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -905,8 +905,8 @@ validate asyncapi file
USAGE
$ asyncapi validate [SPEC-FILE] [-h] [-w] [--log-diagnostics] [--diagnostics-format
json|stylish|junit|html|text|teamcity|pretty|github-actions|sarif|code-climate|gitlab|markdown] [--fail-severity
error|warn|info|hint] [-s <value>] [--score] [--suppressWarnings <value>...] [--suppressAllWarnings] [--proxyHost
<value>] [--proxyPort <value>]
error|warn|info|hint] [-s <value>] [--score] [--suppressWarnings <value>...] [--suppressAllWarnings] [--ruleset
<value>] [--proxyHost <value>] [--proxyPort <value>]

ARGUMENTS
[SPEC-FILE] spec path, url, or context-name
Expand All @@ -928,6 +928,7 @@ FLAGS
document has description, license, server and/or channels.
--suppressAllWarnings Suppress all warnings from the validation output.
--suppressWarnings=<value>... List of warning codes to suppress from the validation output.
--ruleset=<value> Path to a custom Spectral ruleset file used during validation.

DESCRIPTION
validate asyncapi file
Expand Down
40 changes: 40 additions & 0 deletions src/apps/cli/commands/publish.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { Args, Flags } from '@oclif/core';
import Command from '@cli/internal/base';
import { load } from '@models/SpecificationFile';
import { RegistryService } from '@services/registry.service';
import { proxyFlags } from '@cli/internal/flags/proxy.flags';
import { applyProxyToPath } from '@utils/proxy';

export default class Publish extends Command {
static description = 'publish AsyncAPI file to a schema registry or endpoint';

Check warning on line 9 in src/apps/cli/commands/publish.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Make this public static property readonly.

See more on https://sonarcloud.io/project/issues?id=asyncapi_cli&issues=AZ5daXO_dgK5_2HTdnHS&open=AZ5daXO_dgK5_2HTdnHS&pullRequest=2215

static flags = {

Check warning on line 11 in src/apps/cli/commands/publish.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Make this public static property readonly.

See more on https://sonarcloud.io/project/issues?id=asyncapi_cli&issues=AZ5daXO_dgK5_2HTdnHT&open=AZ5daXO_dgK5_2HTdnHT&pullRequest=2215
endpoint: Flags.string({ description: 'Full registry endpoint URL to publish to' }),
'content-type': Flags.string({ description: 'Content-Type for the published document', default: 'application/yaml' }),
...proxyFlags(),
};

static args = {

Check warning on line 17 in src/apps/cli/commands/publish.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Make this public static property readonly.

See more on https://sonarcloud.io/project/issues?id=asyncapi_cli&issues=AZ5daXO_dgK5_2HTdnHU&open=AZ5daXO_dgK5_2HTdnHU&pullRequest=2215
'spec-file': Args.string({ description: 'Spec path or url', required: true }),
};

async run() {
const { args, flags } = await this.parse(Publish);
const filePath = applyProxyToPath(args['spec-file'], flags['proxyHost'], flags['proxyPort']);
this.specFile = await load(filePath);

const registry = new RegistryService();
const endpoint = flags.endpoint || '';

const { success, location, error } = await registry.publish(this.specFile, endpoint || filePath || '', {
endpoint: endpoint || undefined,
contentType: flags['content-type'],
});

if (!success) {
this.error(error || 'Publish failed', { exit: 1 });
}

this.log(`Published successfully${location ? ` at ${location}` : ''}`);

Check warning on line 38 in src/apps/cli/commands/publish.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this code to not use nested template literals.

See more on https://sonarcloud.io/project/issues?id=asyncapi_cli&issues=AZ5daXO_dgK5_2HTdnHV&open=AZ5daXO_dgK5_2HTdnHV&pullRequest=2215
}
}
39 changes: 39 additions & 0 deletions src/apps/cli/commands/share.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Args, Flags } from '@oclif/core';
import Command from '@cli/internal/base';
import { load } from '@models/SpecificationFile';
import { RegistryService } from '@services/registry.service';
import { proxyFlags } from '@cli/internal/flags/proxy.flags';
import { applyProxyToPath } from '@utils/proxy';

export default class Share extends Command {
static description = 'share AsyncAPI file (convenience wrapper around publish)';

Check warning on line 9 in src/apps/cli/commands/share.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Make this public static property readonly.

See more on https://sonarcloud.io/project/issues?id=asyncapi_cli&issues=AZ5daXSfdgK5_2HTdnHd&open=AZ5daXSfdgK5_2HTdnHd&pullRequest=2215

static flags = {

Check warning on line 11 in src/apps/cli/commands/share.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Make this public static property readonly.

See more on https://sonarcloud.io/project/issues?id=asyncapi_cli&issues=AZ5daXSfdgK5_2HTdnHe&open=AZ5daXSfdgK5_2HTdnHe&pullRequest=2215
endpoint: Flags.string({ description: 'Share endpoint URL' }),
...proxyFlags(),
};

static args = {

Check warning on line 16 in src/apps/cli/commands/share.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Make this public static property readonly.

See more on https://sonarcloud.io/project/issues?id=asyncapi_cli&issues=AZ5daXSfdgK5_2HTdnHf&open=AZ5daXSfdgK5_2HTdnHf&pullRequest=2215
'spec-file': Args.string({ description: 'Spec path or url', required: true }),
};

async run() {
const { args, flags } = await this.parse(Share);
const filePath = applyProxyToPath(args['spec-file'], flags['proxyHost'], flags['proxyPort']);
this.specFile = await load(filePath);

const registry = new RegistryService();
const endpoint = flags.endpoint || '';

const { success, location, error } = await registry.publish(this.specFile, endpoint || filePath || '', {
endpoint: endpoint || undefined,
contentType: 'application/yaml',
});

if (!success) {
this.error(error || 'Share failed', { exit: 1 });
}

this.log(`Shared successfully${location ? ` at ${location}` : ''}`);

Check warning on line 37 in src/apps/cli/commands/share.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this code to not use nested template literals.

See more on https://sonarcloud.io/project/issues?id=asyncapi_cli&issues=AZ5daXSfdgK5_2HTdnHg&open=AZ5daXSfdgK5_2HTdnHg&pullRequest=2215
}
}
51 changes: 51 additions & 0 deletions src/apps/cli/commands/sync.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { Args, Flags } from '@oclif/core';
import Command from '@cli/internal/base';
import { load } from '@models/SpecificationFile';
import { RegistryService } from '@services/registry.service';
import { applyProxyToPath } from '@utils/proxy';
import { proxyFlags } from '@cli/internal/flags/proxy.flags';
import { promises as fs } from 'fs';

Check warning on line 7 in src/apps/cli/commands/sync.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Prefer `node:fs` over `fs`.

See more on https://sonarcloud.io/project/issues?id=asyncapi_cli&issues=AZ5daXSCdgK5_2HTdnHW&open=AZ5daXSCdgK5_2HTdnHW&pullRequest=2215
import path from 'path';

Check warning on line 8 in src/apps/cli/commands/sync.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Prefer `node:path` over `path`.

See more on https://sonarcloud.io/project/issues?id=asyncapi_cli&issues=AZ5daXSCdgK5_2HTdnHX&open=AZ5daXSCdgK5_2HTdnHX&pullRequest=2215

export default class Sync extends Command {
static description = 'sync local AsyncAPI file with remote registry (push or pull)';

Check warning on line 11 in src/apps/cli/commands/sync.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Make this public static property readonly.

See more on https://sonarcloud.io/project/issues?id=asyncapi_cli&issues=AZ5daXSCdgK5_2HTdnHY&open=AZ5daXSCdgK5_2HTdnHY&pullRequest=2215

static flags = {

Check warning on line 13 in src/apps/cli/commands/sync.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Make this public static property readonly.

See more on https://sonarcloud.io/project/issues?id=asyncapi_cli&issues=AZ5daXSCdgK5_2HTdnHZ&open=AZ5daXSCdgK5_2HTdnHZ&pullRequest=2215
endpoint: Flags.string({ description: 'Remote registry endpoint or document URL' }),
direction: Flags.string({ description: 'sync direction: push or pull', options: ['push', 'pull'], default: 'push' }),
out: Flags.string({ description: 'Output file when pulling' }),
...proxyFlags(),
};

static args = {

Check warning on line 20 in src/apps/cli/commands/sync.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Make this public static property readonly.

See more on https://sonarcloud.io/project/issues?id=asyncapi_cli&issues=AZ5daXSCdgK5_2HTdnHa&open=AZ5daXSCdgK5_2HTdnHa&pullRequest=2215
'spec-file': Args.string({ description: 'Local spec path (for push) or target file (for pull)', required: true }),
};

async run() {
const { args, flags } = await this.parse(Sync);
const registry = new RegistryService();
const endpoint = flags.endpoint;
const direction = flags.direction as 'push' | 'pull';

if (direction === 'push') {
const filePath = applyProxyToPath(args['spec-file'], flags['proxyHost'], flags['proxyPort']);
this.specFile = await load(filePath);
const { success, error } = await registry.publish(this.specFile, endpoint || filePath || '', { endpoint: endpoint || undefined });
if (!success) this.error(error || 'Push failed', { exit: 1 });
this.log('Push succeeded');
return;
}

// pull
if (!endpoint) {
this.error('Endpoint required for pull', { exit: 1 });
}

const pullRes = await registry.pull(endpoint as string);
if (!pullRes.success) this.error(pullRes.error || 'Pull failed', { exit: 1 });

const outPath = flags.out || args['spec-file'];
await fs.writeFile(path.resolve(outPath), pullRes.content || '', 'utf8');
this.log(`Pulled content saved to ${outPath}`);
}
}
26 changes: 26 additions & 0 deletions src/apps/cli/commands/validate.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { Args } from '@oclif/core';
import { promises as fs } from 'fs';

Check warning on line 2 in src/apps/cli/commands/validate.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Prefer `node:fs` over `fs`.

See more on https://sonarcloud.io/project/issues?id=asyncapi_cli&issues=AZ5daXSXdgK5_2HTdnHb&open=AZ5daXSXdgK5_2HTdnHb&pullRequest=2215
import yaml from 'js-yaml';
import path from 'path';

Check warning on line 4 in src/apps/cli/commands/validate.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Prefer `node:path` over `path`.

See more on https://sonarcloud.io/project/issues?id=asyncapi_cli&issues=AZ5daXSXdgK5_2HTdnHc&open=AZ5daXSXdgK5_2HTdnHc&pullRequest=2215
import Command from '@cli/internal/base';
import { load } from '@models/SpecificationFile';
import { specWatcher } from '@cli/internal/globals';
Expand Down Expand Up @@ -41,6 +44,11 @@

this.specFile = await load(filePath);
const watchMode = flags.watch;
const customRuleset = flags.ruleset
? await this.loadCustomRuleset(flags.ruleset)
: undefined;

this.validationService = new ValidationService({}, customRuleset);

if (watchMode) {
specWatcher({
Expand Down Expand Up @@ -81,6 +89,24 @@
}
}

private async loadCustomRuleset(rulesetPath: string): Promise<Record<string, unknown>> {
const absolutePath = path.resolve(rulesetPath);
const rulesetContent = await fs.readFile(absolutePath, 'utf8');

try {
const parsedRuleset = yaml.load(rulesetContent) as Record<string, unknown>;

if (!parsedRuleset || typeof parsedRuleset !== 'object' || Array.isArray(parsedRuleset)) {
throw new Error('The ruleset file must resolve to an object.');
}

return parsedRuleset;
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
throw new Error(`Failed to load custom ruleset from ${absolutePath}: ${message}`);
}
}

private async handleDiagnostics(
result: ServiceResult<ValidationResult>,
flags: any,
Expand Down
5 changes: 5 additions & 0 deletions src/apps/cli/internal/flags/validate.flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,10 @@ export const validateFlags = () => {
required: false,
default: false,
}),
ruleset: Flags.string({
description:
'Path to a custom Spectral ruleset file used during validation.',
required: false,
}),
};
};
77 changes: 77 additions & 0 deletions src/domains/services/registry.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { BaseService } from './base.service';
import { Specification } from '@models/SpecificationFile';
import { ConfigService } from './config.service';

export interface PublishOptions {
endpoint?: string; // full URL to POST the document to
path?: string; // path appended to endpoint
contentType?: string;
}

export class RegistryService extends BaseService {
/**
* Publish an AsyncAPI specification to a registry endpoint.
* This performs a simple POST with the document text. Authentication
* is taken from `ConfigService` when available for the given URL.
*/
async publish(
spec: Specification,
registryUrl: string,
options: PublishOptions = {},
): Promise<{ success: boolean; location?: string; error?: string }> {
try {
const url = options.endpoint || registryUrl;
const headers: Record<string, string> = {
'Content-Type': options.contentType || 'application/yaml',
'User-Agent': 'AsyncAPI-CLI',
};

const auth = await ConfigService.getAuthForUrl(url);
if (auth) {
headers['Authorization'] = `${auth.authType} ${auth.token}`;
Object.assign(headers, auth.headers || {});
}

const res = await fetch(url + (options.path ?? ''), {
method: 'POST',
headers,
body: spec.text(),
});

if (!res.ok) {
const body = await res.text().catch(() => '');
return { success: false, error: `Publish failed: ${res.status} ${res.statusText} ${body}` };
}

const location = res.headers.get('location') || undefined;
return { success: true, location };
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
return { success: false, error: msg };
}
}

/**
* Pull a document from a remote registry URL.
*/
async pull(url: string): Promise<{ success: boolean; content?: string; error?: string }> {
try {
const headers: Record<string, string> = { 'User-Agent': 'AsyncAPI-CLI' };
const auth = await ConfigService.getAuthForUrl(url);
if (auth) {
headers['Authorization'] = `${auth.authType} ${auth.token}`;
Object.assign(headers, auth.headers || {});
}

const res = await fetch(url, { headers });
if (!res.ok) {
return { success: false, error: `Failed to fetch: ${res.status} ${res.statusText}` };
}
const text = await res.text();
return { success: true, content: text };
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
return { success: false, error: msg };
}
}
}
Loading
Loading