api 7.0.0-alpha.0 → 7.0.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {};
package/dist/bin.js ADDED
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ const commander_1 = require("commander");
30
+ const commands_1 = __importDefault(require("./commands"));
31
+ const pkg = __importStar(require("./packageInfo"));
32
+ (async () => {
33
+ const program = new commander_1.Command();
34
+ program.name(pkg.PACKAGE_NAME);
35
+ program.version(pkg.PACKAGE_VERSION);
36
+ /**
37
+ * Instead of using Commander's `executableDir` API for loading in external command files we're
38
+ * programatically doing it like this because it's cleaner for us to let Commander manage option
39
+ * and argument parsing within this file than having each command manage that itself.
40
+ */
41
+ Object.entries(commands_1.default).forEach(([, cmd]) => {
42
+ program.addCommand(cmd);
43
+ });
44
+ await program.parseAsync(process.argv);
45
+ })();
@@ -0,0 +1,4 @@
1
+ import type CodeGeneratorLanguage from './language';
2
+ import type Oas from 'oas';
3
+ export type SupportedLanguages = 'js' | 'js-cjs' | 'js-esm' | 'ts';
4
+ export default function codegen(language: SupportedLanguages, spec: Oas, specPath: string, identifier: string): CodeGeneratorLanguage;
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const typescript_1 = __importDefault(require("./languages/typescript"));
7
+ function codegen(language, spec, specPath, identifier) {
8
+ switch (language) {
9
+ case 'js':
10
+ throw new TypeError('An export format of CommonJS or ECMAScript is required for JavaScript compilation.');
11
+ case 'js-cjs':
12
+ case 'js-esm':
13
+ case 'ts':
14
+ return new typescript_1.default(spec, specPath, identifier, {
15
+ outputJS: ['js-cjs', 'js-esm'].includes(language),
16
+ // TS will always generate with ESM-like exports.
17
+ compilerTarget: language === 'js-cjs' ? 'cjs' : 'esm',
18
+ });
19
+ default:
20
+ throw new TypeError(`Unsupported language supplied: ${language}`);
21
+ }
22
+ }
23
+ exports.default = codegen;
@@ -0,0 +1,27 @@
1
+ import type Storage from '../storage';
2
+ import type Oas from 'oas';
3
+ export interface InstallerOptions {
4
+ /**
5
+ * Will initiate a dry run install process. Used for simulating installations within a unit test.
6
+ */
7
+ dryRun?: boolean;
8
+ /**
9
+ * Used for stubbing out the logger that we use within the installation process so it can be
10
+ * easily introspected without having to mock out `console.*`.
11
+ */
12
+ logger?: (msg: string) => void;
13
+ }
14
+ export default abstract class CodeGeneratorLanguage {
15
+ spec: Oas;
16
+ specPath: string;
17
+ identifier: string;
18
+ userAgent: string;
19
+ requiredPackages: Record<string, {
20
+ reason: string;
21
+ url: string;
22
+ }>;
23
+ constructor(spec: Oas, specPath: string, identifier: string);
24
+ abstract generator(): Promise<Record<string, string>>;
25
+ abstract installer(storage: Storage, opts?: InstallerOptions): Promise<void>;
26
+ hasRequiredPackages(): boolean;
27
+ }
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const packageInfo_1 = require("../packageInfo");
4
+ class CodeGeneratorLanguage {
5
+ spec;
6
+ specPath;
7
+ identifier;
8
+ userAgent;
9
+ requiredPackages;
10
+ constructor(spec, specPath, identifier) {
11
+ this.spec = spec;
12
+ this.specPath = specPath;
13
+ this.identifier = identifier;
14
+ // User agents should be contextual to the spec in question and the version of `api` that was
15
+ // used to generate the SDK. For example, this'll look like `petstore/1.0.0 (api/4.2.0)` for
16
+ // a `petstore` spec installed on api@4.2.0.
17
+ const info = spec.getDefinition().info;
18
+ this.userAgent = `${identifier}/${info.version} (${packageInfo_1.PACKAGE_NAME}/${packageInfo_1.PACKAGE_VERSION})`;
19
+ /**
20
+ * This check is barbaric but there are a number of issues with how the `transformer` work we
21
+ * have in `oas` and in `.getParametersAsJSONSchema()` and `.getResponseAsJSONSchema()` that
22
+ * are fully crashing when attempting to codegen an SDK for an API definition that has a
23
+ * circular reference.
24
+ *
25
+ * In order to get v5 out the door we're not going to support this case initialy.
26
+ *
27
+ * @see {@link https://github.com/readmeio/api/issues/549}
28
+ */
29
+ if (JSON.stringify(spec.api).includes('"$ref":"#/')) {
30
+ throw new Error('Sorry, this library does not yet support generating an SDK for an OpenAPI definition that contains circular references.');
31
+ }
32
+ }
33
+ hasRequiredPackages() {
34
+ return Boolean(Object.keys(this.requiredPackages));
35
+ }
36
+ }
37
+ exports.default = CodeGeneratorLanguage;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * @see {@link https://www.30secondsofcode.org/js/s/word-wrap}
3
+ */
4
+ export declare function wordWrap(str: string, max?: number): string;
5
+ /**
6
+ * Safely escape some string characters that may break a docblock.
7
+ *
8
+ */
9
+ export declare function docblockEscape(str: string): string;
10
+ export declare function generateTypeName(...parts: string[]): string;
@@ -0,0 +1,170 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.generateTypeName = exports.docblockEscape = exports.wordWrap = void 0;
7
+ const lodash_camelcase_1 = __importDefault(require("lodash.camelcase"));
8
+ const lodash_deburr_1 = __importDefault(require("lodash.deburr"));
9
+ const lodash_startcase_1 = __importDefault(require("lodash.startcase"));
10
+ /**
11
+ * This is a mix of reserved JS words and keywords in TypeScript that might be reserved or
12
+ * allowable but functionally confusing (like `let any = 'buster';`)
13
+ *
14
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar}
15
+ */
16
+ const RESERVED_WORDS = [
17
+ 'abstract',
18
+ 'any',
19
+ 'arguments',
20
+ 'as',
21
+ 'async',
22
+ 'await',
23
+ 'boolean',
24
+ 'break',
25
+ 'byte',
26
+ 'case',
27
+ 'catch',
28
+ 'char',
29
+ 'class',
30
+ 'const',
31
+ 'continue',
32
+ 'constructor',
33
+ 'debugger',
34
+ 'default',
35
+ 'delete',
36
+ 'do',
37
+ 'double',
38
+ 'else',
39
+ 'enum',
40
+ 'eval',
41
+ 'export',
42
+ 'extends',
43
+ 'false',
44
+ 'final',
45
+ 'finally',
46
+ 'float',
47
+ 'for',
48
+ 'from',
49
+ 'function',
50
+ 'get',
51
+ 'goto',
52
+ 'if',
53
+ 'implements',
54
+ 'import',
55
+ 'interface',
56
+ 'in',
57
+ 'instanceof',
58
+ 'int',
59
+ 'let',
60
+ 'long',
61
+ 'native',
62
+ 'new',
63
+ 'null',
64
+ 'number',
65
+ 'of',
66
+ 'package',
67
+ 'private',
68
+ 'protected',
69
+ 'public',
70
+ 'module',
71
+ 'namespace',
72
+ 'return',
73
+ 'set',
74
+ 'short',
75
+ 'static',
76
+ 'string',
77
+ 'super',
78
+ 'switch',
79
+ 'synchronized',
80
+ 'this',
81
+ 'throw',
82
+ 'throws',
83
+ 'transient',
84
+ 'true',
85
+ 'try',
86
+ 'type',
87
+ 'typeof',
88
+ 'var',
89
+ 'void',
90
+ 'while',
91
+ 'with',
92
+ 'volatile',
93
+ 'yield',
94
+ // These aren't reserved keywords but because we maybe codegen'ing an SDK to be used in the
95
+ // browser it'd be very bad if we overwrote these. This obviously doesn't account for browser APIs
96
+ // you can access outside of the `Window` API (like `alert()`), but we can add checks for those
97
+ // later if we need to.
98
+ 'frames',
99
+ 'global',
100
+ 'globalThis',
101
+ 'navigator',
102
+ 'self',
103
+ 'window',
104
+ ];
105
+ /**
106
+ * @see {@link https://www.30secondsofcode.org/js/s/word-wrap}
107
+ */
108
+ function wordWrap(str, max = 88) {
109
+ return str.replace(new RegExp(`(?![^\\n]{1,${max}}$)([^\\n]{1,${max}})\\s`, 'g'), '$1\n');
110
+ }
111
+ exports.wordWrap = wordWrap;
112
+ /**
113
+ * Safely escape some string characters that may break a docblock.
114
+ *
115
+ */
116
+ function docblockEscape(str) {
117
+ return str.replace(/\/\*/g, '/\\*').replace(/\*\//g, '*\\/');
118
+ }
119
+ exports.docblockEscape = docblockEscape;
120
+ /**
121
+ * Convert a string that might contain spaces or special characters to one that can safely be used
122
+ * as a TypeScript interface or enum name.
123
+ *
124
+ * This function has been adapted and slighty modified from `json-schema-to-typescript`.
125
+ *
126
+ * @license MIT
127
+ * @see {@link https://github.com/bcherny/json-schema-to-typescript}
128
+ */
129
+ function toSafeString(str) {
130
+ // identifiers in javaScript/ts:
131
+ // First character: a-zA-Z | _ | $
132
+ // Rest: a-zA-Z | _ | $ | 0-9
133
+ // remove accents, umlauts, ... by their basic latin letters
134
+ return ((0, lodash_deburr_1.default)(str)
135
+ // if the string starts with a number, prefix it with character that typescript can accept
136
+ // https://github.com/bcherny/json-schema-to-typescript/issues/489
137
+ .replace(/^(\d){1}/, '$$1')
138
+ // replace chars which are not valid for typescript identifiers with whitespace
139
+ .replace(/(^\s*[^a-zA-Z_$])|([^a-zA-Z_$\d])/g, ' ')
140
+ // uppercase leading underscores followed by lowercase
141
+ .replace(/^_[a-z]/g, (match) => match.toUpperCase())
142
+ // remove non-leading underscores followed by lowercase (convert snake_case)
143
+ .replace(/_[a-z]/g, (match) => match.substr(1, match.length).toUpperCase())
144
+ // uppercase letters after digits, dollars
145
+ .replace(/([\d$]+[a-zA-Z])/g, (match) => match.toUpperCase())
146
+ // uppercase first letter after whitespace
147
+ .replace(/\s+([a-zA-Z])/g, (match) => match.toUpperCase().trim())
148
+ // remove remaining whitespace
149
+ .replace(/\s/g, ''));
150
+ }
151
+ function generateTypeName(...parts) {
152
+ let str;
153
+ // If the end of our string ends with something like `2XX`, the combination of `startCase` and
154
+ // `camelCase` will transform it into `2Xx`.
155
+ if (parts.length > 1) {
156
+ const last = parts[parts.length - 1];
157
+ if (last.match(/^(\d)XX$/)) {
158
+ str = (0, lodash_startcase_1.default)((0, lodash_camelcase_1.default)(parts.slice(0, -1).join(' ')));
159
+ str += ` ${last}`;
160
+ }
161
+ }
162
+ if (!str) {
163
+ str = (0, lodash_startcase_1.default)((0, lodash_camelcase_1.default)(parts.join(' ')));
164
+ }
165
+ if (RESERVED_WORDS.includes(str.toLowerCase())) {
166
+ str = `$${str}`;
167
+ }
168
+ return toSafeString(str);
169
+ }
170
+ exports.generateTypeName = generateTypeName;
@@ -0,0 +1,111 @@
1
+ import type Storage from '../../storage';
2
+ import type { InstallerOptions } from '../language';
3
+ import type Oas from 'oas';
4
+ import type Operation from 'oas/operation';
5
+ import type { HttpMethods, SchemaObject } from 'oas/rmoas.types';
6
+ import type { ClassDeclaration, JSDocStructure, JSDocTagStructure, OptionalKind } from 'ts-morph';
7
+ import { Project } from 'ts-morph';
8
+ import CodeGeneratorLanguage from '../language';
9
+ export interface TSGeneratorOptions {
10
+ compilerTarget?: 'cjs' | 'esm';
11
+ outputJS?: boolean;
12
+ }
13
+ interface OperationTypeHousing {
14
+ operation: Operation;
15
+ types: {
16
+ params?: false | Record<'body' | 'formData' | 'metadata', string>;
17
+ responses?: Record<string | number, {
18
+ description?: string;
19
+ type: string;
20
+ }>;
21
+ };
22
+ }
23
+ export default class TSGenerator extends CodeGeneratorLanguage {
24
+ project: Project;
25
+ outputJS: boolean;
26
+ compilerTarget: 'cjs' | 'esm';
27
+ types: Map<string, string>;
28
+ sdk: ClassDeclaration;
29
+ schemas: Record<string, {
30
+ body?: unknown;
31
+ metadata?: unknown;
32
+ response?: Record<string, unknown>;
33
+ } | Record<string, unknown>>;
34
+ usesHTTPMethodRangeInterface: boolean;
35
+ constructor(spec: Oas, specPath: string, identifier: string, opts?: TSGeneratorOptions);
36
+ installer(storage: Storage, opts?: InstallerOptions): Promise<void>;
37
+ /**
38
+ * Compile the current OpenAPI definition into a TypeScript library.
39
+ *
40
+ */
41
+ generator(): Promise<{
42
+ [x: string]: string;
43
+ }>;
44
+ /**
45
+ * Create our main SDK source file.
46
+ *
47
+ */
48
+ createSourceFile(): import("ts-morph").SourceFile;
49
+ /**
50
+ * Create our main schemas file. This is where all of the JSON Schema that our TypeScript typing
51
+ * infrastructure sources its data from. Without this there are no types.
52
+ *
53
+ */
54
+ createSchemasFile(): import("ts-morph").SourceFile;
55
+ /**
56
+ * Create our main types file. This sources its data from the JSON Schema `schemas.ts` file and
57
+ * will re-export types to be used in TypeScript implementations and IDE intellisense. This
58
+ * typing work is functional with the `json-schema-to-ts` library.
59
+ *
60
+ * @see {@link https://npm.im/json-schema-to-ts}
61
+ */
62
+ createTypesFile(): import("ts-morph").SourceFile;
63
+ /**
64
+ * Add a new JSDoc `@tag` to an existing docblock.
65
+ *
66
+ */
67
+ static addTagToDocblock(docblock: OptionalKind<JSDocStructure>, tag: OptionalKind<JSDocTagStructure>): {
68
+ tags: OptionalKind<JSDocTagStructure>[];
69
+ description?: string | import("ts-morph").WriterFunction | undefined;
70
+ leadingTrivia?: string | import("ts-morph").WriterFunction | (string | import("ts-morph").WriterFunction)[] | undefined;
71
+ trailingTrivia?: string | import("ts-morph").WriterFunction | (string | import("ts-morph").WriterFunction)[] | undefined;
72
+ kind?: import("ts-morph").StructureKind.JSDoc | undefined;
73
+ };
74
+ /**
75
+ * Create operation accessors on the SDK.
76
+ *
77
+ */
78
+ createOperationAccessor(operation: Operation, operationId: string, paramTypes?: OperationTypeHousing['types']['params'], responseTypes?: OperationTypeHousing['types']['responses']): void;
79
+ /**
80
+ * Scour through the current OpenAPI definition and compile a store of every operation, along
81
+ * with every HTTP method that's in use, and their available TypeScript types that we can use,
82
+ * along with every HTTP method that's in use.
83
+ *
84
+ */
85
+ loadOperationsAndMethods(): {
86
+ operations: Record<string, OperationTypeHousing>;
87
+ methods: Set<HttpMethods>;
88
+ };
89
+ /**
90
+ * Compile the parameter (path, query, cookie, and header) schemas for an API operation into
91
+ * usable TypeScript types.
92
+ *
93
+ */
94
+ prepareParameterTypesForOperation(operation: Operation, operationId: string): false | Record<"body" | "formData" | "metadata", string>;
95
+ /**
96
+ * Compile the response schemas for an API operation into usable TypeScript types.
97
+ *
98
+ */
99
+ prepareResponseTypesForOperation(operation: Operation, operationId: string): {
100
+ [x: string]: {
101
+ type: string;
102
+ description: any;
103
+ };
104
+ } | undefined;
105
+ /**
106
+ * Add a given schema into our schema dataset that we'll be be exporting as types.
107
+ *
108
+ */
109
+ addSchemaToExport(schema: SchemaObject, typeName: string, pointer: string): void;
110
+ }
111
+ export {};