# OasRef

CLASS in `@skmtc/core 0.63.4`

Represents an OpenAPI reference ($ref) in the SKMTC OAS processing system.

The `OasRef` class handles OpenAPI JSON Reference Objects that point to reusable
components within the same document. It provides type-safe reference resolution
with support for chained references and circular reference detection.


**Key Features**


- **Type Safety**: Generic parameter ensures resolved types match the reference type
- **Lazy Resolution**: References are resolved on-demand, not during construction
- **Chain Resolution**: Handles references that point to other references
- **Loop Detection**: A chain of references that loops names nothing (`OasRef.toLoop`)
- **Type Validation**: Ensures resolved objects match expected reference types

## Signature

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

class OasRef<T extends OasRefData['refType']> extends OasBase
```

- `T`: The type of component this reference points to

## Examples

Basic reference resolution:

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

// Reference to a schema component
const userRef = new OasRef<'schema'>({
  refType: 'schema',
  $ref: '#/components/schemas/User'
}, document);

// Resolve the reference
const userSchema = userRef.resolve();
console.log(userSchema.properties); // Access resolved schema properties
```

Working with different reference types:

```ts
// Schema reference
const schemaRef = new OasRef<'schema'>({
  refType: 'schema',
  $ref: '#/components/schemas/Product'
}, document);

// Response reference
const responseRef = new OasRef<'response'>({
  refType: 'response',
  $ref: '#/components/responses/ErrorResponse'
}, document);

// Parameter reference
const paramRef = new OasRef<'parameter'>({
  refType: 'parameter',
  $ref: '#/components/parameters/PageSize'
}, document);
```

Reference checking and conditional resolution:

```ts
function processSchemaOrRef(schema: OasSchema | OasRef<'schema'>) {
  if (schema.isRef()) {
    // Handle reference
    const { refName, refPath } = schema;
    console.log(`Processing reference: ${refName} in ${refPath}`);

    // Resolve only when needed
    const resolved = schema.resolve();
    return processed(resolved);
  } else {
    // Handle direct schema
    return process(schema);
  }
}
```

Chained reference handling:

```ts
// References can point to other references
const chainedRef = new OasRef<'schema'>({
  refType: 'schema',
  $ref: '#/components/schemas/AliasToUser'
}, document);

// resolve() automatically follows the chain
const finalSchema = chainedRef.resolve(); // Follows chain to final schema

// resolveOnce() resolves only one step
const oneStep = chainedRef.resolveOnce(); // May still be a reference
```

## Constructor

### constructor

```ts
constructor(fields: RefFields<T>, context: RefContext)
```

Creates a new OAS reference instance.

- `fields`: Reference field data including refType and $ref
- `context`: The parse context, or what `clone` passes in its place: the document containing the referenced component (refs resolve through the document's components) and the current trail.

## Properties

- `oasType` ('ref'): OAS type identifier
- `type` ('ref'): Type identifier
- `refType` (T): The kind of component the reference points to.
- `$ref` (string): The JSON Reference, as written: a component (`#/components/<bucket>/<name>`) or any other place in the document (`#/components/schemas/Pet/properties/tag`).
- `refName` (RefName): The last segment of the `$ref`'s pointer, unescaped: `Pet` for `#/components/schemas/Pet`, `schema0` for `#/components/schemas/__sharedInput/$defs/schema0`. Empty for a `$ref` that ends in `/`, which names nothing.
- `refPath` (string): The pointer before `refName`, with no percent escapes: `#/components/schemas` for a schema component, `#/components/schemas/__sharedInput/$defs` for the `$defs` entry above. A generator that names by `refName` alone may ignore it.
- `nullable` (SiblingKeywords['nullable']): Use-site nullability (see `SiblingKeywords.nullable`). Assigned even when `undefined`, so `'nullable' in ref` is always true and the value-function nullable read picks it up uniformly.
- `readOnly` (SiblingKeywords['readOnly']): Use-site `readOnly` (see `SiblingKeywords.readOnly`).
- `writeOnly` (SiblingKeywords['writeOnly']): Use-site `writeOnly` (see `SiblingKeywords.writeOnly`).
- `_type` (SiblingKeywords['_type']): The `type` written next to this reference (see `SiblingKeywords._type`).
- `title` (SiblingKeywords['title']): The `title` next to this reference (see `SiblingKeywords`).
- `description` (SiblingKeywords['description']): The `description` next to this reference (see `SiblingKeywords`).
- `deprecated` (SiblingKeywords['deprecated']): The `deprecated` next to this reference (see `SiblingKeywords`).
- `example` (SiblingKeywords['example']): The `example` next to this reference (see `SiblingKeywords`).
- `default` (SiblingKeywords['default']): The `default` next to this reference (see `SiblingKeywords`).
- `enums` (SiblingKeywords['enums']): The `enum` next to this reference (see `SiblingKeywords`).
- `extensionFields` (SiblingKeywords['extensionFields']): The extensions (`x-*`) next to this reference (see `SiblingKeywords`).
- `format` (SiblingKeywords['format']): The `format` next to this reference (see `SiblingKeywords`).
- `minLength` (SiblingKeywords['minLength']): The `minLength` next to this reference (see `SiblingKeywords`).
- `maxLength` (SiblingKeywords['maxLength']): The `maxLength` next to this reference (see `SiblingKeywords`).
- `pattern` (SiblingKeywords['pattern']): The `pattern` next to this reference (see `SiblingKeywords`).
- `multipleOf` (SiblingKeywords['multipleOf']): The `multipleOf` next to this reference (see `SiblingKeywords`).
- `minimum` (SiblingKeywords['minimum']): The `minimum` next to this reference (see `SiblingKeywords`).
- `maximum` (SiblingKeywords['maximum']): The `maximum` next to this reference (see `SiblingKeywords`).
- `exclusiveMinimum` (SiblingKeywords['exclusiveMinimum']): The `exclusiveMinimum` next to this reference (see `SiblingKeywords`).
- `exclusiveMaximum` (SiblingKeywords['exclusiveMaximum']): The `exclusiveMaximum` next to this reference (see `SiblingKeywords`).
- `minItems` (SiblingKeywords['minItems']): The `minItems` next to this reference (see `SiblingKeywords`).
- `maxItems` (SiblingKeywords['maxItems']): The `maxItems` next to this reference (see `SiblingKeywords`).
- `uniqueItems` (SiblingKeywords['uniqueItems']): The `uniqueItems` next to this reference (see `SiblingKeywords`).
- `properties` (SiblingKeywords['properties']): The `properties` next to this reference (see `SiblingKeywords`).
- `required` (SiblingKeywords['required']): The `required` next to this reference (see `SiblingKeywords`).
- `additionalProperties` (SiblingKeywords['additionalProperties']): The `additionalProperties` next to this reference (see `SiblingKeywords`).
- `minProperties` (SiblingKeywords['minProperties']): The `minProperties` next to this reference (see `SiblingKeywords`).
- `maxProperties` (SiblingKeywords['maxProperties']): The `maxProperties` next to this reference (see `SiblingKeywords`).
- `document` (SkmtcParsedDocument): Returns the parsed document this ref resolves through: the parent `OasDocument`, wrapped.

## Methods

### isRef

```ts
isRef(): this is OasRef<T>
```

Type guard to check if this instance is a reference.

Returns: Always true for OasRef instances

### resolve

```ts
resolve(): ResolvedRef<T>
```

Recursively resolves this reference to its final target component.

Follows the chain of references until it reaches a component that is
not a reference. A schema reference returns the
schema at this site: when the keywords next to it, or next to a
reference on the chain (`SiblingKeywords`), change the target, a
copy of the target with them applied. When they change nothing, the
shared target itself. `resolveOnce()` applies no siblings.

The result is shared, so do not modify it: the shared target is the
model every reference to it sees, and a copy is built once, kept on
this reference, and returned on every call.

Returns: The resolved component

Throws:

- `DanglingRefError`: when a reference on the chain names nothing, or the chain loops (`toLoop`), so it never reaches a component. The parser keeps either one only when `parse.danglingRefs` lists its kind.
- `Error`: Error when a reference on the chain names a component of another kind (see `resolveOnce`)

### toLoop

```ts
toLoop(): OasRef<T>[] | undefined
```

The references that form the loop this reference's chain comes back to,
starting with the first one it comes back to, or `undefined` when the
chain reaches a component. `A` a `$ref` to `B`, and `B` to `A`, form a
loop: from `A` the chain goes to `B`, then to `A` again, and never
reaches a component. A reference that leads into a loop is not part of it.

Throws:

- `Error`: what `resolveOnce` throws, at any step of the chain

### resolveOnce

```ts
resolveOnce(): OasRef<T> | ResolvedRef<T>
```

Resolves this reference one level. It reads a component from
`document.components.<bucket>`, and any other target from the targets
the parser kept by pointer (`OasDocument.toRefTarget`).

Returns: Either the resolved component or another reference in the chain

Throws:

- `DanglingRefError`: when the reference names nothing in the document (kept when `skmtc.config.json` `parse.danglingRefs` lists its kind), including a `$ref` with no name, such as `#/components/schemas/`
- `Error`: Error when it names a component of another kind, such as a `requestBody` ref to `#/components/schemas/…`

### isSchemaRef

```ts
isSchemaRef(): this is OasRef<'schema'>
```

Narrows this reference to a schema reference.

Returns: True when this reference points at a schema component.

### traverse

```ts
traverse(path: SchemaPath): OasSchema | OasRef<'schema'>
```

Navigate an `SchemaPath` starting from this reference, resolving it
to descend through. See `traverseSchema`.

Available on every `OasRef` so `.traverse()` works on the common
`OasSchema | OasRef<'schema'>` value (an object property, array `items`).
Schema paths only describe schemas for now, so it throws for non-schema
refs (response/parameter/…); `isSchemaRef` narrows `this`, keeping the
delegation cast-free.

Returns: The schema at the path (may be an unresolved `$ref`).

Throws:

- `Error`: Error when called on a non-schema ref.

### hasSiblings

```ts
hasSiblings(): boolean
```

Whether this reference adds anything at its site: a use-site flag
(`nullable`, `readOnly`, `writeOnly`) or another keyword next to it (see
`RefFields`). `resolve` then returns a copy of the target with
them applied, not the shared target.

### clone

```ts
clone(ref?: OasRef<'schema'>): OasRef<T>
```

A copy of this reference with what `ref` adds at its site merged in: its
flags, and its keywords over this reference's own
(`mergeSiblingKeywords`). It points at the same target. Each schema
class's `clone` does the same for a schema, so one step along a chain of
references can carry a site's keywords (`resolveSchemaRefOnce`). This
reference does not change.

### hasValueSiblings

```ts
hasValueSiblings(): boolean
```

Whether the keywords next to this reference change which values it
accepts (`minLength` next to a string, `properties` next to an object),
not only how it is described (`description`, `deprecated`, `x-*`). No
shared model accepts the same values as such a site, so a generator
applies these keywords where it renders the reference by name. See
`changesValues`.

### toSkippedSiblings

```ts
toSkippedSiblings(): string[]
```

The keywords next to this reference that `resolve` leaves out, by
their names in the document: ones the target's type does not take
(`minLength` next to an array), a `type` that disagrees, and values that
do not fit. The parser cannot tell them while the reference is lazy, so a
generator logs them when it renders the site. See `toSkippedSiblings`.

### isReadOnly

```ts
isReadOnly(): boolean
```

Whether the value is `readOnly` at this site, as Forge reads it: on this
reference (`{ allOf: [{ $ref }], readOnly: true }`), or on what it points
to, through any chain of references. A `readOnly: false` does not undo
another's `true`. `false` for a reference to anything but a schema. In a
loop (`toLoop`), which reaches no schema, only the references count.

### isWriteOnly

```ts
isWriteOnly(): boolean
```

Whether the value is `writeOnly` at this site: on this reference, or on
what it points to, as `isReadOnly` reads `readOnly`.

### toJsonSchema

```ts
toJsonSchema(
  args: ToJsonSchemaOptions
): OpenAPIV3.ReferenceObject | ResolvedRefJsonType<T>
```

The reference as JSON Schema. With `resolve`, the schema at this site,
with the keywords next to the reference applied. Without it, only
`{ $ref }`: the keywords next to the reference are not written yet
(skmtc/skmtc#338).

### toJSON

```ts
toJSON(): object
```

`{ $ref }` only, as `toJsonSchema` without `resolve` (skmtc/skmtc#338).
