Skip to content

Update Prettier, linting deps #1283

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

Merged
merged 2 commits into from
Aug 8, 2023
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
2 changes: 2 additions & 0 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ module.exports = {
rules: {
"@typescript-eslint/consistent-indexed-object-style": "off", // sometimes naming keys is more user-friendly
"@typescript-eslint/no-dynamic-delete": "off", // delete is OK
"@typescript-eslint/no-non-null-assertion": "off", // this is better than "as"
"@typescript-eslint/no-unnecessary-condition": "off", // this gives bad advice
"no-console": "error",
"no-unused-vars": "off",
Expand All @@ -19,6 +20,7 @@ module.exports = {
rules: {
"@typescript-eslint/ban-ts-comment": "off", // allow @ts-ignore only in tests
"@typescript-eslint/no-empty-function": "off", // don’t enforce this in tests
"@typescript-eslint/no-explicit-any": "off", // tests sometimes need this
"no-only-tests/no-only-tests": "error",
"vitest/valid-title": "off", // doesn’t work?
},
Expand Down
2 changes: 1 addition & 1 deletion docs/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ See the [README](./README.md) for basic setup.

## Corrections / small edits

Corrections are always welcome! Please go straight to [opening a PR](https://github.com/drwpow/openapi-typescript/pulls) for correcting typos or misinformation language. Small edits are also welcome, which include shortening verbose language or clarifying confusing wording.
Corrections are always welcome! Please go straight to [opening a PR](https://github.com/drwpow/openapi-typescript/pulls) for correcting typos or misinformation. Small grammar edits are also welcome such as shortening verbose language or clarifying confusing statements.

## Styling fixes

Expand Down
14 changes: 7 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,16 @@
"devDependencies": {
"@changesets/changelog-github": "^0.4.8",
"@changesets/cli": "^2.26.2",
"@typescript-eslint/eslint-plugin": "^5.61.0",
"@typescript-eslint/parser": "^5.61.0",
"@typescript-eslint/eslint-plugin": "^6.3.0",
"@typescript-eslint/parser": "^6.3.0",
"del-cli": "^5.0.0",
"eslint": "^8.44.0",
"eslint-config-prettier": "^8.8.0",
"eslint": "^8.46.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-no-only-tests": "^3.1.0",
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-vitest": "^0.2.6",
"eslint-plugin-prettier": "^5.0.0",
"eslint-plugin-vitest": "^0.2.8",
"npm-run-all": "^4.1.5",
"prettier": "^2.8.8",
"prettier": "^3.0.1",
"typescript": "^5.1.6"
}
}
4 changes: 2 additions & 2 deletions packages/openapi-fetch/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Thanks for being willing to contribute! 🙏

## Open issues

Please check out the [the open issues](https://github.com/drwpow/openapi-fetch/issues). Issues labelled [**Help Wanted**](https://github.com/drwpow/openapi-fetch/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22) and [**Good First Issue**](https://github.com/drwpow/openapi-fetch/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) are especially good to help with.
Please check out the [the open issues](https://github.com/drwpow/openapi-typescript/issues). Issues labelled [**Good First Issue**](https://github.com/drwpow/openapi-typescript/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22)are especially good to start with.

Contributing doesn’t have to be in code! Simply answering questions in open issues, or providing workarounds, is just as important a contribution as making pull requests.

Expand All @@ -26,7 +26,7 @@ However, if adding a feature or breaking change, please **open an issue first to

Create a new branch for your PR with `git checkout -b your-branch-name`. Add the relevant code as well as docs and tests. When you push everything up (`git push`), navigate back to your repo GitHub and you should see a prompt to open a new PR.

While best practices for commit messages are encouraged (e.g. start with an imperative verb, keep it short, use the body if needed), this repo doesn’t follow any specific guidelines like [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/). Clarity is favored over strict rules. Changelogs are generated separately from git (see [the Changelogs section](#changelogs)
While best practices for commit messages are encouraged (e.g. start with an imperative verb, keep it short, use the body if needed), this repo doesn’t follow any specific guidelines. Clarity is favored over strict rules. Changelogs are generated separately from git (see [the Changelogs section](#changelogs))

### Writing the PR

Expand Down
5 changes: 2 additions & 3 deletions packages/openapi-fetch/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,9 @@
},
"devDependencies": {
"del-cli": "^5.0.0",
"esbuild": "^0.18.17",
"esbuild": "^0.19.0",
"nanostores": "^0.9.3",
"openapi-typescript": "*",
"prettier": "^2.8.8",
"openapi-typescript": "^6.4.2",
"typescript": "^5.1.6",
"vitest": "^0.33.0",
"vitest-fetch-mock": "^0.2.2"
Expand Down
11 changes: 6 additions & 5 deletions packages/openapi-fetch/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ describe("client", () => {
new Headers({
...headers, // assert new header got passed
"Content-Type": "application/json", // probably doesn’t need to get tested, but this was simpler than writing lots of code to ignore these
})
}),
);
});

Expand All @@ -333,7 +333,7 @@ describe("client", () => {
new Headers({
"Cache-Control": "no-cache",
"Content-Type": "application/json",
})
}),
);
});

Expand Down Expand Up @@ -372,7 +372,7 @@ describe("client", () => {
it("multipart/form-data", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
const { data } = await client.PUT("/contact", {
await client.PUT("/contact", {
body: {
name: "John Doe",
email: "[email protected]",
Expand Down Expand Up @@ -445,6 +445,7 @@ describe("client", () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
const { data } = await client.GET("/anyMethod", { parseAs: "blob" });
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((data as any).constructor.name).toBe("Blob");
});

Expand Down Expand Up @@ -681,7 +682,7 @@ describe("examples", () => {
setTimeout(() => {
token.set(tokenVal); // simulate promise-like token setting
resolve();
}, 0)
}, 0),
);
await client.get().GET("/blogposts/{post_id}", { params: { path: { post_id: "1234" } } });
expect(fetchMocker.mock.calls[1][1].headers.get("authorization")).toBe(`Bearer ${tokenVal}`);
Expand Down Expand Up @@ -710,7 +711,7 @@ describe("examples", () => {
setTimeout(() => {
token = tokenVal; // simulate promise-like token setting
resolve();
}, 0)
}, 0),
);
await client.GET("/blogposts/{post_id}", { params: { path: { post_id: "1234" } } });
expect(fetchMocker.mock.calls[1][1].headers.get("authorization")).toBe(`Bearer ${tokenVal}`);
Expand Down
4 changes: 4 additions & 0 deletions packages/openapi-fetch/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ const DEFAULT_HEADERS = {
};
const TRAILING_SLASH_RE = /\/*$/;

// Note: though "any" is considered bad practice in general, this library relies
// on "any" for type inference only it can give. Same goes for the "{}" type.
/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types */

/** options for each client instance */
interface ClientOptions extends RequestInit {
/** set the common root URL for all API requests */
Expand Down
4 changes: 2 additions & 2 deletions packages/openapi-typescript/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Thanks for being willing to contribute! 🙏

## Open issues

Please check out the [the open issues](https://github.com/drwpow/openapi-typescript/issues). Issues labelled [**Help Wanted**](https://github.com/drwpow/openapi-typescript/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22) and [**Good First Issue**](https://github.com/drwpow/openapi-typescript/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) are especially good to help with.
Please check out the [the open issues](https://github.com/drwpow/openapi-typescript/issues). Issues labelled [**Good First Issue**](https://github.com/drwpow/openapi-typescript/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22)are especially good to start with.

Contributing doesn’t have to be in code! Simply answering questions in open issues, or providing workarounds, is just as important a contribution as making pull requests.

Expand All @@ -26,7 +26,7 @@ However, if adding a feature or breaking change, please **open an issue first to

Create a new branch for your PR with `git checkout -b your-branch-name`. Add the relevant code as well as docs and tests. When you push everything up (`git push`), navigate back to your repo GitHub and you should see a prompt to open a new PR.

While best practices for commit messages are encouraged (e.g. start with an imperative verb, keep it short, use the body if needed), this repo doesn’t follow any specific guidelines like [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/). Clarity is favored over strict rules. Changelogs are generated separately from git (see [the Changelogs section](#changelogs)
While best practices for commit messages are encouraged (e.g. start with an imperative verb, keep it short, use the body if needed), this repo doesn’t follow any specific guidelines. Clarity is favored over strict rules. Changelogs are generated separately from git (see [the Changelogs section](#changelogs))

When working locally, run:

Expand Down
10 changes: 5 additions & 5 deletions packages/openapi-typescript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,21 +59,21 @@
},
"dependencies": {
"ansi-colors": "^4.1.3",
"fast-glob": "^3.3.0",
"fast-glob": "^3.3.1",
"js-yaml": "^4.1.0",
"supports-color": "^9.4.0",
"undici": "^5.22.1",
"undici": "^5.23.0",
"yargs-parser": "^21.1.1"
},
"devDependencies": {
"@types/degit": "^2.8.3",
"@types/js-yaml": "^4.0.5",
"@types/node": "^20.4.0",
"@types/node": "^20.4.9",
"degit": "^2.8.4",
"del-cli": "^5.0.0",
"esbuild": "^0.18.17",
"esbuild": "^0.19.0",
"execa": "^6.1.0",
"vite": "^4.4.1",
"vite": "^4.4.9",
"vite-node": "^0.33.0",
"vitest": "^0.33.0"
}
Expand Down
13 changes: 7 additions & 6 deletions packages/openapi-typescript/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { GlobalContext, OpenAPI3, OpenAPITSOptions, Subschema } from "./types.js";
import type { GlobalContext, OpenAPI3, OpenAPITSOptions, SchemaObject, Subschema } from "./types.js";
import type { Readable } from "node:stream";
import { URL } from "node:url";
import load, { resolveSchema, VIRTUAL_JSON_URL } from "./load.js";
Expand Down Expand Up @@ -75,6 +75,7 @@ async function openapiTS(schema: string | URL | OpenAPI3 | Readable, options: Op
// 1. basic validation
for (const k of Object.keys(allSchemas)) {
const subschema = allSchemas[k];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (typeof (subschema.schema as any).swagger === "string") {
error("Swagger 2.0 and older no longer supported. Please use v5.");
process.exit(1);
Expand Down Expand Up @@ -156,7 +157,7 @@ async function openapiTS(schema: string | URL | OpenAPI3 | Readable, options: Op
// hack: sometimes subschemas contain only a single SchemaObject or ParameterObject and get incorrectly hinted
// currently unknown what the real fix is, but this is a bandaid
if (typeof subschema.schema === "object" && ("schema" in subschema.schema || "type" in subschema.schema)) {
subschemaOutput = transformSchemaObject(subschema.schema as any, { path, ctx: { ...ctx, indentLv } });
subschemaOutput = transformSchemaObject(subschema.schema as SchemaObject, { path, ctx: { ...ctx, indentLv } });
} else {
subschemaOutput += "{\n";
indentLv++;
Expand All @@ -181,14 +182,14 @@ async function openapiTS(schema: string | URL | OpenAPI3 | Readable, options: Op

outer: for (const [name, schemaObject] of getEntries(subschema.schema!)) {
if (!schemaObject || typeof schemaObject !== "object") continue;
const c = getSchemaObjectComment(schemaObject as any, indentLv);
const c = getSchemaObjectComment(schemaObject as SchemaObject, indentLv);
if (c) subschemaOutput += indent(c, indentLv);

// This might be a Path Item Object; only way to test is if top-level contains a method (not allowed on Schema Object)
if (!("type" in schemaObject) && !("$ref" in schemaObject)) {
for (const method of ["get", "put", "post", "delete", "options", "head", "patch", "trace"] as Method[]) {
if (method in schemaObject) {
subschemaOutput += indent(`${escObjKey(name)}: ${transformPathItemObject(schemaObject as any, { path: `${path}${name}`, ctx: { ...ctx, indentLv } })};\n`, indentLv);
subschemaOutput += indent(`${escObjKey(name)}: ${transformPathItemObject(schemaObject, { path: `${path}${name}`, ctx: { ...ctx, indentLv } })};\n`, indentLv);
continue outer;
}
}
Expand All @@ -207,7 +208,7 @@ async function openapiTS(schema: string | URL | OpenAPI3 | Readable, options: Op
break;
}
default: {
error(`Could not resolve subschema ${subschemaID}. Unknown type "${(subschema as any).hint}".`);
error(`Could not resolve subschema ${subschemaID}. Unknown type "${subschema.hint}".`);
process.exit(1);
}
}
Expand Down Expand Up @@ -244,7 +245,7 @@ async function openapiTS(schema: string | URL | OpenAPI3 | Readable, options: Op
"type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never };",
"type XOR<T, U> = (T | U) extends object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U;",
"type OneOf<T extends any[]> = T extends [infer Only] ? Only : T extends [infer A, infer B, ...infer Rest] ? OneOf<[XOR<A, B>, ...Rest]> : never;",
""
"",
);
}

Expand Down
34 changes: 17 additions & 17 deletions packages/openapi-typescript/src/load.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,20 @@ interface SchemaMap {
const EXT_RE = /\.(yaml|yml|json)$/i;
export const VIRTUAL_JSON_URL = `file:///_json`; // fake URL reserved for dynamic JSON

function parseYAML(schema: any): any {
function parseYAML(schema: string) {
try {
return yaml.load(schema);
} catch (err: any) {
error(`YAML: ${err.toString()}`);
} catch (err) {
error(`YAML: ${String(err)}`);
process.exit(1);
}
}

function parseJSON(schema: any): any {
function parseJSON(schema: string) {
try {
return JSON.parse(schema);
} catch (err: any) {
error(`JSON: ${err.toString()}`);
} catch (err) {
error(`JSON: ${String(err)}`);
process.exit(1);
}
}
Expand Down Expand Up @@ -56,7 +56,7 @@ export function resolveSchema(filename: string): URL {
* @param {HTTPHeaderMap} httpHeaders
* @return {Record<string, string>} {Record<string, string>} Final HTTP headers outcome.
*/
function parseHttpHeaders(httpHeaders: Record<string, any>): Record<string, any> {
function parseHttpHeaders(httpHeaders: Record<string, unknown>): Record<string, unknown> {
const finalHeaders: Record<string, string> = {};

// Obtain the header key
Expand Down Expand Up @@ -84,7 +84,7 @@ export interface LoadOptions extends GlobalContext {
rootURL: URL;
schemas: SchemaMap;
urlCache: Set<string>;
httpHeaders?: Record<string, any>;
httpHeaders?: Record<string, unknown>;
httpMethod?: string;
fetch: Fetch;
parameters: Record<string, ParameterObject>;
Expand All @@ -108,14 +108,14 @@ export default async function load(schema: URL | Subschema | Readable, options:

// remote
if (schema.protocol.startsWith("http")) {
const headers: Record<string, any> = { "User-Agent": "openapi-typescript" };
const headers: Record<string, string> = { "User-Agent": "openapi-typescript" };
if (options.auth) headers.Authorization = options.auth;

// Add custom parsed HTTP headers
if (options.httpHeaders) {
const parsedHeaders = parseHttpHeaders(options.httpHeaders);
for (const [k, v] of Object.entries(parsedHeaders)) {
headers[k] = v;
headers[k] = v as string;
}
}
const res = await options.fetch(schema, {
Expand All @@ -131,7 +131,7 @@ export default async function load(schema: URL | Subschema | Readable, options:
} else if (ext === ".yaml" || ext === ".yml" || contentType?.includes("yaml")) {
options.schemas[schemaID] = {
hint,
schema: parseYAML(await res.text()),
schema: parseYAML(await res.text()) as any, // eslint-disable-line @typescript-eslint/no-explicit-any
};
}
}
Expand All @@ -141,7 +141,7 @@ export default async function load(schema: URL | Subschema | Readable, options:
if (ext === ".yaml" || ext === ".yml")
options.schemas[schemaID] = {
hint,
schema: parseYAML(contents),
schema: parseYAML(contents) as any, // eslint-disable-line @typescript-eslint/no-explicit-any
};
else if (ext === ".json")
options.schemas[schemaID] = {
Expand Down Expand Up @@ -191,12 +191,12 @@ export default async function load(schema: URL | Subschema | Readable, options:
if ("components" in currentSchema && currentSchema.components && "examples" in currentSchema.components) delete currentSchema.components.examples;
}

const refPromises: Promise<any>[] = [];
const refPromises: Promise<unknown>[] = [];
walk(currentSchema, (rawNode, nodePath) => {
// filter custom properties from allOf, anyOf, oneOf
for (const k of ["allOf", "anyOf", "oneOf"]) {
if (Array.isArray(rawNode[k])) {
rawNode[k] = (rawNode as any)[k].filter((o: SchemaObject | ReferenceObject) => {
rawNode[k] = (rawNode as Record<string, SchemaObject[]>)[k].filter((o: SchemaObject | ReferenceObject) => {
if (!o || typeof o !== "object" || Array.isArray(o)) throw new Error(`${nodePath}.${k}: Expected array of objects. Is your schema valid?`);
if (!("$ref" in o) || typeof o.$ref !== "string") return true;
const ref = parseRef(o.$ref);
Expand All @@ -214,7 +214,7 @@ export default async function load(schema: URL | Subschema | Readable, options:
}
// $ref with custom "x-*" property
if (ref.path.some((i) => i.startsWith("x-"))) {
delete (node as any).$ref;
delete (node as unknown as Record<string, unknown>).$ref;
return;
}

Expand Down Expand Up @@ -255,7 +255,7 @@ export default async function load(schema: URL | Subschema | Readable, options:
// 3. transform $refs once, at the root schema, after all have been scanned & downloaded (much easier to do here when we have the context)
if (schemaID === ".") {
for (const subschemaID of Object.keys(options.schemas)) {
walk(options.schemas[subschemaID].schema, (rawNode, nodePath) => {
walk(options.schemas[subschemaID].schema, (rawNode) => {
if (!("$ref" in rawNode) || typeof rawNode.$ref !== "string") return;

const node = rawNode as unknown as ReferenceObject;
Expand Down Expand Up @@ -285,7 +285,7 @@ export default async function load(schema: URL | Subschema | Readable, options:
// note: 'in' is a unique required property of parameters. and parameters can live in subschemas (i.e. "parameters" doesn’t have to be part of the traceable path)
if (typeof rawNode === "object" && "in" in rawNode) {
const key = k === "." ? makeTSIndex(nodePath) : makeTSIndex(["external", k, ...nodePath]);
options.parameters[key] = rawNode as any;
options.parameters[key] = rawNode as unknown as ParameterObject;
}
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,8 @@ export default function transformComponentsObject(components: ComponentsObject,
path: `#/components/requestBodies/${name}`,
ctx: { ...ctx, indentLv },
})};`,
indentLv
)
indentLv,
),
);
} else {
if (!requestBodyObject.required) key = tsOptionalProperty(key);
Expand Down Expand Up @@ -164,8 +164,8 @@ export default function transformComponentsObject(components: ComponentsObject,
path: `#/components/pathItems/${name}`,
ctx: { ...ctx, indentLv },
})};`,
indentLv
)
indentLv,
),
);
}
}
Expand Down
Loading