fix(frontend): generate MSW mocks that satisfy their Zod schemas
This commit is contained in:
1 parent
ad4bb94426
commit
1aa505c743
18 files changed
+1439
-133
No files matched your search
@@ -0,0 +1,201 @@
|
||||
import { readdirSync, readFileSync } from "node:fs";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { parse as parseYaml } from "yaml";
|
||||
import {
|
||||
buildPatternBoundsIndex,
|
||||
moduleSpecifier,
|
||||
rewriteMockSource,
|
||||
type PatternBoundsIndex,
|
||||
} from "./mock-patterns";
|
||||
|
||||
const frontendRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
|
||||
const document = {
|
||||
components: {
|
||||
schemas: {
|
||||
Token: { type: "string", minLength: 32, maxLength: 128, pattern: "^[A-Za-z0-9_-]+$" },
|
||||
Tag: { type: "string", minLength: 1, maxLength: 50, pattern: "^\\S(?:.*\\S)?$" },
|
||||
Session: {
|
||||
type: "object",
|
||||
properties: {
|
||||
token: { $ref: "#/components/schemas/Token" },
|
||||
next_cursor: {
|
||||
oneOf: [
|
||||
{ type: "string", minLength: 1, maxLength: 512, pattern: "^[A-Za-z0-9_-]+$" },
|
||||
{ type: "null" },
|
||||
],
|
||||
},
|
||||
tags: { type: "array", items: { $ref: "#/components/schemas/Tag" } },
|
||||
nested: {
|
||||
type: "object",
|
||||
properties: { code: { type: "string", pattern: "^[a-z]+$" } },
|
||||
},
|
||||
},
|
||||
examples: [{ properties: { ignored: { type: "string", pattern: "x" } } }],
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const header = `/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
*/
|
||||
import {
|
||||
faker
|
||||
} from '@faker-js/faker';
|
||||
|
||||
import {
|
||||
HttpResponse
|
||||
} from 'msw';
|
||||
`;
|
||||
|
||||
const generated = `${header}
|
||||
export const getSessionMock = (): Session => ({token: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), next_cursor: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), null]), tags: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (faker.helpers.fromRegExp("^\\\\S(?:.*\\\\S)?$"))), nested: {code: faker.helpers.fromRegExp("^[a-z]+$")}})
|
||||
`;
|
||||
|
||||
const rewritten = `/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
*/
|
||||
import {
|
||||
faker
|
||||
} from '@faker-js/faker';
|
||||
|
||||
import {
|
||||
fakeFromPattern
|
||||
} from '../../mock-pattern';
|
||||
|
||||
import {
|
||||
HttpResponse
|
||||
} from 'msw';
|
||||
|
||||
export const getSessionMock = (): Session => ({token: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 32, maxLength: 128}), next_cursor: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 512}), null]), tags: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\\\S(?:.*\\\\S)?$", {minLength: 1, maxLength: 50}))), nested: {code: fakeFromPattern("^[a-z]+$")}})
|
||||
`;
|
||||
|
||||
const index = buildPatternBoundsIndex(document);
|
||||
|
||||
function rewrite(source: string, bounds: PatternBoundsIndex = index) {
|
||||
return rewriteMockSource(source, "tag.msw.ts", bounds, "../../mock-pattern");
|
||||
}
|
||||
|
||||
describe("buildPatternBoundsIndex", () => {
|
||||
it("indexes patterned strings by the property that holds them", () => {
|
||||
expect(index.get("token")?.get("^[A-Za-z0-9_-]+$")).toEqual([
|
||||
{ minLength: 32, maxLength: 128 },
|
||||
]);
|
||||
expect(index.get("next_cursor")?.get("^[A-Za-z0-9_-]+$")).toEqual([
|
||||
{ minLength: 1, maxLength: 512 },
|
||||
]);
|
||||
expect(index.get("tags")?.get("^\\S(?:.*\\S)?$")).toEqual([{ minLength: 1, maxLength: 50 }]);
|
||||
expect(index.get("code")?.get("^[a-z]+$")).toEqual([{}]);
|
||||
// A nested object property belongs to its own name, and examples hold
|
||||
// data, not schemas.
|
||||
expect(index.has("nested")).toBe(false);
|
||||
expect(index.has("ignored")).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps every distinct bound of a property and pattern", () => {
|
||||
const ambiguous = buildPatternBoundsIndex({
|
||||
components: {
|
||||
schemas: {
|
||||
A: { properties: { id: { type: "string", maxLength: 8, pattern: "^a+$" } } },
|
||||
B: { properties: { id: { type: "string", maxLength: 9, pattern: "^a+$" } } },
|
||||
C: { properties: { id: { type: "string", maxLength: 8, pattern: "^a+$" } } },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(ambiguous.get("id")?.get("^a+$")).toEqual([{ maxLength: 8 }, { maxLength: 9 }]);
|
||||
});
|
||||
|
||||
it("rejects references outside the document", () => {
|
||||
expect(() =>
|
||||
buildPatternBoundsIndex({ properties: { id: { $ref: "other.yml#/Id" } } }),
|
||||
).toThrow("Only local references are supported");
|
||||
});
|
||||
});
|
||||
|
||||
describe("rewriteMockSource", () => {
|
||||
it("replaces each faker pattern call with the helper and the schema bounds", () => {
|
||||
expect(rewrite(generated)).toEqual({ text: rewritten, rewrittenCalls: 4 });
|
||||
});
|
||||
|
||||
it("leaves its own output unchanged", () => {
|
||||
expect(rewrite(rewritten)).toEqual({ text: rewritten, rewrittenCalls: 0 });
|
||||
});
|
||||
|
||||
it("leaves a file without pattern calls unchanged", () => {
|
||||
const source = `${header}\nexport const getHealthMock = () => ({status: 'ok'})\n`;
|
||||
expect(rewrite(source)).toEqual({ text: source, rewrittenCalls: 0 });
|
||||
});
|
||||
|
||||
it("fails when no schema property has the pattern", () => {
|
||||
const source = `${header}\nexport const m = () => ({token: faker.helpers.fromRegExp("^b+$")})\n`;
|
||||
expect(() => rewrite(source)).toThrow(
|
||||
'tag.msw.ts:13: no schema property "token" with pattern "^b+$"',
|
||||
);
|
||||
});
|
||||
|
||||
it("fails when the schemas disagree on the bounds", () => {
|
||||
const ambiguous = buildPatternBoundsIndex({
|
||||
components: {
|
||||
schemas: {
|
||||
A: { properties: { id: { type: "string", maxLength: 8, pattern: "^a+$" } } },
|
||||
B: { properties: { id: { type: "string", maxLength: 9, pattern: "^a+$" } } },
|
||||
},
|
||||
},
|
||||
});
|
||||
const source = `${header}\nexport const m = () => ({id: faker.helpers.fromRegExp("^a+$")})\n`;
|
||||
expect(() => rewrite(source, ambiguous)).toThrow("so the mock bounds are ambiguous");
|
||||
});
|
||||
|
||||
it("fails on a call that it cannot attribute to a property", () => {
|
||||
const topLevel = `${header}\nexport const m = (): string => faker.helpers.fromRegExp("^a+$")\n`;
|
||||
expect(() => rewrite(topLevel)).toThrow("is not the value of a named property");
|
||||
|
||||
const dynamic = `${header}\nconst p = "^a+$";\nexport const m = () => ({id: faker.helpers.fromRegExp(p)})\n`;
|
||||
expect(() => rewrite(dynamic)).toThrow("must take one string literal");
|
||||
});
|
||||
});
|
||||
|
||||
describe("moduleSpecifier", () => {
|
||||
it("returns an extensionless relative specifier", () => {
|
||||
expect(
|
||||
moduleSpecifier(
|
||||
"/repo/src/shared/api/endpoints/need/need.msw.ts",
|
||||
"/repo/src/shared/api/mock-pattern.ts",
|
||||
),
|
||||
).toBe("../../mock-pattern");
|
||||
expect(moduleSpecifier("/repo/a/b.msw.ts", "/repo/a/mock-pattern.ts")).toBe("./mock-pattern");
|
||||
});
|
||||
});
|
||||
|
||||
describe("generated mocks", () => {
|
||||
// The committed mocks must be a fixed point of the rewrite: generation
|
||||
// followed by this step reproduces them byte for byte.
|
||||
it("are already rewritten against the current contract", () => {
|
||||
const contract: unknown = parseYaml(
|
||||
readFileSync(join(frontendRoot, "../api/core/openapi.bundle.yml"), "utf8"),
|
||||
);
|
||||
const contractIndex = buildPatternBoundsIndex(contract);
|
||||
const endpoints = join(frontendRoot, "src/shared/api/endpoints");
|
||||
const files = readdirSync(endpoints, { recursive: true, encoding: "utf8" }).filter((name) =>
|
||||
name.endsWith(".msw.ts"),
|
||||
);
|
||||
expect(files.length).toBeGreaterThan(0);
|
||||
for (const name of files) {
|
||||
const file = join(endpoints, name);
|
||||
const source = readFileSync(file, "utf8");
|
||||
const result = rewriteMockSource(
|
||||
source,
|
||||
name,
|
||||
contractIndex,
|
||||
moduleSpecifier(file, join(frontendRoot, "src/shared/api/mock-pattern.ts")),
|
||||
);
|
||||
expect(result.rewrittenCalls, name).toBe(0);
|
||||
expect(result.text === source, name).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,374 @@
|
||||
// Post-generation step for the Orval MSW mocks.
|
||||
//
|
||||
// Orval 8.40 mocks a string schema that has a `pattern` with
|
||||
// `faker.helpers.fromRegExp(pattern)`. faker prints anchors and non-capturing
|
||||
// groups literally, and Orval drops minLength and maxLength for such a schema,
|
||||
// so the mock fails the generated Zod schema. Orval has no option that keeps
|
||||
// the Zod output and changes only this mock: its mock overrides match property
|
||||
// names, not schema constraints, and an input transformer changes every
|
||||
// output.
|
||||
//
|
||||
// This step rewrites each such call in the generated *.msw.ts files into
|
||||
// `fakeFromPattern(pattern, { minLength, maxLength })` from
|
||||
// src/shared/api/mock-pattern.ts. The bounds come from the OpenAPI document:
|
||||
// the call's enclosing object property and the pattern identify the schema.
|
||||
// The rewrite fails when a call has an unexpected form, when no schema
|
||||
// matches, or when schemas that match disagree on the bounds, so a contract
|
||||
// change cannot silently produce invalid mocks. Running it again on its own
|
||||
// output changes nothing.
|
||||
//
|
||||
// Usage: node ./codegen/mock-patterns.ts --spec <openapi.yml> --endpoints <dir> [--helper <file>]
|
||||
|
||||
import { readdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join, relative, resolve, sep } from "node:path";
|
||||
import { argv, cwd, stdout } from "node:process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import ts from "typescript";
|
||||
import { parse as parseYaml } from "yaml";
|
||||
|
||||
export interface LengthBounds {
|
||||
readonly minLength?: number;
|
||||
readonly maxLength?: number;
|
||||
}
|
||||
|
||||
/** Property name, then pattern, then every distinct length bound found. */
|
||||
export type PatternBoundsIndex = ReadonlyMap<string, ReadonlyMap<string, readonly LengthBounds[]>>;
|
||||
|
||||
export interface RewriteResult {
|
||||
readonly text: string;
|
||||
readonly rewrittenCalls: number;
|
||||
}
|
||||
|
||||
const helperName = "fakeFromPattern";
|
||||
const fakerModule = "@faker-js/faker";
|
||||
const fakerCallee = "faker.helpers.fromRegExp";
|
||||
// Keys whose values are sample data rather than schemas.
|
||||
const exampleKeys = new Set(["example", "examples"]);
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function boundsKey(bounds: LengthBounds): string {
|
||||
return `${bounds.minLength ?? ""}..${bounds.maxLength ?? ""}`;
|
||||
}
|
||||
|
||||
function describeBounds(bounds: LengthBounds): string {
|
||||
return `minLength ${bounds.minLength ?? "unset"}, maxLength ${bounds.maxLength ?? "unset"}`;
|
||||
}
|
||||
|
||||
function resolveLocalReference(document: unknown, reference: string): unknown {
|
||||
if (!reference.startsWith("#/")) {
|
||||
throw new Error(`Only local references are supported, got ${reference}.`);
|
||||
}
|
||||
let current: unknown = document;
|
||||
for (const segment of reference.slice(2).split("/")) {
|
||||
const key = segment.replaceAll("~1", "/").replaceAll("~0", "~");
|
||||
if (!isRecord(current) || !Object.hasOwn(current, key)) {
|
||||
throw new Error(`Unresolvable reference ${reference}.`);
|
||||
}
|
||||
current = current[key];
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
function lengthBound(schema: Record<string, unknown>, key: "minLength" | "maxLength") {
|
||||
const value = schema[key];
|
||||
if (value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
|
||||
throw new Error(`${key} must be a non-negative integer, got ${String(value)}.`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
// Collects every patterned string schema that a property value can resolve
|
||||
// to. It follows references, compositions, and array items, but not nested
|
||||
// object properties, which have their own names.
|
||||
function collectPatternedStrings(
|
||||
document: unknown,
|
||||
schema: unknown,
|
||||
seenReferences: ReadonlySet<string>,
|
||||
found: Map<string, LengthBounds[]>,
|
||||
): void {
|
||||
if (!isRecord(schema)) {
|
||||
return;
|
||||
}
|
||||
const reference = schema["$ref"];
|
||||
if (typeof reference === "string") {
|
||||
if (!seenReferences.has(reference)) {
|
||||
const target = resolveLocalReference(document, reference);
|
||||
collectPatternedStrings(document, target, new Set([...seenReferences, reference]), found);
|
||||
}
|
||||
}
|
||||
const pattern = schema["pattern"];
|
||||
if (typeof pattern === "string") {
|
||||
const minLength = lengthBound(schema, "minLength");
|
||||
const maxLength = lengthBound(schema, "maxLength");
|
||||
const bounds: LengthBounds = {
|
||||
...(minLength === undefined ? {} : { minLength }),
|
||||
...(maxLength === undefined ? {} : { maxLength }),
|
||||
};
|
||||
const known = found.get(pattern) ?? [];
|
||||
if (!known.some((item) => boundsKey(item) === boundsKey(bounds))) {
|
||||
known.push(bounds);
|
||||
}
|
||||
found.set(pattern, known);
|
||||
}
|
||||
for (const keyword of ["allOf", "oneOf", "anyOf", "prefixItems"]) {
|
||||
const members = schema[keyword];
|
||||
if (Array.isArray(members)) {
|
||||
for (const member of members) {
|
||||
collectPatternedStrings(document, member, seenReferences, found);
|
||||
}
|
||||
}
|
||||
}
|
||||
collectPatternedStrings(document, schema["items"], seenReferences, found);
|
||||
}
|
||||
|
||||
/** Indexes the length bounds of patterned strings by property name. */
|
||||
export function buildPatternBoundsIndex(document: unknown): PatternBoundsIndex {
|
||||
const index = new Map<string, Map<string, LengthBounds[]>>();
|
||||
const visited = new Set<unknown>();
|
||||
|
||||
function addProperty(name: string, schema: unknown): void {
|
||||
const byPattern = index.get(name) ?? new Map<string, LengthBounds[]>();
|
||||
collectPatternedStrings(document, schema, new Set(), byPattern);
|
||||
if (byPattern.size > 0) {
|
||||
index.set(name, byPattern);
|
||||
}
|
||||
}
|
||||
|
||||
function walk(node: unknown): void {
|
||||
if (typeof node !== "object" || node === null || visited.has(node)) {
|
||||
return;
|
||||
}
|
||||
visited.add(node);
|
||||
if (Array.isArray(node)) {
|
||||
node.forEach(walk);
|
||||
return;
|
||||
}
|
||||
const properties = isRecord(node) ? node["properties"] : undefined;
|
||||
if (isRecord(properties)) {
|
||||
for (const [name, schema] of Object.entries(properties)) {
|
||||
addProperty(name, schema);
|
||||
}
|
||||
}
|
||||
for (const [key, value] of Object.entries(node)) {
|
||||
if (!exampleKeys.has(key)) {
|
||||
walk(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
walk(document);
|
||||
return index;
|
||||
}
|
||||
|
||||
function lineOf(sourceFile: ts.SourceFile, node: ts.Node): number {
|
||||
return sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
|
||||
}
|
||||
|
||||
function enclosingPropertyName(node: ts.Node): string | undefined {
|
||||
for (let current = node.parent; current !== undefined; current = current.parent) {
|
||||
if (ts.isPropertyAssignment(current)) {
|
||||
const name = current.name;
|
||||
if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) {
|
||||
return name.text;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
if (ts.isVariableStatement(current) || ts.isSourceFile(current)) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function formatBoundsArgument(bounds: LengthBounds): string {
|
||||
const parts = [
|
||||
...(bounds.minLength === undefined ? [] : [`minLength: ${bounds.minLength}`]),
|
||||
...(bounds.maxLength === undefined ? [] : [`maxLength: ${bounds.maxLength}`]),
|
||||
];
|
||||
return parts.length === 0 ? "" : `, {${parts.join(", ")}}`;
|
||||
}
|
||||
|
||||
function findBounds(
|
||||
index: PatternBoundsIndex,
|
||||
property: string,
|
||||
pattern: string,
|
||||
location: string,
|
||||
): LengthBounds {
|
||||
const candidates = index.get(property)?.get(pattern) ?? [];
|
||||
const [bounds] = candidates;
|
||||
if (bounds === undefined) {
|
||||
throw new Error(
|
||||
`${location}: no schema property "${property}" with pattern ${JSON.stringify(pattern)} in the OpenAPI document.`,
|
||||
);
|
||||
}
|
||||
if (candidates.length > 1) {
|
||||
throw new Error(
|
||||
`${location}: properties named "${property}" with pattern ${JSON.stringify(pattern)} have different length bounds (${candidates
|
||||
.map(describeBounds)
|
||||
.join("; ")}), so the mock bounds are ambiguous.`,
|
||||
);
|
||||
}
|
||||
return bounds;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rewrites the faker pattern calls of one generated mock file. The helper
|
||||
* specifier is the module path that the generated file imports the helper
|
||||
* from.
|
||||
*/
|
||||
export function rewriteMockSource(
|
||||
source: string,
|
||||
fileName: string,
|
||||
index: PatternBoundsIndex,
|
||||
helperSpecifier: string,
|
||||
): RewriteResult {
|
||||
const sourceFile = ts.createSourceFile(
|
||||
fileName,
|
||||
source,
|
||||
ts.ScriptTarget.Latest,
|
||||
true,
|
||||
ts.ScriptKind.TS,
|
||||
);
|
||||
const edits: { start: number; end: number; text: string }[] = [];
|
||||
|
||||
function visit(node: ts.Node): void {
|
||||
if (
|
||||
ts.isCallExpression(node) &&
|
||||
ts.isPropertyAccessExpression(node.expression) &&
|
||||
node.expression.name.text === "fromRegExp"
|
||||
) {
|
||||
const location = `${fileName}:${lineOf(sourceFile, node)}`;
|
||||
if (node.expression.getText(sourceFile) !== fakerCallee) {
|
||||
throw new Error(`${location}: unexpected fromRegExp callee ${node.expression.getText()}.`);
|
||||
}
|
||||
const [argument, ...rest] = node.arguments;
|
||||
if (argument === undefined || rest.length > 0 || !ts.isStringLiteral(argument)) {
|
||||
throw new Error(`${location}: ${fakerCallee} must take one string literal.`);
|
||||
}
|
||||
const property = enclosingPropertyName(node);
|
||||
if (property === undefined) {
|
||||
throw new Error(`${location}: ${fakerCallee} is not the value of a named property.`);
|
||||
}
|
||||
const pattern = argument.text;
|
||||
const bounds = findBounds(index, property, pattern, location);
|
||||
edits.push({
|
||||
start: node.getStart(sourceFile),
|
||||
end: node.getEnd(),
|
||||
text: `${helperName}(${JSON.stringify(pattern)}${formatBoundsArgument(bounds)})`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
}
|
||||
visit(sourceFile);
|
||||
|
||||
const imports = sourceFile.statements.filter(ts.isImportDeclaration);
|
||||
const moduleOf = (declaration: ts.ImportDeclaration) =>
|
||||
ts.isStringLiteral(declaration.moduleSpecifier) ? declaration.moduleSpecifier.text : "";
|
||||
const hasHelperImport = imports.some((declaration) => moduleOf(declaration) === helperSpecifier);
|
||||
if (edits.length > 0 && !hasHelperImport) {
|
||||
const fakerImport = imports.find((declaration) => moduleOf(declaration) === fakerModule);
|
||||
if (fakerImport === undefined) {
|
||||
throw new Error(`${fileName}: no ${fakerModule} import to place the helper import after.`);
|
||||
}
|
||||
edits.push({
|
||||
start: fakerImport.getEnd(),
|
||||
end: fakerImport.getEnd(),
|
||||
text: `\n\nimport {\n ${helperName}\n} from '${helperSpecifier}';`,
|
||||
});
|
||||
}
|
||||
|
||||
let text = source;
|
||||
for (const edit of edits.sort((left, right) => right.start - left.start)) {
|
||||
text = text.slice(0, edit.start) + edit.text + text.slice(edit.end);
|
||||
}
|
||||
if (text.includes("fromRegExp")) {
|
||||
throw new Error(`${fileName}: a fromRegExp reference remains after the rewrite.`);
|
||||
}
|
||||
const rewrittenCalls = edits.filter((edit) => edit.start !== edit.end).length;
|
||||
return { text, rewrittenCalls };
|
||||
}
|
||||
|
||||
function mockFiles(directory: string): string[] {
|
||||
return readdirSync(directory, { recursive: true, encoding: "utf8" })
|
||||
.filter((name) => name.endsWith(".msw.ts"))
|
||||
.map((name) => join(directory, name))
|
||||
.sort();
|
||||
}
|
||||
|
||||
/** Returns the extensionless relative module specifier of `target`. */
|
||||
export function moduleSpecifier(fromFile: string, target: string): string {
|
||||
const path = relative(dirname(fromFile), target).replace(/\.ts$/, "").split(sep).join("/");
|
||||
return path.startsWith(".") ? path : `./${path}`;
|
||||
}
|
||||
|
||||
export function rewriteMockFiles(options: {
|
||||
readonly specPath: string;
|
||||
readonly endpointsDirectory: string;
|
||||
readonly helperPath: string;
|
||||
}): { readonly files: number; readonly calls: number } {
|
||||
const document: unknown = parseYaml(readFileSync(options.specPath, "utf8"));
|
||||
const index = buildPatternBoundsIndex(document);
|
||||
let files = 0;
|
||||
let calls = 0;
|
||||
for (const file of mockFiles(options.endpointsDirectory)) {
|
||||
const source = readFileSync(file, "utf8");
|
||||
const result = rewriteMockSource(
|
||||
source,
|
||||
relative(cwd(), file),
|
||||
index,
|
||||
moduleSpecifier(file, options.helperPath),
|
||||
);
|
||||
if (result.text !== source) {
|
||||
writeFileSync(file, result.text);
|
||||
files += 1;
|
||||
}
|
||||
calls += result.rewrittenCalls;
|
||||
}
|
||||
return { files, calls };
|
||||
}
|
||||
|
||||
function readOption(args: readonly string[], name: string): string | undefined {
|
||||
const position = args.indexOf(name);
|
||||
if (position === -1) {
|
||||
return undefined;
|
||||
}
|
||||
const value = args[position + 1];
|
||||
if (value === undefined || value.startsWith("--")) {
|
||||
throw new Error(`${name} needs a value.`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function main(args: readonly string[]): void {
|
||||
const frontendRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const specPath = readOption(args, "--spec");
|
||||
const endpointsDirectory = readOption(args, "--endpoints");
|
||||
if (specPath === undefined || endpointsDirectory === undefined) {
|
||||
throw new Error(
|
||||
"Usage: mock-patterns.ts --spec <openapi.yml> --endpoints <dir> [--helper <file>]",
|
||||
);
|
||||
}
|
||||
const helperPath = resolve(
|
||||
readOption(args, "--helper") ?? join(frontendRoot, "src/shared/api/mock-pattern.ts"),
|
||||
);
|
||||
const result = rewriteMockFiles({
|
||||
specPath: resolve(specPath),
|
||||
endpointsDirectory: resolve(endpointsDirectory),
|
||||
helperPath,
|
||||
});
|
||||
stdout.write(
|
||||
`Mock patterns: rewrote ${result.calls} ${fakerCallee} calls in ${result.files} files.\n`,
|
||||
);
|
||||
}
|
||||
|
||||
const entryPoint = argv[1];
|
||||
if (entryPoint !== undefined && resolve(entryPoint) === fileURLToPath(import.meta.url)) {
|
||||
main(argv.slice(2));
|
||||
}
|
||||
@@ -85,6 +85,11 @@ function project(inputTarget: string, endpoints: string, schemas: string): Optio
|
||||
generators: [{ type: "msw" }],
|
||||
},
|
||||
override: {
|
||||
// With Zod schemas, the default enum mode makes the MSW mocks pick
|
||||
// from `Object.values(<zod.enum>)`, which yields Zod internals rather
|
||||
// than the enum values. The union mode inlines the literal values in
|
||||
// the mocks; the Zod schemas and the types do not change.
|
||||
enumGenerationType: "union",
|
||||
mutator: {
|
||||
path: "../src/shared/api/client.ts",
|
||||
name: "apiRequest",
|
||||
|
||||
Reference in new issue
Block a user