diff --git a/.vscode/launch.json b/.vscode/launch.json index 270e5574..57096227 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,26 +1,31 @@ { - // Use IntelliSense to learn about possible attributes. - // Hover to view descriptions of existing attributes. - // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 - "version": "0.2.0", - "configurations": [ - { - "type": "node", - "request": "launch", - "name": "Launch Generator", - "program": "${workspaceFolder}\\typescript-axios\\node_modules/@openapitools/openapi-generator-cli/bin/openapi-generator", - "args": [ - "generate", "-i", "schemas/petstore.yaml", "-g", "typescript-axios", "-o", "typescript-axios/out.local", - "-t", "typescript-axios/templates/" - ], - "outFiles": [ - "${workspaceFolder}/**/*.js" - ] - }, - { - "name": ".NET Core Attach", - "type": "coreclr", - "request": "attach" - } - ] -} \ No newline at end of file + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "type": "node", + "request": "launch", + "name": "Launch Generator", + "program": "${workspaceFolder}\\typescript-axios\\node_modules/@openapitools/openapi-generator-cli/bin/openapi-generator", + "args": [ + "generate", + "-i", + "schemas/petstore.yaml", + "-g", + "typescript-axios", + "-o", + "typescript-axios/out.local", + "-t", + "typescript-axios/templates/" + ], + "outFiles": ["${workspaceFolder}/**/*.js"] + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach" + } + ] +} diff --git a/.vscode/tasks.json b/.vscode/tasks.json index d5c43676..6cc9249e 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -1,25 +1,25 @@ { - // See https://go.microsoft.com/fwlink/?LinkId=733558 - // for the documentation about the tasks.json format - "version": "2.0.0", - "tasks": [ - { - "label": "Generate .NET Core Coverage Results", - "type": "shell", - "command": "${workspaceFolder}/eng/code-coverage/generate-code-results.ps1", - "group": "test" - }, - { - "label": "View .NET Core Coverage Results", - "isBackground": true, - "type": "shell", - "command": "npx", - "args": [ - "lite-server", - "-c", - "eng/code-coverage/lite-server-code-coverage-config.json" - ], - "problemMatcher": [] - } - ] -} \ No newline at end of file + // See https://go.microsoft.com/fwlink/?LinkId=733558 + // for the documentation about the tasks.json format + "version": "2.0.0", + "tasks": [ + { + "label": "Generate .NET Core Coverage Results", + "type": "shell", + "command": "${workspaceFolder}/eng/code-coverage/generate-code-results.ps1", + "group": "test" + }, + { + "label": "View .NET Core Coverage Results", + "isBackground": true, + "type": "shell", + "command": "npx", + "args": [ + "lite-server", + "-c", + "eng/code-coverage/lite-server-code-coverage-config.json" + ], + "problemMatcher": [] + } + ] +} diff --git a/eng/code-coverage/lite-server-code-coverage-config.json b/eng/code-coverage/lite-server-code-coverage-config.json index 5370b237..3cb7c608 100644 --- a/eng/code-coverage/lite-server-code-coverage-config.json +++ b/eng/code-coverage/lite-server-code-coverage-config.json @@ -1,4 +1,4 @@ { - "startPath": "index.htm", - "server": { "baseDir": "./artifacts/coveragereport" } -} \ No newline at end of file + "startPath": "index.htm", + "server": { "baseDir": "./artifacts/coveragereport" } +} diff --git a/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample.Oauth/Properties/launchSettings.json b/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample.Oauth/Properties/launchSettings.json index bc919996..95b6c3e2 100644 --- a/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample.Oauth/Properties/launchSettings.json +++ b/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample.Oauth/Properties/launchSettings.json @@ -1,28 +1,28 @@ { - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:9799", - "sslPort": 44342 - } - }, - "profiles": { - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "PrincipleStudios.ServerInterfacesExample.Oauth": { - "commandName": "Project", - "dotnetRunMessages": "true", - "launchBrowser": true, - "applicationUrl": "https://localhost:5001;http://localhost:5000", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - } - } + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:9799", + "sslPort": 44342 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "PrincipleStudios.ServerInterfacesExample.Oauth": { + "commandName": "Project", + "dotnetRunMessages": "true", + "launchBrowser": true, + "applicationUrl": "https://localhost:5001;http://localhost:5000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } } diff --git a/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample.Oauth/appsettings.Development.json b/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample.Oauth/appsettings.Development.json index 8983e0fc..b1c285de 100644 --- a/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample.Oauth/appsettings.Development.json +++ b/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample.Oauth/appsettings.Development.json @@ -1,9 +1,9 @@ { - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft": "Warning", - "Microsoft.Hosting.Lifetime": "Information" - } - } + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + } } diff --git a/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample.Oauth/appsettings.json b/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample.Oauth/appsettings.json index af96abde..57d406d9 100644 --- a/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample.Oauth/appsettings.json +++ b/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample.Oauth/appsettings.json @@ -1,14 +1,14 @@ { - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft": "Warning", - "Microsoft.Hosting.Lifetime": "Information" - } - }, - "AllowedHosts": "*", - "GitHub": { - "ClientId": "FAKE_KEY", - "ClientSecret": "FAKE_KEY" - } + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + }, + "AllowedHosts": "*", + "GitHub": { + "ClientId": "FAKE_KEY", + "ClientSecret": "FAKE_KEY" + } } diff --git a/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample/.vscode/launch.json b/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample/.vscode/launch.json index eef648ce..48b469f0 100644 --- a/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample/.vscode/launch.json +++ b/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample/.vscode/launch.json @@ -1,35 +1,35 @@ { - "version": "0.2.0", - "configurations": [ - { - // Use IntelliSense to find out which attributes exist for C# debugging - // Use hover for the description of the existing attributes - // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md - "name": ".NET Core Launch (web)", - "type": "coreclr", - "request": "launch", - "preLaunchTask": "build", - // If you have changed target frameworks, make sure to update the program path. - "program": "${workspaceFolder}/bin/Debug/net6.0/PrincipleStudios.ServerInterfacesExample.dll", - "args": [], - "cwd": "${workspaceFolder}", - "stopAtEntry": false, - // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser - "serverReadyAction": { - "action": "openExternally", - "pattern": "\\bNow listening on:\\s+(https?://\\S+)" - }, - "env": { - "ASPNETCORE_ENVIRONMENT": "Development" - }, - "sourceFileMap": { - "/Views": "${workspaceFolder}/Views" - } - }, - { - "name": ".NET Core Attach", - "type": "coreclr", - "request": "attach" - } - ] -} \ No newline at end of file + "version": "0.2.0", + "configurations": [ + { + // Use IntelliSense to find out which attributes exist for C# debugging + // Use hover for the description of the existing attributes + // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md + "name": ".NET Core Launch (web)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + // If you have changed target frameworks, make sure to update the program path. + "program": "${workspaceFolder}/bin/Debug/net6.0/PrincipleStudios.ServerInterfacesExample.dll", + "args": [], + "cwd": "${workspaceFolder}", + "stopAtEntry": false, + // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser + "serverReadyAction": { + "action": "openExternally", + "pattern": "\\bNow listening on:\\s+(https?://\\S+)" + }, + "env": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "sourceFileMap": { + "/Views": "${workspaceFolder}/Views" + } + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach" + } + ] +} diff --git a/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample/.vscode/tasks.json b/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample/.vscode/tasks.json index f5ef71a8..3e6f28ac 100644 --- a/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample/.vscode/tasks.json +++ b/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample/.vscode/tasks.json @@ -1,41 +1,41 @@ { - "version": "2.0.0", - "tasks": [ - { - "label": "build", - "command": "dotnet", - "type": "process", - "args": [ - "build", - "${workspaceFolder}/PrincipleStudios.ServerInterfacesExample.csproj", - "/property:GenerateFullPaths=true", - "/consoleloggerparameters:NoSummary" - ], - "problemMatcher": "$msCompile" - }, - { - "label": "publish", - "command": "dotnet", - "type": "process", - "args": [ - "publish", - "${workspaceFolder}/PrincipleStudios.ServerInterfacesExample.csproj", - "/property:GenerateFullPaths=true", - "/consoleloggerparameters:NoSummary" - ], - "problemMatcher": "$msCompile" - }, - { - "label": "watch", - "command": "dotnet", - "type": "process", - "args": [ - "watch", - "run", - "--project", - "${workspaceFolder}/PrincipleStudios.ServerInterfacesExample.csproj" - ], - "problemMatcher": "$msCompile" - } - ] -} \ No newline at end of file + "version": "2.0.0", + "tasks": [ + { + "label": "build", + "command": "dotnet", + "type": "process", + "args": [ + "build", + "${workspaceFolder}/PrincipleStudios.ServerInterfacesExample.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "publish", + "command": "dotnet", + "type": "process", + "args": [ + "publish", + "${workspaceFolder}/PrincipleStudios.ServerInterfacesExample.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "watch", + "command": "dotnet", + "type": "process", + "args": [ + "watch", + "run", + "--project", + "${workspaceFolder}/PrincipleStudios.ServerInterfacesExample.csproj" + ], + "problemMatcher": "$msCompile" + } + ] +} diff --git a/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample/Properties/launchSettings.json b/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample/Properties/launchSettings.json index a3d63673..7ec236f1 100644 --- a/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample/Properties/launchSettings.json +++ b/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample/Properties/launchSettings.json @@ -1,30 +1,30 @@ { - "$schema": "http://json.schemastore.org/launchsettings.json", - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:53350", - "sslPort": 44341 - } - }, - "profiles": { - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "launchUrl": "api/pets", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "PrincipleStudios.ServerInterfacesExample": { - "commandName": "Project", - "launchBrowser": true, - "launchUrl": "", - "applicationUrl": "https://localhost:5001;http://localhost:5000", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - } - } + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:53350", + "sslPort": 44341 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "api/pets", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "PrincipleStudios.ServerInterfacesExample": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "", + "applicationUrl": "https://localhost:5001;http://localhost:5000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } } diff --git a/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample/appsettings.Development.json b/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample/appsettings.Development.json index 8983e0fc..b1c285de 100644 --- a/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample/appsettings.Development.json +++ b/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample/appsettings.Development.json @@ -1,9 +1,9 @@ { - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft": "Warning", - "Microsoft.Hosting.Lifetime": "Information" - } - } + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + } } diff --git a/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample/appsettings.json b/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample/appsettings.json index d9d9a9bf..a7644e48 100644 --- a/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample/appsettings.json +++ b/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample/appsettings.json @@ -1,10 +1,10 @@ { - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft": "Warning", - "Microsoft.Hosting.Lifetime": "Information" - } - }, - "AllowedHosts": "*" + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + }, + "AllowedHosts": "*" } diff --git a/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample/csharp.config.yaml b/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample/csharp.config.yaml index af6587ee..6a3510c8 100644 --- a/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample/csharp.config.yaml +++ b/examples/dotnetcore-server-interfaces/PrincipleStudios.ServerInterfacesExample/csharp.config.yaml @@ -1,4 +1,4 @@ types: integer: formats: - int32: System.Int32 \ No newline at end of file + int32: System.Int32 diff --git a/examples/dotnetstandard-client/PrincipleStudios.ClientInterfacesExample/appsettings.Development.json b/examples/dotnetstandard-client/PrincipleStudios.ClientInterfacesExample/appsettings.Development.json index 8983e0fc..b1c285de 100644 --- a/examples/dotnetstandard-client/PrincipleStudios.ClientInterfacesExample/appsettings.Development.json +++ b/examples/dotnetstandard-client/PrincipleStudios.ClientInterfacesExample/appsettings.Development.json @@ -1,9 +1,9 @@ { - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft": "Warning", - "Microsoft.Hosting.Lifetime": "Information" - } - } + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + } } diff --git a/examples/dotnetstandard-client/PrincipleStudios.ClientInterfacesExample/appsettings.json b/examples/dotnetstandard-client/PrincipleStudios.ClientInterfacesExample/appsettings.json index d9d9a9bf..a7644e48 100644 --- a/examples/dotnetstandard-client/PrincipleStudios.ClientInterfacesExample/appsettings.json +++ b/examples/dotnetstandard-client/PrincipleStudios.ClientInterfacesExample/appsettings.json @@ -1,10 +1,10 @@ { - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft": "Warning", - "Microsoft.Hosting.Lifetime": "Information" - } - }, - "AllowedHosts": "*" + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + }, + "AllowedHosts": "*" } diff --git a/generators/typescript-fetch/babel.config.js b/generators/typescript-fetch/babel.config.js index 9ab199fb..edc01a5c 100644 --- a/generators/typescript-fetch/babel.config.js +++ b/generators/typescript-fetch/babel.config.js @@ -1,12 +1,14 @@ module.exports = { - presets: [ - ['@babel/preset-env', - { - "modules": "commonjs", - "targets": { - "node": "current" - } - }], - '@babel/preset-typescript', - ] - }; + presets: [ + [ + '@babel/preset-env', + { + modules: 'commonjs', + targets: { + node: 'current', + }, + }, + ], + '@babel/preset-typescript', + ], +}; diff --git a/generators/typescript-fetch/jest.config.js b/generators/typescript-fetch/jest.config.js index fac338b1..c1159e70 100644 --- a/generators/typescript-fetch/jest.config.js +++ b/generators/typescript-fetch/jest.config.js @@ -1,8 +1,7 @@ module.exports = { - testEnvironment: 'node', - transform: { - "^.+\\.(js|ts)$": "babel-jest", - }, - transformIgnorePatterns: [ - ], + testEnvironment: 'node', + transform: { + '^.+\\.(js|ts)$': 'babel-jest', + }, + transformIgnorePatterns: [], }; diff --git a/generators/typescript-fetch/tests/multi-path-variables.test.ts b/generators/typescript-fetch/tests/multi-path-variables.test.ts index 1cba7358..f376c304 100644 --- a/generators/typescript-fetch/tests/multi-path-variables.test.ts +++ b/generators/typescript-fetch/tests/multi-path-variables.test.ts @@ -1,41 +1,59 @@ import { toMswHandler } from '@principlestudios/openapi-codegen-typescript-msw'; -import { setupServer } from 'msw/node' +import { setupServer } from 'msw/node'; import fetch from 'node-fetch'; import { toFetchApi, toFetchOperation } from '../src'; -import type { FetchImplementation} from '../src'; +import type { FetchImplementation } from '../src'; import operations from './multi-path-variables/operations'; -const fetchImpl: FetchImplementation = (url, params) => fetch('http://localhost' + String(url), params); +const fetchImpl: FetchImplementation = (url, params) => + fetch('http://localhost' + String(url), params); const fetchApi = toFetchApi(operations, fetchImpl); const getPhotoMeta = toMswHandler(operations.getPhotoMeta); describe('typescript-fetch multi-path-variables.yaml', () => { - const server = setupServer(); + const server = setupServer(); - beforeAll(() => server.listen()); - afterEach(() => server.resetHandlers()); - afterAll(() => server.close()); + beforeAll(() => server.listen()); + afterEach(() => server.resetHandlers()); + afterAll(() => server.close()); - it('can wrap a get as a single operation', async () => { - const getPhotoMetaOperation = toFetchOperation(fetchImpl, operations.getPhotoMeta); - const outputMeta = 'unknown data'; - server.use( - getPhotoMeta({ params: { id: '123', key: 'author'} }, { statusCode: 200, data: outputMeta, mimeType: 'application/json' }) - ); - const response = await getPhotoMetaOperation({ params: { id: '123', key: 'author'} }); - expect(response.statusCode).toBe(200); - expect(response.response.getResponseHeader('Content-Type')).toBe('application/json'); - expect(response.data).toEqual(outputMeta); - }); + it('can wrap a get as a single operation', async () => { + const getPhotoMetaOperation = toFetchOperation( + fetchImpl, + operations.getPhotoMeta, + ); + const outputMeta = 'unknown data'; + server.use( + getPhotoMeta( + { params: { id: '123', key: 'author' } }, + { statusCode: 200, data: outputMeta, mimeType: 'application/json' }, + ), + ); + const response = await getPhotoMetaOperation({ + params: { id: '123', key: 'author' }, + }); + expect(response.statusCode).toBe(200); + expect(response.response.getResponseHeader('Content-Type')).toBe( + 'application/json', + ); + expect(response.data).toEqual(outputMeta); + }); - it('can wrap a get', async () => { - const outputMeta = 'unknown data'; - server.use( - getPhotoMeta({ params: { id: '123', key: 'author'} }, { statusCode: 200, data: outputMeta, mimeType: 'application/json' }) - ); - const response = await fetchApi.getPhotoMeta({ params: { id: '123', key: 'author'} }); - expect(response.statusCode).toBe(200); - expect(response.response.getResponseHeader('Content-Type')).toBe('application/json'); - expect(response.data).toEqual(outputMeta); - }); + it('can wrap a get', async () => { + const outputMeta = 'unknown data'; + server.use( + getPhotoMeta( + { params: { id: '123', key: 'author' } }, + { statusCode: 200, data: outputMeta, mimeType: 'application/json' }, + ), + ); + const response = await fetchApi.getPhotoMeta({ + params: { id: '123', key: 'author' }, + }); + expect(response.statusCode).toBe(200); + expect(response.response.getResponseHeader('Content-Type')).toBe( + 'application/json', + ); + expect(response.data).toEqual(outputMeta); + }); }); diff --git a/generators/typescript-fetch/tests/petstore.test.ts b/generators/typescript-fetch/tests/petstore.test.ts index 2f8acf48..5bdcdc78 100644 --- a/generators/typescript-fetch/tests/petstore.test.ts +++ b/generators/typescript-fetch/tests/petstore.test.ts @@ -1,104 +1,157 @@ -import { toMswHandler, toMswResponse } from '@principlestudios/openapi-codegen-typescript-msw'; -import { setupServer } from 'msw/node' +import { + toMswHandler, + toMswResponse, +} from '@principlestudios/openapi-codegen-typescript-msw'; +import { setupServer } from 'msw/node'; import fetch from 'node-fetch'; import { toFetchApi, toFetchOperation } from '../src'; -import type { FetchImplementation} from '../src'; +import type { FetchImplementation } from '../src'; import operations from './petstore/operations'; -const fetchImpl: FetchImplementation = (url, params) => fetch('http://localhost' + String(url), params); +const fetchImpl: FetchImplementation = (url, params) => + fetch('http://localhost' + String(url), params); const fetchApi = toFetchApi(operations, fetchImpl); const findPets = toMswHandler(operations.findPets); const addPet = toMswHandler(operations.addPet); describe('typescript-fetch petstore.yaml', () => { - const server = setupServer(); + const server = setupServer(); - beforeAll(() => server.listen()); - afterEach(() => server.resetHandlers()); - afterAll(() => server.close()); + beforeAll(() => server.listen()); + afterEach(() => server.resetHandlers()); + afterAll(() => server.close()); - it('can wrap a post as a single operation', async () => { - const addPetOperation = toFetchOperation(fetchImpl, operations.addPet); - const inputPet = { name: 'Fido', tag: 'dog' }; - const outputPet = { ...inputPet, id: 1234 }; - server.use( - addPet({ params: {}, body: inputPet, mimeType: 'application/json'}, { statusCode: 200, data: { ...outputPet }, mimeType: 'application/json' }) - ); - const response = await addPetOperation({ body: inputPet }); - expect(response.statusCode).toBe(200); - expect(response.response.getResponseHeader('Content-Type')).toBe('application/json'); - expect(response.data).toEqual(outputPet); - }); + it('can wrap a post as a single operation', async () => { + const addPetOperation = toFetchOperation(fetchImpl, operations.addPet); + const inputPet = { name: 'Fido', tag: 'dog' }; + const outputPet = { ...inputPet, id: 1234 }; + server.use( + addPet( + { params: {}, body: inputPet, mimeType: 'application/json' }, + { + statusCode: 200, + data: { ...outputPet }, + mimeType: 'application/json', + }, + ), + ); + const response = await addPetOperation({ body: inputPet }); + expect(response.statusCode).toBe(200); + expect(response.response.getResponseHeader('Content-Type')).toBe( + 'application/json', + ); + expect(response.data).toEqual(outputPet); + }); - it('can wrap a post', async () => { - const inputPet = { name: 'Fido', tag: 'dog' }; - const outputPet = { ...inputPet, id: 1234 }; - server.use( - addPet({ params: {}, body: inputPet, mimeType: 'application/json'}, { statusCode: 200, data: { ...outputPet }, mimeType: 'application/json' }) - ); - const response = await fetchApi.addPet({ body: inputPet }); - expect(response.statusCode).toBe(200); - expect(response.response.getResponseHeader('Content-Type')).toBe('application/json'); - expect(response.data).toEqual(outputPet); - }); + it('can wrap a post', async () => { + const inputPet = { name: 'Fido', tag: 'dog' }; + const outputPet = { ...inputPet, id: 1234 }; + server.use( + addPet( + { params: {}, body: inputPet, mimeType: 'application/json' }, + { + statusCode: 200, + data: { ...outputPet }, + mimeType: 'application/json', + }, + ), + ); + const response = await fetchApi.addPet({ body: inputPet }); + expect(response.statusCode).toBe(200); + expect(response.response.getResponseHeader('Content-Type')).toBe( + 'application/json', + ); + expect(response.data).toEqual(outputPet); + }); - it('can wrap two different posts', async () => { - const inputPet1 = { name: 'Fido', tag: 'dog' }; - const inputPet2 = { name: 'Felix', tag: 'cat' }; - const outputPet1 = { ...inputPet1, id: 1234 }; - const outputPet2 = { ...inputPet2, id: 1235 }; - server.use( - addPet({ params: {}, body: inputPet1, mimeType: 'application/json' }, { statusCode: 200, data: { ...outputPet1 }, mimeType: 'application/json' }), - addPet({ params: {}, body: inputPet2, mimeType: 'application/json' }, { statusCode: 200, data: { ...outputPet2 }, mimeType: 'application/json' }) - ); - const response2 = await fetchApi.addPet({ body: inputPet2 }); - const response1 = await fetchApi.addPet({ body: inputPet1 }); - expect(response1.statusCode).toBe(200); - expect(response1.response.getResponseHeader('Content-Type')).toBe('application/json'); - expect(response1.data).toEqual(outputPet1); - expect(response2.statusCode).toBe(200); - expect(response2.response.getResponseHeader('Content-Type')).toBe('application/json'); - expect(response2.data).toEqual(outputPet2); - }); + it('can wrap two different posts', async () => { + const inputPet1 = { name: 'Fido', tag: 'dog' }; + const inputPet2 = { name: 'Felix', tag: 'cat' }; + const outputPet1 = { ...inputPet1, id: 1234 }; + const outputPet2 = { ...inputPet2, id: 1235 }; + server.use( + addPet( + { params: {}, body: inputPet1, mimeType: 'application/json' }, + { + statusCode: 200, + data: { ...outputPet1 }, + mimeType: 'application/json', + }, + ), + addPet( + { params: {}, body: inputPet2, mimeType: 'application/json' }, + { + statusCode: 200, + data: { ...outputPet2 }, + mimeType: 'application/json', + }, + ), + ); + const response2 = await fetchApi.addPet({ body: inputPet2 }); + const response1 = await fetchApi.addPet({ body: inputPet1 }); + expect(response1.statusCode).toBe(200); + expect(response1.response.getResponseHeader('Content-Type')).toBe( + 'application/json', + ); + expect(response1.data).toEqual(outputPet1); + expect(response2.statusCode).toBe(200); + expect(response2.response.getResponseHeader('Content-Type')).toBe( + 'application/json', + ); + expect(response2.data).toEqual(outputPet2); + }); - it('can wrap any post', async () => { - server.use( - addPet({ params: {} }, async (req, res, ctx) => { - return toMswResponse({ - statusCode: 200, - data: { id: 1234, ...(await req.json()) }, - mimeType: 'application/json' - }, res, ctx); - }) - ); - const response = await fetchApi.addPet({ body: ({ name: 'Fido', tag: 'dog' }) }); - expect(response.statusCode).toBe(200); - expect(response.response.getResponseHeader('Content-Type')).toBe('application/json'); - expect(response.data).toEqual({ name: 'Fido', tag: 'dog', id: 1234 }); + it('can wrap any post', async () => { + server.use( + addPet({ params: {} }, async (req, res, ctx) => { + return toMswResponse( + { + statusCode: 200, + data: { id: 1234, ...(await req.json()) }, + mimeType: 'application/json', + }, + res, + ctx, + ); + }), + ); + const response = await fetchApi.addPet({ + body: { name: 'Fido', tag: 'dog' }, + }); + expect(response.statusCode).toBe(200); + expect(response.response.getResponseHeader('Content-Type')).toBe( + 'application/json', + ); + expect(response.data).toEqual({ name: 'Fido', tag: 'dog', id: 1234 }); + const response2 = await fetch('http://localhost/pets', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ name: 'Felix', tag: 'cat' }), + }); + expect(await response2.json()).toEqual({ + name: 'Felix', + tag: 'cat', + id: 1234, + }); + }); - const response2 = await fetch('http://localhost/pets', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ name: 'Felix', tag: 'cat' }), - }); - expect(await response2.json()).toEqual({ name: 'Felix', tag: 'cat', id: 1234 }); - }); - - it('can wrap query strings in a get', async () => { - const inputParams = { tags: ['dog','cat'], limit: 10 }; - const outputPets = [{ name: 'Fido', tag: 'dog', id: 1234 }]; - server.use( - findPets( - { params: inputParams }, - { statusCode: 200, data: outputPets, mimeType: 'application/json' } - ) - ); - const response = await fetchApi.findPets({ params: inputParams }); - expect(response.data).toEqual(outputPets); - expect(response.statusCode).toBe(200); - expect(response.response.getResponseHeader('Content-Type')).toBe('application/json'); - }); -}); \ No newline at end of file + it('can wrap query strings in a get', async () => { + const inputParams = { tags: ['dog', 'cat'], limit: 10 }; + const outputPets = [{ name: 'Fido', tag: 'dog', id: 1234 }]; + server.use( + findPets( + { params: inputParams }, + { statusCode: 200, data: outputPets, mimeType: 'application/json' }, + ), + ); + const response = await fetchApi.findPets({ params: inputParams }); + expect(response.data).toEqual(outputPets); + expect(response.statusCode).toBe(200); + expect(response.response.getResponseHeader('Content-Type')).toBe( + 'application/json', + ); + }); +}); diff --git a/generators/typescript-fetch/tsconfig.json b/generators/typescript-fetch/tsconfig.json index ee6ed124..9854eb41 100644 --- a/generators/typescript-fetch/tsconfig.json +++ b/generators/typescript-fetch/tsconfig.json @@ -1,19 +1,16 @@ { - "compilerOptions": { - "outDir": "./lib", - "noEmit": false, - "declaration": true, - "rootDir": "./src", - "composite": true - }, - "extends": "./tsconfig.node.json", - "include": [ - "./src", - "./types.d.ts" - ], + "compilerOptions": { + "outDir": "./lib", + "noEmit": false, + "declaration": true, + "rootDir": "./src", + "composite": true + }, + "extends": "./tsconfig.node.json", + "include": ["./src", "./types.d.ts"], "references": [ { "path": "./tsconfig.node.json" - }, - ], -} \ No newline at end of file + } + ] +} diff --git a/generators/typescript-fetch/tsconfig.node.json b/generators/typescript-fetch/tsconfig.node.json index 4f3e1189..472ec6fb 100644 --- a/generators/typescript-fetch/tsconfig.node.json +++ b/generators/typescript-fetch/tsconfig.node.json @@ -1,26 +1,24 @@ { - "compilerOptions": { - "target": "es6", - "lib": [ - "esnext" - ], - "allowJs": true, - "skipLibCheck": true, - "esModuleInterop": true, - "strict": true, - "forceConsistentCasingInFileNames": true, - "module": "commonjs", - "moduleResolution": "node", - "resolveJsonModule": true, - "isolatedModules": true, - "noEmit": false, - "composite": true, - "declaration": true, - "outDir": "../../artifacts/generators/typescript-fetch/", - "types": ["node", "jest"], - "rootDir": ".", - "paths": { - "@principlestudios/openapi-codegen-typescript-fetch": ["./src"], - } - } + "compilerOptions": { + "target": "es6", + "lib": ["esnext"], + "allowJs": true, + "skipLibCheck": true, + "esModuleInterop": true, + "strict": true, + "forceConsistentCasingInFileNames": true, + "module": "commonjs", + "moduleResolution": "node", + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": false, + "composite": true, + "declaration": true, + "outDir": "../../artifacts/generators/typescript-fetch/", + "types": ["node", "jest"], + "rootDir": ".", + "paths": { + "@principlestudios/openapi-codegen-typescript-fetch": ["./src"] + } + } } diff --git a/generators/typescript-msw/npm/babel.config.js b/generators/typescript-msw/npm/babel.config.js index 9ab199fb..edc01a5c 100644 --- a/generators/typescript-msw/npm/babel.config.js +++ b/generators/typescript-msw/npm/babel.config.js @@ -1,12 +1,14 @@ module.exports = { - presets: [ - ['@babel/preset-env', - { - "modules": "commonjs", - "targets": { - "node": "current" - } - }], - '@babel/preset-typescript', - ] - }; + presets: [ + [ + '@babel/preset-env', + { + modules: 'commonjs', + targets: { + node: 'current', + }, + }, + ], + '@babel/preset-typescript', + ], +}; diff --git a/generators/typescript-msw/npm/src/index.ts b/generators/typescript-msw/npm/src/index.ts index 01d6782a..438539c5 100644 --- a/generators/typescript-msw/npm/src/index.ts +++ b/generators/typescript-msw/npm/src/index.ts @@ -3,95 +3,172 @@ /* eslint-disable @typescript-eslint/naming-convention */ /* eslint-disable @typescript-eslint/no-unsafe-argument */ // TODO: this likely needs to be rewritten to support newer msw anyway -import type { AdapterRequestArgs, HttpMethod, RequestBodies, RequestConversion, StandardResponse, TransformCallType } from '@principlestudios/openapi-codegen-typescript'; -import type { DefaultBodyType, Match, MockedRequest, MockedResponse, ResponseResolverReturnType, ResponseComposition, RestContext } from 'msw'; -import { RestHandler } from 'msw' +import type { + AdapterRequestArgs, + HttpMethod, + RequestBodies, + RequestConversion, + StandardResponse, + TransformCallType, +} from '@principlestudios/openapi-codegen-typescript'; +import type { + DefaultBodyType, + Match, + MockedRequest, + MockedResponse, + ResponseResolverReturnType, + ResponseComposition, + RestContext, +} from 'msw'; +import { RestHandler } from 'msw'; function deepEqual(x: unknown, y: unknown): boolean { - const tx = typeof x, - ty = typeof y; - if (!x || !y || tx !== 'object' || tx !== ty) return x === y; + const tx = typeof x, + ty = typeof y; + if (!x || !y || tx !== 'object' || tx !== ty) return x === y; - const xKeys = Object.keys(x), - yKeys = Object.keys(y); - return xKeys.length === yKeys.length && xKeys.every(key => - deepEqual((x as Record)[key], (y as Record)[key]) - ); + const xKeys = Object.keys(x), + yKeys = Object.keys(y); + return ( + xKeys.length === yKeys.length && + xKeys.every((key) => + deepEqual( + (x as Record)[key], + (y as Record)[key], + ), + ) + ); } -export type AsyncResponseResolver = (req: RequestType, res: ResponseComposition, context: RestContext) => ResponseResolverReturnType> | Promise>>; +export type AsyncResponseResolver< + RequestType = MockedRequest, + BodyType extends DefaultBodyType = any, +> = ( + req: RequestType, + res: ResponseComposition, + context: RestContext, +) => + | ResponseResolverReturnType> + | Promise>>; -export type SafeResponse = - Omit - & { headers?: Record }; +export type SafeResponse = Omit< + T, + 'response' +> & { headers?: Record }; -export function toMswResponse(response: SafeResponse, res: ResponseComposition, ctx: RestContext) { - return res( - ctx.status(response.statusCode === 'other' ? 0 : response.statusCode), - ctx.json(response.data) - // TODO: support headers - ); +export function toMswResponse( + response: SafeResponse, + res: ResponseComposition, + ctx: RestContext, +) { + return res( + ctx.status(response.statusCode === 'other' ? 0 : response.statusCode), + ctx.json(response.data), + // TODO: support headers + ); } -export class MappedRestHandler extends RestHandler { - constructor(private request: AdapterRequestArgs, response: SafeResponse | AsyncResponseResolver) { - super(request.method, new URL(request.path.split('?')[0], 'http://localhost').toString(), - async (req: T, res, ctx): Promise>> => { - if ('body' in request) { - if (!deepEqual(request.body, await req.json())) { - this.shouldSkip = true; - return res(); - } - } else if (req.bodyUsed) { - this.shouldSkip = true; - return res(); - } - // TODO: request headers aren't checked +export class MappedRestHandler< + T extends MockedRequest = MockedRequest, +> extends RestHandler { + constructor( + private request: AdapterRequestArgs, + response: SafeResponse | AsyncResponseResolver, + ) { + super( + request.method, + new URL(request.path.split('?')[0], 'http://localhost').toString(), + async ( + req: T, + res, + ctx, + ): Promise>> => { + if ('body' in request) { + if (!deepEqual(request.body, await req.json())) { + this.shouldSkip = true; + return res(); + } + } else if (req.bodyUsed) { + this.shouldSkip = true; + return res(); + } + // TODO: request headers aren't checked - if (typeof response === 'function') return response(req, res, ctx); - return toMswResponse(response, res, ctx); - }); - } + if (typeof response === 'function') return response(req, res, ctx); + return toMswResponse(response, res, ctx); + }, + ); + } - override run(...params: Parameters['run']>): ReturnType['run']> { - this.shouldSkip = false; - return super.run(...params); - } + override run( + ...params: Parameters['run']> + ): ReturnType['run']> { + this.shouldSkip = false; + return super.run(...params); + } - override predicate(request: T, parsedResult: Match): boolean { - // body isn't checked here because this can't be async, so instead it is checked in the MappedRestHandler above - return super.predicate(request, parsedResult) && this.queryStringMatch(request); - } + override predicate(request: T, parsedResult: Match): boolean { + // body isn't checked here because this can't be async, so instead it is checked in the MappedRestHandler above + return ( + super.predicate(request, parsedResult) && this.queryStringMatch(request) + ); + } - private queryStringMatch(request: T) { - return request.url.searchParams.toString() == (this.request.path.split('?')[1] ?? ''); - } + private queryStringMatch(request: T) { + return ( + request.url.searchParams.toString() == + (this.request.path.split('?')[1] ?? '') + ); + } } export function toMswHandler< - TMethod extends HttpMethod, - TUrlParams extends {}, - TRequestParams extends TUrlParams, - TRequestBodies extends RequestBodies, - TResponses extends StandardResponse, - TCallType extends TransformCallType ->(conversion: RequestConversion) { - type MyRequest = - | (TCallType extends 'no-body' | 'optional' - ? { params: TRequestParams, body?: never, mimeType?: never } - : never) - | (TCallType extends 'body' | 'optional' - ? { [K in keyof TRequestBodies]: { params: TRequestParams, body?: TRequestBodies[K], mimeType?: K } }[keyof TRequestBodies] - : never); + TMethod extends HttpMethod, + TUrlParams extends {}, + TRequestParams extends TUrlParams, + TRequestBodies extends RequestBodies, + TResponses extends StandardResponse, + TCallType extends TransformCallType, +>( + conversion: RequestConversion< + TMethod, + TUrlParams, + TRequestParams, + TRequestBodies, + TResponses, + TCallType + >, +) { + type MyRequest = + | (TCallType extends 'no-body' | 'optional' + ? { params: TRequestParams; body?: never; mimeType?: never } + : never) + | (TCallType extends 'body' | 'optional' + ? { + [K in keyof TRequestBodies]: { + params: TRequestParams; + body?: TRequestBodies[K]; + mimeType?: K; + }; + }[keyof TRequestBodies] + : never); - return function (request: MyRequest, response: AsyncResponseResolver | SafeResponse) { - const standardRequest: AdapterRequestArgs = 'body' in request - ? conversion.request(request.params, request.body as TRequestBodies[keyof TRequestBodies], request.mimeType as keyof TRequestBodies) - : { - method: conversion.method, - path: conversion.url(request.params), - // TODO: headers support? - }; - return new MappedRestHandler(standardRequest, response); - } + return function ( + request: MyRequest, + response: AsyncResponseResolver | SafeResponse, + ) { + const standardRequest: AdapterRequestArgs = + 'body' in request + ? conversion.request( + request.params, + request.body as TRequestBodies[keyof TRequestBodies], + request.mimeType as keyof TRequestBodies, + ) + : { + method: conversion.method, + path: conversion.url(request.params), + // TODO: headers support? + }; + return new MappedRestHandler(standardRequest, response); + }; } diff --git a/generators/typescript-msw/npm/tests/petstore.test.ts b/generators/typescript-msw/npm/tests/petstore.test.ts index cabda2c4..379c31d9 100644 --- a/generators/typescript-msw/npm/tests/petstore.test.ts +++ b/generators/typescript-msw/npm/tests/petstore.test.ts @@ -1,4 +1,4 @@ -import { setupServer } from 'msw/node' +import { setupServer } from 'msw/node'; import fetch from 'node-fetch'; import { toMswHandler, toMswResponse } from '../src'; import operations from './petstore/operations'; @@ -7,105 +7,139 @@ const findPets = toMswHandler(operations.findPets); const addPet = toMswHandler(operations.addPet); describe('typescript-rxjs petstore.yaml', () => { - const server = setupServer(); + const server = setupServer(); - beforeAll(() => server.listen()); - afterEach(() => server.resetHandlers()); - afterAll(() => server.close()); + beforeAll(() => server.listen()); + afterEach(() => server.resetHandlers()); + afterAll(() => server.close()); - it('can wrap a post', async () => { - const inputPet = { name: 'Fido', tag: 'dog' }; - const outputPet = { ...inputPet, id: 1234 }; - server.use( - addPet({ params: {}, body: inputPet, mimeType: 'application/json'}, { statusCode: 200, data: { ...outputPet }, mimeType: 'application/json' }) - ); - const response = await fetch('http://localhost/pets', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify(inputPet), - }); - expect(response.status).toBe(200); - expect(response.headers.get('Content-Type')).toBe('application/json'); - expect(await response.json()).toEqual(outputPet); - }); + it('can wrap a post', async () => { + const inputPet = { name: 'Fido', tag: 'dog' }; + const outputPet = { ...inputPet, id: 1234 }; + server.use( + addPet( + { params: {}, body: inputPet, mimeType: 'application/json' }, + { + statusCode: 200, + data: { ...outputPet }, + mimeType: 'application/json', + }, + ), + ); + const response = await fetch('http://localhost/pets', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(inputPet), + }); + expect(response.status).toBe(200); + expect(response.headers.get('Content-Type')).toBe('application/json'); + expect(await response.json()).toEqual(outputPet); + }); - it('can wrap two different posts', async () => { - const inputPet1 = { name: 'Fido', tag: 'dog' }; - const inputPet2 = { name: 'Felix', tag: 'cat' }; - const outputPet1 = { ...inputPet1, id: 1234 }; - const outputPet2 = { ...inputPet2, id: 1235 }; - server.use( - addPet({ params: {}, body: inputPet1, mimeType: 'application/json' }, { statusCode: 200, data: { ...outputPet1 }, mimeType: 'application/json' }), - addPet({ params: {}, body: inputPet2, mimeType: 'application/json' }, { statusCode: 200, data: { ...outputPet2 }, mimeType: 'application/json' }) - ); - const response2 = await fetch('http://localhost/pets', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify(inputPet2), - }); - const response1 = await fetch('http://localhost/pets', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify(inputPet1), - }); - expect(response1.status).toBe(200); - expect(response1.headers.get('Content-Type')).toBe('application/json'); - expect(await response1.json()).toEqual(outputPet1); - expect(response2.status).toBe(200); - expect(response2.headers.get('Content-Type')).toBe('application/json'); - expect(await response2.json()).toEqual(outputPet2); - }); + it('can wrap two different posts', async () => { + const inputPet1 = { name: 'Fido', tag: 'dog' }; + const inputPet2 = { name: 'Felix', tag: 'cat' }; + const outputPet1 = { ...inputPet1, id: 1234 }; + const outputPet2 = { ...inputPet2, id: 1235 }; + server.use( + addPet( + { params: {}, body: inputPet1, mimeType: 'application/json' }, + { + statusCode: 200, + data: { ...outputPet1 }, + mimeType: 'application/json', + }, + ), + addPet( + { params: {}, body: inputPet2, mimeType: 'application/json' }, + { + statusCode: 200, + data: { ...outputPet2 }, + mimeType: 'application/json', + }, + ), + ); + const response2 = await fetch('http://localhost/pets', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(inputPet2), + }); + const response1 = await fetch('http://localhost/pets', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(inputPet1), + }); + expect(response1.status).toBe(200); + expect(response1.headers.get('Content-Type')).toBe('application/json'); + expect(await response1.json()).toEqual(outputPet1); + expect(response2.status).toBe(200); + expect(response2.headers.get('Content-Type')).toBe('application/json'); + expect(await response2.json()).toEqual(outputPet2); + }); - it('can wrap any post', async () => { - server.use( - addPet({ params: {} }, async (req, res, ctx) => { - return toMswResponse({ - statusCode: 200, - data: { id: 1234, ...(await req.json()) }, - mimeType: 'application/json' - }, res, ctx); - }) - ); - const response = await fetch('http://localhost/pets', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ name: 'Fido', tag: 'dog' }), - }); - expect(response.status).toBe(200); - expect(response.headers.get('Content-Type')).toBe('application/json'); - expect(await response.json()).toEqual({ name: 'Fido', tag: 'dog', id: 1234 }); + it('can wrap any post', async () => { + server.use( + addPet({ params: {} }, async (req, res, ctx) => { + return toMswResponse( + { + statusCode: 200, + data: { id: 1234, ...(await req.json()) }, + mimeType: 'application/json', + }, + res, + ctx, + ); + }), + ); + const response = await fetch('http://localhost/pets', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ name: 'Fido', tag: 'dog' }), + }); + expect(response.status).toBe(200); + expect(response.headers.get('Content-Type')).toBe('application/json'); + expect(await response.json()).toEqual({ + name: 'Fido', + tag: 'dog', + id: 1234, + }); + const response2 = await fetch('http://localhost/pets', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ name: 'Felix', tag: 'cat' }), + }); + expect(await response2.json()).toEqual({ + name: 'Felix', + tag: 'cat', + id: 1234, + }); + }); - const response2 = await fetch('http://localhost/pets', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ name: 'Felix', tag: 'cat' }), - }); - expect(await response2.json()).toEqual({ name: 'Felix', tag: 'cat', id: 1234 }); - }); - - it('can wrap query strings in a get', async () => { - const inputParams = { tags: ['dog','cat'], limit: 10 }; - const outputPets = [{ name: 'Fido', tag: 'dog', id: 1234 }]; - server.use( - findPets( - { params: inputParams }, - { statusCode: 200, data: outputPets, mimeType: 'application/json' } - ) - ); - const response = await fetch('http://localhost/pets?tags=dog&tags=cat&limit=10'); - expect(await response.json()).toEqual(outputPets); - expect(response.status).toBe(200); - expect(response.headers.get('Content-Type')).toBe('application/json'); - }); -}); \ No newline at end of file + it('can wrap query strings in a get', async () => { + const inputParams = { tags: ['dog', 'cat'], limit: 10 }; + const outputPets = [{ name: 'Fido', tag: 'dog', id: 1234 }]; + server.use( + findPets( + { params: inputParams }, + { statusCode: 200, data: outputPets, mimeType: 'application/json' }, + ), + ); + const response = await fetch( + 'http://localhost/pets?tags=dog&tags=cat&limit=10', + ); + expect(await response.json()).toEqual(outputPets); + expect(response.status).toBe(200); + expect(response.headers.get('Content-Type')).toBe('application/json'); + }); +}); diff --git a/generators/typescript-msw/npm/tsconfig.json b/generators/typescript-msw/npm/tsconfig.json index 148e67ad..ddb84d43 100644 --- a/generators/typescript-msw/npm/tsconfig.json +++ b/generators/typescript-msw/npm/tsconfig.json @@ -1,16 +1,14 @@ { - "compilerOptions": { - "outDir": "./lib", - "declaration": true, - "rootDir": "./src" - }, - "extends": "./tsconfig.node.json", - "include": [ - "./src" - ], + "compilerOptions": { + "outDir": "./lib", + "declaration": true, + "rootDir": "./src" + }, + "extends": "./tsconfig.node.json", + "include": ["./src"], "references": [ { "path": "./tsconfig.node.json" - }, - ], -} \ No newline at end of file + } + ] +} diff --git a/generators/typescript-msw/npm/tsconfig.node.json b/generators/typescript-msw/npm/tsconfig.node.json index e187c7e5..14701e11 100644 --- a/generators/typescript-msw/npm/tsconfig.node.json +++ b/generators/typescript-msw/npm/tsconfig.node.json @@ -1,27 +1,25 @@ { - "compilerOptions": { - "target": "es6", - "lib": [ - "esnext", "DOM" - ], - "allowJs": true, - "skipLibCheck": true, - "esModuleInterop": true, - "strict": true, - "forceConsistentCasingInFileNames": true, - "module": "commonjs", - "moduleResolution": "node", - "resolveJsonModule": true, - "isolatedModules": true, - "noEmit": false, - "composite": true, - "types": ["node", "jest"], - "declaration": true, - "rootDir": ".", - "outDir": "../../../artifacts/generators/typescript-msw/npm", - "paths": { - "@principlestudios/openapi-codegen-typescript-msw": ["./src"], - } - }, - "exclude": ["./lib"] + "compilerOptions": { + "target": "es6", + "lib": ["esnext", "DOM"], + "allowJs": true, + "skipLibCheck": true, + "esModuleInterop": true, + "strict": true, + "forceConsistentCasingInFileNames": true, + "module": "commonjs", + "moduleResolution": "node", + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": false, + "composite": true, + "types": ["node", "jest"], + "declaration": true, + "rootDir": ".", + "outDir": "../../../artifacts/generators/typescript-msw/npm", + "paths": { + "@principlestudios/openapi-codegen-typescript-msw": ["./src"] + } + }, + "exclude": ["./lib"] } diff --git a/generators/typescript-rxjs/npm/babel.config.js b/generators/typescript-rxjs/npm/babel.config.js index 9ab199fb..edc01a5c 100644 --- a/generators/typescript-rxjs/npm/babel.config.js +++ b/generators/typescript-rxjs/npm/babel.config.js @@ -1,12 +1,14 @@ module.exports = { - presets: [ - ['@babel/preset-env', - { - "modules": "commonjs", - "targets": { - "node": "current" - } - }], - '@babel/preset-typescript', - ] - }; + presets: [ + [ + '@babel/preset-env', + { + modules: 'commonjs', + targets: { + node: 'current', + }, + }, + ], + '@babel/preset-typescript', + ], +}; diff --git a/generators/typescript-rxjs/npm/src/index.ts b/generators/typescript-rxjs/npm/src/index.ts index f146d3fc..81397ca3 100644 --- a/generators/typescript-rxjs/npm/src/index.ts +++ b/generators/typescript-rxjs/npm/src/index.ts @@ -9,9 +9,9 @@ import type { TransformCallType, AdapterRequestArgs, RequestConversions, - HttpMethod + HttpMethod, } from '@principlestudios/openapi-codegen-typescript'; -import type { Observable} from 'rxjs'; +import type { Observable } from 'rxjs'; import { of } from 'rxjs'; import type { AjaxError, AjaxRequest, AjaxResponse } from 'rxjs/ajax'; import { ajax } from 'rxjs/ajax'; @@ -20,7 +20,10 @@ import { catchError, map } from 'rxjs/operators'; export const toUrl = (prefix: string, requestOpts: AdapterRequestArgs) => `${prefix}${requestOpts.path}`; -function rxWithPrefix(prefix: string, rxjsRequest: (params: AjaxRequest) => Observable = ajax) { +function rxWithPrefix( + prefix: string, + rxjsRequest: (params: AjaxRequest) => Observable = ajax, +) { const createRequestArgs = (requestOpts: AdapterRequestArgs): AjaxRequest => { const url = toUrl(prefix, requestOpts); @@ -29,7 +32,9 @@ function rxWithPrefix(prefix: string, rxjsRequest: (params: AjaxRequest) => Obse method: requestOpts.method, headers: requestOpts.headers, body: - requestOpts.headers && requestOpts.headers['Content-Type'] === 'application/x-www-form-urlencoded' + requestOpts.headers && + requestOpts.headers['Content-Type'] === + 'application/x-www-form-urlencoded' ? requestOpts.body : JSON.stringify(requestOpts.body), responseType: 'json', @@ -40,13 +45,26 @@ function rxWithPrefix(prefix: string, rxjsRequest: (params: AjaxRequest) => Obse TParams extends {}, TBody extends RequestBodies, TResponse extends StandardResponse, - TCallType extends TransformCallType - >(conversion: RequestConversion) { - function transform({ params = {}, body = undefined, mimeType = undefined }: any = {}): Observable { + TCallType extends TransformCallType, + >( + conversion: RequestConversion< + HttpMethod, + any, + TParams, + TBody, + TResponse, + TCallType + >, + ) { + function transform({ + params = {}, + body = undefined, + mimeType = undefined, + }: any = {}): Observable { const requestOpts: AdapterRequestArgs = conversion.request( params, body, - mimeType || (body ? 'application/json' : undefined) + mimeType || (body ? 'application/json' : undefined), ); return rxjsRequest(createRequestArgs(requestOpts)).pipe( catchError((ex: AjaxError) => of(ex)), @@ -57,51 +75,65 @@ function rxWithPrefix(prefix: string, rxjsRequest: (params: AjaxRequest) => Obse getResponseHeader(header) { return response.xhr.getResponseHeader(header); }, - }) - ) + }), + ), ); } return transform; }; } -type ParamPart = {} extends TParams ? { params?: TParams } : { params: TParams }; -type BodyPartInner = Mime extends 'application/json' +type ParamPart = {} extends TParams + ? { params?: TParams } + : { params: TParams }; +type BodyPartInner< + TBodies extends RequestBodies, + Mime extends keyof TBodies, +> = Mime extends 'application/json' ? { body: TBodies['application/json']; mimeType?: 'application/json' } : { body: TBodies[Mime]; mimeType: Mime }; type BodyPart< TBodies extends RequestBodies, Mime extends keyof TBodies, - TCallType extends TransformCallType + TCallType extends TransformCallType, > = TCallType extends 'no-body' ? {} : TCallType extends 'optional' - ? BodyPartInner | {} - : BodyPartInner; + ? BodyPartInner | {} + : BodyPartInner; type RequestParam< TCallType extends TransformCallType, TParams, TBodies extends RequestBodies, - Mime extends keyof TBodies + Mime extends keyof TBodies, > = ParamPart & BodyPart; -type Converted> = TConversion extends RequestConversion< - any, - any, - infer TParams, - infer TBodies, - infer TResponse, - infer TCallType -> - ? {} extends RequestParam - ? (req?: RequestParam) => Observable - : (req: RequestParam) => Observable - : never; +type Converted< + TConversion extends RequestConversion, +> = + TConversion extends RequestConversion< + any, + any, + infer TParams, + infer TBodies, + infer TResponse, + infer TCallType + > + ? {} extends RequestParam + ? ( + req?: RequestParam, + ) => Observable + : ( + req: RequestParam, + ) => Observable + : never; function applyTransform( methods: TMethods, - transform: (input: RequestConversion) => Converted> + transform: ( + input: RequestConversion, + ) => Converted>, ): { [K in keyof TMethods]: Converted; } { @@ -109,14 +141,14 @@ function applyTransform( (prev, next) => ({ ...prev, [next]: transform(methods[next]) }), {} as { [K in keyof TMethods]: Converted; - } + }, ); } export function toRxjsApi( api: TMethods, prefix = '', - rxjsRequest: (params: AjaxRequest) => Observable = ajax + rxjsRequest: (params: AjaxRequest) => Observable = ajax, ) { return applyTransform(api, rxWithPrefix(prefix, rxjsRequest)); } diff --git a/generators/typescript-rxjs/npm/tests/mwcMappedRestHandler.ts b/generators/typescript-rxjs/npm/tests/mwcMappedRestHandler.ts index 038b5708..1de7f61b 100644 --- a/generators/typescript-rxjs/npm/tests/mwcMappedRestHandler.ts +++ b/generators/typescript-rxjs/npm/tests/mwcMappedRestHandler.ts @@ -1,4 +1,4 @@ export { toMswHandler } from '@principlestudios/openapi-codegen-typescript-msw'; // eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-unsafe-member-access -global.XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; +global.XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; diff --git a/generators/typescript-rxjs/npm/tests/petstore.test.ts b/generators/typescript-rxjs/npm/tests/petstore.test.ts index 99227005..76291390 100644 --- a/generators/typescript-rxjs/npm/tests/petstore.test.ts +++ b/generators/typescript-rxjs/npm/tests/petstore.test.ts @@ -9,54 +9,79 @@ const findPets = toMswHandler(findPetsConversion); const addPet = toMswHandler(addPetConversion); describe('typescript-rxjs petstore.yaml', () => { - const wrapped = toRxjsApi(operations); - const server = setupServer(); + const wrapped = toRxjsApi(operations); + const server = setupServer(); - beforeAll(() => server.listen()); - afterEach(() => server.resetHandlers()); - afterAll(() => server.close()); + beforeAll(() => server.listen()); + afterEach(() => server.resetHandlers()); + afterAll(() => server.close()); - it('can wrap a post', async () => { - const inputPet = { name: 'Fido', tag: 'dog' }; - const outputPet = { ...inputPet, id: 1234 }; - server.use( - addPet({ params: {}, body: inputPet, mimeType: 'application/json'}, { statusCode: 200, data: { ...outputPet }, mimeType: 'application/json' }) - ); - const response = await wrapped.addPet({ body: inputPet }).toPromise(); - expect(response.statusCode).toBe(200); - expect(response.mimeType).toBe('application/json'); - expect(response.data).toEqual(outputPet); - }); + it('can wrap a post', async () => { + const inputPet = { name: 'Fido', tag: 'dog' }; + const outputPet = { ...inputPet, id: 1234 }; + server.use( + addPet( + { params: {}, body: inputPet, mimeType: 'application/json' }, + { + statusCode: 200, + data: { ...outputPet }, + mimeType: 'application/json', + }, + ), + ); + const response = await wrapped.addPet({ body: inputPet }).toPromise(); + expect(response.statusCode).toBe(200); + expect(response.mimeType).toBe('application/json'); + expect(response.data).toEqual(outputPet); + }); - it('can wrap two different posts', async () => { - const inputPet1 = { name: 'Fido', tag: 'dog' }; - const inputPet2 = { name: 'Felix', tag: 'cat' }; - const outputPet1 = { ...inputPet1, id: 1234 }; - const outputPet2 = { ...inputPet2, id: 1235 }; - server.use( - addPet({ params: {}, body: inputPet1, mimeType: 'application/json' }, { statusCode: 200, data: { ...outputPet1 }, mimeType: 'application/json' }), - addPet({ params: {}, body: inputPet2, mimeType: 'application/json' }, { statusCode: 200, data: { ...outputPet2 }, mimeType: 'application/json' }) - ); - const response2 = await wrapped.addPet({ body: inputPet2 }).toPromise(); - const response1 = await wrapped.addPet({ body: inputPet1 }).toPromise(); - expect(response1.statusCode).toBe(200); - expect(response1.mimeType).toBe('application/json'); - expect(response1.data).toEqual(outputPet1); - expect(response2.statusCode).toBe(200); - expect(response2.mimeType).toBe('application/json'); - expect(response2.data).toEqual(outputPet2); - }); + it('can wrap two different posts', async () => { + const inputPet1 = { name: 'Fido', tag: 'dog' }; + const inputPet2 = { name: 'Felix', tag: 'cat' }; + const outputPet1 = { ...inputPet1, id: 1234 }; + const outputPet2 = { ...inputPet2, id: 1235 }; + server.use( + addPet( + { params: {}, body: inputPet1, mimeType: 'application/json' }, + { + statusCode: 200, + data: { ...outputPet1 }, + mimeType: 'application/json', + }, + ), + addPet( + { params: {}, body: inputPet2, mimeType: 'application/json' }, + { + statusCode: 200, + data: { ...outputPet2 }, + mimeType: 'application/json', + }, + ), + ); + const response2 = await wrapped.addPet({ body: inputPet2 }).toPromise(); + const response1 = await wrapped.addPet({ body: inputPet1 }).toPromise(); + expect(response1.statusCode).toBe(200); + expect(response1.mimeType).toBe('application/json'); + expect(response1.data).toEqual(outputPet1); + expect(response2.statusCode).toBe(200); + expect(response2.mimeType).toBe('application/json'); + expect(response2.data).toEqual(outputPet2); + }); - it('can wrap query strings in a get', async () => { - const inputParams = { tags: ['dog','cat'], limit: 10 }; - const outputPets = [{ name: 'Fido', tag: 'dog', id: 1234 }]; - server.use( - findPets({ params: inputParams }, - { statusCode: 200, data: outputPets, mimeType: 'application/json' }) - ); - const response = await wrapped.findPets({ params: inputParams }).toPromise(); - expect(response.data).toEqual(outputPets); - expect(response.statusCode).toBe(200); - expect(response.mimeType).toBe('application/json'); - }); -}); \ No newline at end of file + it('can wrap query strings in a get', async () => { + const inputParams = { tags: ['dog', 'cat'], limit: 10 }; + const outputPets = [{ name: 'Fido', tag: 'dog', id: 1234 }]; + server.use( + findPets( + { params: inputParams }, + { statusCode: 200, data: outputPets, mimeType: 'application/json' }, + ), + ); + const response = await wrapped + .findPets({ params: inputParams }) + .toPromise(); + expect(response.data).toEqual(outputPets); + expect(response.statusCode).toBe(200); + expect(response.mimeType).toBe('application/json'); + }); +}); diff --git a/generators/typescript-rxjs/npm/tsconfig.json b/generators/typescript-rxjs/npm/tsconfig.json index f49361aa..142b83ef 100644 --- a/generators/typescript-rxjs/npm/tsconfig.json +++ b/generators/typescript-rxjs/npm/tsconfig.json @@ -1,17 +1,15 @@ { - "compilerOptions": { - "outDir": "./lib", - "noEmit": false, - "declaration": true, - "rootDir": "./src", - }, - "extends": "./tsconfig.node.json", - "include": [ - "./src" - ], + "compilerOptions": { + "outDir": "./lib", + "noEmit": false, + "declaration": true, + "rootDir": "./src" + }, + "extends": "./tsconfig.node.json", + "include": ["./src"], "references": [ { "path": "./tsconfig.node.json" - }, - ], -} \ No newline at end of file + } + ] +} diff --git a/generators/typescript-rxjs/npm/tsconfig.node.json b/generators/typescript-rxjs/npm/tsconfig.node.json index 6cf35c9d..efda74d4 100644 --- a/generators/typescript-rxjs/npm/tsconfig.node.json +++ b/generators/typescript-rxjs/npm/tsconfig.node.json @@ -1,26 +1,24 @@ { - "compilerOptions": { - "target": "es5", - "lib": [ - "esnext", "DOM" - ], - "allowJs": true, - "skipLibCheck": true, - "esModuleInterop": true, - "strict": true, - "forceConsistentCasingInFileNames": true, - "module": "commonjs", - "moduleResolution": "node", - "resolveJsonModule": true, - "isolatedModules": true, - "noEmit": false, - "composite": true, - "types": ["node", "jest"], - "declaration": true, - "rootDir": ".", - "outDir": "../../../artifacts/generators/typescript-rxjs/npm", - "paths": { - "@principlestudios/openapi-codegen-typescript-rxjs": ["./src"], - } - } + "compilerOptions": { + "target": "es5", + "lib": ["esnext", "DOM"], + "allowJs": true, + "skipLibCheck": true, + "esModuleInterop": true, + "strict": true, + "forceConsistentCasingInFileNames": true, + "module": "commonjs", + "moduleResolution": "node", + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": false, + "composite": true, + "types": ["node", "jest"], + "declaration": true, + "rootDir": ".", + "outDir": "../../../artifacts/generators/typescript-rxjs/npm", + "paths": { + "@principlestudios/openapi-codegen-typescript-rxjs": ["./src"] + } + } } diff --git a/generators/typescript/PrincipleStudios.OpenApiCodegen.Client.TypeScript/Properties/launchSettings.json b/generators/typescript/PrincipleStudios.OpenApiCodegen.Client.TypeScript/Properties/launchSettings.json index 59dfe4de..279dc1ea 100644 --- a/generators/typescript/PrincipleStudios.OpenApiCodegen.Client.TypeScript/Properties/launchSettings.json +++ b/generators/typescript/PrincipleStudios.OpenApiCodegen.Client.TypeScript/Properties/launchSettings.json @@ -1,8 +1,8 @@ { - "profiles": { - "PrincipleStudios.OpenApiCodegen.Client.TypeScript": { - "commandName": "Project", - "commandLineArgs": "\"$(SolutionDir)schemas/local.yaml\" \"$(ProjectDir)demo/\" -c" - } - } -} \ No newline at end of file + "profiles": { + "PrincipleStudios.OpenApiCodegen.Client.TypeScript": { + "commandName": "Project", + "commandLineArgs": "\"$(SolutionDir)schemas/local.yaml\" \"$(ProjectDir)demo/\" -c" + } + } +} diff --git a/generators/typescript/npm/babel.config.js b/generators/typescript/npm/babel.config.js index b8f051a7..88d2ef83 100644 --- a/generators/typescript/npm/babel.config.js +++ b/generators/typescript/npm/babel.config.js @@ -1,15 +1,15 @@ module.exports = { - presets: [ - ['@babel/preset-env', - { - "modules": "commonjs", - "targets": { - "node": "current" - } - }], - '@babel/preset-typescript', - ], - "plugins": [ - "@babel/plugin-proposal-class-properties" - ] - }; + presets: [ + [ + '@babel/preset-env', + { + modules: 'commonjs', + targets: { + node: 'current', + }, + }, + ], + '@babel/preset-typescript', + ], + plugins: ['@babel/plugin-proposal-class-properties'], +}; diff --git a/generators/typescript/npm/bin/index.js b/generators/typescript/npm/bin/index.js index 3547cf8b..a47db48b 100644 --- a/generators/typescript/npm/bin/index.js +++ b/generators/typescript/npm/bin/index.js @@ -2,12 +2,17 @@ const { join } = require('path'); -const dllPath = join(__dirname, '../dotnet/PrincipleStudios.OpenApiCodegen.Client.TypeScript.dll'); +const dllPath = join( + __dirname, + '../dotnet/PrincipleStudios.OpenApiCodegen.Client.TypeScript.dll', +); -const [,, ...args] = process.argv; -require("child_process"). - spawn( `dotnet`, [dllPath, ...args] , { - argv0:"dotnet" , stdio :'inherit' - }).on('close' , code=> { - process.exit(code); - }); +const [, , ...args] = process.argv; +require('child_process') + .spawn(`dotnet`, [dllPath, ...args], { + argv0: 'dotnet', + stdio: 'inherit', + }) + .on('close', (code) => { + process.exit(code); + }); diff --git a/generators/typescript/npm/jest.config.js b/generators/typescript/npm/jest.config.js index d5b63480..e391b32c 100644 --- a/generators/typescript/npm/jest.config.js +++ b/generators/typescript/npm/jest.config.js @@ -4,194 +4,194 @@ */ module.exports = { - // All imported modules in your tests should be mocked automatically - // automock: false, + // All imported modules in your tests should be mocked automatically + // automock: false, - // Stop running tests after `n` failures - // bail: 0, + // Stop running tests after `n` failures + // bail: 0, - // The directory where Jest should store its cached dependency information - // cacheDirectory: "C:\\Users\\mattd\\AppData\\Local\\Temp\\jest", + // The directory where Jest should store its cached dependency information + // cacheDirectory: "C:\\Users\\mattd\\AppData\\Local\\Temp\\jest", - // Automatically clear mock calls and instances between every test - // clearMocks: false, + // Automatically clear mock calls and instances between every test + // clearMocks: false, - // Indicates whether the coverage information should be collected while executing the test - // collectCoverage: false, + // Indicates whether the coverage information should be collected while executing the test + // collectCoverage: false, - // An array of glob patterns indicating a set of files for which coverage information should be collected - // collectCoverageFrom: undefined, + // An array of glob patterns indicating a set of files for which coverage information should be collected + // collectCoverageFrom: undefined, - // The directory where Jest should output its coverage files - // coverageDirectory: undefined, + // The directory where Jest should output its coverage files + // coverageDirectory: undefined, - // An array of regexp pattern strings used to skip coverage collection - // coveragePathIgnorePatterns: [ - // "\\\\node_modules\\\\" - // ], + // An array of regexp pattern strings used to skip coverage collection + // coveragePathIgnorePatterns: [ + // "\\\\node_modules\\\\" + // ], - // Indicates which provider should be used to instrument code for coverage - // coverageProvider: "babel", + // Indicates which provider should be used to instrument code for coverage + // coverageProvider: "babel", - // A list of reporter names that Jest uses when writing coverage reports - // coverageReporters: [ - // "json", - // "text", - // "lcov", - // "clover" - // ], + // A list of reporter names that Jest uses when writing coverage reports + // coverageReporters: [ + // "json", + // "text", + // "lcov", + // "clover" + // ], - // An object that configures minimum threshold enforcement for coverage results - // coverageThreshold: undefined, + // An object that configures minimum threshold enforcement for coverage results + // coverageThreshold: undefined, - // A path to a custom dependency extractor - // dependencyExtractor: undefined, + // A path to a custom dependency extractor + // dependencyExtractor: undefined, - // Make calling deprecated APIs throw helpful error messages - // errorOnDeprecated: false, + // Make calling deprecated APIs throw helpful error messages + // errorOnDeprecated: false, - // Force coverage collection from ignored files using an array of glob patterns - // forceCoverageMatch: [], + // Force coverage collection from ignored files using an array of glob patterns + // forceCoverageMatch: [], - // A path to a module which exports an async function that is triggered once before all test suites - // globalSetup: undefined, + // A path to a module which exports an async function that is triggered once before all test suites + // globalSetup: undefined, - // A path to a module which exports an async function that is triggered once after all test suites - // globalTeardown: undefined, + // A path to a module which exports an async function that is triggered once after all test suites + // globalTeardown: undefined, - // A set of global variables that need to be available in all test environments - // globals: {}, + // A set of global variables that need to be available in all test environments + // globals: {}, - // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. - // maxWorkers: "50%", + // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. + // maxWorkers: "50%", - // An array of directory names to be searched recursively up from the requiring module's location - // moduleDirectories: [ - // "node_modules" - // ], + // An array of directory names to be searched recursively up from the requiring module's location + // moduleDirectories: [ + // "node_modules" + // ], - // An array of file extensions your modules use - // moduleFileExtensions: [ - // "js", - // "jsx", - // "ts", - // "tsx", - // "json", - // "node" - // ], + // An array of file extensions your modules use + // moduleFileExtensions: [ + // "js", + // "jsx", + // "ts", + // "tsx", + // "json", + // "node" + // ], - // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module - // moduleNameMapper: {}, - "moduleNameMapper": { - "@principlestudios/openapi-codegen-typescript": "/src" - }, + // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module + // moduleNameMapper: {}, + moduleNameMapper: { + '@principlestudios/openapi-codegen-typescript': '/src', + }, - // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader - // modulePathIgnorePatterns: [], + // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader + // modulePathIgnorePatterns: [], - // Activates notifications for test results - // notify: false, + // Activates notifications for test results + // notify: false, - // An enum that specifies notification mode. Requires { notify: true } - // notifyMode: "failure-change", + // An enum that specifies notification mode. Requires { notify: true } + // notifyMode: "failure-change", - // A preset that is used as a base for Jest's configuration - // preset: undefined, + // A preset that is used as a base for Jest's configuration + // preset: undefined, - // Run tests from one or more projects - // projects: undefined, + // Run tests from one or more projects + // projects: undefined, - // Use this configuration option to add custom reporters to Jest - // reporters: undefined, + // Use this configuration option to add custom reporters to Jest + // reporters: undefined, - // Automatically reset mock state between every test - // resetMocks: false, + // Automatically reset mock state between every test + // resetMocks: false, - // Reset the module registry before running each individual test - // resetModules: false, + // Reset the module registry before running each individual test + // resetModules: false, - // A path to a custom resolver - // resolver: undefined, + // A path to a custom resolver + // resolver: undefined, - // Automatically restore mock state between every test - // restoreMocks: false, + // Automatically restore mock state between every test + // restoreMocks: false, - // The root directory that Jest should scan for tests and modules within - // rootDir: undefined, + // The root directory that Jest should scan for tests and modules within + // rootDir: undefined, - // A list of paths to directories that Jest should use to search for files in - // roots: [ - // "" - // ], + // A list of paths to directories that Jest should use to search for files in + // roots: [ + // "" + // ], - // Allows you to use a custom runner instead of Jest's default test runner - // runner: "jest-runner", + // Allows you to use a custom runner instead of Jest's default test runner + // runner: "jest-runner", - // The paths to modules that run some code to configure or set up the testing environment before each test - // setupFiles: [], + // The paths to modules that run some code to configure or set up the testing environment before each test + // setupFiles: [], - // A list of paths to modules that run some code to configure or set up the testing framework before each test - // setupFilesAfterEnv: [], + // A list of paths to modules that run some code to configure or set up the testing framework before each test + // setupFilesAfterEnv: [], - // The number of seconds after which a test is considered as slow and reported as such in the results. - // slowTestThreshold: 5, + // The number of seconds after which a test is considered as slow and reported as such in the results. + // slowTestThreshold: 5, - // A list of paths to snapshot serializer modules Jest should use for snapshot testing - // snapshotSerializers: [], + // A list of paths to snapshot serializer modules Jest should use for snapshot testing + // snapshotSerializers: [], - // The test environment that will be used for testing - // testEnvironment: "jest-environment-node", + // The test environment that will be used for testing + // testEnvironment: "jest-environment-node", - // Options that will be passed to the testEnvironment - // testEnvironmentOptions: {}, + // Options that will be passed to the testEnvironment + // testEnvironmentOptions: {}, - // Adds a location field to test results - // testLocationInResults: false, + // Adds a location field to test results + // testLocationInResults: false, - // The glob patterns Jest uses to detect test files - // testMatch: [ - // "**/__tests__/**/*.[jt]s?(x)", - // "**/?(*.)+(spec|test).[tj]s?(x)" - // ], + // The glob patterns Jest uses to detect test files + // testMatch: [ + // "**/__tests__/**/*.[jt]s?(x)", + // "**/?(*.)+(spec|test).[tj]s?(x)" + // ], - // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped - // testPathIgnorePatterns: [ - // "\\\\node_modules\\\\" - // ], + // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped + // testPathIgnorePatterns: [ + // "\\\\node_modules\\\\" + // ], - // The regexp pattern or array of patterns that Jest uses to detect test files - // testRegex: [], + // The regexp pattern or array of patterns that Jest uses to detect test files + // testRegex: [], - // This option allows the use of a custom results processor - // testResultsProcessor: undefined, + // This option allows the use of a custom results processor + // testResultsProcessor: undefined, - // This option allows use of a custom test runner - // testRunner: "jest-circus/runner", + // This option allows use of a custom test runner + // testRunner: "jest-circus/runner", - // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href - // testURL: "http://localhost", + // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href + // testURL: "http://localhost", - // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout" - // timers: "real", + // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout" + // timers: "real", - // A map from regular expressions to paths to transformers - // transform: undefined, + // A map from regular expressions to paths to transformers + // transform: undefined, - // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation - // transformIgnorePatterns: [ - // "\\\\node_modules\\\\", - // "\\.pnp\\.[^\\\\]+$" - // ], + // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation + // transformIgnorePatterns: [ + // "\\\\node_modules\\\\", + // "\\.pnp\\.[^\\\\]+$" + // ], - // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them - // unmockedModulePathPatterns: undefined, + // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them + // unmockedModulePathPatterns: undefined, - // Indicates whether each individual test should be reported during the run - // verbose: undefined, + // Indicates whether each individual test should be reported during the run + // verbose: undefined, - // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode - // watchPathIgnorePatterns: [], + // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode + // watchPathIgnorePatterns: [], - // Whether to use watchman for file crawling - // watchman: true, + // Whether to use watchman for file crawling + // watchman: true, }; diff --git a/generators/typescript/npm/src/helpers.ts b/generators/typescript/npm/src/helpers.ts index 1db14080..86ee3d1c 100644 --- a/generators/typescript/npm/src/helpers.ts +++ b/generators/typescript/npm/src/helpers.ts @@ -1,8 +1,9 @@ - export const encodeURI = (value: unknown) => encodeURIComponent(String(value)); export const throwIfNullOrUndefined = (value: unknown, nickname?: string) => { - if (value == null) { - throw new Error(`Parameter "${value}" was null or undefined when calling "${nickname}".`); - } + if (value == null) { + throw new Error( + `Parameter "${value}" was null or undefined when calling "${nickname}".`, + ); + } }; diff --git a/generators/typescript/npm/src/inputs-outputs.ts b/generators/typescript/npm/src/inputs-outputs.ts index 7f776d8b..af63c4b4 100644 --- a/generators/typescript/npm/src/inputs-outputs.ts +++ b/generators/typescript/npm/src/inputs-outputs.ts @@ -1,19 +1,25 @@ - -export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD'; -export type HttpHeaders = { [key: string]: string | null; }; +export type HttpMethod = + | 'GET' + | 'POST' + | 'PUT' + | 'PATCH' + | 'DELETE' + | 'OPTIONS' + | 'HEAD'; +export type HttpHeaders = { [key: string]: string | null }; /** Standardized request to be sent to the adapter layer */ export type AdapterRequestArgs = { - path: string; - method: HttpMethod; - headers?: HttpHeaders; - body?: unknown; - responseType?: 'json' | 'blob' | 'arraybuffer' | 'text'; -} + path: string; + method: HttpMethod; + headers?: HttpHeaders; + body?: unknown; + responseType?: 'json' | 'blob' | 'arraybuffer' | 'text'; +}; /** Standardize response to be received from the adapter layer */ export type AdapterResponseArgs = { - status: number; - getResponseHeader(header: string): string | null; - response: unknown; + status: number; + getResponseHeader(header: string): string | null; + response: unknown; }; diff --git a/generators/typescript/npm/src/types.ts b/generators/typescript/npm/src/types.ts index a2a54b02..31bc78e5 100644 --- a/generators/typescript/npm/src/types.ts +++ b/generators/typescript/npm/src/types.ts @@ -1,48 +1,110 @@ -import type { HttpMethod, AdapterRequestArgs, AdapterResponseArgs } from "./inputs-outputs"; +import type { + HttpMethod, + AdapterRequestArgs, + AdapterResponseArgs, +} from './inputs-outputs'; export type RequestBodies = { - [mimeType: string]: any; -} + [mimeType: string]: any; +}; export type Responses = { - 'other'?: { - [mimeType: string]: any; - }; - [statusCode: number]: { - [mimeType: string]: any; - } -} - -export type StandardResponse = - { statusCode: TStatusCode; mimeType: TMimeType; data: TBody; response: AdapterResponseArgs }; - -export type TransformRequestNoBody = (params: TRequestParams) => TResult; -export type TransformRequestWithBody = - (params: TRequestParams, body: TRequestBodies[TMimeType], mimeType: TMimeType) => TResult; -export type TransformRequestWithOptionalBody = - TransformRequestNoBody & TransformRequestWithBody; + other?: { + [mimeType: string]: any; + }; + [statusCode: number]: { + [mimeType: string]: any; + }; +}; + +export type StandardResponse< + TStatusCode extends number | 'other' = number | 'other', + TMimeType extends string = string, + TBody = unknown, +> = { + statusCode: TStatusCode; + mimeType: TMimeType; + data: TBody; + response: AdapterResponseArgs; +}; + +export type TransformRequestNoBody = ( + params: TRequestParams, +) => TResult; +export type TransformRequestWithBody< + TRequestParams extends {}, + TRequestBodies extends RequestBodies, + TResult, +> = ( + params: TRequestParams, + body: TRequestBodies[TMimeType], + mimeType: TMimeType, +) => TResult; +export type TransformRequestWithOptionalBody< + TRequestParams extends {}, + TRequestBodies extends RequestBodies, + TResult, +> = TransformRequestNoBody & + TransformRequestWithBody; export type TransformCallType = 'no-body' | 'body' | 'optional'; -export type TransformRequest = - TCallType extends 'no-body' ? TransformRequestNoBody - : TCallType extends 'body' ? TransformRequestWithBody - : TCallType extends 'optional' ? TransformRequestWithOptionalBody - : never; - -export type TransformResponse = (args: AdapterResponseArgs) => TResponses; - -export type RequestConversion = { - name: string; - method: TMethod; - url: (params: TUrlParams) => string; - callType: TCallType; - request: TransformRequest; - response: TransformResponse; -} & (TCallType extends 'no-body' ? {} : { - bodies: { - [K in keyof TRequestBodies]: (input: TRequestBodies[K]) => unknown; - } -}); - -export type RequestConversions = Record>; +export type TransformRequest< + TRequestParams extends {}, + TRequestBodies extends RequestBodies, + TCallType extends TransformCallType, + TResult, +> = TCallType extends 'no-body' + ? TransformRequestNoBody + : TCallType extends 'body' + ? TransformRequestWithBody + : TCallType extends 'optional' + ? TransformRequestWithOptionalBody< + TRequestParams, + TRequestBodies, + TResult + > + : never; + +export type TransformResponse = ( + args: AdapterResponseArgs, +) => TResponses; + +export type RequestConversion< + TMethod extends HttpMethod, + TUrlParams extends {}, + TRequestParams extends TUrlParams, + TRequestBodies extends RequestBodies, + TResponses extends StandardResponse, + TCallType extends TransformCallType, +> = { + name: string; + method: TMethod; + url: (params: TUrlParams) => string; + callType: TCallType; + request: TransformRequest< + TRequestParams, + TRequestBodies, + TCallType, + AdapterRequestArgs + >; + response: TransformResponse; +} & (TCallType extends 'no-body' + ? {} + : { + bodies: { + [K in keyof TRequestBodies]: (input: TRequestBodies[K]) => unknown; + }; + }); + +export type RequestConversions = Record< + string, + RequestConversion< + HttpMethod, + any, + any, + any, + StandardResponse, + TransformCallType + > +>; diff --git a/generators/typescript/npm/tests/DestructureResponses.ts b/generators/typescript/npm/tests/DestructureResponses.ts index 0fe1aca2..e2ab8771 100644 --- a/generators/typescript/npm/tests/DestructureResponses.ts +++ b/generators/typescript/npm/tests/DestructureResponses.ts @@ -1,13 +1,25 @@ -import type { StructuredResponses } from "./no-refs/operations/lookupRecord"; -import type { StandardResponse } from "~/src/types"; +import type { StructuredResponses } from './no-refs/operations/lookupRecord'; +import type { StandardResponse } from '~/src/types'; -type DestructureMime = { - [K in keyof T]: K extends string ? StandardResponse : never; +type DestructureMime< + TStatusCode extends number | 'other', + T extends { [mimeType: string]: any }, +> = { + [K in keyof T]: K extends string + ? StandardResponse + : never; }[keyof T]; -type Destructure = { - [K in keyof T]: K extends number | 'other' ? DestructureMime : never; +type Destructure< + T extends { [statusCode: string | number]: { [mimeType: string]: any } }, +> = { + [K in keyof T]: K extends number | 'other' ? DestructureMime : never; }[keyof T]; type Destructured = Destructure; // So, it is possible to destructure the response, but... this could end up with complex (therefore slow) type checking. I'd rather not. -({ statusCode: 409, mimeType: 'application/json', data: { multiple: {} as any }, response: {} as any }) satisfies Destructured; +({ + statusCode: 409, + mimeType: 'application/json', + data: { multiple: {} as any }, + response: {} as any, +}) satisfies Destructured; diff --git a/generators/typescript/npm/tests/fetchRequest.ts b/generators/typescript/npm/tests/fetchRequest.ts index bbb3fc9d..57f521bd 100644 --- a/generators/typescript/npm/tests/fetchRequest.ts +++ b/generators/typescript/npm/tests/fetchRequest.ts @@ -1,43 +1,106 @@ -import allOperations from "./no-refs/operations"; -import type { Responses as LookupResponses } from "./no-refs/operations/lookupRecord"; -import { conversion as lookupRecord } from "./no-refs/operations/lookupRecord"; -import type { AdapterRequestArgs, AdapterResponseArgs } from "~/src/inputs-outputs"; -import type { RequestConversion, RequestBodies, RequestConversions, TransformRequest, StandardResponse, TransformCallType } from "~/src/types"; +import allOperations from './no-refs/operations'; +import type { Responses as LookupResponses } from './no-refs/operations/lookupRecord'; +import { conversion as lookupRecord } from './no-refs/operations/lookupRecord'; +import type { + AdapterRequestArgs, + AdapterResponseArgs, +} from '~/src/inputs-outputs'; +import type { + RequestConversion, + RequestBodies, + RequestConversions, + TransformRequest, + StandardResponse, + TransformCallType, +} from '~/src/types'; -function fetchRequest( - conversion: RequestConversion +function fetchRequest< + TParams extends {}, + TBody extends RequestBodies, + TResponse extends StandardResponse, + TCallType extends TransformCallType, +>( + conversion: RequestConversion, ): TransformRequest> { - - function transform(params: TParams): Promise; - function transform(params: TParams, body: TBody[TMimeType], mimeType: TMimeType): Promise; - async function transform(params: TParams, body: TBody[any] | null = null, mimeType: string | null = null): Promise { - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const requestOpts: AdapterRequestArgs = conversion.request(params, body as TBody[any], mimeType!); - const response: AdapterResponseArgs = await Promise.reject(); // This is just a demo that always fails - return conversion.response(response); - } - return transform as TransformRequest>; + function transform(params: TParams): Promise; + function transform( + params: TParams, + body: TBody[TMimeType], + mimeType: TMimeType, + ): Promise; + async function transform( + params: TParams, + body: TBody[any] | null = null, + mimeType: string | null = null, + ): Promise { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const requestOpts: AdapterRequestArgs = conversion.request( + params, + body as TBody[any], + mimeType!, + ); + const response: AdapterResponseArgs = + await Promise.reject(); // This is just a demo that always fails + return conversion.response(response); + } + return transform as TransformRequest< + TParams, + TBody, + TCallType, + Promise + >; } const fetchLookupRecord = fetchRequest(lookupRecord); -type Converted> = TConversion extends RequestConversion ? TransformRequest> : never; +type Converted< + TConversion extends RequestConversion, +> = + TConversion extends RequestConversion< + any, + any, + infer TParams, + infer TBody, + infer TResponse, + infer TCallType + > + ? TransformRequest> + : never; function applyTransform( - methods: TMethods, - transform: (input: RequestConversion) => Converted> + methods: TMethods, + transform: ( + input: RequestConversion, + ) => Converted>, ): { - [K in keyof TMethods]: Converted; - } { - return Object.keys(methods).reduce((prev, next) => ({ ...prev, [next]: transform(methods[next]) }), {} as { - [K in keyof TMethods]: Converted; - }); + [K in keyof TMethods]: Converted; +} { + return Object.keys(methods).reduce( + (prev, next) => ({ ...prev, [next]: transform(methods[next]) }), + {} as { + [K in keyof TMethods]: Converted; + }, + ); } const fetchTemp = applyTransform(allOperations, fetchRequest); // eslint-disable-next-line @typescript-eslint/no-unused-vars async function testPipe() { - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const response: LookupResponses = await fetchLookupRecord({}, { formattedAddress: '123 Main St', location: { latitude: 0, longitude: 0 } }, 'application/json'); - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const response2: LookupResponses = await fetchTemp.lookupRecord({}, { formattedAddress: '123 Main St', location: { latitude: 0, longitude: 0 } }, 'application/json'); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const response: LookupResponses = await fetchLookupRecord( + {}, + { + formattedAddress: '123 Main St', + location: { latitude: 0, longitude: 0 }, + }, + 'application/json', + ); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const response2: LookupResponses = await fetchTemp.lookupRecord( + {}, + { + formattedAddress: '123 Main St', + location: { latitude: 0, longitude: 0 }, + }, + 'application/json', + ); } diff --git a/generators/typescript/npm/tests/operation.test.ts b/generators/typescript/npm/tests/operation.test.ts index d32b5089..aa062b00 100644 --- a/generators/typescript/npm/tests/operation.test.ts +++ b/generators/typescript/npm/tests/operation.test.ts @@ -1,27 +1,59 @@ -import type allOperations from "./no-refs/operations"; -import { conversion as getPhoto } from "./no-refs/operations/getPhoto"; -import type { RequestBodies as LookupRecordRequestBodies, Responses as LookupResponses } from "./no-refs/operations/lookupRecord"; -import { conversion as lookupRecord } from "./no-refs/operations/lookupRecord"; -import type { AdapterRequestArgs } from "~/src/inputs-outputs"; -import type { RequestConversion, RequestBodies, RequestConversions, TransformRequest} from "~/src/types"; +import type allOperations from './no-refs/operations'; +import { conversion as getPhoto } from './no-refs/operations/getPhoto'; +import type { + RequestBodies as LookupRecordRequestBodies, + Responses as LookupResponses, +} from './no-refs/operations/lookupRecord'; +import { conversion as lookupRecord } from './no-refs/operations/lookupRecord'; +import type { AdapterRequestArgs } from '~/src/inputs-outputs'; +import type { + RequestConversion, + RequestBodies, + RequestConversions, + TransformRequest, +} from '~/src/types'; describe('no-refs', () => { - it('has successful typings', () => { - lookupRecord.request({}, { formattedAddress: '123 Main St', location: { latitude: 0, longitude: 0 }}, 'application/json'); - // lookupRecord.request({}); - getPhoto.request({ id: 'foo' }); - }); + it('has successful typings', () => { + lookupRecord.request( + {}, + { + formattedAddress: '123 Main St', + location: { latitude: 0, longitude: 0 }, + }, + 'application/json', + ); + // lookupRecord.request({}); + getPhoto.request({ id: 'foo' }); + }); }); -lookupRecord.request satisfies TransformRequest, LookupRecordRequestBodies, 'body', AdapterRequestArgs>; -lookupRecord satisfies RequestConversion; -getPhoto.request satisfies TransformRequest; +lookupRecord.request satisfies TransformRequest< + NonNullable, + LookupRecordRequestBodies, + 'body', + AdapterRequestArgs +>; +lookupRecord satisfies RequestConversion< + any, + Object, + Object, + LookupRecordRequestBodies, + LookupResponses, + 'body' +>; +getPhoto.request satisfies TransformRequest< + any, + never, + 'no-body', + AdapterRequestArgs +>; const temp = { - lookupRecord, - getPhoto, + lookupRecord, + getPhoto, } as const; -true satisfies ({} extends RequestBodies ? true : false); -true satisfies (typeof temp extends RequestConversions ? true : false); -true satisfies (typeof allOperations extends RequestConversions ? true : false); +true satisfies {} extends RequestBodies ? true : false; +true satisfies typeof temp extends RequestConversions ? true : false; +true satisfies typeof allOperations extends RequestConversions ? true : false; diff --git a/generators/typescript/npm/tsconfig.build.json b/generators/typescript/npm/tsconfig.build.json index 04eb91e3..677dec19 100644 --- a/generators/typescript/npm/tsconfig.build.json +++ b/generators/typescript/npm/tsconfig.build.json @@ -1,16 +1,14 @@ { - "compilerOptions": { - "outDir": "./lib", - "noEmit": false, - "declaration": true, - "rootDir": "./src", - "composite": true, - "paths": { - "@principlestudios/openapi-codegen-typescript": ["./src"], - } - }, - "extends": "./tsconfig.json", - "include": [ - "./src" - ], -} \ No newline at end of file + "compilerOptions": { + "outDir": "./lib", + "noEmit": false, + "declaration": true, + "rootDir": "./src", + "composite": true, + "paths": { + "@principlestudios/openapi-codegen-typescript": ["./src"] + } + }, + "extends": "./tsconfig.json", + "include": ["./src"] +} diff --git a/generators/typescript/npm/tsconfig.json b/generators/typescript/npm/tsconfig.json index 51f94311..85d91785 100644 --- a/generators/typescript/npm/tsconfig.json +++ b/generators/typescript/npm/tsconfig.json @@ -1,32 +1,30 @@ { - "compilerOptions": { - "target": "es5", - "lib": [ - "esnext", "DOM" - ], - "allowJs": true, - "skipLibCheck": true, - "esModuleInterop": true, - "strict": true, - "forceConsistentCasingInFileNames": true, - "module": "commonjs", - "moduleResolution": "node", - "resolveJsonModule": true, - "isolatedModules": true, - "noEmit": false, - "composite": true, - "declaration": true, - "outDir": "../../../artifacts/generators/typescript/npm/", - "types": ["node", "jest"], - "rootDir": ".", - "paths": { - "~/*": ["./*"], - "@principlestudios/openapi-codegen-typescript": ["./src"], - } - }, + "compilerOptions": { + "target": "es5", + "lib": ["esnext", "DOM"], + "allowJs": true, + "skipLibCheck": true, + "esModuleInterop": true, + "strict": true, + "forceConsistentCasingInFileNames": true, + "module": "commonjs", + "moduleResolution": "node", + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": false, + "composite": true, + "declaration": true, + "outDir": "../../../artifacts/generators/typescript/npm/", + "types": ["node", "jest"], + "rootDir": ".", + "paths": { + "~/*": ["./*"], + "@principlestudios/openapi-codegen-typescript": ["./src"] + } + }, "references": [ { "path": "./tsconfig.build.json" - }, - ], + } + ] } diff --git a/global.json b/global.json index 05c3e12f..349f97af 100644 --- a/global.json +++ b/global.json @@ -4,4 +4,4 @@ "rollForward": "latestMinor", "allowPrerelease": false } -} \ No newline at end of file +} diff --git a/lib/PrincipleStudios.OpenApi.CSharp/csharp.config.yaml b/lib/PrincipleStudios.OpenApi.CSharp/csharp.config.yaml index f9469c33..4ade4b0f 100644 --- a/lib/PrincipleStudios.OpenApi.CSharp/csharp.config.yaml +++ b/lib/PrincipleStudios.OpenApi.CSharp/csharp.config.yaml @@ -1,159 +1,159 @@ controllerNameExtension: dotnet-mvc-server-controller globalReservedIdentifiers: - - "string" - - "bool" - - "double" - - "decimal" - - "int" - - "long" - - "float" - - "abstract" - - "as" - - "base" - - "bool" - - "break" - - "byte" - - "case" - - "catch" - - "char" - - "checked" - - "class" - - "const" - - "continue" - - "decimal" - - "default" - - "delegate" - - "do" - - "double" - - "else" - - "enum" - - "event" - - "explicit" - - "extern" - - "false" - - "finally" - - "fixed" - - "float" - - "for" - - "foreach" - - "goto" - - "if" - - "implicit" - - "in" - - "int" - - "interface" - - "internal" - - "is" - - "lock" - - "long" - - "namespace" - - "new" - - "null" - - "object" - - "operator" - - "out" - - "override" - - "params" - - "private" - - "protected" - - "public" - - "readonly" - - "ref" - - "return" - - "sbyte" - - "sealed" - - "short" - - "sizeof" - - "stackalloc" - - "static" - - "string" - - "struct" - - "switch" - - "this" - - "throw" - - "true" - - "try" - - "typeof" - - "uint" - - "ulong" - - "unchecked" - - "unsafe" - - "ushort" - - "using" - - "virtual" - - "void" - - "volatile" - - "while" - - "global" - - "GetType" - - "ToString" - - "Equals" - - "GetHashCode" + - 'string' + - 'bool' + - 'double' + - 'decimal' + - 'int' + - 'long' + - 'float' + - 'abstract' + - 'as' + - 'base' + - 'bool' + - 'break' + - 'byte' + - 'case' + - 'catch' + - 'char' + - 'checked' + - 'class' + - 'const' + - 'continue' + - 'decimal' + - 'default' + - 'delegate' + - 'do' + - 'double' + - 'else' + - 'enum' + - 'event' + - 'explicit' + - 'extern' + - 'false' + - 'finally' + - 'fixed' + - 'float' + - 'for' + - 'foreach' + - 'goto' + - 'if' + - 'implicit' + - 'in' + - 'int' + - 'interface' + - 'internal' + - 'is' + - 'lock' + - 'long' + - 'namespace' + - 'new' + - 'null' + - 'object' + - 'operator' + - 'out' + - 'override' + - 'params' + - 'private' + - 'protected' + - 'public' + - 'readonly' + - 'ref' + - 'return' + - 'sbyte' + - 'sealed' + - 'short' + - 'sizeof' + - 'stackalloc' + - 'static' + - 'string' + - 'struct' + - 'switch' + - 'this' + - 'throw' + - 'true' + - 'try' + - 'typeof' + - 'uint' + - 'ulong' + - 'unchecked' + - 'unsafe' + - 'ushort' + - 'using' + - 'virtual' + - 'void' + - 'volatile' + - 'while' + - 'global' + - 'GetType' + - 'ToString' + - 'Equals' + - 'GetHashCode' contextualReservedIdentifiers: ControllerBase: # public members of ControllerBase - - "Conflict" - - "Problem" - - "ValidationProblem" - - "Created" - - "CreatedAtAction" - - "CreatedAtRoute" - - "Accepted" - - "AcceptedAtAction" - - "AcceptedAtRoute" - - "Challenge" - - "Forbid" - - "SignIn" - - "SignOut" - - "TryUpdateModelAsync" - - "TryValidateModel" - - "StatusCode" - - "Content" - - "NoContent" - - "Ok" - - "Redirect" - - "RedirectPermanent" - - "RedirectPreserveMethod" - - "RedirectPermanentPreserveMethod" - - "LocalRedirect" - - "LocalRedirectPermanent" - - "LocalRedirectPreserveMethod" - - "LocalRedirectPermanentPreserveMethod" - - "RedirectToAction" - - "RedirectToActionPreserveMethod" - - "RedirectToActionPermanent" - - "RedirectToActionPermanentPreserveMethod" - - "RedirectToRoute" - - "RedirectToRoutePreserveMethod" - - "RedirectToRoutePermanent" - - "RedirectToRoutePermanentPreserveMethod" - - "RedirectToPage" - - "RedirectToPagePermanent" - - "RedirectToPagePreserveMethod" - - "RedirectToPagePermanentPreserveMethod" - - "File" - - "PhysicalFile" - - "Unauthorized" - - "NotFound" - - "BadRequest" - - "UnprocessableEntity" - - "HttpContext" - - "Request" - - "Response" - - "RouteData" - - "ModelState" - - "ControllerContext" - - "MetadataProvider" - - "ModelBinderFactory" - - "Url" - - "ObjectValidator" - - "ProblemDetailsFactory" - - "User" + - 'Conflict' + - 'Problem' + - 'ValidationProblem' + - 'Created' + - 'CreatedAtAction' + - 'CreatedAtRoute' + - 'Accepted' + - 'AcceptedAtAction' + - 'AcceptedAtRoute' + - 'Challenge' + - 'Forbid' + - 'SignIn' + - 'SignOut' + - 'TryUpdateModelAsync' + - 'TryValidateModel' + - 'StatusCode' + - 'Content' + - 'NoContent' + - 'Ok' + - 'Redirect' + - 'RedirectPermanent' + - 'RedirectPreserveMethod' + - 'RedirectPermanentPreserveMethod' + - 'LocalRedirect' + - 'LocalRedirectPermanent' + - 'LocalRedirectPreserveMethod' + - 'LocalRedirectPermanentPreserveMethod' + - 'RedirectToAction' + - 'RedirectToActionPreserveMethod' + - 'RedirectToActionPermanent' + - 'RedirectToActionPermanentPreserveMethod' + - 'RedirectToRoute' + - 'RedirectToRoutePreserveMethod' + - 'RedirectToRoutePermanent' + - 'RedirectToRoutePermanentPreserveMethod' + - 'RedirectToPage' + - 'RedirectToPagePermanent' + - 'RedirectToPagePreserveMethod' + - 'RedirectToPagePermanentPreserveMethod' + - 'File' + - 'PhysicalFile' + - 'Unauthorized' + - 'NotFound' + - 'BadRequest' + - 'UnprocessableEntity' + - 'HttpContext' + - 'Request' + - 'Response' + - 'RouteData' + - 'ModelState' + - 'ControllerContext' + - 'MetadataProvider' + - 'ModelBinderFactory' + - 'Url' + - 'ObjectValidator' + - 'ProblemDetailsFactory' + - 'User' enum: - - "Format" - - "GetNames" - - "GetValues" - - "IsDefined" + - 'Format' + - 'GetNames' + - 'GetValues' + - 'IsDefined' - Parse - ToObject - TryParse @@ -195,4 +195,4 @@ types: default: int object: formats: - any: global::System.Text.Json.Nodes.JsonNode \ No newline at end of file + any: global::System.Text.Json.Nodes.JsonNode diff --git a/lib/PrincipleStudios.OpenApi.TypeScript/typescript.config.yaml b/lib/PrincipleStudios.OpenApi.TypeScript/typescript.config.yaml index 0d0c92ca..23ed129a 100644 --- a/lib/PrincipleStudios.OpenApi.TypeScript/typescript.config.yaml +++ b/lib/PrincipleStudios.OpenApi.TypeScript/typescript.config.yaml @@ -3,70 +3,70 @@ - application/x-www-form-urlencoded - application/octet-stream globalReservedIdentifiers: - - "break" - - "case" - - "catch" - - "class" - - "const" - - "continue" - - "debugger" - - "default" - - "delete" - - "do" - - "else" - - "enum" - - "export" - - "exports" - - "extends" - - "false" - - "finally" - - "for" - - "function" - - "if" - - "import" - - "in" - - "instanceof" - - "new" - - "null" - - "return" - - "super" - - "switch" - - "this" - - "throw" - - "true" - - "try" - - "typeof" - - "var" - - "void" - - "while" - - "with" - - "as" - - "implements" - - "interface" - - "let" - - "package" - - "private" - - "protected" - - "public" - - "static" - - "yield" - - "any" - - "boolean" - - "constructor" - - "declare" - - "get" - - "module" - - "require" - - "number" - - "set" - - "string" - - "symbol" - - "type" - - "from" - - "of" - - "Record" - - "Array" - - "Error" + - 'break' + - 'case' + - 'catch' + - 'class' + - 'const' + - 'continue' + - 'debugger' + - 'default' + - 'delete' + - 'do' + - 'else' + - 'enum' + - 'export' + - 'exports' + - 'extends' + - 'false' + - 'finally' + - 'for' + - 'function' + - 'if' + - 'import' + - 'in' + - 'instanceof' + - 'new' + - 'null' + - 'return' + - 'super' + - 'switch' + - 'this' + - 'throw' + - 'true' + - 'try' + - 'typeof' + - 'var' + - 'void' + - 'while' + - 'with' + - 'as' + - 'implements' + - 'interface' + - 'let' + - 'package' + - 'private' + - 'protected' + - 'public' + - 'static' + - 'yield' + - 'any' + - 'boolean' + - 'constructor' + - 'declare' + - 'get' + - 'module' + - 'require' + - 'number' + - 'set' + - 'string' + - 'symbol' + - 'type' + - 'from' + - 'of' + - 'Record' + - 'Array' + - 'Error' # The following are reserved for @principlestudios/openapi-codegen-typescript - HttpHeaders - HttpQuery diff --git a/lib/PrincipleStudios.OpenApiCodegen.Client.TypeScript.Test/testing/tsconfig.json b/lib/PrincipleStudios.OpenApiCodegen.Client.TypeScript.Test/testing/tsconfig.json index d04a24d1..f6ae52a9 100644 --- a/lib/PrincipleStudios.OpenApiCodegen.Client.TypeScript.Test/testing/tsconfig.json +++ b/lib/PrincipleStudios.OpenApiCodegen.Client.TypeScript.Test/testing/tsconfig.json @@ -1,13 +1,10 @@ { - "compilerOptions": { - "lib": [ - "ESNext", - "DOM" - ], - "strict": true, - "moduleResolution": "node", - "noEmit": false, - "composite": true, - "outDir": "./dist" - } -} \ No newline at end of file + "compilerOptions": { + "lib": ["ESNext", "DOM"], + "strict": true, + "moduleResolution": "node", + "noEmit": false, + "composite": true, + "outDir": "./dist" + } +} diff --git a/lib/TestApp/Properties/launchSettings.json b/lib/TestApp/Properties/launchSettings.json index 5cb6bfbf..881efe0d 100644 --- a/lib/TestApp/Properties/launchSettings.json +++ b/lib/TestApp/Properties/launchSettings.json @@ -1,12 +1,12 @@ { - "profiles": { - "PrincipleStudios.OpenApiCodegen.Server.Mvc.TestApp": { - "commandName": "Project", - "launchBrowser": true, - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - }, - "applicationUrl": "https://localhost:52841;http://localhost:52842" - } - } -} \ No newline at end of file + "profiles": { + "PrincipleStudios.OpenApiCodegen.Server.Mvc.TestApp": { + "commandName": "Project", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "applicationUrl": "https://localhost:52841;http://localhost:52842" + } + } +} diff --git a/tsconfig.json b/tsconfig.json index 01405681..acda706f 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -14,12 +14,7 @@ }, { "path": "./lib/PrincipleStudios.OpenApiCodegen.Client.TypeScript.Test/testing" - }, + } ], - "exclude": [ - "./artifacts", - "./examples", - "./lib", - "./generators" - ] + "exclude": ["./artifacts", "./examples", "./lib", "./generators"] }