Skip to content

Commit 8474ab0

Browse files
authored
fix: resolve nested remote schema references (#160)
## Summary This pull request fixes Issue #90, where a schema referenced from a remote document could contain another local reference and cause a stack overflow during code generation. Reference resolution now uses the document containing each reference as the base point, and traverses nested local and remote references across multiple documents. The regression scenario covers the following chain: `v1 → v0#/components/schemas/Book → v0#/components/schemas/BookIDAlias → v2#/components/schemas/BookID` The implementation also detects circular schema references and includes Japanese comments explaining the reference-resolution flow. ## Test Plan The change follows a two-commit TDD sequence: 1. 94cd890 adds only the Issue #90 reproduction fixtures. CI failed as expected with `RangeError: Maximum call stack size exceeded` in `findSchemaByPathArray`. 2. 6989bd0 adds the implementation, regression tests, complex chained-reference fixtures, and updated snapshots. Verification: - `pnpm test` passes: 43 unit tests and 55 snapshot tests. - Type checking and Biome checks pass. - GitHub Actions Build passes on Ubuntu and Windows. Closes #90
1 parent 900d18a commit 8474ab0

11 files changed

Lines changed: 174 additions & 34 deletions

File tree

‎src/internal/OpenApiTools/TypeNodeContext.ts‎

Lines changed: 60 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import * as DotProp from "dot-prop";
33

44
import type { OpenApi } from "../../types";
55
import { DevelopmentError } from "../Exception";
6+
import { FileSystem } from "../FileSystem";
67
import type * as TypeScriptCodeGenerator from "../TsGenerator";
78
import type * as ConverterContext from "./ConverterContext";
89
import * as Reference from "./components/Reference";
@@ -30,8 +31,11 @@ export interface ReferencePathSet {
3031
* // 返り値の例: { pathArray: ["Common"], base: "components/schemas" }
3132
*/
3233
export const generatePath = (entryPoint: string, currentPoint: string, referencePath: string): ReferencePathSet => {
33-
const ext = Path.extname(currentPoint); // .yml
34-
const from = Path.relative(Path.dirname(entryPoint), currentPoint).replace(ext, ""); // components/schemas/A/B
34+
// JSON Pointerのフラグメントはドキュメント内の位置を示すため、ファイルシステム上の相対パス計算には影響させない。
35+
const documentEntryPoint = Reference.getDocumentPoint(entryPoint);
36+
const documentCurrentPoint = Reference.getDocumentPoint(currentPoint);
37+
const ext = Path.extname(documentCurrentPoint); // .yml
38+
const from = Path.relative(Path.dirname(documentEntryPoint), documentCurrentPoint).replace(ext, ""); // components/schemas/A/B
3539
const base = Path.dirname(from).replace(Path.sep, "/");
3640
const result = Path.posix.relative(base, referencePath); // remoteの場合? localの場合 referencePath.split("/")
3741
const pathArray = result.split("/");
@@ -119,33 +123,50 @@ export const create = (
119123
return calculateReferencePath(store, base, pathArray, converterContext);
120124
};
121125
const findSchemaByPathArray = (
126+
currentPoint: string,
122127
pathArray: string[],
123-
remainPathArray: string[] = [],
128+
visited: Set<string> = new Set(),
124129
): OpenApi.Schema | OpenApi.Reference | OpenApi.JSONSchemaDefinition => {
125-
const schema = DotProp.getProperty(rootSchema, pathArray.join("."));
126-
if (!schema) {
127-
return findSchemaByPathArray(pathArray.slice(0, pathArray.length - 1), [pathArray[pathArray.length - 1], ...remainPathArray]);
130+
// 参照解決はドキュメント境界をまたぐ可能性があるため、エントリポイントではなく現在の参照を所有するドキュメントを基準に解決する。
131+
const documentPoint = Reference.getDocumentPoint(currentPoint);
132+
// スキーマが自身を参照する場合にコールスタックがあふれないよう、再帰済みの参照を追跡する。
133+
const visitKey = `${documentPoint}|${pathArray.join("/")}`;
134+
if (visited.has(visitKey)) {
135+
throw new DevelopmentError(`Circular schema reference \n${JSON.stringify({ currentPoint, pathArray }, null, 2)}`);
128136
}
129-
if (Guard.isReference(schema)) {
130-
const ref = Reference.generate(entryPoint, entryPoint, schema);
131-
return findSchemaByPathArray(ref.path.split("/"), remainPathArray);
132-
}
133-
if (remainPathArray.length) {
134-
const moreNestSchema = DotProp.getProperty(schema, remainPathArray.join("."));
135-
if (!moreNestSchema) {
136-
throw new Error("Not found");
137+
visited.add(visitKey);
138+
139+
// エントリポイントは既に読み込み済みだが、リモートドキュメントは自身のファイルから読み込む。
140+
const isEntryPoint = Path.resolve(documentPoint) === Path.resolve(Reference.getDocumentPoint(entryPoint));
141+
const document = isEntryPoint ? rootSchema : FileSystem.loadJsonOrYaml(documentPoint);
142+
let schema: unknown = document;
143+
// パスを1要素ずつたどり、途中で参照が見つかった場合は参照先ドキュメントで残りのパスを解決する。
144+
for (const [index, path] of pathArray.entries()) {
145+
schema = DotProp.getProperty(schema, [path]);
146+
if (schema === undefined) {
147+
throw new DevelopmentError(
148+
`Schema not found \n${JSON.stringify({ currentPoint: documentPoint, pathArray, missingPath: pathArray.slice(0, index + 1) }, null, 2)}`,
149+
);
150+
}
151+
if (Guard.isReference(schema)) {
152+
// 参照をたどると解決対象のドキュメントが変わる可能性がある。
153+
const ref = Reference.generate(entryPoint, documentPoint, schema);
154+
const nextPoint = ref.type === "local" ? documentPoint : ref.referencePoint;
155+
return findSchemaByPathArray(nextPoint, [...ref.path.split("/"), ...pathArray.slice(index + 1)], visited);
137156
}
138-
return moreNestSchema;
139157
}
140-
return schema;
158+
if (schema === document) {
159+
throw new DevelopmentError(`Schema path is empty \n${JSON.stringify({ currentPoint: documentPoint, pathArray }, null, 2)}`);
160+
}
161+
return schema as OpenApi.Schema | OpenApi.Reference | OpenApi.JSONSchemaDefinition;
141162
};
142163
const setReferenceHandler: ToTypeNode.Context["setReferenceHandler"] = (currentPoint, reference) => {
143164
if (store.hasStatement(reference.path, ["interface", "typeAlias"])) {
144165
return;
145166
}
167+
const context = { rootSchema, setReferenceHandler, resolveReferencePath, findSchemaByPathArray };
146168
if (reference.type === "remote") {
147169
const data = reference.data;
148-
const context = { rootSchema, setReferenceHandler, resolveReferencePath, findSchemaByPathArray };
149170
// Determine if the schema should be treated as an interface equivalent
150171
// (e.g., plain object schemas that are not nullable and don't produce IntersectionTypeNode)
151172
const isInterfaceEquivalent = (() => {
@@ -208,6 +229,28 @@ export const create = (
208229
store.addStatement(reference.path, { name: reference.name, kind: "typeAlias", value });
209230
}
210231
} else if (reference.type === "local") {
232+
// リモートドキュメント内のローカル参照は、エントリポイントのルートスキーマではなく、
233+
// そのリモートドキュメントを基準に解決する。
234+
const isExternalDocument =
235+
Path.resolve(Reference.getDocumentPoint(currentPoint)) !== Path.resolve(Reference.getDocumentPoint(entryPoint));
236+
if (isExternalDocument) {
237+
const schema = findSchemaByPathArray(currentPoint, reference.path.split("/"));
238+
const declarationName = Path.posix.basename(reference.path);
239+
if (typeof schema === "boolean") {
240+
store.addStatement(reference.path, {
241+
name: declarationName,
242+
kind: "typeAlias",
243+
value: factory.TypeAliasDeclaration.create({
244+
export: true,
245+
name: converterContext.escapeDeclarationText(declarationName),
246+
type: ToTypeNode.convert(entryPoint, currentPoint, factory, schema, context, converterContext),
247+
}),
248+
});
249+
} else if (!Guard.isReference(schema)) {
250+
Schema.addSchema(entryPoint, currentPoint, store, factory, reference.path, declarationName, schema, context, converterContext);
251+
}
252+
return;
253+
}
211254
if (!store.isAfterDefined(reference.path)) {
212255
const { maybeResolvedName } = resolveReferencePath(currentPoint, reference.path);
213256
const value = factory.TypeAliasDeclaration.create({
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import { describe, expect, it } from "vitest";
2+
import * as Reference from "../components/Reference";
3+
4+
describe("Reference", () => {
5+
describe("getDocumentPoint", () => {
6+
it("JSON Pointerのフラグメントを除いたファイルパスを返すこと", () => {
7+
expect(Reference.getDocumentPoint("test/remote.ref.access/v0.yml#/components/schemas/Book")).toBe("test/remote.ref.access/v0.yml");
8+
});
9+
10+
it("フラグメントがない場合は入力値をそのまま返すこと", () => {
11+
expect(Reference.getDocumentPoint("test/remote.ref.access/v0.yml")).toBe("test/remote.ref.access/v0.yml");
12+
});
13+
});
14+
15+
describe("generate", () => {
16+
it("リモート参照のreferencePointをドキュメント単位で返すこと", () => {
17+
const result = Reference.generate("test/remote.ref.access/v1.yml", "test/remote.ref.access/v1.yml", {
18+
$ref: "v0.yml#/components/schemas/Book",
19+
});
20+
21+
expect(result).toMatchObject({
22+
type: "remote",
23+
referencePoint: "test/remote.ref.access/v0.yml",
24+
path: "components/schemas/Book",
25+
});
26+
});
27+
});
28+
29+
describe("resolveRemoteReference", () => {
30+
it("解決済みリモート参照のreferencePointをドキュメント単位で返すこと", () => {
31+
const result = Reference.resolveRemoteReference("test/remote.ref.access/v1.yml", "test/remote.ref.access/v1.yml", {
32+
$ref: "v0.yml#/components/schemas/Book",
33+
});
34+
35+
expect(result.referencePoint).toBe("test/remote.ref.access/v0.yml");
36+
expect(result.data).toMatchObject({
37+
type: "object",
38+
properties: {
39+
id: {
40+
$ref: "#/components/schemas/BookIDAlias",
41+
},
42+
},
43+
});
44+
});
45+
});
46+
});

‎src/internal/OpenApiTools/__tests__/TypeNodeContext.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,17 @@ describe("TypeNodeContext", () => {
4141
expect(result.base).toBe("components/schemas");
4242
expect(result.pathArray).toEqual(["Common"]);
4343
});
44+
45+
it("フラグメントを含むリモート参照元でもドキュメント単位でパスを計算できること", () => {
46+
const entryPoint = "test/remote.ref.access/v1.yml";
47+
const currentPoint = "test/remote.ref.access/v0.yml#/components/schemas/Book";
48+
const referencePath = "components/schemas/BookID";
49+
50+
const result = TypeNodeContext.generatePath(entryPoint, currentPoint, referencePath);
51+
52+
expect(result.base).toBe(".");
53+
expect(result.pathArray).toEqual(["components", "schemas", "BookID"]);
54+
});
4455
});
4556

4657
describe("calculateReferencePath", () => {

‎src/internal/OpenApiTools/components/Reference.ts‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,17 @@ export const generateReferencePoint = (currentPoint: string, reference: OpenApi.
118118
return referencePoint;
119119
};
120120

121+
/**
122+
* JSON Pointerのフラグメントを除いた参照先のファイルパスを返す。
123+
*
124+
* 参照先はネストした参照を解決する際の現在のドキュメントとして使用する。
125+
* フラグメントはそのドキュメント内のデータを示すが、ネストした相対参照のパス解決には影響させない。
126+
*/
127+
export const getDocumentPoint = (referencePoint: string): string => {
128+
const fragmentIndex = referencePoint.indexOf("#/");
129+
return fragmentIndex === -1 ? referencePoint : referencePoint.substring(0, fragmentIndex);
130+
};
131+
121132
export const generate = <T>(entryPoint: string, currentPoint: string, reference: OpenApi.Reference): Type<T> => {
122133
const localReference = generateLocalReference(reference);
123134
if (localReference) {
@@ -129,6 +140,8 @@ export const generate = <T>(entryPoint: string, currentPoint: string, reference:
129140
}
130141

131142
const referencePoint = generateReferencePoint(currentPoint, reference);
143+
// 参照先の値を読み込む際はフラグメントを保持するが、その値に含まれる相対参照はドキュメントパスを基準に解決する。
144+
const documentPoint = getDocumentPoint(referencePoint);
132145

133146
if (!FileSystem.existSync(referencePoint)) {
134147
Logger.showFilePosition(entryPoint, currentPoint, referencePoint);
@@ -156,12 +169,12 @@ export const generate = <T>(entryPoint: string, currentPoint: string, reference:
156169

157170
const data = FileSystem.loadJsonOrYaml(referencePoint);
158171
if (Guard.isReference(data)) {
159-
return generate<T>(entryPoint, referencePoint, data);
172+
return generate<T>(entryPoint, documentPoint, data);
160173
}
161174

162175
return {
163176
type: "remote",
164-
referencePoint,
177+
referencePoint: documentPoint,
165178
path: targetPath,
166179
name: schemaName,
167180
componentName: Guard.isComponentName(componentName) ? componentName : undefined,
@@ -178,17 +191,19 @@ export const resolveRemoteReference = (
178191
return { referencePoint: currentPoint, data: reference };
179192
}
180193
const referencePoint = generateReferencePoint(currentPoint, reference);
194+
// 解決したデータはフラグメントで選択される場合があるが、ネストした相対参照は常に格納元のドキュメントを基準にする。
195+
const documentPoint = getDocumentPoint(referencePoint);
181196
if (!FileSystem.existSync(referencePoint)) {
182197
Logger.showFilePosition(entryPoint, currentPoint, referencePoint);
183198
Logger.error(JSON.stringify(reference, null, 2));
184199
throw new NotFoundFileError(`Not found reference point from current point. \n Path: ${referencePoint}`);
185200
}
186201
const data = FileSystem.loadJsonOrYaml(referencePoint);
187202
if (Guard.isReference(data)) {
188-
return resolveRemoteReference(entryPoint, referencePoint, data);
203+
return resolveRemoteReference(entryPoint, documentPoint, data);
189204
}
190205
return {
191-
referencePoint,
206+
referencePoint: documentPoint,
192207
data,
193208
};
194209
};

‎src/internal/OpenApiTools/components/Schemas.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,14 +30,14 @@ export const generateNamespace = (
3030
const schema = targetSchema;
3131
const reference = Reference.generate<OpenApi.Schema>(entryPoint, currentPoint, schema);
3232
if (reference.type === "local") {
33-
const { maybeResolvedName, depth, pathArray } = context.resolveReferencePath(currentPoint, reference.path);
33+
const { maybeResolvedName, depth } = context.resolveReferencePath(currentPoint, reference.path);
3434
const createTypeNode = () => {
3535
if (depth === 2) {
3636
return factory.TypeReferenceNode.create({
3737
name: convertContext.escapeReferenceDeclarationText(maybeResolvedName),
3838
});
3939
}
40-
const schema = context.findSchemaByPathArray(pathArray);
40+
const schema = context.findSchemaByPathArray(currentPoint, reference.path.split("/"));
4141
return ToTypeNode.convert(entryPoint, currentPoint, factory, schema, context, convertContext, { parent: schema });
4242
};
4343
return store.addStatement(`${basePath}/${name}`, {

‎src/internal/OpenApiTools/toTypeNode.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ export interface Context {
2626
readonly rootSchema: OpenApi.Document;
2727
setReferenceHandler: (currentPoint: string, reference: Reference.Type<OpenApi.Schema | OpenApi.JSONSchemaDefinition>) => void;
2828
resolveReferencePath: (currentPoint: string, referencePath: string) => ResolveReferencePath;
29-
findSchemaByPathArray: (paths: string[]) => OpenApi.Schema | OpenApi.Reference | OpenApi.JSONSchemaDefinition;
29+
findSchemaByPathArray: (currentPoint: string, paths: string[]) => OpenApi.Schema | OpenApi.Reference | OpenApi.JSONSchemaDefinition;
3030
}
3131

3232
export type Convert = (
@@ -131,11 +131,11 @@ export const convert: Convert = (
131131
if (reference.type === "local") {
132132
// Type Aliasを作成 (or すでにある場合は作成しない)
133133
context.setReferenceHandler(currentPoint, reference);
134-
const { maybeResolvedName, depth, pathArray } = context.resolveReferencePath(currentPoint, reference.path);
134+
const { maybeResolvedName, depth } = context.resolveReferencePath(currentPoint, reference.path);
135135
if (depth === 2) {
136136
return factory.TypeReferenceNode.create({ name: converterContext.escapeReferenceDeclarationText(maybeResolvedName) });
137137
}
138-
const resolveSchema = context.findSchemaByPathArray(pathArray);
138+
const resolveSchema = context.findSchemaByPathArray(currentPoint, reference.path.split("/"));
139139
return convert(entryPoint, currentPoint, factory, resolveSchema, context, converterContext, { parent: schema });
140140
}
141141
// サポートしているディレクトリに対して存在する場合

‎test/__tests__/class/__snapshots__/typedef-with-template/remote-ref-access.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@
88

99

1010
export namespace Schemas {
11+
export type BookIDAlias = string;
1112
export interface Book {
13+
id: Schemas.BookIDAlias;
1214
author?: {
1315
name?: string;
1416
age?: string;
@@ -40,17 +42,18 @@ export namespace Schemas {
4042
}
4143
export type Author = Schemas.Book.properties.author;
4244
export type Publisher = Schemas.Book.properties.publisher;
45+
export type BookID = string;
4346
}
4447
export interface Parameter$getBook {
4548
/** Book ID */
46-
id: string;
49+
id: Schemas.BookID;
4750
}
4851
export interface Response$getBook$Status$200 {
4952
"application/json": Schemas.Book;
5053
}
5154
export interface Parameter$getDescription {
5255
/** Book ID */
53-
id: string;
56+
id: Schemas.BookID;
5457
}
5558
export interface Response$getDescription$Status$200 {
5659
"application/json": Schemas.Book.properties.metadata.properties.description;

‎test/__tests__/functional/__snapshots__/typedef-with-template/remote-ref-access.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@
88

99

1010
export namespace Schemas {
11+
export type BookIDAlias = string;
1112
export interface Book {
13+
id: Schemas.BookIDAlias;
1214
author?: {
1315
name?: string;
1416
age?: string;
@@ -40,17 +42,18 @@ export namespace Schemas {
4042
}
4143
export type Author = Schemas.Book.properties.author;
4244
export type Publisher = Schemas.Book.properties.publisher;
45+
export type BookID = string;
4346
}
4447
export interface Parameter$getBook {
4548
/** Book ID */
46-
id: string;
49+
id: Schemas.BookID;
4750
}
4851
export interface Response$getBook$Status$200 {
4952
"application/json": Schemas.Book;
5053
}
5154
export interface Parameter$getDescription {
5255
/** Book ID */
53-
id: string;
56+
id: Schemas.BookID;
5457
}
5558
export interface Response$getDescription$Status$200 {
5659
"application/json": Schemas.Book.properties.metadata.properties.description;

‎test/remote.ref.access/v0.yml‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,19 @@ tags:
1717

1818
components:
1919
schemas:
20+
BookID:
21+
type: string
22+
format: uuid
23+
BookIDAlias:
24+
$ref: "v2.yml#/components/schemas/BookID"
2025
Book:
2126
type: object
2227
required:
28+
- id
2329
- metadata
2430
properties:
31+
id:
32+
$ref: "#/components/schemas/BookIDAlias"
2533
author:
2634
type: object
2735
properties:

‎test/remote.ref.access/v1.yml‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,7 @@ paths:
3232
required: true
3333
description: Book ID
3434
schema:
35-
type: string
36-
format: uuid
35+
$ref: "v0.yml#/components/schemas/BookID"
3736
get:
3837
operationId: getBook
3938
responses:
@@ -50,8 +49,7 @@ paths:
5049
required: true
5150
description: Book ID
5251
schema:
53-
type: string
54-
format: uuid
52+
$ref: "v0.yml#/components/schemas/BookID"
5553
get:
5654
operationId: getDescription
5755
responses:

0 commit comments

Comments
 (0)