# toArtifacts

FUNCTION in `@skmtc/core 0.63.4`

Transforms an OpenAPI v3 document into generated code artifacts and metadata.

This is the primary function for the SKMTC transformation pipeline. It orchestrates
the three-phase process of parsing OpenAPI documents, generating code artifacts,
and rendering them to formatted files.

The function creates a `CoreContext` instance and executes the full pipeline:
1. **Parse**: Converts the OpenAPI document into internal OAS objects
2. **Generate**: Transforms OAS objects using the provided generator configuration
3. **Render**: Formats and prepares the final code artifacts

## Signature

```ts
import { toArtifacts } from '@skmtc/core'

toArtifacts(
  args: TransformArgs
): { artifacts: Record<string, string>; manifest: ManifestContent; logs: LogLine[]; sidecars?: Record<string, Sidecar>; generationMap?: GenerationMapEntry[]; inspection?: unknown }
```

## Parameters

- `args` (TransformArgs, required): Configuration for the transformation process
  - `traceId` (string, required): Unique identifier for the transformation trace
  - `spanId` (string, required): Unique identifier for this transformation span
  - `document` (SkmtcDocumentInput, required): Source document: an OpenAPI v3 document (`{ type: 'oas', value }`). Parsing runs inside the pipeline.
  - `settings` (ClientSettings | undefined, required): Client settings for customizing generation behavior
  - `logsPath` (string): Optional path for writing log files
  - `stackTrail` (StackTrail, required): Stack trail for distributed tracing
  - `toGeneratorConfigMap` (<EnrichmentType = undefined>() => GeneratorsMapContainer<EnrichmentType>, required): Function that returns the generator configuration map
  - `startAt` (number, required): Timestamp when transformation started
  - `silent` (boolean, required): Whether to suppress console output during generation
  - `logLevel` (LogLineLevel): The lowest level kept in the returned `logs`. Defaults to `'WARN'`, so `DEBUG` and `INFO` lines are left out unless asked for.
  - `attribution` (AttributionState): Optional attribution (gen-maps) state. When set with a `postPass` block, the pipeline emits sidecars + a generation-map index alongside the standard artifacts. See `AttributionState`.
  - `inspect` (boolean): When `true`, the result carries an `inspection` snapshot - a cycle-safe, depth-bounded JSON serialization of the live `inspectedFiles` graph. Opt-in; the generate/render pipeline is unaffected.
  - `onArtifact` ((path: string, content: string) => void): Called with each file of the run when the file is complete: its path, as a key of `artifacts`, and its text. The run then keeps no file's text, and `artifacts` of the result is empty; `manifest.files` has every file. For an OpenAPI document the run gives a file as soon as no subject left to run can write to it or read from it, so that a host can write it and the run can let it go. That run goes subject by subject, and writes the same files. A file can have its definitions in another order when more than one generator inserts into it: each subject runs every generator before the next subject runs. A run without `onArtifact` takes the model generators first, then the operation generators, then the webhook generators, so the order of these kinds in the config changes no file. A run with `attribution.postPass` or `inspect` gives every file at the end. A run that fails has no files. What it gave before it failed, the host must drop. After the first subject that fails it gives no more.

## Examples

Basic usage:

```ts
import { toArtifacts } from '@skmtc/core';

const result = await toArtifacts({
  traceId: 'my-api-generation',
  spanId: 'user-service',
  documentObject: myOpenApiDoc,
  settings: {
    basePath: './src/generated',
    skip: {
      models: ['InternalModel', 'DebugInfo'],
      operations: {
        '/internal/**': ['get', 'post']
      }
    }
  },
  toGeneratorConfigMap: () => ({
    models: modelGenerator,
    operations: operationGenerator
  }),
  startAt: Date.now(),
  silent: false
});

// Access generated files
Object.entries(result.artifacts).forEach(([path, content]) => {
  console.log(`Generated: ${path}`);
  await Deno.writeTextFile(path, content);
});

// Access generation metadata
console.log(`Generated ${Object.keys(result.manifest.files).length} files`);
console.log(`Generation took ${result.manifest.endAt - result.manifest.startAt}ms`);
```

Error handling:

```ts
try {
  const result = await toArtifacts(transformArgs);

  // Check for generation errors in the results
  const hasErrors = Object.values(result.manifest.results)
    .some(result => result === 'error');

  if (hasErrors) {
    console.warn('Generation completed with errors');
  }
} catch (error) {
  console.error('Transformation failed:', error);
}
```

## Returns

`{ artifacts: Record<string, string>; manifest: ManifestContent; logs: LogLine[]; sidecars?: Record<string, Sidecar>; generationMap?: GenerationMapEntry[]; inspection?: unknown }`

A promise resolving to the generated artifacts and manifest
