import { GenerateContext } from './GenerateContext.js'; import { RenderContext } from './RenderContext.js'; import { ParseContext } from './ParseContext.js'; import type { OasDocument } from '../oas/document/Document.js'; import type { ClientSettings } from '../types/Settings.js'; import type { ResultType } from '../types/Results.js'; import type { Logger } from '../types/Logger.js'; import type { LogLineLevel } from '../types/LogLine.js'; import { StackTrail } from './StackTrail.js'; import type { GeneratorsMapContainer } from '../types/GeneratorType.js'; import type { OpenAPIV3 } from 'openapi-types'; import type { ToArtifactsResult } from './generateTypes.js'; import type { SkmtcDocumentInput } from '../types/SkmtcDocument.js'; import type { AttributionState } from '../types/AttributionState.js'; import type { SupportedSubjects } from '../types/SupportedSubjects.js'; import type { EnrichmentDefaults } from '../types/EnrichmentDefaults.js'; import type { ParseIssue } from './ParseIssue.js'; /** * Represents the parse phase of the SKMTC pipeline. * * The parse phase converts OpenAPI v3 JSON documents into internal OAS objects, * handling schema validation, reference resolution, and data transformation. */ export type ParsePhase = { /** Identifies this as the parse phase */ type: 'parse'; /** The unified parse context — handles both OAS and GQL via its * internal protocol-discriminated state. */ context: ParseContext; }; /** * Represents the generate phase of the SKMTC pipeline. * * The generate phase transforms parsed OAS objects into generator-specific artifacts, * applying templates, handling references, and preparing output files. */ export type GeneratePhase = { /** Identifies this as the generate phase */ type: 'generate'; /** The generate context for artifact creation and processing */ context: GenerateContext; }; /** * Represents the render phase of the SKMTC pipeline. * * The render phase takes generator artifacts and renders them to formatted files, * applying code formatting, file system operations, and final output generation. */ export type RenderPhase = { /** Identifies this as the render phase */ type: 'render'; /** The render context for file output and formatting */ context: RenderContext; }; /** * Union type representing any phase of the SKMTC pipeline execution. * * Each execution phase contains its type identifier and associated context, * allowing for type-safe phase handling and context access throughout the pipeline. */ export type ExecutionPhase = ParsePhase | GeneratePhase | RenderPhase; type CoreContextArgs = { spanId: string; logsPath?: string; silent: boolean; /** The lowest level kept in the returned `logs`. Defaults to `'WARN'`. */ logLevel?: LogLineLevel; }; /** * Arguments for the `toArtifacts` method of CoreContext. * * Contains all the necessary configuration for transforming a * source document into code artifacts through the SKMTC parse + * generate + render phases. * * On the OAS side `document.value` is the *raw* OpenAPI v3 document — * `CoreContext.toArtifacts` runs the parse phase itself. On the GQL * side `document.value` is a pre-parsed {@link GqlDocument}, since SDL * parsing lives in the `parsers/graphql` sub-export to keep the * `graphql` npm dependency optional for consumers. */ export type ToArtifactsArgs = { /** Stack trail for distributed tracing */ stackTrail: StackTrail; /** * Source document. OAS variant carries the raw OpenAPI v3 JSON; GQL * variant carries a pre-parsed {@link GqlDocument}. The generate * phase reads the post-parse {@link SkmtcDocument}; both model and * operation generators dispatch on `document.type`. */ document: SkmtcDocumentInput; /** Client settings for customization (optional) */ settings: ClientSettings | undefined; /** Function that returns the generator configuration map */ toGeneratorConfigMap: () => GeneratorsMapContainer; /** Whether to suppress console output */ silent: boolean; /** * Optional attribution (gen-maps) **emission** config. Capture is * always on; when `postPass` is set, the pipeline emits sidecars + a * generation map alongside the usual artifacts. See * {@link AttributionState}. */ attribution?: AttributionState; /** * When `true`, serialize the live `inspectedFiles` graph into the result's * `inspection` field (see {@link toInspection}). Off by default; the pipeline * is otherwise untouched. */ inspect?: boolean; }; /** * The main orchestration class for the SKMTC transformation pipeline. * * `CoreContext` manages the three-phase process of transforming OpenAPI v3 documents * into code artifacts. It coordinates parsing, generation, and rendering phases while * providing logging, tracing, and error handling capabilities. * * ## Pipeline Phases * * 1. **Parse Phase**: Uses {@link ParseContext} to convert OpenAPI JSON into OAS objects * 2. **Generate Phase**: Uses {@link GenerateContext} to transform OAS objects with generators * 3. **Render Phase**: Uses {@link RenderContext} to format and prepare final artifacts * * @example Basic usage * ```typescript * import { CoreContext } from '@skmtc/core'; * * const context = new CoreContext({ * spanId: 'user-api-generation', * logsPath: './logs', * silent: false * }); * * const result = await context.toArtifacts({ * document: { type: 'oas', value: openApiDoc }, * settings: clientSettings, * toGeneratorConfigMap: () => generators, * silent: false, * stackTrail: new StackTrail(['gen']) * }); * ``` * * @example Using individual phases * ```typescript * const context = new CoreContext({ * spanId: 'custom-pipeline', * silent: true * }); * * // Parse phase only * const { oasDocument } = context.parse(openApiDoc); * * // Then use document for custom processing * console.log('Parsed schemas:', Object.keys(oasDocument.components.schemas)); * ``` */ export declare class CoreContext { #private; /** Logger instance for the context */ logger: Logger; /** Whether to suppress console output */ silent: boolean; /** * Creates a new CoreContext instance. * * @param args - Configuration for the context * @param args.spanId - Unique identifier for this transformation span * @param args.logsPath - Optional directory path for log files * @param args.silent - Whether to suppress console output * * @example * ```typescript * // Basic context with console logging * const context = new CoreContext({ * spanId: 'my-generation', * silent: false * }); * * // Context with file logging * const context = new CoreContext({ * spanId: 'batch-job-123', * logsPath: './logs/generation', * silent: true * }); * ``` */ constructor({ spanId, logsPath, silent, logLevel }: CoreContextArgs); /** * The trail of the subject being generated, or `undefined` outside one * (parse, render, and generate work that is not a subject's variant). */ get currentSubjectTrail(): StackTrail | undefined; /** * Parses an OpenAPI v3 document into internal OAS objects. * * This method executes only the parse phase of the pipeline, converting * the raw OpenAPI JSON into structured OAS objects that can be used for * generation or custom processing. * * @param documentObject - The OpenAPI v3 document to parse * @returns An object containing the parsed OAS document * * @example * ```typescript * import { CoreContext } from '@skmtc/core'; * * const context = new CoreContext({ * spanId: 'parse-only', * silent: true * }); * * const { oasDocument } = context.parse(openApiDoc); * * // Access parsed components * console.log('Models:', Object.keys(oasDocument.components.schemas)); * console.log('Paths:', Object.keys(oasDocument.paths)); * * // Use for custom processing * const userModel = oasDocument.components.schemas['User']; * if (userModel && !userModel.isRef()) { * console.log('User properties:', Object.keys(userModel.properties)); * } * ``` */ parse(documentObject: OpenAPIV3.Document, stackTrail: StackTrail): { oasDocument: OasDocument; }; /** * Executes the complete transformation pipeline to generate code artifacts. * * This method orchestrates all three phases: * 1. **Parse**: Convert OpenAPI document to OAS objects * 2. **Generate**: Transform OAS objects using generators * 3. **Render**: Format and prepare final artifacts * * The result includes both the generated code files and comprehensive metadata * about the generation process, including file mappings, previews, and results. * * @param args - Configuration for the artifact generation * @param args.document - The source document, discriminated by protocol * (`{ type: 'oas', value: OpenAPIV3.Document }` or * `{ type: 'gql', value: GqlDocument }`) * @param args.settings - Client settings for customization * @param args.toGeneratorConfigMap - Function returning generator configuration * @param args.silent - Whether to suppress console output during generation * @param args.stackTrail - Stack trail for distributed tracing * @returns Promise resolving to rendered artifacts and metadata * * @example Complete pipeline * ```typescript * import { CoreContext, StackTrail, toModelEntry, toOasOperationEntry } from '@skmtc/core'; * * const context = new CoreContext({ * spanId: 'api-client-gen', * silent: false * }); * * const result = context.toArtifacts({ * document: { type: 'oas', value: openApiDoc }, * settings: { * basePath: './src/api' * }, * toGeneratorConfigMap: () => ({ * 'typescript-models': toModelEntry({ * id: 'typescript-models', * transform: ({ context, refName }) => {} * }), * 'api-client': toOasOperationEntry({ * id: 'api-client', * transform: ({ context, operation }) => {} * }) * }), * silent: false, * stackTrail: new StackTrail(['gen']) * }); * * // Access generated artifacts * console.log('Generated files:', Object.keys(result.artifacts)); * * // Write to filesystem * for (const [path, content] of Object.entries(result.artifacts)) { * await Deno.writeTextFile(path, content); * } * * // Access metadata * console.log('Generation results:', result.results); * console.log('File mappings:', result.files); * ``` * * @throws Will throw an error if any phase of the pipeline fails */ toArtifacts({ document, settings, toGeneratorConfigMap, stackTrail, attribution, inspect }: ToArtifactsArgs): ToArtifactsResult; /** * Capability-only sibling of {@link toArtifacts}: parse the document, then * evaluate each generator's `isSupported` over its subjects — no transform, * no render. Returns the subjects each generator supports, plus parse issues. */ toSupportedSubjects({ document, settings, toGeneratorConfigMap, stackTrail }: Pick): { subjects: SupportedSubjects; parseIssues: ParseIssue[]; }; /** * Seed-values sibling of {@link toSupportedSubjects}: parse the document, then * call each generator's `toEnrichmentDefaults` over its supported subjects — * no transform, no render. Returns the default enrichment values keyed by the * `client.json#settings.enrichments` routing, plus parse issues. Fails open * like {@link toArtifacts}: a bad schema surfaces as a `parseIssue` and the * defaults map is returned empty. */ toEnrichmentDefaults({ document, settings, toGeneratorConfigMap, stackTrail }: Pick): { enrichmentDefaults: EnrichmentDefaults; parseIssues: ParseIssue[]; }; /** * Captures a result at `stackTrail`. Each frame of the trail becomes one * level of the `manifest.results` tree. * * @param result - The type of result to capture (success, warning, error, etc.) * @param stackTrail - The trail the result belongs to * * @example * ```typescript * stackTrail.trace(['/pets', 'get'], opTrail => { * context.captureCurrentResult('success', opTrail) * }) * // manifest.results: { …, '/pets': { get: 'success' } } * ``` */ captureCurrentResult(result: ResultType, stackTrail: StackTrail): void; } /** * Arguments for the SKMTC log formatter. * * Contains the log record and stack trail information needed to format * human-readable log entries for the SKMTC processing pipeline. */ export type JsonFormatterArgs = { /** The Deno log record containing log level, message, and metadata */ logRecord: { /** The log level name */ levelName: string; /** The timestamp when the log was created */ datetime: Date; /** The log message */ msg: string; /** Additional log arguments */ args: unknown[]; }; /** String representation of the current stack trail position */ stackTrail: string; }; /** * Custom pretty-print formatter for SKMTC log entries. * * Formats log records into human-readable, color-coded output with properly * formatted stack traces, making it easier to trace execution and debug issues * in the SKMTC pipeline. * * @param args - Formatter arguments containing log record and stack trail * @returns Formatted string for the log entry * * @example Usage in logger setup * ```typescript * const handler = new ConsoleHandler("DEBUG", { * formatter: (logRecord) => skmtcFormatter({ * logRecord, * stackTrail: context.stackTrail.toString() * }) * }); * ``` * * @example Output format * ``` * [ERROR] 2024-01-16 10:32:59.772 * Error: Invariant failed: Expected object schema * at invariant (file:///.../bundle.js:4445:9) * at new Table (file:///.../bundle.js:17632:5) * ``` */ export declare function skmtcFormatter({ logRecord, stackTrail }: JsonFormatterArgs): string; /** * JSON formatter for SKMTC file logs. * * Formats log records into structured JSON for file-based logging, * making it easier to parse and analyze logs programmatically. * * @param args - Formatter arguments containing log record and stack trail * @returns Formatted JSON string for the log entry * * @example Output format * ```json * { * "stackTrail": "components.schemas.User.properties.email", * "level": "INFO", * "datetime": 1645123456789, * "message": "Processing email property", * "args": { "format": "email", "required": true } * } * ``` */ export declare function skmtcJsonFormatter({ logRecord, stackTrail }: JsonFormatterArgs): string; export {};