api 7.0.0-alpha.0 → 7.0.0-alpha.1

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,91 @@
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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ var __generator = (this && this.__generator) || function (thisArg, body) {
35
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
36
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
37
+ function verb(n) { return function (v) { return step([n, v]); }; }
38
+ function step(op) {
39
+ if (f) throw new TypeError("Generator is already executing.");
40
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
41
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
42
+ if (y = 0, t) op = [op[0] & 2, t.value];
43
+ switch (op[0]) {
44
+ case 0: case 1: t = op; break;
45
+ case 4: _.label++; return { value: op[1], done: false };
46
+ case 5: _.label++; y = op[1]; op = [0]; continue;
47
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
48
+ default:
49
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
50
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
51
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
52
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
53
+ if (t[2]) _.ops.pop();
54
+ _.trys.pop(); continue;
55
+ }
56
+ op = body.call(thisArg, _);
57
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
58
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
59
+ }
60
+ };
61
+ var __importDefault = (this && this.__importDefault) || function (mod) {
62
+ return (mod && mod.__esModule) ? mod : { "default": mod };
63
+ };
64
+ Object.defineProperty(exports, "__esModule", { value: true });
65
+ var commander_1 = require("commander");
66
+ var commands_1 = __importDefault(require("./commands"));
67
+ var pkg = __importStar(require("./packageInfo"));
68
+ (function () { return __awaiter(void 0, void 0, void 0, function () {
69
+ var program;
70
+ return __generator(this, function (_a) {
71
+ switch (_a.label) {
72
+ case 0:
73
+ program = new commander_1.Command();
74
+ program.name(pkg.PACKAGE_NAME);
75
+ program.version(pkg.PACKAGE_VERSION);
76
+ /**
77
+ * Instead of using Commander's `executableDir` API for loading in external command files we're
78
+ * programatically doing it like this because it's cleaner for us to let Commander manage option
79
+ * and argument parsing within this file than having each command manage that itself.
80
+ */
81
+ Object.entries(commands_1.default).forEach(function (_a) {
82
+ var cmd = _a[1];
83
+ program.addCommand(cmd);
84
+ });
85
+ return [4 /*yield*/, program.parseAsync(process.argv)];
86
+ case 1:
87
+ _a.sent();
88
+ return [2 /*return*/];
89
+ }
90
+ });
91
+ }); })();
@@ -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
+ var 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: ".concat(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,33 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ var packageInfo_1 = require("../packageInfo");
4
+ var CodeGeneratorLanguage = /** @class */ (function () {
5
+ function CodeGeneratorLanguage(spec, specPath, identifier) {
6
+ this.spec = spec;
7
+ this.specPath = specPath;
8
+ this.identifier = identifier;
9
+ // User agents should be contextual to the spec in question and the version of `api` that was
10
+ // used to generate the SDK. For example, this'll look like `petstore/1.0.0 (api/4.2.0)` for
11
+ // a `petstore` spec installed on api@4.2.0.
12
+ var info = spec.getDefinition().info;
13
+ this.userAgent = "".concat(identifier, "/").concat(info.version, " (").concat(packageInfo_1.PACKAGE_NAME, "/").concat(packageInfo_1.PACKAGE_VERSION, ")");
14
+ /**
15
+ * This check is barbaric but there are a number of issues with how the `transformer` work we
16
+ * have in `oas` and in `.getParametersAsJSONSchema()` and `.getResponseAsJSONSchema()` that
17
+ * are fully crashing when attempting to codegen an SDK for an API definition that has a
18
+ * circular reference.
19
+ *
20
+ * In order to get v5 out the door we're not going to support this case initialy.
21
+ *
22
+ * @see {@link https://github.com/readmeio/api/issues/549}
23
+ */
24
+ if (JSON.stringify(spec.api).includes('"$ref":"#/')) {
25
+ throw new Error('Sorry, this library does not yet support generating an SDK for an OpenAPI definition that contains circular references.');
26
+ }
27
+ }
28
+ CodeGeneratorLanguage.prototype.hasRequiredPackages = function () {
29
+ return Boolean(Object.keys(this.requiredPackages));
30
+ };
31
+ return CodeGeneratorLanguage;
32
+ }());
33
+ 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,175 @@
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
+ var lodash_camelcase_1 = __importDefault(require("lodash.camelcase"));
8
+ var lodash_deburr_1 = __importDefault(require("lodash.deburr"));
9
+ var 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
+ var 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) {
109
+ if (max === void 0) { max = 88; }
110
+ return str.replace(new RegExp("(?![^\\n]{1,".concat(max, "}$)([^\\n]{1,").concat(max, "})\\s"), 'g'), '$1\n');
111
+ }
112
+ exports.wordWrap = wordWrap;
113
+ /**
114
+ * Safely escape some string characters that may break a docblock.
115
+ *
116
+ */
117
+ function docblockEscape(str) {
118
+ return str.replace(/\/\*/g, '/\\*').replace(/\*\//g, '*\\/');
119
+ }
120
+ exports.docblockEscape = docblockEscape;
121
+ /**
122
+ * Convert a string that might contain spaces or special characters to one that can safely be used
123
+ * as a TypeScript interface or enum name.
124
+ *
125
+ * This function has been adapted and slighty modified from `json-schema-to-typescript`.
126
+ *
127
+ * @license MIT
128
+ * @see {@link https://github.com/bcherny/json-schema-to-typescript}
129
+ */
130
+ function toSafeString(str) {
131
+ // identifiers in javaScript/ts:
132
+ // First character: a-zA-Z | _ | $
133
+ // Rest: a-zA-Z | _ | $ | 0-9
134
+ // remove accents, umlauts, ... by their basic latin letters
135
+ return ((0, lodash_deburr_1.default)(str)
136
+ // if the string starts with a number, prefix it with character that typescript can accept
137
+ // https://github.com/bcherny/json-schema-to-typescript/issues/489
138
+ .replace(/^(\d){1}/, '$$1')
139
+ // replace chars which are not valid for typescript identifiers with whitespace
140
+ .replace(/(^\s*[^a-zA-Z_$])|([^a-zA-Z_$\d])/g, ' ')
141
+ // uppercase leading underscores followed by lowercase
142
+ .replace(/^_[a-z]/g, function (match) { return match.toUpperCase(); })
143
+ // remove non-leading underscores followed by lowercase (convert snake_case)
144
+ .replace(/_[a-z]/g, function (match) { return match.substr(1, match.length).toUpperCase(); })
145
+ // uppercase letters after digits, dollars
146
+ .replace(/([\d$]+[a-zA-Z])/g, function (match) { return match.toUpperCase(); })
147
+ // uppercase first letter after whitespace
148
+ .replace(/\s+([a-zA-Z])/g, function (match) { return match.toUpperCase().trim(); })
149
+ // remove remaining whitespace
150
+ .replace(/\s/g, ''));
151
+ }
152
+ function generateTypeName() {
153
+ var parts = [];
154
+ for (var _i = 0; _i < arguments.length; _i++) {
155
+ parts[_i] = arguments[_i];
156
+ }
157
+ var str;
158
+ // If the end of our string ends with something like `2XX`, the combination of `startCase` and
159
+ // `camelCase` will transform it into `2Xx`.
160
+ if (parts.length > 1) {
161
+ var last = parts[parts.length - 1];
162
+ if (last.match(/^(\d)XX$/)) {
163
+ str = (0, lodash_startcase_1.default)((0, lodash_camelcase_1.default)(parts.slice(0, -1).join(' ')));
164
+ str += " ".concat(last);
165
+ }
166
+ }
167
+ if (!str) {
168
+ str = (0, lodash_startcase_1.default)((0, lodash_camelcase_1.default)(parts.join(' ')));
169
+ }
170
+ if (RESERVED_WORDS.includes(str.toLowerCase())) {
171
+ str = "$".concat(str);
172
+ }
173
+ return toSafeString(str);
174
+ }
175
+ 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';
5
+ import type { HttpMethods, SchemaObject } from 'oas/dist/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<"formData" | "body" | "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 {};