@hey-api/openapi-ts 0.90.1 → 0.90.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.
@@ -0,0 +1,616 @@
1
+
2
+ const require_openApi = require('./openApi-BwUPqtP_.cjs');
3
+ let _hey_api_codegen_core = require("@hey-api/codegen-core");
4
+ let ansi_colors = require("ansi-colors");
5
+ ansi_colors = require_openApi.__toESM(ansi_colors);
6
+ let color_support = require("color-support");
7
+ color_support = require_openApi.__toESM(color_support);
8
+ let node_fs = require("node:fs");
9
+ node_fs = require_openApi.__toESM(node_fs);
10
+ let node_path = require("node:path");
11
+ node_path = require_openApi.__toESM(node_path);
12
+ let _hey_api_json_schema_ref_parser = require("@hey-api/json-schema-ref-parser");
13
+
14
+ //#region src/config/engine.ts
15
+ const checkNodeVersion = () => {
16
+ if (typeof Bun !== "undefined") {
17
+ const [major] = Bun.version.split(".").map(Number);
18
+ if (major < 1) throw new require_openApi.ConfigError(`Unsupported Bun version ${Bun.version}. Please use Bun 1.0.0 or newer.`);
19
+ } else if (typeof process !== "undefined" && process.versions?.node) {
20
+ const [major] = process.versions.node.split(".").map(Number);
21
+ if (major < 20) throw new require_openApi.ConfigError(`Unsupported Node version ${process.versions.node}. Please use Node 20 or newer.`);
22
+ }
23
+ };
24
+
25
+ //#endregion
26
+ //#region src/ir/intents.ts
27
+ var IntentContext = class {
28
+ spec;
29
+ constructor(spec) {
30
+ this.spec = spec;
31
+ }
32
+ getOperation(path$2, method) {
33
+ const paths = this.spec.paths;
34
+ if (!paths) return;
35
+ return paths[path$2]?.[method];
36
+ }
37
+ setExample(operation, example) {
38
+ const source = this.getOperation(operation.path, operation.method);
39
+ if (!source) return;
40
+ source["x-codeSamples"] ||= [];
41
+ source["x-codeSamples"].push(example);
42
+ }
43
+ };
44
+
45
+ //#endregion
46
+ //#region src/generate/output.ts
47
+ const generateOutput = async ({ context }) => {
48
+ const outputPath = node_path.default.resolve(context.config.output.path);
49
+ if (context.config.output.clean) {
50
+ if (node_fs.default.existsSync(outputPath)) node_fs.default.rmSync(outputPath, {
51
+ force: true,
52
+ recursive: true
53
+ });
54
+ }
55
+ const client = require_openApi.getClientPlugin(context.config);
56
+ if ("bundle" in client.config && client.config.bundle && !context.config.dryRun) context.config._FRAGILE_CLIENT_BUNDLE_RENAMED = require_openApi.generateClientBundle({
57
+ meta: { importFileExtension: context.config.output.importFileExtension },
58
+ outputPath,
59
+ plugin: client,
60
+ project: context.gen
61
+ });
62
+ for (const plugin of context.registerPlugins()) await plugin.run();
63
+ context.gen.plan();
64
+ const ctx = new IntentContext(context.spec);
65
+ for (const intent of context.intents) await intent.run(ctx);
66
+ for (const file of context.gen.render()) {
67
+ const filePath = node_path.default.resolve(outputPath, file.path);
68
+ const dir = node_path.default.dirname(filePath);
69
+ if (!context.config.dryRun) {
70
+ node_fs.default.mkdirSync(dir, { recursive: true });
71
+ node_fs.default.writeFileSync(filePath, file.content, { encoding: "utf8" });
72
+ }
73
+ }
74
+ const { source } = context.config.output;
75
+ if (source.enabled) {
76
+ const sourcePath = source.path === null ? void 0 : node_path.default.resolve(outputPath, source.path);
77
+ if (!context.config.dryRun && sourcePath && sourcePath !== outputPath) node_fs.default.mkdirSync(sourcePath, { recursive: true });
78
+ const serialized = await source.serialize(context.spec);
79
+ if (!context.config.dryRun && sourcePath) node_fs.default.writeFileSync(node_path.default.resolve(sourcePath, `${source.fileName}.${source.extension}`), serialized, { encoding: "utf8" });
80
+ if (source.callback) await source.callback(serialized);
81
+ }
82
+ };
83
+
84
+ //#endregion
85
+ //#region src/openApi/shared/utils/patch.ts
86
+ const patchOpenApiSpec = ({ patchOptions, spec: _spec }) => {
87
+ if (!patchOptions) return;
88
+ const spec = _spec;
89
+ if ("swagger" in spec) {
90
+ if (patchOptions.version && spec.swagger) spec.swagger = typeof patchOptions.version === "string" ? patchOptions.version : patchOptions.version(spec.swagger);
91
+ if (patchOptions.meta && spec.info) patchOptions.meta(spec.info);
92
+ if (patchOptions.schemas && spec.definitions) for (const key in patchOptions.schemas) {
93
+ const schema = spec.definitions[key];
94
+ if (!schema || typeof schema !== "object") continue;
95
+ const patchFn = patchOptions.schemas[key];
96
+ patchFn(schema);
97
+ }
98
+ if (patchOptions.operations && spec.paths) for (const key in patchOptions.operations) {
99
+ const [method, path$2] = key.split(" ");
100
+ if (!method || !path$2) continue;
101
+ const pathItem = spec.paths[path$2];
102
+ if (!pathItem) continue;
103
+ const operation = pathItem[method.toLocaleLowerCase()] || pathItem[method.toLocaleUpperCase()];
104
+ if (!operation || typeof operation !== "object") continue;
105
+ const patchFn = patchOptions.operations[key];
106
+ patchFn(operation);
107
+ }
108
+ return;
109
+ }
110
+ if (patchOptions.version && spec.openapi) spec.openapi = typeof patchOptions.version === "string" ? patchOptions.version : patchOptions.version(spec.openapi);
111
+ if (patchOptions.meta && spec.info) patchOptions.meta(spec.info);
112
+ if (spec.components) {
113
+ if (patchOptions.schemas && spec.components.schemas) for (const key in patchOptions.schemas) {
114
+ const schema = spec.components.schemas[key];
115
+ if (!schema || typeof schema !== "object") continue;
116
+ const patchFn = patchOptions.schemas[key];
117
+ patchFn(schema);
118
+ }
119
+ if (patchOptions.parameters && spec.components.parameters) for (const key in patchOptions.parameters) {
120
+ const schema = spec.components.parameters[key];
121
+ if (!schema || typeof schema !== "object") continue;
122
+ const patchFn = patchOptions.parameters[key];
123
+ patchFn(schema);
124
+ }
125
+ if (patchOptions.requestBodies && spec.components.requestBodies) for (const key in patchOptions.requestBodies) {
126
+ const schema = spec.components.requestBodies[key];
127
+ if (!schema || typeof schema !== "object") continue;
128
+ const patchFn = patchOptions.requestBodies[key];
129
+ patchFn(schema);
130
+ }
131
+ if (patchOptions.responses && spec.components.responses) for (const key in patchOptions.responses) {
132
+ const schema = spec.components.responses[key];
133
+ if (!schema || typeof schema !== "object") continue;
134
+ const patchFn = patchOptions.responses[key];
135
+ patchFn(schema);
136
+ }
137
+ }
138
+ if (patchOptions.operations && spec.paths) for (const key in patchOptions.operations) {
139
+ const [method, path$2] = key.split(" ");
140
+ if (!method || !path$2) continue;
141
+ const pathItem = spec.paths[path$2];
142
+ if (!pathItem) continue;
143
+ const operation = pathItem[method.toLocaleLowerCase()] || pathItem[method.toLocaleUpperCase()];
144
+ if (!operation || typeof operation !== "object") continue;
145
+ const patchFn = patchOptions.operations[key];
146
+ patchFn(operation);
147
+ }
148
+ };
149
+
150
+ //#endregion
151
+ //#region src/createClient.ts
152
+ const compileInputPath = (input) => {
153
+ const result = {
154
+ ...input,
155
+ path: ""
156
+ };
157
+ if (input.path && (typeof input.path !== "string" || input.registry !== "hey-api")) {
158
+ result.path = input.path;
159
+ return result;
160
+ }
161
+ const [basePath, baseQuery] = input.path.split("?");
162
+ const queryPath = (baseQuery || "").split("&").map((part) => part.split("="));
163
+ let path$2 = basePath || "";
164
+ if (path$2.endsWith("/")) path$2 = path$2.slice(0, path$2.length - 1);
165
+ const [, pathUrl] = path$2.split("://");
166
+ const [baseUrl, organization, project] = (pathUrl || "").split("/");
167
+ result.organization = organization || input.organization;
168
+ result.project = project || input.project;
169
+ const queryParams = [];
170
+ const kApiKey = "api_key";
171
+ result.api_key = queryPath.find(([key]) => key === kApiKey)?.[1] || input.api_key || process.env.HEY_API_TOKEN;
172
+ if (result.api_key) queryParams.push(`${kApiKey}=${result.api_key}`);
173
+ const kBranch = "branch";
174
+ result.branch = queryPath.find(([key]) => key === kBranch)?.[1] || input.branch;
175
+ if (result.branch) queryParams.push(`${kBranch}=${result.branch}`);
176
+ const kCommitSha = "commit_sha";
177
+ result.commit_sha = queryPath.find(([key]) => key === kCommitSha)?.[1] || input.commit_sha;
178
+ if (result.commit_sha) queryParams.push(`${kCommitSha}=${result.commit_sha}`);
179
+ const kTags = "tags";
180
+ result.tags = queryPath.find(([key]) => key === kTags)?.[1]?.split(",") || input.tags;
181
+ if (result.tags?.length) queryParams.push(`${kTags}=${result.tags.join(",")}`);
182
+ const kVersion = "version";
183
+ result.version = queryPath.find(([key]) => key === kVersion)?.[1] || input.version;
184
+ if (result.version) queryParams.push(`${kVersion}=${result.version}`);
185
+ if (!result.organization) throw new Error("missing organization - from which Hey API Platform organization do you want to generate your output?");
186
+ if (!result.project) throw new Error("missing project - from which Hey API Platform project do you want to generate your output?");
187
+ const query = queryParams.join("&");
188
+ const platformUrl = baseUrl || "get.heyapi.dev";
189
+ const isLocalhost = platformUrl.startsWith("localhost");
190
+ const platformUrlWithProtocol = [isLocalhost ? "http" : "https", platformUrl].join("://");
191
+ const compiledPath = isLocalhost ? [
192
+ platformUrlWithProtocol,
193
+ "v1",
194
+ "get",
195
+ result.organization,
196
+ result.project
197
+ ].join("/") : [
198
+ platformUrlWithProtocol,
199
+ result.organization,
200
+ result.project
201
+ ].join("/");
202
+ result.path = query ? `${compiledPath}?${query}` : compiledPath;
203
+ return result;
204
+ };
205
+ const logInputPaths = (inputPaths, jobIndex) => {
206
+ const lines = [];
207
+ const jobPrefix = ansi_colors.default.gray(`[Job ${jobIndex + 1}] `);
208
+ const count = inputPaths.length;
209
+ const baseString = ansi_colors.default.cyan(`Generating from ${count} ${count === 1 ? "input" : "inputs"}:`);
210
+ lines.push(`${jobPrefix}⏳ ${baseString}`);
211
+ inputPaths.forEach((inputPath, index) => {
212
+ const itemPrefixStr = ` [${index + 1}] `;
213
+ const itemPrefix = ansi_colors.default.cyan(itemPrefixStr);
214
+ const detailIndent = " ".repeat(itemPrefixStr.length);
215
+ if (typeof inputPath.path !== "string") {
216
+ lines.push(`${jobPrefix}${itemPrefix}raw OpenAPI specification`);
217
+ return;
218
+ }
219
+ switch (inputPath.registry) {
220
+ case "hey-api": {
221
+ const baseInput = [inputPath.organization, inputPath.project].filter(Boolean).join("/");
222
+ lines.push(`${jobPrefix}${itemPrefix}${baseInput}`);
223
+ if (inputPath.branch) lines.push(`${jobPrefix}${detailIndent}${ansi_colors.default.gray("branch:")} ${ansi_colors.default.green(inputPath.branch)}`);
224
+ if (inputPath.commit_sha) lines.push(`${jobPrefix}${detailIndent}${ansi_colors.default.gray("commit:")} ${ansi_colors.default.green(inputPath.commit_sha)}`);
225
+ if (inputPath.tags?.length) lines.push(`${jobPrefix}${detailIndent}${ansi_colors.default.gray("tags:")} ${ansi_colors.default.green(inputPath.tags.join(", "))}`);
226
+ if (inputPath.version) lines.push(`${jobPrefix}${detailIndent}${ansi_colors.default.gray("version:")} ${ansi_colors.default.green(inputPath.version)}`);
227
+ lines.push(`${jobPrefix}${detailIndent}${ansi_colors.default.gray("registry:")} ${ansi_colors.default.green("Hey API")}`);
228
+ break;
229
+ }
230
+ case "readme": {
231
+ const baseInput = [inputPath.organization, inputPath.project].filter(Boolean).join("/");
232
+ if (!baseInput) lines.push(`${jobPrefix}${itemPrefix}${inputPath.path}`);
233
+ else lines.push(`${jobPrefix}${itemPrefix}${baseInput}`);
234
+ if (inputPath.uuid) lines.push(`${jobPrefix}${detailIndent}${ansi_colors.default.gray("uuid:")} ${ansi_colors.default.green(inputPath.uuid)}`);
235
+ lines.push(`${jobPrefix}${detailIndent}${ansi_colors.default.gray("registry:")} ${ansi_colors.default.green("ReadMe")}`);
236
+ break;
237
+ }
238
+ case "scalar": {
239
+ const baseInput = [inputPath.organization, inputPath.project].filter(Boolean).join("/");
240
+ lines.push(`${jobPrefix}${itemPrefix}${baseInput}`);
241
+ lines.push(`${jobPrefix}${detailIndent}${ansi_colors.default.gray("registry:")} ${ansi_colors.default.green("Scalar")}`);
242
+ break;
243
+ }
244
+ default:
245
+ lines.push(`${jobPrefix}${itemPrefix}${inputPath.path}`);
246
+ break;
247
+ }
248
+ });
249
+ for (const line of lines) console.log(line);
250
+ };
251
+ const createClient$1 = async ({ config, dependencies, jobIndex, logger, watches: _watches }) => {
252
+ const watches = _watches || Array.from({ length: config.input.length }, () => ({ headers: new Headers() }));
253
+ const inputPaths = config.input.map((input) => compileInputPath(input));
254
+ if (config.logs.level !== "silent" && !_watches) logInputPaths(inputPaths, jobIndex);
255
+ const getSpecData = async (input, index) => {
256
+ const eventSpec = logger.timeEvent("spec");
257
+ const { arrayBuffer, error, resolvedInput, response } = await require_openApi.getSpec({
258
+ fetchOptions: input.fetch,
259
+ inputPath: inputPaths[index].path,
260
+ timeout: input.watch.timeout,
261
+ watch: watches[index]
262
+ });
263
+ eventSpec.timeEnd();
264
+ if (error && !_watches) throw new Error(`Request failed with status ${response.status}: ${response.statusText}`);
265
+ return {
266
+ arrayBuffer,
267
+ resolvedInput
268
+ };
269
+ };
270
+ const specData = (await Promise.all(config.input.map((input, index) => getSpecData(input, index)))).filter((data) => data.arrayBuffer || data.resolvedInput);
271
+ let context;
272
+ if (specData.length) {
273
+ const refParser = new _hey_api_json_schema_ref_parser.$RefParser();
274
+ const data = specData.length > 1 ? await refParser.bundleMany({
275
+ arrayBuffer: specData.map((data$1) => data$1.arrayBuffer),
276
+ pathOrUrlOrSchemas: [],
277
+ resolvedInputs: specData.map((data$1) => data$1.resolvedInput)
278
+ }) : await refParser.bundle({
279
+ arrayBuffer: specData[0].arrayBuffer,
280
+ pathOrUrlOrSchema: void 0,
281
+ resolvedInput: specData[0].resolvedInput
282
+ });
283
+ if (config.logs.level !== "silent" && _watches) {
284
+ console.clear();
285
+ logInputPaths(inputPaths, jobIndex);
286
+ }
287
+ const eventInputPatch = logger.timeEvent("input.patch");
288
+ patchOpenApiSpec({
289
+ patchOptions: config.parser.patch,
290
+ spec: data
291
+ });
292
+ eventInputPatch.timeEnd();
293
+ const eventParser = logger.timeEvent("parser");
294
+ context = require_openApi.parseOpenApiSpec({
295
+ config,
296
+ dependencies,
297
+ logger,
298
+ spec: data
299
+ });
300
+ context.graph = require_openApi.buildGraph(context.ir, logger).graph;
301
+ eventParser.timeEnd();
302
+ const eventGenerator = logger.timeEvent("generator");
303
+ await generateOutput({ context });
304
+ eventGenerator.timeEnd();
305
+ const eventPostprocess = logger.timeEvent("postprocess");
306
+ if (!config.dryRun) {
307
+ require_openApi.postprocessOutput(config.output);
308
+ if (config.logs.level !== "silent") {
309
+ const outputPath = process.env.INIT_CWD ? `./${node_path.default.relative(process.env.INIT_CWD, config.output.path)}` : config.output.path;
310
+ const jobPrefix = ansi_colors.default.gray(`[Job ${jobIndex + 1}] `);
311
+ console.log(`${jobPrefix}${ansi_colors.default.green("✅ Done!")} Your output is in ${ansi_colors.default.cyanBright(outputPath)}`);
312
+ }
313
+ }
314
+ eventPostprocess.timeEnd();
315
+ }
316
+ const watchedInput = config.input.find((input, index) => input.watch.enabled && typeof inputPaths[index].path === "string");
317
+ if (watchedInput) setTimeout(() => {
318
+ createClient$1({
319
+ config,
320
+ dependencies,
321
+ jobIndex,
322
+ logger,
323
+ watches
324
+ });
325
+ }, watchedInput.watch.interval);
326
+ return context;
327
+ };
328
+
329
+ //#endregion
330
+ //#region src/utils/cli.ts
331
+ const textAscii = `
332
+ 888 | e 888~-_ 888
333
+ 888___| e88~~8e Y88b / d8b 888 \\ 888
334
+ 888 | d888 88b Y888/ /Y88b 888 | 888
335
+ 888 | 8888__888 Y8/ / Y88b 888 / 888
336
+ 888 | Y888 , Y /____Y88b 888_-~ 888
337
+ 888 | "88___/ / / Y88b 888 888
338
+ _/
339
+ `;
340
+ const asciiToLines = (ascii, options) => {
341
+ const lines = [];
342
+ const padding = Array.from({ length: options?.padding ?? 0 }).fill("");
343
+ lines.push(...padding);
344
+ let maxLineLength = 0;
345
+ let line = "";
346
+ for (const char of ascii) if (char === "\n") {
347
+ if (line) {
348
+ lines.push(line);
349
+ maxLineLength = Math.max(maxLineLength, line.length);
350
+ line = "";
351
+ }
352
+ } else line += char;
353
+ lines.push(...padding);
354
+ return {
355
+ lines,
356
+ maxLineLength
357
+ };
358
+ };
359
+ function printCliIntro() {
360
+ const packageJson = require_openApi.loadPackageJson();
361
+ const text = asciiToLines(textAscii, { padding: 1 });
362
+ for (const line of text.lines) console.log(ansi_colors.default.cyan(line));
363
+ console.log(ansi_colors.default.gray(`${packageJson.name} v${packageJson.version}`));
364
+ console.log("");
365
+ }
366
+
367
+ //#endregion
368
+ //#region src/utils/logger.ts
369
+ let loggerCounter = 0;
370
+ const nameToId = (name) => `${name}-${loggerCounter++}`;
371
+ const idEnd = (id) => `${id}-end`;
372
+ const idLength = (id) => `${id}-length`;
373
+ const idStart = (id) => `${id}-start`;
374
+ const getSeverity = (duration, percentage) => {
375
+ if (duration > 200) return {
376
+ color: ansi_colors.default.red,
377
+ type: "duration"
378
+ };
379
+ if (percentage > 30) return {
380
+ color: ansi_colors.default.red,
381
+ type: "percentage"
382
+ };
383
+ if (duration > 50) return {
384
+ color: ansi_colors.default.yellow,
385
+ type: "duration"
386
+ };
387
+ if (percentage > 10) return {
388
+ color: ansi_colors.default.yellow,
389
+ type: "percentage"
390
+ };
391
+ };
392
+ var Logger = class {
393
+ events = [];
394
+ end(result) {
395
+ let event;
396
+ let events = this.events;
397
+ for (const index of result.position) {
398
+ event = events[index];
399
+ if (event?.events) events = event.events;
400
+ }
401
+ if (event && !event.end) event.end = performance.mark(idEnd(event.id));
402
+ }
403
+ /**
404
+ * Recursively end all unended events in the event tree.
405
+ * This ensures all events have end marks before measuring.
406
+ */
407
+ endAllEvents(events) {
408
+ for (const event of events) {
409
+ if (!event.end) event.end = performance.mark(idEnd(event.id));
410
+ if (event.events.length > 0) this.endAllEvents(event.events);
411
+ }
412
+ }
413
+ report(print = true) {
414
+ const firstEvent = this.events[0];
415
+ if (!firstEvent) return;
416
+ this.endAllEvents(this.events);
417
+ const lastEvent = this.events[this.events.length - 1];
418
+ const name = "root";
419
+ const id = nameToId(name);
420
+ try {
421
+ const measure = performance.measure(idLength(id), idStart(firstEvent.id), idEnd(lastEvent.id));
422
+ if (print) this.reportEvent({
423
+ end: lastEvent.end,
424
+ events: this.events,
425
+ id,
426
+ indent: 0,
427
+ measure,
428
+ name,
429
+ start: firstEvent.start
430
+ });
431
+ return measure;
432
+ } catch {
433
+ return;
434
+ }
435
+ }
436
+ reportEvent({ indent, ...parent }) {
437
+ const color = !indent ? ansi_colors.default.cyan : ansi_colors.default.gray;
438
+ const lastIndex = parent.events.length - 1;
439
+ parent.events.forEach((event, index) => {
440
+ try {
441
+ const measure = performance.measure(idLength(event.id), idStart(event.id), idEnd(event.id));
442
+ const duration = Math.ceil(measure.duration * 100) / 100;
443
+ const percentage = Math.ceil(measure.duration / parent.measure.duration * 100 * 100) / 100;
444
+ const severity = indent ? getSeverity(duration, percentage) : void 0;
445
+ let durationLabel = `${duration.toFixed(2).padStart(8)}ms`;
446
+ if (severity?.type === "duration") durationLabel = severity.color(durationLabel);
447
+ const branch = index === lastIndex ? "└─ " : "├─ ";
448
+ const prefix = !indent ? "" : "│ ".repeat(indent - 1) + branch;
449
+ const maxLength = 38 - prefix.length;
450
+ const percentageBranch = !indent ? "" : "↳ ";
451
+ let percentageLabel = `${indent ? " ".repeat(indent - 1) + percentageBranch : ""}${percentage.toFixed(2)}%`;
452
+ if (severity?.type === "percentage") percentageLabel = severity.color(percentageLabel);
453
+ const jobPrefix = ansi_colors.default.gray("[root] ");
454
+ console.log(`${jobPrefix}${ansi_colors.default.gray(prefix)}${color(`${event.name.padEnd(maxLength)} ${durationLabel} (${percentageLabel})`)}`);
455
+ this.reportEvent({
456
+ ...event,
457
+ indent: indent + 1,
458
+ measure
459
+ });
460
+ } catch {}
461
+ });
462
+ }
463
+ start(id) {
464
+ return performance.mark(idStart(id));
465
+ }
466
+ storeEvent({ result, ...event }) {
467
+ const lastEventIndex = event.events.length - 1;
468
+ const lastEvent = event.events[lastEventIndex];
469
+ if (lastEvent && !lastEvent.end) {
470
+ result.position = [...result.position, lastEventIndex];
471
+ this.storeEvent({
472
+ ...event,
473
+ events: lastEvent.events,
474
+ result
475
+ });
476
+ return;
477
+ }
478
+ const length = event.events.push({
479
+ ...event,
480
+ events: []
481
+ });
482
+ result.position = [...result.position, length - 1];
483
+ }
484
+ timeEvent(name) {
485
+ const id = nameToId(name);
486
+ const start = this.start(id);
487
+ const event = {
488
+ events: this.events,
489
+ id,
490
+ name,
491
+ start
492
+ };
493
+ const result = { position: [] };
494
+ this.storeEvent({
495
+ ...event,
496
+ result
497
+ });
498
+ return {
499
+ mark: start,
500
+ timeEnd: () => this.end(result)
501
+ };
502
+ }
503
+ };
504
+
505
+ //#endregion
506
+ //#region src/generate.ts
507
+ /**
508
+ * Generate a client from the provided configuration.
509
+ *
510
+ * @param userConfig User provided {@link UserConfig} configuration(s).
511
+ */
512
+ const createClient = async (userConfig, logger = new Logger()) => {
513
+ const resolvedConfig = typeof userConfig === "function" ? await userConfig() : userConfig;
514
+ const userConfigs = resolvedConfig ? resolvedConfig instanceof Array ? resolvedConfig : [resolvedConfig] : [];
515
+ let rawLogs = userConfigs.find((config) => require_openApi.getLogs(config).level !== "silent")?.logs;
516
+ if (typeof rawLogs === "string") rawLogs = require_openApi.getLogs({ logs: rawLogs });
517
+ let configs;
518
+ try {
519
+ checkNodeVersion();
520
+ const eventCreateClient = logger.timeEvent("createClient");
521
+ const eventConfig = logger.timeEvent("config");
522
+ configs = await require_openApi.initConfigs({
523
+ logger,
524
+ userConfigs
525
+ });
526
+ if (configs.results.some((result$1) => result$1.config.logs.level !== "silent")) printCliIntro();
527
+ eventConfig.timeEnd();
528
+ const allConfigErrors = configs.results.flatMap((result$1) => result$1.errors.map((error) => ({
529
+ error,
530
+ jobIndex: result$1.jobIndex
531
+ })));
532
+ if (allConfigErrors.length) throw new require_openApi.ConfigValidationError(allConfigErrors);
533
+ const result = (await Promise.all(configs.results.map(async (result$1) => {
534
+ try {
535
+ return await createClient$1({
536
+ config: result$1.config,
537
+ dependencies: configs.dependencies,
538
+ jobIndex: result$1.jobIndex,
539
+ logger
540
+ });
541
+ } catch (error) {
542
+ throw new require_openApi.JobError("", {
543
+ error,
544
+ jobIndex: result$1.jobIndex
545
+ });
546
+ }
547
+ }))).filter((client) => Boolean(client));
548
+ eventCreateClient.timeEnd();
549
+ const printLogs = configs.results.some((result$1) => result$1.config.logs.level === "debug");
550
+ logger.report(printLogs);
551
+ return result;
552
+ } catch (error) {
553
+ const results = configs?.results ?? [];
554
+ const logs = results.find((result) => result.config.logs.level !== "silent")?.config.logs ?? results[0]?.config.logs ?? rawLogs;
555
+ const dryRun = results.some((result) => result.config.dryRun) ?? userConfigs.some((config) => config.dryRun) ?? false;
556
+ const logPath = logs?.file && !dryRun ? require_openApi.logCrashReport(error, logs.path ?? "") : void 0;
557
+ if (!logs || logs.level !== "silent") {
558
+ require_openApi.printCrashReport({
559
+ error,
560
+ logPath
561
+ });
562
+ if (await require_openApi.shouldReportCrash({
563
+ error,
564
+ isInteractive: results.some((result) => result.config.interactive) ?? userConfigs.some((config) => config.interactive) ?? false
565
+ })) await require_openApi.openGitHubIssueWithCrashReport(error);
566
+ }
567
+ throw error;
568
+ }
569
+ };
570
+
571
+ //#endregion
572
+ //#region src/utils/exports.ts
573
+ /**
574
+ * Utilities shared across the package.
575
+ */
576
+ const utils = {
577
+ stringCase({ case: casing, stripLeadingSeparators, value }) {
578
+ return require_openApi.toCase(value, casing, { stripLeadingSeparators });
579
+ },
580
+ toCase: require_openApi.toCase
581
+ };
582
+
583
+ //#endregion
584
+ //#region src/index.ts
585
+ ansi_colors.default.enabled = (0, color_support.default)().hasBasic;
586
+ /**
587
+ * Type helper for openapi-ts.config.ts, returns {@link MaybeArray<UserConfig>} object(s)
588
+ */
589
+ const defineConfig = async (config) => typeof config === "function" ? await config() : config;
590
+
591
+ //#endregion
592
+ Object.defineProperty(exports, 'Logger', {
593
+ enumerable: true,
594
+ get: function () {
595
+ return Logger;
596
+ }
597
+ });
598
+ Object.defineProperty(exports, 'createClient', {
599
+ enumerable: true,
600
+ get: function () {
601
+ return createClient;
602
+ }
603
+ });
604
+ Object.defineProperty(exports, 'defineConfig', {
605
+ enumerable: true,
606
+ get: function () {
607
+ return defineConfig;
608
+ }
609
+ });
610
+ Object.defineProperty(exports, 'utils', {
611
+ enumerable: true,
612
+ get: function () {
613
+ return utils;
614
+ }
615
+ });
616
+ //# sourceMappingURL=src-hU76ergi.cjs.map