Skip to content

Commit

Permalink
Merge pull request #343 from hey-api/fix/files-header
Browse files Browse the repository at this point in the history
fix(parser): add header to generated files
  • Loading branch information
mrlubos authored Apr 11, 2024
2 parents 44a8f23 + 0b6bfba commit 336d19c
Show file tree
Hide file tree
Showing 42 changed files with 128 additions and 40 deletions.
29 changes: 20 additions & 9 deletions packages/openapi-ts/src/compiler/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,31 +5,42 @@ import ts from 'typescript';
import * as module from './module';
import * as typedef from './typedef';
import * as types from './types';
import { tsNodeToString } from './utils';
import { addLeadingComment, tsNodeToString } from './utils';

export type { Property } from './typedef';
export type { Comments } from './utils';
export type { Node } from 'typescript';

export class TypeScriptFile {
private _headers: Array<string> = [];
private _imports: Array<ts.Node> = [];
private _items: Array<ts.Node | string> = [];

public addNamedImport(...params: Parameters<typeof module.createNamedImportDeclarations>): void {
this._imports.push(compiler.import.named(...params));
public add(...nodes: Array<ts.Node | string>): void {
this._items = [...this._items, ...nodes];
}

public add(...nodes: Array<ts.Node | string>): void {
this._items.push(...nodes);
public addHeader() {
const text = 'This file is auto-generated by @hey-api/openapi-ts';
const comment = addLeadingComment(undefined, [text], true, false)
this._headers = [...this._headers, comment]
return this;
}

public addNamedImport(...params: Parameters<typeof module.createNamedImportDeclarations>): void {
this._imports = [...this._imports, compiler.import.named(...params)];
}

public toString(seperator: string = '\n') {
const values: string[] = [];
let output: string[] = [];
if (this._headers.length) {
output = [...output, this._headers.join('\n')];
}
if (this._imports.length) {
values.push(this._imports.map(v => tsNodeToString(v)).join('\n'));
output = [...output, this._imports.map(v => tsNodeToString(v)).join('\n')];
}
values.push(...this._items.map(v => (typeof v === 'string' ? v : tsNodeToString(v))));
return values.join(seperator);
output = [...output, ...this._items.map(v => (typeof v === 'string' ? v : tsNodeToString(v)))];
return output.join(seperator);
}

public write(file: PathOrFileDescriptor, seperator: string = '\n') {
Expand Down
6 changes: 3 additions & 3 deletions packages/openapi-ts/src/compiler/typedef.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import ts from 'typescript';

import { addLeadingJSDocComment, type Comments } from './utils';
import { addLeadingComment, type Comments } from './utils';

export const createTypeNode = (base: any) => ts.factory.createTypeReferenceNode(base as string);

Expand All @@ -23,7 +23,7 @@ export const createTypeAliasDeclaration = (
ts.factory.createTypeReferenceNode(type)
);
if (comments?.length) {
addLeadingJSDocComment(node, comments);
addLeadingComment(node, comments);
}
return node;
};
Expand Down Expand Up @@ -54,7 +54,7 @@ export const createTypeInterfaceNode = (properties: Property[], isNullable: bool
);
const comment = property.comment;
if (comment) {
addLeadingJSDocComment(signature, comment);
addLeadingComment(signature, comment);
}
return signature;
})
Expand Down
8 changes: 4 additions & 4 deletions packages/openapi-ts/src/compiler/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import ts from 'typescript';

import { addLeadingJSDocComment, type Comments, isType, ots } from './utils';
import { addLeadingComment, type Comments, isType, ots } from './utils';

/**
* Convert an unknown value to an expression.
Expand Down Expand Up @@ -77,7 +77,7 @@ export const createObjectType = <T extends object>(
}
const assignment = ts.factory.createPropertyAssignment(key, initializer);
if (c?.length) {
addLeadingJSDocComment(assignment, c);
addLeadingComment(assignment, c);
}
return assignment;
})
Expand Down Expand Up @@ -109,13 +109,13 @@ export const createEnumDeclaration = <T extends object>(
const assignment = ts.factory.createEnumMember(key, initializer);
const c = comments?.[key];
if (c) {
addLeadingJSDocComment(assignment, c);
addLeadingComment(assignment, c);
}
return assignment;
})
);
if (comment.length) {
addLeadingJSDocComment(declaration, comment);
addLeadingComment(declaration, comment);
}
return declaration;
};
35 changes: 22 additions & 13 deletions packages/openapi-ts/src/compiler/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,25 +88,34 @@ export const isType = <T>(value: T | undefined): value is T => value !== undefin

export type Comments = Array<string | null | false | undefined>;

export const addLeadingJSDocComment = (
export const addLeadingComment = (
node: ts.Node | undefined,
text: Comments,
hasTrailingNewLine: boolean = true
hasTrailingNewLine: boolean = true,
useJSDocStyle = true,
): string => {
if (!text.filter(Boolean).length) {
const comments = text.filter(Boolean);

if (!comments.length) {
return '';
}

// if node is falsy, assume string mode
if (node) {
ts.addSyntheticLeadingComment(
node,
ts.SyntaxKind.MultiLineCommentTrivia,
['*', ...text, ' '].filter(Boolean).join('\n'),
hasTrailingNewLine
);
return '';
if (!node) {
if (useJSDocStyle) {
const result = ['/**', ...comments.map(row => ` * ${row}`), ' */'].join('\n');
return hasTrailingNewLine ? `${result}\n` : result;
}

const result = comments.map(row => `// ${row}`).join('\n');
return hasTrailingNewLine ? `${result}\n` : result;
}

const result = ['/**', ...text, ' */'].filter(Boolean).join('\n');
return hasTrailingNewLine ? `${result}\n` : result;
ts.addSyntheticLeadingComment(
node,
ts.SyntaxKind.MultiLineCommentTrivia,
['*', ...comments.map(row => ` * ${row}`), ' '].join('\n'),
hasTrailingNewLine
);
return '';
};
4 changes: 3 additions & 1 deletion packages/openapi-ts/src/utils/write/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ import { getConfig } from '../config';
*/
export const writeClientIndex = async (client: Client, outputPath: string): Promise<void> => {
const config = getConfig();
const file = new TypeScriptFile();

const file = new TypeScriptFile().addHeader();

if (config.name) {
file.add(compiler.export.named([config.name], `./${config.name}`));
}
Expand Down
12 changes: 6 additions & 6 deletions packages/openapi-ts/src/utils/write/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,14 @@ const processEnum = (client: Client, model: Model, exportType: boolean) => {
properties[key] = value;
const comment = enumerator.customDescription || enumerator.description;
if (comment) {
comments[key] = [` * ${escapeComment(comment)}`];
comments[key] = [escapeComment(comment)];
}
});

if (exportType) {
const comment: Comments = [
model.description && ` * ${escapeComment(model.description)}`,
model.deprecated && ' * @deprecated',
model.description && escapeComment(model.description),
model.deprecated && '@deprecated',
];
if (config.enums === 'typescript') {
nodes = [...nodes, compiler.types.enum(model.name, properties, comment, comments)];
Expand All @@ -57,8 +57,8 @@ const processEnum = (client: Client, model: Model, exportType: boolean) => {

const processType = (client: Client, model: Model) => {
const comment: Comments = [
model.description && ` * ${escapeComment(model.description)}`,
model.deprecated && ' * @deprecated',
model.description && escapeComment(model.description),
model.deprecated && '@deprecated',
];
const type = toType(model);
return compiler.typedef.alias(model.name, type!, comment);
Expand Down Expand Up @@ -245,7 +245,7 @@ const processServiceTypes = (services: Service[]) => {
* @param client Client containing models, schemas, and services
*/
export const writeClientModels = async (openApi: OpenApi, outputPath: string, client: Client): Promise<void> => {
const file = new TypeScriptFile();
const file = new TypeScriptFile().addHeader();

for (const model of client.models) {
const nodes = processModel(client, model);
Expand Down
2 changes: 1 addition & 1 deletion packages/openapi-ts/src/utils/write/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { ensureValidTypeScriptJavaScriptIdentifier } from '../../openApi/common/
* @param outputPath Directory to write the generated files to
*/
export const writeClientSchemas = async (openApi: OpenApi, outputPath: string): Promise<void> => {
const file = new TypeScriptFile();
const file = new TypeScriptFile().addHeader();

const addSchema = (name: string, obj: any) => {
const validName = `$${ensureValidTypeScriptJavaScriptIdentifier(name)}`;
Expand Down
2 changes: 1 addition & 1 deletion packages/openapi-ts/src/utils/write/services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export const writeClientServices = async (
templates: Templates
): Promise<void> => {
const config = getConfig();
const file = new TypeScriptFile();
const file = new TypeScriptFile().addHeader();

let imports: string[] = [];
let results: string[] = [];
Expand Down
4 changes: 2 additions & 2 deletions packages/openapi-ts/src/utils/write/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@ const typeInterface = (model: Model) => {
}
return {
comment: [
property.description && ` * ${escapeComment(property.description)}`,
property.deprecated && ` * @deprecated`,
property.description && escapeComment(property.description),
property.deprecated && '@deprecated',
],
isReadOnly: property.isReadOnly,
isRequired: maybeRequired === '',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// This file is auto-generated by @hey-api/openapi-ts

export { ApiError } from './core/ApiError';
export { CancelablePromise, CancelError } from './core/CancelablePromise';
export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// This file is auto-generated by @hey-api/openapi-ts

/**
* Testing multiline comments in string: First line
* Second line
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// This file is auto-generated by @hey-api/openapi-ts

export const $CommentWithBreaks = {
description: `Testing multiline comments in string: First line
Second line
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// This file is auto-generated by @hey-api/openapi-ts

import type { CancelablePromise } from './core/CancelablePromise';
import { OpenAPI } from './core/OpenAPI';
import { request as __request } from './core/request';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// This file is auto-generated by @hey-api/openapi-ts

export { ApiError } from './core/ApiError';
export { CancelablePromise, CancelError } from './core/CancelablePromise';
export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// This file is auto-generated by @hey-api/openapi-ts

/**
* Testing multiline comments in string: First line
* Second line
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// This file is auto-generated by @hey-api/openapi-ts

export const $CommentWithBreaks = {
description: `Testing multiline comments in string: First line
Second line
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// This file is auto-generated by @hey-api/openapi-ts

import type { CancelablePromise } from './core/CancelablePromise';
import { OpenAPI } from './core/OpenAPI';
import { request as __request } from './core/request';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// This file is auto-generated by @hey-api/openapi-ts

export { ApiError } from './core/ApiError';
export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI';
export * from './models';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// This file is auto-generated by @hey-api/openapi-ts

/**
* Testing multiline comments in string: First line
* Second line
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// This file is auto-generated by @hey-api/openapi-ts

export const $CommentWithBreaks = {
description: `Testing multiline comments in string: First line
Second line
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// This file is auto-generated by @hey-api/openapi-ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import type { Observable } from 'rxjs';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// This file is auto-generated by @hey-api/openapi-ts

export { ApiError } from './core/ApiError';
export { CancelablePromise, CancelError } from './core/CancelablePromise';
export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI';
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// This file is auto-generated by @hey-api/openapi-ts

export { ApiClient } from './ApiClient';
export { ApiError } from './core/ApiError';
export { BaseHttpRequest } from './core/BaseHttpRequest';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// This file is auto-generated by @hey-api/openapi-ts

/**
* Testing multiline comments in string: First line
* Second line
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// This file is auto-generated by @hey-api/openapi-ts

import type { CancelablePromise } from './core/CancelablePromise';
import type { BaseHttpRequest } from './core/BaseHttpRequest';
import type { $OpenApiTs } from './models';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts

export * from './models';
export * from './schemas';
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// This file is auto-generated by @hey-api/openapi-ts

/**
* This is a model that contains a some patterns
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// This file is auto-generated by @hey-api/openapi-ts

export const $CommentWithBreaks = {
description: `Testing multiline comments in string: First line
Second line
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// This file is auto-generated by @hey-api/openapi-ts

export { ApiError } from './core/ApiError';
export { CancelablePromise, CancelError } from './core/CancelablePromise';
export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// This file is auto-generated by @hey-api/openapi-ts

/**
* Testing multiline comments in string: First line
* Second line
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// This file is auto-generated by @hey-api/openapi-ts

export const $CommentWithBreaks = {
description: `Testing multiline comments in string: First line
Second line
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// This file is auto-generated by @hey-api/openapi-ts

import type { CancelablePromise } from './core/CancelablePromise';
import { OpenAPI } from './core/OpenAPI';
import { request as __request } from './core/request';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// This file is auto-generated by @hey-api/openapi-ts

export { ApiError } from './core/ApiError';
export { CancelablePromise, CancelError } from './core/CancelablePromise';
export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// This file is auto-generated by @hey-api/openapi-ts

/**
* This is a model with one string property
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// This file is auto-generated by @hey-api/openapi-ts

import type { CancelablePromise } from './core/CancelablePromise';
import { OpenAPI } from './core/OpenAPI';
import { request as __request } from './core/request';
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
// This file is auto-generated by @hey-api/openapi-ts

export * from './models';
Loading

0 comments on commit 336d19c

Please sign in to comment.