New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

openapi-typescript

Package Overview
Dependencies
Maintainers
1
Versions
145
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

openapi-typescript - npm Package Compare versions

Comparing version 6.0.3 to 6.1.0

dist/transform/webhooks-object.d.ts

9

bin/cli.js
#!/usr/bin/env node
import fs from "node:fs";
import path from "path";
import { URL } from "node:url";

@@ -180,4 +181,8 @@ import glob from "fast-glob";

if (flags.output !== "." && output === OUTPUT_FILE) {
if (isGlob) outputDir = new URL(specPath, outputDir);
fs.mkdirSync(outputDir, { recursive: true }); // recursively make parent dirs
if (isGlob) {
fs.mkdirSync(new URL(path.dirname(specPath), outputDir), { recursive: true }); // recursively make parent dirs
}
else {
fs.mkdirSync(outputDir, { recursive: true }); // recursively make parent dirs
}
}

@@ -184,0 +189,0 @@ await generateSchema(specPath);

@@ -10,3 +10,3 @@ import { URL } from "node:url";

import transformSchemaObject from "./transform/schema-object.js";
import { error, escObjKey, getEntries, indent } from "./utils.js";
import { error, escObjKey, getDefaultFetch, getEntries, indent } from "./utils.js";
export * from "./types.js";

@@ -46,2 +46,3 @@ const EMPTY_OBJECT_RE = /^\s*\{?\s*\}?\s*$/;

httpMethod: options.httpMethod,
fetch: options.fetch ?? getDefaultFetch(),
});

@@ -69,3 +70,2 @@ for (const k of Object.keys(allSchemas)) {

}
output.push("/** Type helpers */", "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;", "");
if (options.inject)

@@ -162,2 +162,5 @@ output.push(options.inject);

}
if (output.join("\n").includes("OneOf")) {
output.splice(1, 0, "/** Type helpers */", "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;", "");
}
return output.join("\n");

@@ -164,0 +167,0 @@ }

/// <reference types="node" />
/// <reference types="node" />
import type { GlobalContext, Subschema } from "./types";
import type { Fetch, GlobalContext, Subschema } from "./types";
import { Readable } from "node:stream";
import { URL } from "node:url";
declare type SchemaMap = {
type SchemaMap = {
[id: string]: Subschema;

@@ -11,3 +11,3 @@ };

export declare function resolveSchema(filename: string): URL;
interface LoadOptions extends GlobalContext {
export interface LoadOptions extends GlobalContext {
hint?: Subschema["hint"];

@@ -20,2 +20,3 @@ auth?: string;

httpMethod?: string;
fetch: Fetch;
}

@@ -22,0 +23,0 @@ export default function load(schema: URL | Subschema | Readable, options: LoadOptions): Promise<{

@@ -6,3 +6,2 @@ import fs from "node:fs";

import yaml from "js-yaml";
import { request } from "undici";
import { parseRef, error, makeTSIndex, walk, isRemoteURL, isFilepath } from "./utils.js";

@@ -82,10 +81,11 @@ export const VIRTUAL_JSON_URL = `file:///_json`;

}
const res = await request(schema, { method: options.httpMethod || "GET", headers });
const contentType = Array.isArray(res.headers["Content-Type"])
? res.headers["Content-Type"][0]
: res.headers["Content-Type"];
const res = await options.fetch(schema, {
method: options.httpMethod || "GET",
headers,
});
const contentType = res.headers.get("content-type");
if (ext === ".json" || (contentType && contentType.includes("json"))) {
options.schemas[schemaID] = {
hint,
schema: parseJSON(await res.body.text()),
schema: parseJSON(await res.text()),
};

@@ -96,3 +96,3 @@ }

hint,
schema: parseYAML(await res.body.text()),
schema: parseYAML(await res.text()),
};

@@ -99,0 +99,0 @@ }

import transformComponentsObject from "./components-object.js";
import transformPathsObject from "./paths-object.js";
import transformWebhooksObject from "./webhooks-object.js";
export function transformSchema(schema, ctx) {

@@ -11,2 +12,6 @@ if (!schema)

output.paths = "";
if (schema.webhooks)
output.webhooks = transformWebhooksObject(schema.webhooks, ctx);
else
output.webhooks = "";
if (schema.components)

@@ -13,0 +18,0 @@ output.components = transformComponentsObject(schema.components, ctx);

@@ -5,3 +5,4 @@ import type { GlobalContext, OperationObject } from "../types";

ctx: GlobalContext;
wrapObject?: boolean;
}
export default function transformOperationObject(operationObject: OperationObject, { path, ctx }: TransformOperationObjectOptions): string;
export default function transformOperationObject(operationObject: OperationObject, { path, ctx, wrapObject }: TransformOperationObjectOptions): string;

@@ -6,5 +6,5 @@ import { escObjKey, getEntries, getSchemaObjectComment, indent, makeTSIndex, parseTSIndex, tsIntersectionOf, tsNonNullable, tsOptionalProperty, tsPick, tsReadonly, } from "../utils.js";

import transformSchemaObject from "./schema-object.js";
export default function transformOperationObject(operationObject, { path, ctx }) {
export default function transformOperationObject(operationObject, { path, ctx, wrapObject = true }) {
let { indentLv } = ctx;
const output = ["{"];
const output = wrapObject ? ["{"] : [];
indentLv++;

@@ -126,5 +126,7 @@ const c = getSchemaObjectComment(operationObject, indentLv);

indentLv--;
output.push(indent("}", indentLv));
if (wrapObject) {
output.push(indent("}", indentLv));
}
return output.join("\n");
}
//# sourceMappingURL=operation-object.js.map
import { escStr, getSchemaObjectComment, indent } from "../utils.js";
import transformOperationObject from "./operation-object.js";
const UNWRAP_OBJ_RE = /^\s*{\s*([^.]+)\s*}\s*$/;
export default function transformPathItemObject(pathItem, { path, ctx }) {

@@ -30,5 +29,3 @@ let { indentLv } = ctx;

if (pathItem.parameters && pathItem.parameters.length) {
output.push(indent(transformOperationObject({ parameters: pathItem.parameters }, { path, ctx })
.replace(UNWRAP_OBJ_RE, "$1")
.trim(), indentLv));
output.push(indent(transformOperationObject({ parameters: pathItem.parameters }, { path, ctx, wrapObject: false }).trim(), indentLv));
}

@@ -35,0 +32,0 @@ indentLv--;

/// <reference types="node" />
import type { URL } from "node:url";
import type { TransformSchemaObjectOptions } from "./transform/schema-object";
import type { RequestInfo, RequestInit, Response } from "undici";
export interface Extensable {

@@ -64,5 +65,8 @@ [key: `x-${string}`]: any;

}
export declare type PathsObject = {
export type PathsObject = {
[pathname: string]: PathItemObject;
};
export type WebhooksObject = {
[name: string]: PathItemObject;
};
export interface PathItemObject extends Extensable {

@@ -143,3 +147,3 @@ get?: OperationObject | ReferenceObject;

}
export declare type ResponsesObject = {
export type ResponsesObject = {
[responseCode: string]: ResponseObject | ReferenceObject;

@@ -161,3 +165,3 @@ } & {

}
export declare type CallbackObject = Record<string, PathItemObject>;
export type CallbackObject = Record<string, PathItemObject>;
export interface ExampleObject extends Extensable {

@@ -179,3 +183,3 @@ summary?: string;

}
export declare type HeaderObject = Omit<ParameterObject, "name" | "in">;
export type HeaderObject = Omit<ParameterObject, "name" | "in">;
export interface TagObject extends Extensable {

@@ -191,3 +195,3 @@ name: string;

}
export declare type SchemaObject = {
export type SchemaObject = {
discriminator?: DiscriminatorObject;

@@ -260,3 +264,3 @@ xml?: XMLObject;

}
export declare type SecuritySchemeObject = {
export type SecuritySchemeObject = {
description?: string;

@@ -295,3 +299,3 @@ [key: `x-${string}`]: any;

}
export declare type SecurityRequirementObject = Record<keyof ComponentsObject["securitySchemes"], string[]>;
export type SecurityRequirementObject = Record<keyof ComponentsObject["securitySchemes"], string[]>;
export interface OpenAPITSOptions {

@@ -315,4 +319,5 @@ additionalProperties?: boolean;

inject?: string;
fetch?: Fetch;
}
export declare type Subschema = {
export type Subschema = {
hint: "LinkObject";

@@ -361,1 +366,2 @@ schema: LinkObject;

}
export type Fetch = (input: RequestInfo, init?: RequestInit) => Promise<Response>;
import c from "ansi-colors";
import { Fetch } from "types";
export { c };
declare type CommentObject = {
type CommentObject = {
const?: unknown;

@@ -47,1 +48,2 @@ default?: unknown;

export declare function isFilepath(url: string): boolean;
export declare function getDefaultFetch(): Fetch;
import c from "ansi-colors";
import { isAbsolute } from "node:path";
import supportsColor from "supports-color";
import { fetch as unidiciFetch } from "undici";
if (!supportsColor.stdout || supportsColor.stdout.hasBasic === false)

@@ -171,2 +172,9 @@ c.enabled = false;

}
export function getDefaultFetch() {
const globalFetch = globalThis.fetch;
if (typeof globalFetch === "undefined") {
return unidiciFetch;
}
return globalFetch;
}
//# sourceMappingURL=utils.js.map
{
"name": "openapi-typescript",
"description": "Generate TypeScript types from Swagger OpenAPI specs",
"version": "6.0.3",
"version": "6.1.0",
"author": "drew@pow.rs",

@@ -61,16 +61,16 @@ "license": "MIT",

"@types/node": "^18.11.9",
"@typescript-eslint/eslint-plugin": "^5.42.1",
"@typescript-eslint/parser": "^5.42.1",
"@vitest/coverage-c8": "^0.25.1",
"@typescript-eslint/eslint-plugin": "^5.44.0",
"@typescript-eslint/parser": "^5.44.0",
"@vitest/coverage-c8": "^0.25.3",
"degit": "^2.8.4",
"del-cli": "^5.0.0",
"eslint": "^8.27.0",
"eslint": "^8.28.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-prettier": "^4.2.1",
"execa": "^6.1.0",
"prettier": "^2.7.1",
"typescript": "^4.8.4",
"vite-node": "^0.25.1",
"vitest": "^0.25.1"
"prettier": "^2.8.0",
"typescript": "^4.9.3",
"vite-node": "^0.25.3",
"vitest": "^0.25.3"
}
}

@@ -6,3 +6,3 @@ [![version(scoped)](https://img.shields.io/npm/v/openapi-typescript.svg)](https://www.npmjs.com/package/openapi-typescript)

<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-55-orange.svg?style=flat-square)](#contributors-)
[![All Contributors](https://img.shields.io/badge/all_contributors-60-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END -->

@@ -389,3 +389,10 @@

<td align="center"><a href="http://jeremyliberman.com/"><img src="https://avatars.githubusercontent.com/u/2754163?v=4?s=100" width="100px;" alt="Jeremy Liberman"/><br /><sub><b>Jeremy Liberman</b></sub></a><br /><a href="https://github.com/drwpow/openapi-typescript/commits?author=MrLeebo" title="Code">💻</a> <a href="https://github.com/drwpow/openapi-typescript/commits?author=MrLeebo" title="Tests">⚠️</a></td>
<td align="center"><a href="http://axelhzf.com"><img src="https://avatars.githubusercontent.com/u/175627?v=4?s=100" width="100px;" alt="Axel Hernández Ferrera"/><br /><sub><b>Axel Hernández Ferrera</b></sub></a><br /><a href="https://github.com/drwpow/openapi-typescript/commits?author=axelhzf" title="Code">💻</a> <a href="https://github.com/drwpow/openapi-typescript/issues?q=author%3Aaxelhzf" title="Bug reports">🐛</a> <a href="https://github.com/drwpow/openapi-typescript/commits?author=axelhzf" title="Tests">⚠️</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/imagoiq"><img src="https://avatars.githubusercontent.com/u/12294151?v=4?s=100" width="100px;" alt="Loïc Fürhoff"/><br /><sub><b>Loïc Fürhoff</b></sub></a><br /><a href="https://github.com/drwpow/openapi-typescript/commits?author=imagoiq" title="Code">💻</a> <a href="https://github.com/drwpow/openapi-typescript/commits?author=imagoiq" title="Tests">⚠️</a> <a href="https://github.com/drwpow/openapi-typescript/issues?q=author%3Aimagoiq" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/BTMPL"><img src="https://avatars.githubusercontent.com/u/247153?v=4?s=100" width="100px;" alt="Bartosz Szczeciński"/><br /><sub><b>Bartosz Szczeciński</b></sub></a><br /><a href="https://github.com/drwpow/openapi-typescript/commits?author=BTMPL" title="Code">💻</a> <a href="https://github.com/drwpow/openapi-typescript/issues?q=author%3ABTMPL" title="Bug reports">🐛</a> <a href="https://github.com/drwpow/openapi-typescript/commits?author=BTMPL" title="Tests">⚠️</a></td>
<td align="center"><a href="https://github.com/HiiiiD"><img src="https://avatars.githubusercontent.com/u/61231210?v=4?s=100" width="100px;" alt="Marco Salomone"/><br /><sub><b>Marco Salomone</b></sub></a><br /><a href="https://github.com/drwpow/openapi-typescript/commits?author=HiiiiD" title="Code">💻</a> <a href="https://github.com/drwpow/openapi-typescript/commits?author=HiiiiD" title="Tests">⚠️</a></td>
<td align="center"><a href="https://github.com/yacinehmito"><img src="https://avatars.githubusercontent.com/u/6893840?v=4?s=100" width="100px;" alt="Yacine Hmito"/><br /><sub><b>Yacine Hmito</b></sub></a><br /><a href="https://github.com/drwpow/openapi-typescript/commits?author=yacinehmito" title="Code">💻</a> <a href="https://github.com/drwpow/openapi-typescript/commits?author=yacinehmito" title="Tests">⚠️</a> <a href="https://github.com/drwpow/openapi-typescript/issues?q=author%3Ayacinehmito" title="Bug reports">🐛</a></td>
</tr>
</tbody>

@@ -392,0 +399,0 @@ </table>

@@ -12,3 +12,3 @@ import type { GlobalContext, OpenAPI3, OpenAPITSOptions, Subschema } from "./types";

import transformSchemaObject from "./transform/schema-object.js";
import { error, escObjKey, getEntries, indent } from "./utils.js";
import { error, escObjKey, getDefaultFetch, getEntries, indent } from "./utils.js";
export * from "./types.js"; // expose all types to consumers

@@ -71,2 +71,3 @@

httpMethod: options.httpMethod,
fetch: options.fetch ?? getDefaultFetch(),
});

@@ -99,15 +100,6 @@

// 2b. OneOf helper (@see https://github.com/Microsoft/TypeScript/issues/14094#issuecomment-723571692)
output.push(
"/** Type helpers */",
"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;",
""
);
// 2c. options.inject
// 2b. options.inject
if (options.inject) output.push(options.inject);
// 2d. root schema
// 2c. root schema
const rootTypes = transformSchema(allSchemas["."].schema as OpenAPI3, ctx);

@@ -127,3 +119,3 @@ for (const k of Object.keys(rootTypes)) {

// 2e. external schemas (subschemas)
// 2d. external schemas (subschemas)
const externalKeys = Object.keys(allSchemas); // root schema (".") should already be removed

@@ -205,2 +197,15 @@ if (externalKeys.length) {

// 4. OneOf type helper (@see https://github.com/Microsoft/TypeScript/issues/14094#issuecomment-723571692)
if (output.join("\n").includes("OneOf")) {
output.splice(
1,
0,
"/** Type helpers */",
"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;",
""
);
}
return output.join("\n");

@@ -207,0 +212,0 @@ }

import type {
ComponentsObject,
Fetch,
GlobalContext,

@@ -18,3 +19,3 @@ OpenAPI3,

import yaml from "js-yaml";
import { request, type Dispatcher } from "undici";
import type { Dispatcher } from "undici";
import { parseRef, error, makeTSIndex, walk, isRemoteURL, isFilepath } from "./utils.js";

@@ -91,3 +92,3 @@

interface LoadOptions extends GlobalContext {
export interface LoadOptions extends GlobalContext {
/** Subschemas may be any type; this helps transform correctly */

@@ -101,2 +102,3 @@ hint?: Subschema["hint"];

httpMethod?: string;
fetch: Fetch;
}

@@ -110,3 +112,2 @@

let schemaID = ".";
// 1. load contents

@@ -137,10 +138,11 @@ // 1a. URL

}
const res = await request(schema, { method: (options.httpMethod as Dispatcher.HttpMethod) || "GET", headers });
const contentType = Array.isArray(res.headers["Content-Type"])
? res.headers["Content-Type"][0]
: res.headers["Content-Type"];
const res = await options.fetch(schema, {
method: (options.httpMethod as Dispatcher.HttpMethod) || "GET",
headers,
});
const contentType = res.headers.get("content-type");
if (ext === ".json" || (contentType && contentType.includes("json"))) {
options.schemas[schemaID] = {
hint,
schema: parseJSON(await res.body.text()),
schema: parseJSON(await res.text()),
};

@@ -150,3 +152,3 @@ } else if (ext === ".yaml" || ext === ".yml" || (contentType && contentType.includes("yaml"))) {

hint,
schema: parseYAML(await res.body.text()),
schema: parseYAML(await res.text()),
};

@@ -153,0 +155,0 @@ }

import type { GlobalContext, OpenAPI3 } from "../types";
import transformComponentsObject from "./components-object.js";
import transformPathsObject from "./paths-object.js";
import transformWebhooksObject from "./webhooks-object.js";

@@ -15,2 +16,6 @@ /** transform top-level schema */

// webhooks
if (schema.webhooks) output.webhooks = transformWebhooksObject(schema.webhooks, ctx);
else output.webhooks = "";
// components

@@ -17,0 +22,0 @@ if (schema.components) output.components = transformComponentsObject(schema.components, ctx);

@@ -23,2 +23,3 @@ import type { GlobalContext, OperationObject, ParameterObject } from "../types";

ctx: GlobalContext;
wrapObject?: boolean;
}

@@ -28,6 +29,6 @@

operationObject: OperationObject,
{ path, ctx }: TransformOperationObjectOptions
{ path, ctx, wrapObject = true }: TransformOperationObjectOptions
): string {
let { indentLv } = ctx;
const output: string[] = ["{"];
const output: string[] = wrapObject ? ["{"] : [];
indentLv++;

@@ -159,4 +160,6 @@ const c = getSchemaObjectComment(operationObject, indentLv);

indentLv--;
output.push(indent("}", indentLv));
if (wrapObject) {
output.push(indent("}", indentLv));
}
return output.join("\n");
}

@@ -12,4 +12,2 @@ import type { GlobalContext, PathItemObject } from "../types";

const UNWRAP_OBJ_RE = /^\s*{\s*([^.]+)\s*}\s*$/;
export default function transformPathItemObject(

@@ -48,5 +46,3 @@ pathItem: PathItemObject,

indent(
transformOperationObject({ parameters: pathItem.parameters }, { path, ctx })
.replace(UNWRAP_OBJ_RE, "$1")
.trim(),
transformOperationObject({ parameters: pathItem.parameters }, { path, ctx, wrapObject: false }).trim(),
indentLv

@@ -53,0 +49,0 @@ )

import type { URL } from "node:url";
import type { TransformSchemaObjectOptions } from "./transform/schema-object";
import type { RequestInfo, RequestInit, Response } from "undici";

@@ -142,2 +143,8 @@ export interface Extensable {

/**
* [x.x.x] Webhooks Object
* Holds the webhooks definitions, indexed by their names. A webhook is defined by a Path Item Object; the only difference is that the request is initiated by the API provider.
*/
export type WebhooksObject = { [name: string]: PathItemObject };
/**
* [4.8.9] Path Item Object

@@ -606,2 +613,7 @@ * Describes the operations available on a single path. A Path Item MAY be empty, due to ACL constraints. The path itself is still exposed to the documentation viewer but they will not know which operations and parameters are available.

inject?: string;
/**
* (optional) A fetch implementation. Will default to the global fetch
* function if available; else, it will use unidici's fetch function.
*/
fetch?: Fetch;
}

@@ -636,1 +648,8 @@

}
// Fetch is available in the global scope starting with Node v18.
// However, @types/node does not have it yet available.
// GitHub issue: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/60924
// Because node's underlying implementation relies on unidici, it is safe to
// rely on unidici's type until @types/node ships it.
export type Fetch = (input: RequestInfo, init?: RequestInit) => Promise<Response>;
import c from "ansi-colors";
import { isAbsolute } from "node:path";
import supportsColor from "supports-color";
import { fetch as unidiciFetch } from "undici";
import { Fetch } from "types";

@@ -242,1 +244,9 @@ if (!supportsColor.stdout || supportsColor.stdout.hasBasic === false) c.enabled = false;

}
export function getDefaultFetch(): Fetch {
const globalFetch: Fetch | undefined = (globalThis as any).fetch;
if (typeof globalFetch === "undefined") {
return unidiciFetch;
}
return globalFetch;
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc