Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions lib/bundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export interface InventoryEntry {
scopeBase: string;
dynamicIdScope: boolean;
nestedIdScope: boolean;
scopePathFromRoot?: string;
targetResourceBase: string;
targetResourceId?: string;
rootReference?: string;
Expand Down Expand Up @@ -107,6 +108,7 @@ function crawl<S extends object = JSONSchema, O extends ParserOptions<S> = Parse
embeddedResourcePaths: Set<string>,
seen: Set<object>,
matcherAlreadyChecked = false,
scopePathFromRoot?: string,
) {
const obj = key === null ? parent : parent[key as keyof typeof parent];
const bundleOptions = (options.bundle || {}) as BundleOptions;
Expand Down Expand Up @@ -141,6 +143,7 @@ function crawl<S extends object = JSONSchema, O extends ParserOptions<S> = Parse
options,
embeddedResourcePaths,
seen,
scopePathFromRoot,
);
} else {
// Crawl the object in a specific order that's optimized for bundling.
Expand Down Expand Up @@ -180,6 +183,7 @@ function crawl<S extends object = JSONSchema, O extends ParserOptions<S> = Parse
: currentScopeBase;
const childHasSchemaIdentifier = dynamicIdScope && hasSchemaIdentifier(value, childLegacyIdScope);
const childNestedIdScope = nestedIdScope || childHasSchemaIdentifier;
const childScopePathFromRoot = childHasSchemaIdentifier ? keyPathFromRoot : scopePathFromRoot;
let childEmbeddedResourcePaths = embeddedResourcePaths;
if (childHasSchemaIdentifier) {
childEmbeddedResourcePaths = new Set(embeddedResourcePaths);
Expand All @@ -201,6 +205,7 @@ function crawl<S extends object = JSONSchema, O extends ParserOptions<S> = Parse
options,
childEmbeddedResourcePaths,
seen,
childScopePathFromRoot,
);
} else {
crawl(
Expand All @@ -219,6 +224,7 @@ function crawl<S extends object = JSONSchema, O extends ParserOptions<S> = Parse
childEmbeddedResourcePaths,
seen,
true,
childScopePathFromRoot,
);
}

Expand Down Expand Up @@ -261,6 +267,7 @@ function inventory$Ref<S extends object = JSONSchema, O extends ParserOptions<S>
options: O,
embeddedResourcePaths: Set<string>,
seen: Set<object>,
scopePathFromRoot?: string,
) {
const $ref = $refKey === null ? $refParent : $refParent[$refKey];
const shouldResolveOnCwd = $Ref.isExternal$Ref($ref) && options.dereference?.externalReferenceResolution === "root";
Expand Down Expand Up @@ -322,13 +329,15 @@ function inventory$Ref<S extends object = JSONSchema, O extends ParserOptions<S>
targetResourceBase, // The canonical URI of the resource containing the target
...(targetResourceId === undefined ? {} : { targetResourceId }),
...(rootReference === undefined ? {} : { rootReference }),
...(scopePathFromRoot === undefined ? {} : { scopePathFromRoot }),
});

// Recursively crawl the resolved value
if (!existingEntry || external) {
const resolvedScopeBase = pointer.$ref.dynamicIdScope ? pointer.scopeBase : pointer.$ref.path!;
const resolvedNestedIdScope =
nestedIdScope || (pointer.$ref.dynamicIdScope && hasSchemaIdentifier(pointer.value, pointer.legacyIdScope));
const resolvedHasSchemaIdentifier =
pointer.$ref.dynamicIdScope && hasSchemaIdentifier(pointer.value, pointer.legacyIdScope);
const resolvedNestedIdScope = nestedIdScope || resolvedHasSchemaIdentifier;
const resolvedEmbeddedResourcePaths = new Set(embeddedResourcePaths);
if (pointer.value === pointer.$ref.value && hasSchemaIdentifier(pointer.$ref.value, pointer.$ref.legacyIdScope)) {
resolvedEmbeddedResourcePaths.add(url.stripHash(pointer.$ref.path!));
Expand All @@ -349,6 +358,8 @@ function inventory$Ref<S extends object = JSONSchema, O extends ParserOptions<S>
options,
resolvedEmbeddedResourcePaths,
seen,
false,
resolvedHasSchemaIdentifier ? pathFromRoot : scopePathFromRoot,
);
}
}
Expand Down Expand Up @@ -550,6 +561,7 @@ function preserveRecursiveTargets(
scopeBase: getSchemaBasePath(scope.scopeBase, value, legacyIdScope),
dynamicIdScope: true,
nestedIdScope: true,
scopePathFromRoot: path,
};
}
if (targets.has(value)) {
Expand Down Expand Up @@ -746,6 +758,12 @@ function qualifyPathFromRoot(
return pathFromRoot;
}

// A target inside the same resource can be pointed to from that resource, which needs no URI.
const scopePath = entry.scopePathFromRoot;
if (scopePath !== undefined && (pathFromRoot === scopePath || pathFromRoot.startsWith(scopePath + "/"))) {
return "#" + pathFromRoot.slice(scopePath.length);
}

// A fragment-only reference inside a nested schema resource resolves against
// that resource's $id. Point back to the root resource explicitly instead.
// Prefer the root's declared $id when it resolves correctly from this scope;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { describe, it, expect } from "vitest";
import $RefParser from "../../../lib/index.js";
import path from "../../utils/path.js";

const fixture = (file: string) => path.rel(`test/specs/bundle-id-refs-no-root-id/${file}`);

/** Bundles a fixture and checks the bundle carries no local file paths and dereferences on its own. */
async function bundlePortably(file: string) {
const bundled = await new $RefParser().bundle(fixture(file));
expect(JSON.stringify(bundled)).not.toContain(path.abs("test/specs"));

const dereferenced = await $RefParser.dereference(structuredClone(bundled));
return { bundled, dereferenced };
}

const testSchema = { type: "object", properties: { name: { type: "string" } } };

describe("Bundle with $id in sub-schemas and no root $id", () => {
it("should point repeat refs from the nested resource instead of the root's file path", async () => {
const { bundled, dereferenced } = await bundlePortably("root.schema.json");
const search = bundled.properties.search;

expect(search.$id).toBe("requests/search.schema.json");
expect(search.properties.test2.$ref).toBe("#/properties/test1");
expect(search.properties.page.$ref).toBe("#/$defs/page");
expect(dereferenced.properties.search.properties.test2).toEqual(testSchema);
expect(dereferenced.properties.search.properties.page).toEqual({ type: "integer" });
});

it("should keep a URI ref to the nested resource as written", async () => {
const { bundled, dereferenced } = await bundlePortably("uri-ref.schema.json");
const search = bundled.properties.search;

expect(search.$id).toBe("requests/search-uri.schema.json");
expect(search.properties.test2.$ref).toBe("#/properties/test1");
expect(search.properties.page.$ref).toBe("search-uri.schema.json#/$defs/page");
expect(dereferenced.properties.search.properties.page).toEqual({ type: "integer" });
});

it("should point repeat refs from the innermost nested resource", async () => {
const { bundled, dereferenced } = await bundlePortably("nested.schema.json");
const inner = bundled.properties.search.properties.inner;

expect(inner.$id).toBe("inner/inner.schema.json");
expect(inner.properties.test2.$ref).toBe("#/properties/test1");
expect(dereferenced.properties.search.properties.inner.properties.test2).toEqual(testSchema);
});

it("should still qualify refs whose target is outside the nested resource", async () => {
const bundled = await new $RefParser().bundle(fixture("outside.schema.json"));
const search = bundled.properties.search;

// No ref written inside the resource can reach the document root without a root $id.
expect(search.$id).toBe("requests/search.schema.json");
expect(search.properties.test1.$ref).toMatch(/outside\.schema\.json#\/properties\/a$/);
});
});
7 changes: 7 additions & 0 deletions test/specs/bundle-id-refs-no-root-id/nested.schema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"$schema": "https://json-schema.org/draft/2019-09/schema",
"type": "object",
"properties": {
"search": { "$ref": "schemas/requests/nested-search.schema.json" }
}
}
8 changes: 8 additions & 0 deletions test/specs/bundle-id-refs-no-root-id/outside.schema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"$schema": "https://json-schema.org/draft/2019-09/schema",
"type": "object",
"properties": {
"a": { "$ref": "schemas/requests/test.json" },
"search": { "$ref": "schemas/requests/search.schema.json" }
}
}
7 changes: 7 additions & 0 deletions test/specs/bundle-id-refs-no-root-id/root.schema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"$schema": "https://json-schema.org/draft/2019-09/schema",
"type": "object",
"properties": {
"search": { "$ref": "schemas/requests/search.schema.json" }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"$id": "requests/nested-search.schema.json",
"type": "object",
"properties": {
"inner": {
"$id": "inner/inner.schema.json",
"type": "object",
"properties": {
"test1": { "$ref": "../../test.json" },
"test2": { "$ref": "../../test.json" }
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"$id": "requests/search-uri.schema.json",
"type": "object",
"properties": {
"test1": { "$ref": "../test.json" },
"test2": { "$ref": "../test.json" },
"page": { "$ref": "search-uri.schema.json#/$defs/page" }
},
"$defs": {
"page": { "type": "integer" }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"$id": "requests/search.schema.json",
"type": "object",
"properties": {
"test1": { "$ref": "../test.json" },
"test2": { "$ref": "../test.json" },
"page": { "$ref": "#/$defs/page" }
},
"$defs": {
"page": { "type": "integer" }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"type": "object",
"properties": {
"name": { "type": "string" }
}
}
7 changes: 7 additions & 0 deletions test/specs/bundle-id-refs-no-root-id/uri-ref.schema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"$schema": "https://json-schema.org/draft/2019-09/schema",
"type": "object",
"properties": {
"search": { "$ref": "schemas/requests/search-uri.schema.json" }
}
}