Skip to content
Merged
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: 5 additions & 0 deletions packages/api/src/fetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ export default class Fetcher {
uri: string | OASDocument;

/**
* @note This regex also exists in `httpsnippet-client-api`.
*
* @example @petstore/v1.0#n6kvf10vakpemvplx
* @example @petstore#n6kvf10vakpemvplx
*/
Expand Down Expand Up @@ -45,6 +47,9 @@ export default class Fetcher {
return /\/\/github.com\/[-_a-zA-Z0-9]+\/[-_a-zA-Z0-9]+\/blob\/(.*).(yaml|json|yml)/.test(uri);
}

/**
* @note This function also exists in `httpsnippet-client-api`.
*/
static getProjectPrefixFromRegistryUUID(uri: string) {
const matches = uri.match(Fetcher.registryUUIDRegex);
if (!matches) {
Expand Down
46 changes: 44 additions & 2 deletions packages/httpsnippet-client-api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,26 @@ import Oas from 'oas';
import { matchesMimeType } from 'oas/utils';
import stringifyObject from 'stringify-object';

/**
* @note This regex also exists in `api/fetcher`.
*
* @example @petstore/v1.0#n6kvf10vakpemvplx
* @example @petstore#n6kvf10vakpemvplx
*/
const registryUUIDRegex = /^@(?<project>[a-zA-Z0-9-_]+)(\/?(?<version>.+))?#(?<uuid>[a-z0-9]+)$/;

/**
* @note This function also exists in `api/fetcher`.
*/
function getProjectPrefixFromRegistryUUID(uri: string) {
const matches = uri.match(registryUUIDRegex);

Check failure

Code scanning / CodeQL

Polynomial regular expression used on uncontrolled data

This [regular expression](1) that depends on [library input](2) may run slow on strings starting with '@-' and with many repetitions of '--'.
if (!matches) {
return undefined;
}

return matches.groups?.project;
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function stringify(obj: any, opts = {}) {
return stringifyObject(obj, { indent: ' ', ...opts });
Expand Down Expand Up @@ -76,8 +96,20 @@ function getAuthSources(operation: Operation) {

interface APIOptions {
apiDefinition: OASDocument;
/**
* The URI that is used to download this API definition from `npx api install`.
*
* @example @developers/v2.0#17273l2glm9fq4l5
*/
apiDefinitionUri: string;
escapeBrackets?: boolean;
/**
* The string to identify this SDK as. This is used in the `import sdk from '@api/<identifier>'`
* sample as well as the the variable name we attach the SDK to.
*
* @example developers
*/
identifier?: string;
indent?: string | false;
}

Expand Down Expand Up @@ -110,6 +142,16 @@ const client: Client<APIOptions> = {
);
}

let sdkPackageName;
let sdkVariable;
if (opts.identifier) {
sdkPackageName = opts.identifier;
sdkVariable = opts.identifier;
} else {
sdkPackageName = getProjectPrefixFromRegistryUUID(opts.apiDefinitionUri);
sdkVariable = 'sdk';
}

const operationSlugs = foundOperation.url.slugs;
const operation = oas.operation(foundOperation.url.nonNormalizedPath, method);
const operationPathParameters = operation.getParameters().filter(param => param.in === 'path');
Expand All @@ -119,7 +161,7 @@ const client: Client<APIOptions> = {

const { blank, push, join } = new CodeBuilder({ indent: opts.indent || ' ' });

push(`const sdk = require('api')('${opts.apiDefinitionUri}');`);
push(`import ${sdkVariable} from '@api/${sdkPackageName}';`);
blank();

// If we have multiple servers configured and our source URL differs from the stock URL that we
Expand Down Expand Up @@ -306,7 +348,7 @@ const client: Client<APIOptions> = {
push(configData.join('\n'));
}

push(`sdk.${accessor}(${args.join(', ')})`);
push(`${sdkVariable}.${accessor}(${args.join(', ')})`);
push('.then(({ data }) => console.log(data))', 1);
push('.catch(err => console.error(err));', 1);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/alternate-server.json');
import sdk from '@api/alternate-server';

sdk.server('http://dev.local/v2');
sdk.postGlobal()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/application-form-encoded.json');
import sdk from '@api/application-form-encoded';

sdk.postAnything({foo: 'bar', hello: 'world'})
.then(({ data }) => console.log(data))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/application-json.json');
import sdk from '@api/application-json';

sdk.postAnything({
number: 1,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/auth-apikey-cookie.json');
import sdk from '@api/auth-apikey-cookie';

sdk.auth('buster');
sdk.postAnythingApikey()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/auth-apikey-header.json');
import sdk from '@api/auth-apikey-header';

sdk.auth('a5a220e');
sdk.putAnythingApikey()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/auth-basic-full.json');
import sdk from '@api/auth-basic-full';

sdk.auth('buster', 'pug');
sdk.getAPISpecification({perPage: '10', page: '1'})
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/auth-basic-password-only.json');
import sdk from '@api/auth-basic-password-only';

sdk.auth('', 'pug');
sdk.getAPISpecification({perPage: '10', page: '1'})
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/auth-basic-username-only.json');
import sdk from '@api/auth-basic-username-only';

sdk.auth('buster');
sdk.getAPISpecification({perPage: '10', page: '1'})
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/auth-bearer.json');
import sdk from '@api/auth-bearer';

sdk.auth('myBearerToken');
sdk.postAnythingBearer()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/auth-query.json');
import sdk from '@api/auth-query';

sdk.auth('a5a220e');
sdk.getAnythingApikey()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/cookies.json');
import sdk from '@api/cookies';

sdk.postAnything({bar: 'baz', foo: 'bar'})
.then(({ data }) => console.log(data))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/full-many-query-params.json');
import sdk from '@api/full-many-query-params';

sdk.postAnything({
foo: 'bar',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/full.json');
import sdk from '@api/full';

sdk.postAnything({foo: 'bar'}, {
foo: ['bar', 'baz'],
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/headers.json');
import sdk from '@api/headers';

sdk.getAnything({'x-foo': 'Bar', 'x-bar': 'foo'})
.then(({ data }) => console.log(data))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/http-insecure.json');
import sdk from '@api/http-insecure';

sdk.getAnything()
.then(({ data }) => console.log(data))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/issue-128.json');
import sdk from '@api/issue-128';

sdk.auth('authKey\'With\'Apostrophes');
sdk.getItem()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/issue-76.json');
import sdk from '@api/issue-76';

sdk.auth('a5a220e');
sdk.getPetFindbystatus({status: 'available'})
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/issue-78-operationid.json');
import sdk from '@api/issue-78-operationid';

sdk.getOrder({orderId: '1234'})
.then(({ data }) => console.log(data))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/issue-78.json');
import sdk from '@api/issue-78';

sdk.getStoreOrderOrderidTrackingTrackingid({orderId: '1234', trackingId: '5678'})
.then(({ data }) => console.log(data))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/jsonObj-multiline.json');
import sdk from '@api/jsonObj-multiline';

sdk.postAnything({foo: 'bar'})
.then(({ data }) => console.log(data))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/jsonObj-null-value.json');
import sdk from '@api/jsonObj-null-value';

sdk.postAnything({foo: null})
.then(({ data }) => console.log(data))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/multipart-data.json');
import sdk from '@api/multipart-data';

sdk.postAnything({foo: 'test/__fixtures__/files/hello.txt'})
.then(({ data }) => console.log(data))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/multipart-file.json');
import sdk from '@api/multipart-file';

sdk.postAnything({foo: 'test/__fixtures__/files/hello.txt'})
.then(({ data }) => console.log(data))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/multipart-form-data-no-params.json');
import sdk from '@api/multipart-form-data-no-params';

sdk.postAnything()
.then(({ data }) => console.log(data))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/multipart-form-data.json');
import sdk from '@api/multipart-form-data';

sdk.postAnything({foo: 'bar'})
.then(({ data }) => console.log(data))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/operationid-non-alphanumerical.json');
import sdk from '@api/operationid-non-alphanumerical';

sdk.auth('123');
sdk.findPetsByStatus({status: 'available'})
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/operationid-with-underscores.json');
import sdk from '@api/operationid-with-underscores';

sdk.anything_Operation()
.then(({ data }) => console.log(data))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/parameter-special-characters.json');
import sdk from '@api/parameter-special-characters';

sdk.getAppIdNumInstalls_reportV5({'app-id': '1234', num: '5678'})
.then(({ data }) => console.log(data))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/petstore.json');
import sdk from '@api/petstore';

sdk.auth('123');
sdk.findPetsByStatus({status: 'available', accept: 'application/xml'})
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/query.json');
import sdk from '@api/query';

sdk.getAnything({foo: ['bar', 'baz'], baz: 'abc', key: 'value'})
.then(({ data }) => console.log(data))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/short.json');
import sdk from '@api/short';

sdk.getAnything()
.then(({ data }) => console.log(data))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sdk = require('api')('https://api.example.com/text-plain.json');
import sdk from '@api/text-plain';

sdk.postAnything('Hello World')
.then(({ data }) => console.log(data))
Expand Down
31 changes: 20 additions & 11 deletions packages/httpsnippet-client-api/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import path from 'node:path';
import { HTTPSnippet, addTargetClient } from '@readme/httpsnippet';
import readme from '@readme/oas-examples/3.0/json/readme.json';
import openapiParser from '@readme/openapi-parser';
import { describe, afterEach, beforeEach, expect, it, vi } from 'vitest';
import { describe, beforeEach, expect, it } from 'vitest';

import client from '../src/index.js';

Expand Down Expand Up @@ -60,7 +60,7 @@ describe('httpsnippet-client-api', () => {

await expect(
snippet.convert('node', 'api', {
apiDefinitionUri: 'https://api.example.com/openapi.json',
apiDefinitionUri: '@developers/v2.0#17273l2glm9fq4l5',
}),
).rejects.toThrow(/must have an `apiDefinition` option supplied/);
});
Expand All @@ -81,7 +81,7 @@ describe('httpsnippet-client-api', () => {

await expect(
snippet.convert('node', 'api', {
apiDefinitionUri: 'https://api.example.com/openapi.json',
apiDefinitionUri: '@developers/v2.0#17273l2glm9fq4l5',
apiDefinition: readme,
}),
).rejects.toThrow(/unable to locate a matching operation/i);
Expand All @@ -90,11 +90,8 @@ describe('httpsnippet-client-api', () => {
describe('snippets', () => {
describe.each(SNIPPETS)('%s', snippet => {
let mock: SnippetMock;
let consoleStub;

beforeEach(async () => {
consoleStub = vi.spyOn(console, 'log').mockImplementation(() => {});

mock = await getSnippetDataset(snippet);

// `OpenAPIParser.validate()` updates the spec that's passed and we just want to validate
Expand All @@ -103,20 +100,32 @@ describe('httpsnippet-client-api', () => {
await openapiParser.validate(spec);
});

afterEach(() => {
consoleStub.mockRestore();
});

it('should generate the expected snippet', async () => {
const expected = await fs.readFile(path.join(DATASETS_DIR, snippet, 'output.js'), 'utf-8');

const code = await new HTTPSnippet(mock.har).convert('node', 'api', {
apiDefinitionUri: `https://api.example.com/${snippet}.json`,
apiDefinitionUri: `@${snippet}/v2.0#17273l2glm9fq4l5`,
apiDefinition: mock.definition,
});

expect(`${code}\n`).toStrictEqual(expected);
});
});

it('should support custom SDK variable names', async () => {
const mock = await getSnippetDataset('short');

const code = await new HTTPSnippet(mock.har).convert('node', 'api', {
apiDefinitionUri: '@developers/v2.0#17273l2glm9fq4l5',
identifier: 'developers',
apiDefinition: mock.definition,
});

expect(code).toStrictEqual(`import developers from '@api/developers';

developers.getAnything()
.then(({ data }) => console.log(data))
.catch(err => console.error(err));`);
});
});
});