Skip to content
Open
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
5 changes: 4 additions & 1 deletion apps/api/src/openapi-snapshot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import { describe, it, expect, vi } from "vitest";
import { readFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { serializeOpenAPIDocument } from "./openapi/serialize.js";

// Stub checkMigrations before index.ts can import it
vi.mock("db-migrations/check-migrations", () => ({
Expand Down Expand Up @@ -61,6 +62,8 @@ describe("OpenAPI spec snapshot", () => {
new URL("../../../website/src/openapi/scope-openapi.json", import.meta.url),
);
const websiteSpec = await readFile(websiteSpecPath, "utf8");
expect(websiteSpec).toBe(JSON.stringify(doc));
const serialized = serializeOpenAPIDocument(doc);
expect(websiteSpec).toBe(serialized);
expect(serializeOpenAPIDocument(generateOpenAPIDocument())).toBe(serialized);
}, 30_000); // index.ts pulls in the entire route surface; 5s default is too tight under full-suite load.
});
3 changes: 2 additions & 1 deletion apps/api/src/openapi/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@ import { writeFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import "../index.js";
import { generateOpenAPIDocument } from "./registry.js";
import { serializeOpenAPIDocument } from "./serialize.js";

const websiteSpecPath = fileURLToPath(
new URL("../../../../website/src/openapi/scope-openapi.json", import.meta.url),
);
const document = generateOpenAPIDocument();

await writeFile(websiteSpecPath, JSON.stringify(document));
await writeFile(websiteSpecPath, serializeOpenAPIDocument(document));
console.log(`Wrote OpenAPI specification to ${websiteSpecPath}`);
91 changes: 91 additions & 0 deletions apps/api/src/openapi/serialize.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

import type { OpenAPIObject } from "openapi3-ts/oas31";
import { describe, expect, it } from "vitest";
import { serializeOpenAPIDocument } from "./serialize.js";

describe("serializeOpenAPIDocument", () => {
it("uses sorted keys, two spaces, LF line endings, and a final newline", () => {
expect(serializeOpenAPIDocument({
openapi: "3.1.0",
info: { version: "1.0.0", title: "Test API" },
paths: {},
})).toBe(
'{\n "info": {\n "title": "Test API",\n "version": "1.0.0"\n },\n "openapi": "3.1.0",\n "paths": {}\n}\n',
);
});

it("is deterministic across nested object insertion orders", () => {
const document: OpenAPIObject = {
openapi: "3.1.0",
info: { title: "Test API", version: "1.0.0" },
paths: {},
servers: [{ url: "/", description: "Current server" }],
components: {
schemas: {
Example: {
type: "object",
properties: { zebra: { type: "number" }, alpha: { type: "string" } },
},
},
},
};

// Reverse all object keys, including objects nested inside arrays.
const reordered: OpenAPIObject = JSON.parse(JSON.stringify(document, (_key, value: unknown): unknown => {
if (value !== null && typeof value === "object" && !Array.isArray(value)) {
const object = value as Record<string, unknown>;
return Object.fromEntries(Object.keys(object).reverse().map((key) => [key, object[key]]));
}
return value;
}));

const serialized = serializeOpenAPIDocument(document);
expect(serializeOpenAPIDocument(reordered)).toBe(serialized);
expect(serializeOpenAPIDocument(document)).toBe(serialized);
});

it("preserves parsed content and array order without mutating the document", () => {
const document: OpenAPIObject = {
openapi: "3.1.0",
info: { title: "Test\r\nAPI", version: "1.0.0" },
paths: {},
servers: [{ url: "/z", description: "First" }, { url: "/a" }],
components: {
schemas: {
Example: { enum: ["zebra", "alpha", null], required: ["zebra", "alpha"] },
},
},
};
const original = JSON.stringify(document);
const serialized = serializeOpenAPIDocument(document);
const parsed: unknown = JSON.parse(serialized);

expect(parsed).toEqual(document);
expect(serialized).not.toContain("\r");
expect(JSON.stringify(document)).toBe(original);
});

it("limits a small schema change to its corresponding line", () => {
const document: OpenAPIObject = {
openapi: "3.1.0",
info: { title: "Test API", version: "1.0.0" },
paths: {},
components: { schemas: { Example: { type: "string", description: "Before" } } },
};
const before = serializeOpenAPIDocument(document).split("\n");
const changed = structuredClone(document);
changed.components!.schemas!.Example = { type: "string", description: "After" };
const after = serializeOpenAPIDocument(changed).split("\n");

// Only the edited description should change; neighboring schema lines stay put.
expect(after).toHaveLength(before.length);
expect(before.filter((line, index) => line !== after[index])).toEqual([
' "description": "Before",',
]);
expect(after.filter((line, index) => line !== before[index])).toEqual([
' "description": "After",',
]);
});
});
22 changes: 22 additions & 0 deletions apps/api/src/openapi/serialize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

import type { OpenAPIObject } from "openapi3-ts/oas31";

/**
* Serialize a generated document with stable object keys, two-space indentation,
* LF line endings, and a trailing newline. Array order is preserved.
* @param document OpenAPI document containing JSON-compatible values.
*/
export function serializeOpenAPIDocument(document: OpenAPIObject): string {
return JSON.stringify(document, (_key, value: unknown): unknown => {
// Canonicalize objects at every depth without reordering arrays.
if (value !== null && typeof value === "object" && !Array.isArray(value)) {
const object = value as Record<string, unknown>;
return Object.fromEntries(
Object.keys(object).sort().map((key) => [key, object[key]]),
);
}
return value;
}, 2) + "\n";
}
5 changes: 4 additions & 1 deletion docs/architecture/app-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -784,4 +784,7 @@ The static documentation site consumes the committed artifact at
`website/src/openapi/scope-openapi.json`. Generate it from the API
registry with `pnpm --filter api generate:openapi` rather than fetching
the spec from a deployed environment. The API snapshot test verifies
that the artifact remains current.
that the artifact remains current. Generation recursively sorts object keys
while preserving array order and writes two-space-indented JSON with LF line
endings and a trailing newline. Unchanged definitions produce byte-identical
output; schema edits produce localized line diffs after the formatting migration.
12,102 changes: 12,101 additions & 1 deletion website/src/openapi/scope-openapi.json

Large diffs are not rendered by default.

Loading