@devbie/apits 0.0.0-stage → 1.0.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.
@@ -0,0 +1,355 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // src/utils/utils.ts
20
+ var utils_exports = {};
21
+ __export(utils_exports, {
22
+ formatContent: () => formatContent,
23
+ getRequestDataJsonSchema: () => getRequestDataJsonSchema,
24
+ getResponseDataJsonSchema: () => getResponseDataJsonSchema,
25
+ jsonSchemaToTsCode: () => jsonSchemaToTsCode,
26
+ preprocessSchema: () => preprocessSchema,
27
+ processJsonSchema: () => processJsonSchema,
28
+ topNotesContent: () => topNotesContent
29
+ });
30
+ module.exports = __toCommonJS(utils_exports);
31
+ var import_vtilsLite = require("./vtilsLite.js");
32
+ var import_json_schema_to_typescript = require("json-schema-to-typescript");
33
+ var import_prettier = require("prettier");
34
+ var import_types = require("../types.js");
35
+ function upperFirst(value) {
36
+ return value ? value.charAt(0).toUpperCase() + value.slice(1) : value;
37
+ }
38
+ function processJsonSchema(jsonSchema) {
39
+ if (!(0, import_vtilsLite.isObject)(jsonSchema))
40
+ return jsonSchema;
41
+ delete jsonSchema.title;
42
+ delete jsonSchema.id;
43
+ delete jsonSchema.minItems;
44
+ delete jsonSchema.maxItems;
45
+ delete jsonSchema.default;
46
+ if (jsonSchema.nullable === true) {
47
+ if (jsonSchema.type) {
48
+ const types = (0, import_vtilsLite.castArray)(jsonSchema.type).filter((t) => t !== "null");
49
+ if (!types.includes("null"))
50
+ types.push("null");
51
+ jsonSchema.type = types.length === 1 ? types[0] : types;
52
+ } else if (jsonSchema.enum && Array.isArray(jsonSchema.enum)) {
53
+ if (!jsonSchema.enum.includes(null)) {
54
+ jsonSchema.enum = [...jsonSchema.enum, null];
55
+ }
56
+ }
57
+ delete jsonSchema.nullable;
58
+ }
59
+ if (jsonSchema.type) {
60
+ const isMultiple = Array.isArray(jsonSchema.type);
61
+ const types = (0, import_vtilsLite.castArray)(jsonSchema.type).map((type) => {
62
+ type = type.toLowerCase();
63
+ type = {
64
+ int: "integer"
65
+ }[type] || type;
66
+ return type;
67
+ });
68
+ jsonSchema.type = isMultiple ? types : types[0];
69
+ }
70
+ if ((0, import_vtilsLite.isArray)(jsonSchema.properties)) {
71
+ jsonSchema.properties = jsonSchema.properties.reduce(
72
+ (props, js) => {
73
+ props[js.name] = js;
74
+ return props;
75
+ },
76
+ {}
77
+ );
78
+ }
79
+ if (jsonSchema.properties) {
80
+ (0, import_vtilsLite.forOwn)(jsonSchema.properties, (_, prop) => {
81
+ const propDef = jsonSchema.properties[prop];
82
+ delete jsonSchema.properties[prop];
83
+ jsonSchema.properties[prop.trim()] = propDef;
84
+ });
85
+ jsonSchema.required = jsonSchema.required && jsonSchema.required.map((prop) => prop.trim());
86
+ }
87
+ if (jsonSchema.properties) {
88
+ (0, import_vtilsLite.forOwn)(jsonSchema.properties, processJsonSchema);
89
+ }
90
+ if (jsonSchema.items) {
91
+ (0, import_vtilsLite.castArray)(jsonSchema.items).forEach(processJsonSchema);
92
+ }
93
+ if (jsonSchema.oneOf) {
94
+ jsonSchema.oneOf.forEach(processJsonSchema);
95
+ }
96
+ if (jsonSchema.anyOf) {
97
+ jsonSchema.anyOf.forEach(processJsonSchema);
98
+ }
99
+ if (jsonSchema.allOf) {
100
+ jsonSchema.allOf.forEach(processJsonSchema);
101
+ }
102
+ return jsonSchema;
103
+ }
104
+ function jsonSchemaStringToJsonSchema(str) {
105
+ return processJsonSchema(JSON.parse(str));
106
+ }
107
+ function propDefinitionsToJsonSchema(propDefinitions) {
108
+ return processJsonSchema({
109
+ type: "object",
110
+ required: propDefinitions.reduce((res, prop) => {
111
+ if (prop.required) {
112
+ res.push(prop.name);
113
+ }
114
+ return res;
115
+ }, []),
116
+ properties: propDefinitions.reduce((res, prop) => {
117
+ res[prop.name] = {
118
+ type: prop.type,
119
+ description: prop.comment,
120
+ // File fields emit the native DOM `File` type (or `File[]` for
121
+ // multi-file arrays) so generated code has no dangling reference
122
+ // to the generator-internal `FileData` class. Non-file fields with
123
+ // an enum constraint emit a literal union.
124
+ ...prop.type === "file" ? { tsType: prop.isArray ? "File[]" : "File" } : Array.isArray(prop.enum) && prop.enum.length ? { enum: prop.enum } : {}
125
+ };
126
+ return res;
127
+ }, {})
128
+ });
129
+ }
130
+ function preprocessSchema(schema) {
131
+ if (!(0, import_vtilsLite.isObject)(schema)) {
132
+ return schema;
133
+ }
134
+ if (Array.isArray(schema)) {
135
+ return schema.map(preprocessSchema);
136
+ }
137
+ const processed = { ...schema };
138
+ if (processed.enum && Array.isArray(processed.enum) && processed.enum.length === 0) {
139
+ delete processed.enum;
140
+ }
141
+ if (processed.nullable === true) {
142
+ if (processed.type) {
143
+ const typeList = (0, import_vtilsLite.castArray)(processed.type).filter((typeName) => typeName !== "null");
144
+ typeList.push("null");
145
+ processed.type = typeList.length === 1 ? typeList[0] : typeList;
146
+ } else if (Array.isArray(processed.enum)) {
147
+ if (!processed.enum.includes(null))
148
+ processed.enum = [...processed.enum, null];
149
+ }
150
+ delete processed.nullable;
151
+ }
152
+ for (const key in processed) {
153
+ if (processed.hasOwnProperty(key)) {
154
+ processed[key] = preprocessSchema(processed[key]);
155
+ }
156
+ }
157
+ return processed;
158
+ }
159
+ function jsonSchemaTypeToTs(propSchema) {
160
+ if (!propSchema || typeof propSchema !== "object") {
161
+ return "unknown";
162
+ }
163
+ if (propSchema.tsType) {
164
+ return propSchema.tsType;
165
+ }
166
+ if (propSchema.enum && Array.isArray(propSchema.enum) && propSchema.enum.length) {
167
+ return propSchema.enum.map((v) => v === null ? "null" : `'${String(v).replace(/'/g, "\\'")}'`).join(" | ");
168
+ }
169
+ switch (propSchema.type) {
170
+ case "integer":
171
+ case "number":
172
+ return "number";
173
+ case "boolean":
174
+ return "boolean";
175
+ case "string":
176
+ return "string";
177
+ case "null":
178
+ return "null";
179
+ case "array": {
180
+ const itemSchema = Array.isArray(propSchema.items) ? propSchema.items[0] : propSchema.items;
181
+ const itemTs = itemSchema && (itemSchema.tsType || jsonSchemaTypeToTs(itemSchema));
182
+ return itemTs ? `${itemTs}[]` : "any[]";
183
+ }
184
+ case "object":
185
+ case void 0:
186
+ default:
187
+ return "unknown";
188
+ }
189
+ }
190
+ async function jsonSchemaToTsCode(jsonSchema, typeName) {
191
+ jsonSchema = preprocessSchema(jsonSchema);
192
+ typeName = upperFirst(typeName);
193
+ if ((0, import_vtilsLite.isEmpty)(jsonSchema)) {
194
+ return `export interface ${typeName} {}`;
195
+ }
196
+ if (jsonSchema.__is_any__) {
197
+ delete jsonSchema.__is_any__;
198
+ return `export type ${typeName} = any`;
199
+ }
200
+ function rewriteRefs(obj) {
201
+ for (const key in obj) {
202
+ if (obj.hasOwnProperty(key)) {
203
+ if (key === "$ref" && typeof obj[key] === "string") {
204
+ let refValue = obj[key];
205
+ if (refValue.startsWith("#components")) {
206
+ refValue = refValue.replace("#components", "#/components");
207
+ }
208
+ if (refValue.startsWith("#/components/schemas/")) {
209
+ const interfaceName = refValue.replace("#/components/schemas/", "");
210
+ obj["tsType"] = upperFirst(interfaceName);
211
+ if (obj.properties) {
212
+ const requiredArr = Array.isArray(obj.required) ? obj.required : [];
213
+ const propParts = [];
214
+ Object.keys(obj.properties).forEach((key2) => {
215
+ const propSchema = obj.properties[key2];
216
+ const tsType = propSchema.tsType || jsonSchemaTypeToTs(propSchema);
217
+ const optional = requiredArr.includes(key2) ? "" : "?";
218
+ propParts.push(`${key2}${optional}: ${tsType}`);
219
+ });
220
+ obj["tsType"] += ` & { ${propParts.join("; ")} }`;
221
+ }
222
+ delete obj["$ref"];
223
+ }
224
+ } else if (typeof obj[key] === "object" && obj[key] !== null) {
225
+ rewriteRefs(obj[key]);
226
+ }
227
+ }
228
+ }
229
+ }
230
+ rewriteRefs(jsonSchema);
231
+ const fakeTypeName = "THISISAFAKETYPENAME";
232
+ const code = await (0, import_json_schema_to_typescript.compile)(jsonSchema, fakeTypeName, {
233
+ bannerComment: "",
234
+ additionalProperties: false,
235
+ declareExternallyReferenced: false
236
+ });
237
+ delete jsonSchema.id;
238
+ return code.replace(fakeTypeName, typeName).trim();
239
+ }
240
+ function getRequestDataJsonSchema(interfaceInfo) {
241
+ let jsonSchema;
242
+ switch (interfaceInfo.req_body_type) {
243
+ case import_types.RequestBodyType.form:
244
+ jsonSchema = propDefinitionsToJsonSchema(
245
+ interfaceInfo.req_body_form.map((item) => ({
246
+ name: item.name,
247
+ required: item.required === import_types.Required.true,
248
+ type: item.type === import_types.RequestFormItemType.file ? "file" : "string",
249
+ comment: item.desc,
250
+ // Carry multi-file and enum markers from the OAS3 multipart schema
251
+ // expansion so propDefinitionsToJsonSchema can emit `File[]` and
252
+ // literal unions instead of collapsing every field to `string`.
253
+ ...item.isArray ? { isArray: true } : {},
254
+ ...Array.isArray(item.enum) && item.enum.length ? { enum: item.enum } : {}
255
+ }))
256
+ );
257
+ break;
258
+ case import_types.RequestBodyType.json:
259
+ if (interfaceInfo.req_body_other) {
260
+ jsonSchema = jsonSchemaStringToJsonSchema(interfaceInfo.req_body_other);
261
+ }
262
+ break;
263
+ default:
264
+ break;
265
+ }
266
+ if (jsonSchema && jsonSchema.type && jsonSchema.type !== "object" && !jsonSchema.properties && !jsonSchema.$ref && !jsonSchema.oneOf && !jsonSchema.anyOf && !jsonSchema.allOf) {
267
+ delete jsonSchema.type;
268
+ delete jsonSchema.tsType;
269
+ }
270
+ if ((0, import_vtilsLite.isArray)(interfaceInfo.req_query) && interfaceInfo.req_query.length) {
271
+ const queryJsonSchema = propDefinitionsToJsonSchema(
272
+ interfaceInfo.req_query.map((item) => ({
273
+ name: item.name,
274
+ required: item.required === import_types.Required.true,
275
+ type: item.type || "any",
276
+ // `object` resolves to `{}`, which causes declaration issues, so strip it for now
277
+ comment: item.desc
278
+ }))
279
+ );
280
+ if (jsonSchema) {
281
+ jsonSchema.properties = {
282
+ ...jsonSchema.properties,
283
+ ...queryJsonSchema.properties
284
+ };
285
+ jsonSchema.required = [
286
+ ...jsonSchema.required || [],
287
+ ...queryJsonSchema.required || []
288
+ ];
289
+ } else {
290
+ jsonSchema = queryJsonSchema;
291
+ }
292
+ }
293
+ if ((0, import_vtilsLite.isArray)(interfaceInfo.req_params) && interfaceInfo.req_params.length) {
294
+ const paramsJsonSchema = propDefinitionsToJsonSchema(
295
+ interfaceInfo.req_params.map((item) => ({
296
+ name: item.name,
297
+ required: true,
298
+ type: item.type || "string",
299
+ comment: item.desc
300
+ }))
301
+ );
302
+ if (jsonSchema) {
303
+ jsonSchema.properties = {
304
+ ...jsonSchema.properties,
305
+ ...paramsJsonSchema.properties
306
+ };
307
+ jsonSchema.required = [
308
+ ...jsonSchema.required || [],
309
+ ...paramsJsonSchema.required || []
310
+ ];
311
+ } else {
312
+ jsonSchema = paramsJsonSchema;
313
+ }
314
+ }
315
+ return jsonSchema;
316
+ }
317
+ function getResponseDataJsonSchema(interfaceInfo) {
318
+ let jsonSchema = {};
319
+ switch (interfaceInfo.res_body_type) {
320
+ case import_types.ResponseBodyType.json:
321
+ if (interfaceInfo.res_body) {
322
+ jsonSchema = jsonSchemaStringToJsonSchema(interfaceInfo.res_body);
323
+ }
324
+ break;
325
+ default:
326
+ jsonSchema = { __is_any__: true };
327
+ break;
328
+ }
329
+ return jsonSchema;
330
+ }
331
+ async function formatContent(content, filePath) {
332
+ if (!filePath) {
333
+ return (0, import_prettier.format)(content, { parser: "babel-ts" });
334
+ }
335
+ const consumerConfig = await (0, import_prettier.resolveConfig)(filePath) ?? {};
336
+ return (0, import_prettier.format)(content, { ...consumerConfig, filepath: filePath });
337
+ }
338
+ function topNotesContent() {
339
+ return `
340
+ /**
341
+ * Created By @devbie/apits
342
+ */
343
+
344
+ `;
345
+ }
346
+ // Annotate the CommonJS export names for ESM import in node:
347
+ 0 && (module.exports = {
348
+ formatContent,
349
+ getRequestDataJsonSchema,
350
+ getResponseDataJsonSchema,
351
+ jsonSchemaToTsCode,
352
+ preprocessSchema,
353
+ processJsonSchema,
354
+ topNotesContent
355
+ });
@@ -0,0 +1,123 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // src/utils/vtilsLite.ts
20
+ var vtilsLite_exports = {};
21
+ __export(vtilsLite_exports, {
22
+ castArray: () => castArray,
23
+ dedent: () => dedent,
24
+ each: () => each,
25
+ find: () => find,
26
+ forOwn: () => forOwn,
27
+ isArray: () => isArray,
28
+ isEmpty: () => isEmpty,
29
+ isObject: () => isObject
30
+ });
31
+ module.exports = __toCommonJS(vtilsLite_exports);
32
+ function castArray(value) {
33
+ return Array.isArray(value) ? value : [value];
34
+ }
35
+ var isArray = Array.isArray;
36
+ function isObject(value) {
37
+ return value != null && typeof value === "object" && !Array.isArray(value);
38
+ }
39
+ function isEmpty(value) {
40
+ if (value == null)
41
+ return true;
42
+ if (typeof value === "string" || Array.isArray(value))
43
+ return value.length === 0;
44
+ if (typeof value === "object")
45
+ return Object.keys(value).length === 0;
46
+ return true;
47
+ }
48
+ function forOwn(obj, callback) {
49
+ if (obj == null)
50
+ return;
51
+ Object.keys(obj).forEach((key) => {
52
+ callback(obj[key], key);
53
+ });
54
+ }
55
+ function each(collection, callback) {
56
+ if (collection == null)
57
+ return;
58
+ if (Array.isArray(collection)) {
59
+ collection.forEach((value, index) => callback(value, index));
60
+ } else if (typeof collection === "object") {
61
+ Object.keys(collection).forEach((key) => {
62
+ callback(collection[key], key);
63
+ });
64
+ }
65
+ }
66
+ function find(collection, predicate) {
67
+ if (collection == null)
68
+ return void 0;
69
+ if (Array.isArray(collection)) {
70
+ return collection.find((value, index) => predicate(value, index));
71
+ }
72
+ if (typeof collection === "object") {
73
+ for (const key of Object.keys(collection)) {
74
+ const value = collection[key];
75
+ if (predicate(value, key))
76
+ return value;
77
+ }
78
+ }
79
+ return void 0;
80
+ }
81
+ function dedent(literals, ...interpolations) {
82
+ let text = "";
83
+ for (let i = 0; i < interpolations.length; i++) {
84
+ const literal = literals[i];
85
+ const interpolation = String(interpolations[i]);
86
+ const match = literal.match(/(?:^|[\r\n]+)([^\S\r\n]*)$/);
87
+ if (match && match[1]) {
88
+ text += literal + interpolation.replace(/([\r\n]+)(?=[^\r\n])/g, `$1${match[1]}`);
89
+ } else {
90
+ text += literal + interpolation;
91
+ }
92
+ }
93
+ text += literals[literals.length - 1];
94
+ const lines = text.split(/[\r\n]/g);
95
+ let commonLeadingWhitespace = null;
96
+ let firstLineIndex = null;
97
+ let lastLineIndex = null;
98
+ for (let i = 0; i < lines.length; i++) {
99
+ const leadingWhitespace = lines[i].match(/^\s*/)[0];
100
+ if (leadingWhitespace.length !== lines[i].length) {
101
+ lastLineIndex = i;
102
+ if (firstLineIndex == null)
103
+ firstLineIndex = i;
104
+ if (commonLeadingWhitespace == null || leadingWhitespace.length < commonLeadingWhitespace.length) {
105
+ commonLeadingWhitespace = leadingWhitespace;
106
+ }
107
+ }
108
+ }
109
+ if (commonLeadingWhitespace == null)
110
+ return text;
111
+ return lines.slice(firstLineIndex, lastLineIndex + 1).map((line) => line.slice(commonLeadingWhitespace.length)).join("\n");
112
+ }
113
+ // Annotate the CommonJS export names for ESM import in node:
114
+ 0 && (module.exports = {
115
+ castArray,
116
+ dedent,
117
+ each,
118
+ find,
119
+ forOwn,
120
+ isArray,
121
+ isEmpty,
122
+ isObject
123
+ });
@@ -0,0 +1,29 @@
1
+ import yargs from "yargs";
2
+ /** Flags accepted by the `gen` command. */
3
+ interface GenFlags {
4
+ /** OpenAPI document URL or local file path. */
5
+ input?: string;
6
+ /** Output directory. */
7
+ output?: string;
8
+ /** File base name (CLI mode) or name filter (config-file mode). */
9
+ name?: string;
10
+ /** Runtime baseURL (string; `[code]:` prefix supported). */
11
+ baseUrl?: string;
12
+ /** Whether to scaffold the default request.ts client. */
13
+ client?: boolean;
14
+ /** Watch local input files and regenerate on change. */
15
+ watch?: boolean;
16
+ }
17
+ /** Scaffold an optional apits.config.ts template. */
18
+ export declare function genConfig(prefill?: {
19
+ input?: string;
20
+ }): Promise<void>;
21
+ export declare function start(flags?: GenFlags): Promise<void>;
22
+ export default class CLI {
23
+ run(args: string[]): {
24
+ [x: string]: any;
25
+ };
26
+ private genBuilder;
27
+ init(): yargs.Argv<any>;
28
+ }
29
+ export {};