11import type { Document } from '../doc/Document.ts'
2- import { hasAnchor } from './identity.ts'
2+ import { hasAnchor , isAlias } from './identity.ts'
33import type { Node } from './Node.ts'
4+ import type { Alias } from './Alias.ts'
5+ import type { Scalar } from './Scalar.ts'
6+ import type { YAMLMap } from './YAMLMap.ts'
7+ import type { YAMLSeq } from './YAMLSeq.ts'
48
59export interface AnchorData {
610 aliasCount : number
@@ -10,6 +14,8 @@ export interface AnchorData {
1014
1115export interface ToJSContext {
1216 anchors : Map < Node , AnchorData >
17+ /** Cached anchor and allias nodes in the order they occurred in the document */
18+ anchorAndAliasNodes ?: ( Alias | Scalar | YAMLMap | YAMLSeq ) [ ]
1319 doc : Document < Node , boolean >
1420 keep : boolean
1521 mapAsMap : boolean
@@ -33,13 +39,24 @@ export function toJS(value: any, arg: string | null, ctx?: ToJSContext): any {
3339 if ( Array . isArray ( value ) ) return value . map ( ( v , i ) => toJS ( v , String ( i ) , ctx ) )
3440 if ( value && typeof value . toJSON === 'function' ) {
3541 // eslint-disable-next-line @typescript-eslint/no-unsafe-call
36- if ( ! ctx || ! hasAnchor ( value ) ) return value . toJSON ( arg , ctx )
42+ if ( ! ctx ) return value . toJSON ( arg , ctx )
43+
44+ if ( ! hasAnchor ( value ) ) {
45+ if ( ctx . anchorAndAliasNodes && isAlias ( value ) )
46+ ctx . anchorAndAliasNodes . push ( value )
47+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call
48+ return value . toJSON ( arg , ctx )
49+ }
50+
3751 const data : AnchorData = { aliasCount : 0 , count : 1 , res : undefined }
3852 ctx . anchors . set ( value , data )
3953 ctx . onCreate = res => {
4054 data . res = res
4155 delete ctx . onCreate
4256 }
57+
58+ if ( ctx . anchorAndAliasNodes ) ctx . anchorAndAliasNodes . push ( value )
59+
4360 const res = value . toJSON ( arg , ctx )
4461 if ( ctx . onCreate ) ctx . onCreate ( res )
4562 return res
0 commit comments