Repository navigation
feat(mock): support separate mock output paths - #3559
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds optional ChangesMock output paths and de-inlining
Sequence Diagram(s)sequenceDiagram
participant Normalizer
participant Writer
participant MockUtils
participant FS
Normalizer->>Writer: normalized mock config (includes shared `path`)
Writer->>MockUtils: getMockDir(entry, mockConfig)
Writer->>MockUtils: resolveMockSchemasPath(mockFilePath, schemasTarget)
Writer->>FS: write main file
alt de-inlined
Writer->>FS: write per-mock files
Writer->>FS: write per-dir index barrels
end
FS-->>Writer: written paths
Writer-->>Normalizer: returned generated paths
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related issues
Possibly related PRs
Suggested reviewers
✨ Finishing Touches🧪 Generate unit tests (beta)
|
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (1)
packages/core/src/writers/tags-mode.ts (1)
126-127: 💤 Low valueConsider hoisting
collapseInlineMockOutputsto avoid redundant computation.
collapseInlineMockOutputs(rawMockOutputs)is called three times within the!shouldDeinlineMocksbranch with identical input. Hoisting the result to a single variable at the start of the per-tag processing would improve efficiency and reduce maintenance risk.♻️ Suggested refactor
Collapse once at the top of the try block:
try { const { imports, implementation, mockOutputs: rawMockOutputs, // ... } = target; + // Collapse once for all inline-mock branches + const inlineMockOutputs = !shouldDeinlineMocks + ? collapseInlineMockOutputs(rawMockOutputs) + : []; // ... later uses become: - const mockOutputs = collapseInlineMockOutputs(rawMockOutputs); + // use inlineMockOutputs directlyAlso applies to: 172-173, 260-261
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/core/src/writers/tags-mode.ts` around lines 126 - 127, The branch inside tags-mode.ts calling collapseInlineMockOutputs(rawMockOutputs) multiple times should compute that value once and reuse it: inside the per-tag processing try block (the !shouldDeinlineMocks branch), hoist collapseInlineMockOutputs(rawMockOutputs) into a local const (e.g. collapsedMockOutputs) before the repeated uses and then replace the three duplicate calls with references to that const; update any usages that expect the original shape accordingly (functions/mappings that read mockOutputs/rawMockOutputs should now use collapsedMockOutputs) to avoid redundant computation and ensure consistent results.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/core/src/writers/single-mode.ts`:
- Around line 278-337: The loop over rawMockOutputs in single-mode.ts causes
de-inlined mocks of the same type to overwrite each other; before iterating (the
block that uses rawMockOutputs and computes mockFilePath, mockExtension, etc.),
collapse/merge the outputs by calling the same collapseInlineMockOutputs used
for the inline path (or an equivalent merge function) and iterate over that
collapsed array instead of rawMockOutputs; update references inside the loop
(e.g., mockOutput, mockOutput.implementation, mockOutput.imports) to use the
merged entries so multiple outputs of the same type (MSW, etc.) are merged
rather than overwritten.
In `@packages/core/src/writers/split-mode.test.ts`:
- Around line 241-291: The test's custom importsMock may not be applied because
createSplitModeProps(target).builder could be frozen/sealed so the nested spread
doesn't override importsMock; modify the props construction to ensure
builder.importsMock is actually set (e.g., start from a shallow clone or
construct builder explicitly rather than relying on nested spread of
createSplitModeProps(...).builder) and keep the importsMockCalls capture logic,
and add a defensive assertion (e.g.,
expect(importsMockCalls.length).toBeGreaterThan(0)) before accessing
importsMockCalls[0]; reference the importsMock function, importsMockCalls array,
createSplitModeProps, and writeSplitMode to locate where to apply these changes.
In `@packages/core/src/writers/split-tags-mode.ts`:
- Around line 300-312: The index generation currently iterates tagEntries for
every mockIndexEntry, causing exports for tags that may not have a mock file in
that mockDir; modify the mock generation to record which tags actually produced
files per (ext, mockDir) during the mock emission loop (collect tuples of {ext,
mockDir, tag}), then when output.mock.indexMockFiles is true, group those tuples
by ext+mockDir (instead of using tagEntries) and build indexContent from only
the tags present for that group (using the same localMockPath logic with
upath.joinSafe and the OutputMockType.MSW branch) before calling
writeGeneratedFile for each indexPath; ensure helpers referenced
(mockIndexEntries, OutputMockType.MSW, pascal, writeGeneratedFile) are reused
as-is.
In `@packages/core/src/writers/tags-mode.ts`:
- Around line 359-377: The index generator currently iterates all tagEntries for
each mockIndexEntries entry causing exports for non-existent mock files; update
the logic to only include tags that actually have a mock for the given (ext,
mockDir). For example, when building mockIndexEntries or just before mapping
tagEntries in the block around shouldDeinlineMocks/output.mock.indexMockFiles,
filter tagEntries using either a precomputed map of which tags provide which ext
types or by checking the mock file existence for the resolved localMockPath,
then generate exports only for those filtered tags (use the same symbols:
mockIndexEntries, tagEntries, OutputMockType, writeGeneratedFile,
generatedFilePathsArray). Also update the tracking structure for each (ext,
mockDir) entry to record contributing tags so generated index files contain only
valid exports.
---
Nitpick comments:
In `@packages/core/src/writers/tags-mode.ts`:
- Around line 126-127: The branch inside tags-mode.ts calling
collapseInlineMockOutputs(rawMockOutputs) multiple times should compute that
value once and reuse it: inside the per-tag processing try block (the
!shouldDeinlineMocks branch), hoist collapseInlineMockOutputs(rawMockOutputs)
into a local const (e.g. collapsedMockOutputs) before the repeated uses and then
replace the three duplicate calls with references to that const; update any
usages that expect the original shape accordingly (functions/mappings that read
mockOutputs/rawMockOutputs should now use collapsedMockOutputs) to avoid
redundant computation and ensure consistent results.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 7a489390-bbc7-4eca-ab7f-dc2635c415a0
📒 Files selected for processing (12)
packages/core/src/types.tspackages/core/src/writers/mock-utils.test.tspackages/core/src/writers/mock-utils.tspackages/core/src/writers/single-mode.tspackages/core/src/writers/split-mode.test.tspackages/core/src/writers/split-mode.tspackages/core/src/writers/split-tags-mode.test.tspackages/core/src/writers/split-tags-mode.tspackages/core/src/writers/tags-mode.test.tspackages/core/src/writers/tags-mode.tspackages/orval/src/utils/options.tstests/api-generation.spec.ts
|
@melloware It is because I didn't include the snapshot updates. they're > 150 files and will cause rabbit to not review the code. |
f5226b9 to
de607fc
Compare
|
@wadakatu please review this when available |
d7042ef to
f46b20d
Compare
|
I noticed the implementation intentionally keeps the generated snapshot refresh out of this PR for reviewability, but that is also where a lot of the new path/import behavior will be exercised. Before merging, I would add at least one committed fixture that combines That would lock down the highest-risk contract here: generated MSW/faker files living outside the client tree still import schemas from the right relative path, and the per-directory barrels stay deterministic after tags are sorted. The unit tests cover the helpers well, but a generated-output fixture would catch a future writer-level regression where one mode bypasses the shared helper or computes the mock directory before normalization. |
|
@suzunn already added in a previous commit. |
wadakatu
left a comment
There was a problem hiding this comment.
@melloware @aqeelat — took a thorough pass through the source changes (the 7 non-snapshot files) and exercised the new code paths locally. The core design is solid: the de-inline logic preserves existing no-path behavior (only the index-mock-file sort diff changed among existing snapshots), import resolution is correct across all the path layouts I tried (mocks/ → ../model, mocks/<tag>/ → ../../model, and the inline-schema ../endpoints / ../endpoints.schemas cases), and the #3554 function-generator unification works as intended.
Two things I'd want addressed before merge, left as inline comments below: one confirmed determinism bug, and a test-coverage gap around the new path code.
| if (shouldDeinlineMocks && output.mock.indexMockFiles) { | ||
| for (const { ext, mockDir, tags } of mockIndexEntries) { | ||
| const indexPath = path.join(mockDir, `index.${ext}${extension}`); | ||
| const indexContent = tags |
There was a problem hiding this comment.
tags mode + mock.path + indexMockFiles produces a non-deterministic barrel.
The ordering fix from f46b20db2 was only applied to split-tags-mode.ts, not here. mockIndexEntries[].tags is populated inside the concurrent Promise.all(tagEntries.map(async …)) loop via indexEntry.tags.push(kebabTag), so insertion order depends on which async write resolves first — and this barrel emit maps over tags without sorting.
Generating the same spec 8× (petstore, tags pets/health) flips the order between runs:
run 1: export { getPetsMock } … ; export { getHealthMock } …
run 2: export { getHealthMock } … ; export { getPetsMock } …
run 5: export { getPetsMock } … ; export { getHealthMock } …
(other runs: health → pets)
This causes regeneration diff noise for users and would make any future fixture for this combo a flaky snapshot. split-tags-mode is unaffected (it sorts) and single mode is unaffected (single mock file per type).
Fix — sort at emit time, mirroring split-tags-mode.ts:
const sortedTags = [...tags].sort();
const indexContent = sortedTags.map((kebabTag) => { … }).join('');There was a problem hiding this comment.
Thanks for the fast turnaround — and the three new fixtures (singleMockPath, tagsMockPath, tagsSplitPerGeneratorPath) close the coverage gap nicely. 🙏
However, the determinism fix in e9e2d838a doesn't actually resolve it, and it regressed split-tags-mode. Sorting Object.entries(target) at the source doesn't constrain the barrel order, because indexEntry.tags is accumulated after await writeGeneratedFile(...) inside the concurrent Promise.all(tagEntries.map(async …)) — so the push order follows I/O completion, not the sorted input order. Removing the emit-time [...tags].sort() therefore re-opens the race.
Verified locally by regenerating the new fixtures 10× each:
tagsMockPath (tags + path + index): still flips health↔pets across runs
tagsSplitMockPath (split-tags, per-gen paths): now ALSO flips ← regressed by removing the emit-time sort
So tagsMockPath, tagsSplitMockPath, and the existing index-mock-file snapshots are now flaky — CI passing here is just luck of the draw on the I/O completion order.
The robust fix is to keep the sort at emit time (where the order actually matters), in both writers:
// tags-mode.ts and split-tags-mode.ts — barrel emit loop
const indexContent = [...tags]
.sort()
.map((tag) => { … })
.join('');With that restored, all three fixtures are stable across 10/10 regenerations. The .toSorted() on tagEntries is harmless but isn't sufficient on its own.
| target: '../specifications/faker-array-items-tags-split.yaml', | ||
| }, | ||
| }, | ||
| splitMockPath: { |
There was a problem hiding this comment.
Committed fixtures don't cover the most complex new path code.
These configs only exercise a shared mock.path in split / tags-split. The following new behaviors have no committed fixture — I verified them manually and they generate correctly, but there's no regression net:
| Combination | Covered? |
|---|---|
single mode + path (de-inline path) |
❌ |
tags mode + path (+ indexMockFiles) |
❌ — this is exactly where the determinism bug lives |
per-generator distinct path (e.g. msw → ./msw, faker → ./faker) |
❌ |
The de-inline branch in single-mode.ts / tags-mode.ts is the largest piece of new logic, so a fixture there is the highest-value addition (and a tags+path+indexMockFiles fixture would have caught the ordering bug). This is the part of @suzunn's earlier request that's still open — single/tags and per-generator paths aren't in the current fixtures.
f46b20d to
e9e2d83
Compare
|
@coderabbitai review --dir packages |
|
🧠 Learnings used✅ Action performedReview finished.
|
|
@melloware @wadakatu the PR is ready |
|
@aqeelat Left a follow-up on the determinism thread — the new fixtures look great, but the |
5b0355e to
66950c0
Compare
|
@coderabbitai full review but ignore |
|
✅ Action performedFull review finished. |
|
@melloware is it a good idea to configure coderabbit to ignore |
|
@wadakatu I now understand the issue. I fixed it and added a test case for it. The test has a 10ms delay but I couldn't get around that. |
|
@aqeelat sorry I just merged another PR and you have merge conflicts! Apologies! |
|
@aqeelat i just asked @anymaniax if we can ignore |
Adds per-generator and shared output paths to the mock configuration,
so MSW handlers and faker fixtures can be written to a separate
package entrypoint instead of next to the generated client services.
Output config now supports:
mock: {
path: '<shared mock output dir>',
generators: [
{ type: 'msw', path: '<msw dir>' },
{ type: 'faker', path: '<faker dir>' },
(client, options) => ..., // ClientMockBuilder
],
}
A per-entry `path` overrides the shared `mock.path`. Function-form
generators (ClientMockBuilder) cannot carry a `path` and fall back
to the shared `mock.path`.
Function-form generators are now mapped to MSW consistently across
all four write modes (single, split, tags, tags-split). Previously,
`split` mode silently skipped them and `tags-split` mode threw
`Function mock generators ... are not supported in tags-split mode`.
`mock-utils.ts` centralizes the shared `getMockDir`,
`hasAnyMockPath`, and `resolveMockSchemasPath` helpers used by
all four writers. The relative-import computation now treats a
trailing `.schemas` on the schemas target as a logical marker
(not a real extension) so `output.schemas` paths keep their
`<filename>.schemas` suffix in generated mock imports.
Closes orval-labs#3537
Fixes orval-labs#3554
Use .toSorted() on Object.entries(target) in tags-mode and split-tags-mode so that Promise.all accumulation order is deterministic, removing the need for emit-time sorting. Also adds test fixtures for previously uncovered mock path combos: - single mode + mock.path + indexMockFiles - tags mode + mock.path + indexMockFiles - tags-split mode with per-generator distinct paths
Add unit tests that mock writeGeneratedFile with a 10ms delay on the health tag to force reverse I/O completion order. Asserts the barrel exports appear in locale-sorted order (admin, health, pets) regardless of Promise.all settle order. Also adds emit-time .toSorted() on the tags array in both tags-mode and split-tags-mode barrel generation as a belt-and-suspenders fix alongside the existing source-level sort.
66950c0 to
471dd63
Compare
|
@melloware rebased |
Adds support for writing mock outputs to separate directories via a shared
mock.pathor per-generatorpathvalues. This lets MSW handlers and faker fixtures live outside the production client entrypoint while preserving imports back to generated schemas.Also fixes function-form mock generators so they are consistently treated as MSW across write modes, matching the upstream normalization in
client.ts.Closes #3537
Fixes #3554
Validation:
node_modules/.bin/vitest run --config vitest.config.ts packages/core/src/writers/split-mode.test.ts packages/core/src/writers/tags-mode.test.ts packages/core/src/writers/split-tags-mode.test.ts packages/core/src/writers/mock-utils.test.tsnode_modules/.bin/vp run -F './packages/*' typechecknode_modules/.bin/vp lint --type-aware --type-check packages/core packages/orvalSnapshot note:
Running
bun run test:snapshots:updategenerated 199 files. I did not include those generated snapshot/fixture updates in this PR yet; I will add them after the source changes are reviewed.Summary by CodeRabbit
New Features
Bug Fixes
Documentation
Tests