Skip to content

feat: debugging mode #1029

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/api/src/bin.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { logger } from '@readme/api-core/logger';
import { Command } from 'commander';
import updateNotifier from 'update-notifier';

import commands from './commands/index.js';
import logger from './logger.js';
import * as pkg from './packageInfo.js'; // eslint-disable-line readme/no-wildcard-imports

updateNotifier({ pkg: { name: pkg.PACKAGE_NAME, version: pkg.PACKAGE_VERSION } }).notify();
Expand Down
48 changes: 47 additions & 1 deletion packages/api/src/codegen/languages/typescript/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import type { JsonObject, PackageJson, TsConfigJson } from 'type-fest';

import path from 'node:path';

import { logger } from '@readme/api-core/logger';
import corePkg from '@readme/api-core/package.json' with { type: 'json' };
import { execa } from 'execa';
import { getLicense } from 'license';
Expand All @@ -28,7 +29,6 @@ import semver from 'semver';
import { IndentationText, Project, QuoteKind, ScriptTarget, VariableDeclarationKind } from 'ts-morph';

import { buildCodeSnippetForOperation, getSuggestedOperation } from '../../../lib/suggestedOperations.js';
import logger from '../../../logger.js';
import { PACKAGE_VERSION } from '../../../packageInfo.js';
import Storage from '../../../storage.js';
import CodeGenerator from '../../codegenerator.js';
Expand Down Expand Up @@ -433,6 +433,52 @@ sdk.server('https://eu.api.example.com/v14');`),
},
],
},
{
name: 'debug',
parameters: [],
returnType: 'SDK',
statements: writer => {
writer.writeLine('this.core.setDebugMode(true);');
writer.writeLine('const self = this;');
writer.writeLine('return new Proxy(this, {');
writer.writeLine('get(target: SDK, prop: keyof SDK) {');
writer.writeLine('if (typeof target[prop] === "function" && prop !== \'debug\') {');
writer.writeLine('return async(...args: unknown[]) => {');
writer.writeLine('try {');
writer.writeLine('return await (target[prop] as Function).apply(target, args);');
writer.writeLine('} catch (err) {');
writer.writeLine('throw err;');
writer.writeLine('} finally {');
writer.writeLine('self.core.setDebugMode(false);');
writer.writeLine('}');
writer.writeLine('}');
writer.writeLine('}');
writer.writeLine('return Reflect.get(target, prop);');
writer.writeLine('},');
writer.writeLine('});');
return writer;
},
docs: [
{
description: writer =>
writer.writeLine(
wordWrap(`Enables debug mode for SDK operations. Debug mode captures additional internal information such as request/response payloads and timing, which may assist in troubleshooting issues during development.

This method can be used in two modes:

- **Global mode**: Calls \`sdk.debug();\` and enables debug logging for all subsequent operations.
- **Chained mode**: Calls \`sdk.debug().operation();\` and enables debug logging only for the single operation invoked. Debug mode is automatically turned off afterward.

@example <caption>Global debug mode</caption>
sdk.debug();
sdk.getPets();

@example <caption>Chained debug mode (single operation)</caption>
sdk.debug().getPets();`),
),
},
],
},
]);

// Add all available operation ID accessors into the SDK.
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/commands/install.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { SupportedLanguage } from '../codegen/factory.js';

import { logger, oraOptions } from '@readme/api-core/logger';
import chalk from 'chalk';
import { Command, Option } from 'commander';
import { createEmphasize, common } from 'emphasize';
Expand All @@ -11,7 +12,6 @@ import uslug from 'uslug';
import { SupportedLanguages, codegenFactory } from '../codegen/factory.js';
import Fetcher from '../fetcher.js';
import promptTerminal from '../lib/prompt.js';
import logger, { oraOptions } from '../logger.js';
import Storage from '../storage.js';

const { highlight } = createEmphasize(common);
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/commands/list.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { logger } from '@readme/api-core/logger';
import chalk from 'chalk';
import { Command } from 'commander';

import { SupportedLanguages } from '../codegen/factory.js';
import logger from '../logger.js';
import Storage from '../storage.js';

const cmd = new Command();
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/commands/uninstall.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import path from 'node:path';

import { logger, oraOptions } from '@readme/api-core/logger';
import chalk from 'chalk';
import { Command, Option } from 'commander';
import ora from 'ora';

import { SupportedLanguages, uninstallerFactory } from '../codegen/factory.js';
import promptTerminal from '../lib/prompt.js';
import logger, { oraOptions } from '../logger.js';
import Storage from '../storage.js';

interface Options {
Expand Down
6 changes: 6 additions & 0 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@
"require": "./dist/types.d.cjs",
"import": "./dist/types.d.js"
},
"./logger": {
"require": "./dist/logger.cjs",
"import": "./dist/logger.js"
},
"./package.json": "./package.json"
},
"main": "dist/index.cjs",
Expand Down Expand Up @@ -51,12 +55,14 @@
"dependencies": {
"@readme/oas-to-har": "^26.0.0",
"caseless": "^0.12.0",
"chalk": "^5.4.1",
"datauri": "^4.1.0",
"fetch-har": "^11.0.1",
"json-schema-to-ts": "^3.0.0",
"json-schema-traverse": "^1.0.0",
"lodash.merge": "^4.6.2",
"oas": "^27.0.0",
"ora": "^8.0.1",
"remove-undefined-objects": "^6.0.0"
},
"devDependencies": {
Expand Down
12 changes: 12 additions & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import Oas from 'oas';

import FetchError from './errors/fetchError.js';
import { parseResponse, prepareAuth, prepareParams, prepareServer } from './lib/index.js';
import { logger } from './logger.js';

export default class APICore {
spec!: Oas;
Expand All @@ -27,6 +28,8 @@ export default class APICore {

private userAgent!: string;

private debugMode: boolean = false;

constructor(definition?: OASDocument | Record<string, unknown>, userAgent?: string) {
if (definition) this.spec = Oas.init(definition);
if (userAgent) this.userAgent = userAgent;
Expand Down Expand Up @@ -56,6 +59,11 @@ export default class APICore {
return this;
}

setDebugMode(debugMode: boolean) {
this.debugMode = debugMode;
return this;
}

async fetch<HTTPStatus extends number = number>(
path: string,
method: HttpMethods,
Expand Down Expand Up @@ -96,6 +104,10 @@ export default class APICore {

const har = this.getHARForRequest(operation, data, prepareAuth(this.auth, operation));

if (this.debugMode) {
logger(`[DEBUG] HAR: ${JSON.stringify(har, null, 2)}`);
}

let timeoutSignal: NodeJS.Timeout;
const init: RequestInit = {};
if (this.config.timeout) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { Options as OraOptions } from 'ora';

import chalk from 'chalk';

export default function logger(log: string, error?: boolean) {
export function logger(log: string, error?: boolean) {
if (error) {
console.error(chalk.red(log));
} else {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/tsup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export default defineConfig((options: Options) => ({
...options,
...config,

entry: ['src/errors/fetchError.ts', 'src/lib/index.ts', 'src/index.ts', 'src/types.ts'],
entry: ['src/errors/fetchError.ts', 'src/lib/index.ts', 'src/index.ts', 'src/types.ts', 'src/logger.ts'],

noExternal: [
// These dependencies are ESM-only but because we're building for ESM **and** CJS we can't
Expand Down
41 changes: 41 additions & 0 deletions packages/test-utils/sdks/alby/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,47 @@ export default class SDK {
this.core.setServer(url, variables);
}

/**
* Enables debug mode for SDK operations. Debug mode captures additional internal
* information such as request/response payloads and timing, which may assist in
* troubleshooting issues during development.
*
* This method can be used in two modes:
*
* - **Global mode**: Calls `sdk.debug();` and enables debug logging for all subsequent
* operations.
* - **Chained mode**: Calls `sdk.debug().operation();` and enables debug logging only for
* the single operation invoked. Debug mode is automatically turned off afterward.
*
* @example <caption>Global debug mode</caption>
* sdk.debug();
* sdk.getPets();
*
* @example <caption>Chained debug mode (single operation)</caption>
* sdk.debug().getPets();
*
*/
debug(): SDK {
this.core.setDebugMode(true);
const self = this;
return new Proxy(this, {
get(target: SDK, prop: keyof SDK) {
if (typeof target[prop] === "function" && prop !== 'debug') {
return async (...args: unknown[]) => {
try {
return await (target[prop] as Function).apply(target, args);
} catch (err) {
throw err;
} finally {
self.core.setDebugMode(false);
}
}
}
return Reflect.get(target, prop);
},
});
}

/**
* List all applications for the specified account ID.
*
Expand Down
41 changes: 41 additions & 0 deletions packages/test-utils/sdks/metrotransit/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,47 @@ export default class SDK {
this.core.setServer(url, variables);
}

/**
* Enables debug mode for SDK operations. Debug mode captures additional internal
* information such as request/response payloads and timing, which may assist in
* troubleshooting issues during development.
*
* This method can be used in two modes:
*
* - **Global mode**: Calls `sdk.debug();` and enables debug logging for all subsequent
* operations.
* - **Chained mode**: Calls `sdk.debug().operation();` and enables debug logging only for
* the single operation invoked. Debug mode is automatically turned off afterward.
*
* @example <caption>Global debug mode</caption>
* sdk.debug();
* sdk.getPets();
*
* @example <caption>Chained debug mode (single operation)</caption>
* sdk.debug().getPets();
*
*/
debug(): SDK {
this.core.setDebugMode(true);
const self = this;
return new Proxy(this, {
get(target: SDK, prop: keyof SDK) {
if (typeof target[prop] === "function" && prop !== 'debug') {
return async (...args: unknown[]) => {
try {
return await (target[prop] as Function).apply(target, args);
} catch (err) {
throw err;
} finally {
self.core.setDebugMode(false);
}
}
}
return Reflect.get(target, prop);
},
});
}

/** @throws FetchError<400, types.ProblemDetails> Bad Request */
getNextripAgencies(): Promise<FetchResponse<200, types.GetNextripAgenciesResponse200>> {
return this.core.fetch('/nextrip/agencies', 'get');
Expand Down
41 changes: 41 additions & 0 deletions packages/test-utils/sdks/operationid-quirks/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,47 @@ export default class SDK {
this.core.setServer(url, variables);
}

/**
* Enables debug mode for SDK operations. Debug mode captures additional internal
* information such as request/response payloads and timing, which may assist in
* troubleshooting issues during development.
*
* This method can be used in two modes:
*
* - **Global mode**: Calls `sdk.debug();` and enables debug logging for all subsequent
* operations.
* - **Chained mode**: Calls `sdk.debug().operation();` and enables debug logging only for
* the single operation invoked. Debug mode is automatically turned off afterward.
*
* @example <caption>Global debug mode</caption>
* sdk.debug();
* sdk.getPets();
*
* @example <caption>Chained debug mode (single operation)</caption>
* sdk.debug().getPets();
*
*/
debug(): SDK {
this.core.setDebugMode(true);
const self = this;
return new Proxy(this, {
get(target: SDK, prop: keyof SDK) {
if (typeof target[prop] === "function" && prop !== 'debug') {
return async (...args: unknown[]) => {
try {
return await (target[prop] as Function).apply(target, args);
} catch (err) {
throw err;
} finally {
self.core.setDebugMode(false);
}
}
}
return Reflect.get(target, prop);
},
});
}

/**
* This mess of a string is intentionally nasty so we can be sure that we're not including
* anything that wouldn't look right as an operationID for a potential method accessor in
Expand Down
Loading