Conversation
- Add buildTreatyRouteTree, emitTreatyRouteTree, generateTreatyModuleFromMetadata - Add zenko treaty CLI and optional treatyOutput in config - Add zod devDependency for dynamic import of generated modules in tests - Document plan in docs/plans
📝 WalkthroughWalkthroughThis PR adds a Treaty client generation/runtime pipeline: the schema generator now emits per-operation Changes
Sequence DiagramssequenceDiagram
participant User as User/CLI
participant SchemaGen as Schema<br/>Generator
participant OpParser as Operation<br/>Parser
participant TreatyGen as Treaty<br/>Generator
participant TreeBuilder as Route Tree<br/>Builder
participant Output as Output<br/>File
User->>SchemaGen: Invoke with spec
SchemaGen->>OpParser: parseOperations()
OpParser->>OpParser: Extract method, path,<br/>success/error response maps
OpParser-->>SchemaGen: Operations + response maps
SchemaGen->>Output: Write .gen.ts with<br/>operationMetadata
User->>TreatyGen: generateTreatyModule(input .gen.ts)
TreatyGen->>TreatyGen: Import .gen.ts & read metadata
TreatyGen->>TreeBuilder: buildTreatyRouteTree(metadata)
TreeBuilder-->>TreatyGen: Nested route tree
TreatyGen->>Output: Write .treaty.gen.ts (routes + createClient)
sequenceDiagram
participant App as Application
participant Client as Treaty<br/>Client (proxy)
participant Router as Proxy<br/>Router
participant Fetcher as Fetch<br/>Layer
participant Server as HTTP<br/>Server
App->>Client: createTreatyClient({ baseUrl, routes })
App->>Router: client.board.get()
Router->>Router: Walk route tree, detect leaf
Router->>Fetcher: Invoke leaf caller (opts)
Fetcher->>Server: HTTP request (URL, method, body, headers)
Server-->>Fetcher: HTTP response
Fetcher->>App: TreatySuccess or TreatyFailure envelope
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## master #75 +/- ##
==========================================
- Coverage 97.92% 96.11% -1.82%
==========================================
Files 16 19 +3
Lines 2309 2700 +391
==========================================
+ Hits 2261 2595 +334
- Misses 48 105 +57 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/zenko/package.json (1)
27-34:⚠️ Potential issue | 🟠 MajorAll
bunexport targets are excluded from the published packageThe
bunconditions in all three exports—.,./types, and./treaty—point to source files (./index.ts,./src/types.ts,./src/treaty.ts) that are not covered by thefileswhitelist. The whitelist only includesdist/**artifacts (plus LICENSE and README.md), so installed consumers resolving thebuncondition will fail at runtime due to missing files.💡 Suggested fix (point all bun conditions to published dist files)
"exports": { ".": { "types": "./dist/index.d.ts", - "bun": "./index.ts", + "bun": "./dist/index.mjs", "import": "./dist/index.mjs", "require": "./dist/index.cjs" }, "./types": { "types": "./dist/types.d.ts", - "bun": "./src/types.ts", + "bun": "./dist/types.mjs", "import": "./dist/types.mjs", "require": "./dist/types.cjs" }, "./treaty": { "types": "./dist/treaty.d.ts", - "bun": "./src/treaty.ts", + "bun": "./dist/treaty.mjs", "import": "./dist/treaty.mjs", "require": "./dist/treaty.cjs" } },🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/zenko/package.json` around lines 27 - 34, The package's "exports" bun conditions (for "." , "./types", and "./treaty") point to source files (e.g., "./index.ts", "./src/types.ts", "./src/treaty.ts") that are not included in the "files" whitelist; update each bun condition to reference the published build artifacts inside dist (for example point "." bun to the built ESM like "./dist/index.mjs", "./types" bun to "./dist/src/types.mjs" or "./dist/types.mjs" as appropriate, and "./treaty" bun to its corresponding "./dist/..." artifact) and ensure those dist files are present in the package files list so consumers resolving the bun condition will find the compiled outputs.
🧹 Nitpick comments (9)
packages/zenko/src/__tests__/tictactoe.test.ts (1)
109-114: Use snapshot assertion for generated metadata output.These string-fragment checks are brittle to formatting-only changes. Prefer a named snapshot for this generated block.
♻️ Suggested change
- expect(result).toContain("export const operationMetadata = {") - expect(result).toContain("getSquare: {") - expect(result).toContain('method: "get"') - expect(result).toContain('path: "/board/{row}/{column}"') - expect(result).toContain('"200":"mark"') - expect(result).toContain('"400":"errorMessage"') + expect(result).toMatchSnapshot("tictactoe-operation-metadata-output")As per coding guidelines "Use snapshot testing with expect(result).toMatchSnapshot() for output verification."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/zenko/src/__tests__/tictactoe.test.ts` around lines 109 - 114, Replace the brittle fragment assertions on the generated metadata block with a snapshot assertion: remove the multiple expect(result).toContain(...) checks that reference strings like "export const operationMetadata = {", "getSquare: {", 'method: "get"', 'path: "/board/{row}/{column}"', '"200":"mark"', and '"400":"errorMessage"' and instead call expect(result).toMatchSnapshot() (optionally with a descriptive snapshot name) to capture the full generated metadata output in one stable snapshot; update the test around the result variable in the tictactoe test to use this single snapshot assertion.packages/zenko/src/__tests__/treaty-runtime.test.ts (1)
48-70: Test name and asserted behavior are inconsistent.The test says “JSON bodies” but validates a raw body string (
"X"). Either serialize/assert JSON payload explicitly or rename the test to avoid ambiguity.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/zenko/src/__tests__/treaty-runtime.test.ts` around lines 48 - 70, The test titled "walks dynamic segments and sends JSON bodies" is inconsistent because it asserts a raw string body ("X") from the call via createTreatyClient -> client.board(...).put; update the test to either (A) assert a JSON body by calling .put with an object payload and expect fetchMock to receive body: JSON.stringify(yourObject) and Content-Type: "application/json", or (B) rename the test to reflect that it sends raw string bodies and keep the existing assertion; adjust references in the assertion to use fetchMock and the client.board({ row: "1" })({ column: "2" }).put call accordingly so the test name and the fetchMock expect.objectContaining check are consistent.packages/zenko/src/__tests__/cli.test.ts (1)
113-116: Prefer snapshots for treaty output verification.For generated module content, these
toContainchecks are narrow and formatting-sensitive. Use named snapshots so structural changes are reviewed explicitly.♻️ Suggested change
- expect(output).toContain("export const treatyRoutes = {") - expect(output).toContain( - 'import { createTreatyClient, type TreatyClient } from "zenko/treaty"' - ) + expect(output).toMatchSnapshot("cli-treaty-command-output") ... - expect(treaty).toContain("export const treatyRoutes = {") + expect(treaty).toMatchSnapshot("cli-config-treaty-output")As per coding guidelines "Use snapshot testing with expect(result).toMatchSnapshot() for output verification."
Also applies to: 207-209
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/zenko/src/__tests__/cli.test.ts` around lines 113 - 116, Replace the brittle string-contains assertions that check generated treaty module text (the expectations referencing "export const treatyRoutes = {" and the import of createTreatyClient/type TreatyClient) with a named snapshot assertion so the entire generated output is compared structurally; locate the test that builds the treaty module output (the variable currently asserted via expect(output).toContain(...)) and change those assertions to a single expect(<that output variable>).toMatchSnapshot('treaty-treatyModule-output') (also update the analogous checks near the other occurrence mentioned) so formatting changes are reviewed via snapshot diffs.packages/examples/src/__tests__/train-travel-treaty-fetch.test.ts (1)
68-71: Avoid asserting full query-string orderingConsider asserting query params via
URL.searchParamsinstead of full URL string equality to reduce test brittleness when serialization order changes.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/examples/src/__tests__/train-travel-treaty-fetch.test.ts` around lines 68 - 71, The test currently asserts the full URL string when checking fetchMock calls (`expect(fetchMock).toHaveBeenCalledWith(\`${origin}/stations?...`, which is brittle due to query-string ordering); instead, extract the actual URL argument from the fetchMock call (e.g., inspect fetchMock.mock.calls[0][0] or use fetchMock.mock.calls to find the call) and create a new URL(...) from it, then assert individual query params via url.searchParams.get('limit'), url.searchParams.get('page'), url.searchParams.get('country') and assert the pathname equals '/stations' and the method via expect.objectContaining({ method: 'GET' }) as before. Ensure you update the assertion around `expect(fetchMock).toHaveBeenCalledWith(...)` to use these URL.searchParams checks so the test no longer depends on param ordering.packages/zenko/src/utils/__tests__/treaty-tree.test.ts (1)
37-45: Prefer snapshot assertion for emitted route-tree outputThis output-verification test is a good candidate for
toMatchSnapshot(...)so regressions in emitted structure are caught holistically, not only by a fewtoContainchecks.As per coding guidelines: "Use snapshot testing with expect(result).toMatchSnapshot() for output verification" and "Name snapshots descriptively when using toMatchSnapshot()"
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/zenko/src/utils/__tests__/treaty-tree.test.ts` around lines 37 - 45, Replace the ad-hoc contains assertions in the "emitTreatyRouteTree emits quoted :param keys" test with a snapshot assertion: call emitTreatyRouteTree(tree) and use expect(emitted).toMatchSnapshot("emitTreatyRouteTree - quoted param keys") so the entire emitted structure from buildTreatyRouteTree/emitTreatyRouteTree is captured; update the test name if needed to remain descriptive and remove the three expect(...).toContain(...) lines referencing "board: {", '":row": {', and "getSquare,".packages/zenko/src/__tests__/treaty-generator.test.ts (1)
39-50: Use snapshot verification for generated module outputThis generated-source assertion set would be stronger as
toMatchSnapshot("treaty-generator-tictactoe-output"), with a few focusedtoContainchecks kept only for critical anchors if needed.As per coding guidelines: "Use snapshot testing with expect(result).toMatchSnapshot() for output verification" and "Name snapshots descriptively when using toMatchSnapshot()"
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/zenko/src/__tests__/treaty-generator.test.ts` around lines 39 - 50, Replace the many granular expect(...).toContain assertions with a snapshot assertion to verify the generated module output: call expect(output).toMatchSnapshot("treaty-generator-tictactoe-output") in the test and optionally retain a couple of critical anchor checks (e.g., that output contains "export const treatyRoutes =" or "createClient(") if you want focused guarantees; update the test in treaty-generator.test.ts to remove the repetitive toContain checks for "import { createTreatyClient, type TreatyClient }", "getBoard", "getSquare", "putSquare", and the object fragments, and add the descriptive snapshot name per guidelines.packages/zenko/src/treaty-infer.ts (1)
12-20: Consider usingunknown[]instead ofany[]for type safety.Per coding guidelines, prefer
unknownoveranywhere possible. The function signature(...args: any[]) => stringcould be(...args: unknown[]) => string.Suggested change
type AnyOperationDefinition = OperationDefinition< RequestMethod, - (...args: any[]) => string, + (...args: unknown[]) => string, unknown, unknown, AnyHeaderFn | undefined, OperationErrors | undefined, readonly SecurityRequirement[] | undefined >🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/zenko/src/treaty-infer.ts` around lines 12 - 20, Update the AnyOperationDefinition type to use unknown[] for the varargs function signature: replace the function type (...args: any[]) => string with (...args: unknown[]) => string inside the OperationDefinition type alias (symbol: AnyOperationDefinition) to improve type safety; ensure any downstream usage expecting any[] is adjusted or narrowed via proper type assertions/casts where necessary.packages/zenko/src/core/operation-parser.ts (1)
326-343: Consider typing theschemaparameter more precisely.The
schemaparameter usesanytype. While this matches the existing codebase patterns, consider using a more specific type orunknownfor better type safety. This is a minor nit given the existing code style.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/zenko/src/core/operation-parser.ts` around lines 326 - 343, The schema parameter in buildErrorResponsesMap is typed as any; change it to a stricter type (prefer unknown or a specific Schema type used elsewhere) to improve type safety. Update the function signature for buildErrorResponsesMap to use schema: unknown (or the chosen Schema interface) and adjust any downstream usage: particularly the call to resolveResponseType so its parameter type matches (or perform a safe type-assertion/validation before passing schema). Make sure to update any related type declarations for resolveResponseType if needed and keep identifiers intact (buildErrorResponsesMap, resolveResponseType, mapStatusToIdentifier).packages/zenko/src/treaty-generator.ts (1)
41-58: Verify error handling for missing input file.The dynamic import on line 46 will throw if the file doesn't exist, but the error message may not be user-friendly. Consider whether wrapping this with a more descriptive error would improve the developer experience.
Suggested improvement for clearer error messages
export async function generateTreatyModule(options: { inputFile: string importPath: string }): Promise<string> { const url = pathToFileURL(options.inputFile).href - const mod = await import(url) + let mod: Record<string, unknown> + try { + mod = await import(url) + } catch (err) { + throw new Error( + `Failed to import ${options.inputFile}: ${err instanceof Error ? err.message : String(err)}` + ) + } if (!mod.operationMetadata) {🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/zenko/src/treaty-generator.ts` around lines 41 - 58, The dynamic import in generateTreatyModule (specifically the import(url) call using options.inputFile) can throw an unfriendly error if the file is missing or invalid; wrap the await import(url) in a try/catch, catch any error, and throw a new, clearer Error that mentions the problematic options.inputFile and includes the original error message/details (e.g., via error.message or by attaching the original error) so callers see a descriptive failure when the input file cannot be loaded.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/zenko/src/treaty.ts`:
- Around line 209-215: The fetch options spread currently allows init to
override the previously set method/body (in the fetchImpl call that uses url,
upper, headers, isGetOrHead, requestBody), so prevent accidental overrides by
ensuring init is applied safely: either spread init first before explicitly
setting method/body, or create a safeInit that strips method and body (e.g.,
destructure init to exclude method/body) and spread safeInit after your explicit
method/body/headers/body entries; update the fetchImpl invocation to use that
safe ordering or safeInit.
In `@packages/zenko/src/utils/treaty-tree.ts`:
- Around line 20-30: Docstring example in pathTemplateToSegments is wrong:
update the comment so parameter segments show colon prefixes (i.e., change
`/{a}/{b} → ["a", ":b"]` to `/{a}/{b} → [":a", ":b"]`) to match the function
behavior; locate the docstring above the pathTemplateToSegments function and
correct the example text accordingly.
---
Outside diff comments:
In `@packages/zenko/package.json`:
- Around line 27-34: The package's "exports" bun conditions (for "." ,
"./types", and "./treaty") point to source files (e.g., "./index.ts",
"./src/types.ts", "./src/treaty.ts") that are not included in the "files"
whitelist; update each bun condition to reference the published build artifacts
inside dist (for example point "." bun to the built ESM like "./dist/index.mjs",
"./types" bun to "./dist/src/types.mjs" or "./dist/types.mjs" as appropriate,
and "./treaty" bun to its corresponding "./dist/..." artifact) and ensure those
dist files are present in the package files list so consumers resolving the bun
condition will find the compiled outputs.
---
Nitpick comments:
In `@packages/examples/src/__tests__/train-travel-treaty-fetch.test.ts`:
- Around line 68-71: The test currently asserts the full URL string when
checking fetchMock calls
(`expect(fetchMock).toHaveBeenCalledWith(\`${origin}/stations?...`, which is
brittle due to query-string ordering); instead, extract the actual URL argument
from the fetchMock call (e.g., inspect fetchMock.mock.calls[0][0] or use
fetchMock.mock.calls to find the call) and create a new URL(...) from it, then
assert individual query params via url.searchParams.get('limit'),
url.searchParams.get('page'), url.searchParams.get('country') and assert the
pathname equals '/stations' and the method via expect.objectContaining({ method:
'GET' }) as before. Ensure you update the assertion around
`expect(fetchMock).toHaveBeenCalledWith(...)` to use these URL.searchParams
checks so the test no longer depends on param ordering.
In `@packages/zenko/src/__tests__/cli.test.ts`:
- Around line 113-116: Replace the brittle string-contains assertions that check
generated treaty module text (the expectations referencing "export const
treatyRoutes = {" and the import of createTreatyClient/type TreatyClient) with a
named snapshot assertion so the entire generated output is compared
structurally; locate the test that builds the treaty module output (the variable
currently asserted via expect(output).toContain(...)) and change those
assertions to a single expect(<that output
variable>).toMatchSnapshot('treaty-treatyModule-output') (also update the
analogous checks near the other occurrence mentioned) so formatting changes are
reviewed via snapshot diffs.
In `@packages/zenko/src/__tests__/tictactoe.test.ts`:
- Around line 109-114: Replace the brittle fragment assertions on the generated
metadata block with a snapshot assertion: remove the multiple
expect(result).toContain(...) checks that reference strings like "export const
operationMetadata = {", "getSquare: {", 'method: "get"', 'path:
"/board/{row}/{column}"', '"200":"mark"', and '"400":"errorMessage"' and instead
call expect(result).toMatchSnapshot() (optionally with a descriptive snapshot
name) to capture the full generated metadata output in one stable snapshot;
update the test around the result variable in the tictactoe test to use this
single snapshot assertion.
In `@packages/zenko/src/__tests__/treaty-generator.test.ts`:
- Around line 39-50: Replace the many granular expect(...).toContain assertions
with a snapshot assertion to verify the generated module output: call
expect(output).toMatchSnapshot("treaty-generator-tictactoe-output") in the test
and optionally retain a couple of critical anchor checks (e.g., that output
contains "export const treatyRoutes =" or "createClient(") if you want focused
guarantees; update the test in treaty-generator.test.ts to remove the repetitive
toContain checks for "import { createTreatyClient, type TreatyClient }",
"getBoard", "getSquare", "putSquare", and the object fragments, and add the
descriptive snapshot name per guidelines.
In `@packages/zenko/src/__tests__/treaty-runtime.test.ts`:
- Around line 48-70: The test titled "walks dynamic segments and sends JSON
bodies" is inconsistent because it asserts a raw string body ("X") from the call
via createTreatyClient -> client.board(...).put; update the test to either (A)
assert a JSON body by calling .put with an object payload and expect fetchMock
to receive body: JSON.stringify(yourObject) and Content-Type:
"application/json", or (B) rename the test to reflect that it sends raw string
bodies and keep the existing assertion; adjust references in the assertion to
use fetchMock and the client.board({ row: "1" })({ column: "2" }).put call
accordingly so the test name and the fetchMock expect.objectContaining check are
consistent.
In `@packages/zenko/src/core/operation-parser.ts`:
- Around line 326-343: The schema parameter in buildErrorResponsesMap is typed
as any; change it to a stricter type (prefer unknown or a specific Schema type
used elsewhere) to improve type safety. Update the function signature for
buildErrorResponsesMap to use schema: unknown (or the chosen Schema interface)
and adjust any downstream usage: particularly the call to resolveResponseType so
its parameter type matches (or perform a safe type-assertion/validation before
passing schema). Make sure to update any related type declarations for
resolveResponseType if needed and keep identifiers intact
(buildErrorResponsesMap, resolveResponseType, mapStatusToIdentifier).
In `@packages/zenko/src/treaty-generator.ts`:
- Around line 41-58: The dynamic import in generateTreatyModule (specifically
the import(url) call using options.inputFile) can throw an unfriendly error if
the file is missing or invalid; wrap the await import(url) in a try/catch, catch
any error, and throw a new, clearer Error that mentions the problematic
options.inputFile and includes the original error message/details (e.g., via
error.message or by attaching the original error) so callers see a descriptive
failure when the input file cannot be loaded.
In `@packages/zenko/src/treaty-infer.ts`:
- Around line 12-20: Update the AnyOperationDefinition type to use unknown[] for
the varargs function signature: replace the function type (...args: any[]) =>
string with (...args: unknown[]) => string inside the OperationDefinition type
alias (symbol: AnyOperationDefinition) to improve type safety; ensure any
downstream usage expecting any[] is adjusted or narrowed via proper type
assertions/casts where necessary.
In `@packages/zenko/src/utils/__tests__/treaty-tree.test.ts`:
- Around line 37-45: Replace the ad-hoc contains assertions in the
"emitTreatyRouteTree emits quoted :param keys" test with a snapshot assertion:
call emitTreatyRouteTree(tree) and use
expect(emitted).toMatchSnapshot("emitTreatyRouteTree - quoted param keys") so
the entire emitted structure from buildTreatyRouteTree/emitTreatyRouteTree is
captured; update the test name if needed to remain descriptive and remove the
three expect(...).toContain(...) lines referencing "board: {", '":row": {', and
"getSquare,".
🪄 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: defaults
Review profile: CHILL
Plan: Pro
Run ID: 4f0fca64-c758-4400-b4d6-ef5c6628fe4b
⛔ Files ignored due to path filters (20)
bun.lockis excluded by!**/*.lockpackages/zenko/src/__tests__/__snapshots__/additional-properties.test.ts.snapis excluded by!**/*.snappackages/zenko/src/__tests__/__snapshots__/anyof-combinations.test.ts.snapis excluded by!**/*.snappackages/zenko/src/__tests__/__snapshots__/cli.test.ts.snapis excluded by!**/*.snappackages/zenko/src/__tests__/__snapshots__/complex-composition.test.ts.snapis excluded by!**/*.snappackages/zenko/src/__tests__/__snapshots__/date-enum.test.ts.snapis excluded by!**/*.snappackages/zenko/src/__tests__/__snapshots__/form-data.test.ts.snapis excluded by!**/*.snappackages/zenko/src/__tests__/__snapshots__/inline-response-array.test.ts.snapis excluded by!**/*.snappackages/zenko/src/__tests__/__snapshots__/mixed-headers.test.ts.snapis excluded by!**/*.snappackages/zenko/src/__tests__/__snapshots__/no-response-content.test.ts.snapis excluded by!**/*.snappackages/zenko/src/__tests__/__snapshots__/non-json-responses.test.ts.snapis excluded by!**/*.snappackages/zenko/src/__tests__/__snapshots__/oneof-discriminator.test.ts.snapis excluded by!**/*.snappackages/zenko/src/__tests__/__snapshots__/petstore.test.ts.snapis excluded by!**/*.snappackages/zenko/src/__tests__/__snapshots__/property-metadata.test.ts.snapis excluded by!**/*.snappackages/zenko/src/__tests__/__snapshots__/security-schemes.test.ts.snapis excluded by!**/*.snappackages/zenko/src/__tests__/__snapshots__/selective-operations.test.ts.snapis excluded by!**/*.snappackages/zenko/src/__tests__/__snapshots__/tictactoe.test.ts.snapis excluded by!**/*.snappackages/zenko/src/__tests__/__snapshots__/train-travel.test.ts.snapis excluded by!**/*.snappackages/zenko/src/__tests__/__snapshots__/webhook.test.ts.snapis excluded by!**/*.snappackages/zenko/src/__tests__/__snapshots__/zenko.test.ts.snapis excluded by!**/*.snap
📒 Files selected for processing (24)
docs/plans/2026-03-29-zenko-treaty-client.mdpackages/examples/generate.jspackages/examples/src/__tests__/train-travel-treaty-fetch.test.tspackages/examples/tsconfig.jsonpackages/zenko/index.tspackages/zenko/package.jsonpackages/zenko/src/__tests__/cli.test.tspackages/zenko/src/__tests__/tictactoe.test.tspackages/zenko/src/__tests__/treaty-client-types.test.tspackages/zenko/src/__tests__/treaty-generator.test.tspackages/zenko/src/__tests__/treaty-runtime.test.tspackages/zenko/src/cli.tspackages/zenko/src/core/__tests__/operation-parser.test.tspackages/zenko/src/core/operation-parser.tspackages/zenko/src/treaty-generator.tspackages/zenko/src/treaty-infer.tspackages/zenko/src/treaty-types.tspackages/zenko/src/treaty.tspackages/zenko/src/types/operation.tspackages/zenko/src/utils/__tests__/treaty-tree.test.tspackages/zenko/src/utils/treaty-tree.tspackages/zenko/src/zenko.tspackages/zenko/tsdown.config.tspackages/zenko/zenko-config.schema.json
There was a problem hiding this comment.
🧹 Nitpick comments (2)
packages/zenko/src/utils/treaty-tree.ts (2)
83-87: Line exceeds 80-character limit.The error message template string on line 85 exceeds the 80-character line width guideline when fully indented.
♻️ Suggested refactor
if (bucket[method] !== undefined) { + const existing = JSON.stringify(bucket[method]) throw new Error( - `Duplicate ${method} on ${segment} for ${operationExport} vs ${JSON.stringify(bucket[method])}` + `Duplicate ${method} on ${segment} ` + + `for ${operationExport} vs ${existing}` ) }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/zenko/src/utils/treaty-tree.ts` around lines 83 - 87, The error string in the duplicate-check (bucket[method] !== undefined) is longer than 80 chars; split the message across concatenated strings or build it in parts so each source line stays under 80 chars while preserving content and using JSON.stringify(bucket[method]) and the same variables (method, segment, operationExport, bucket[method]); update the throw in the function handling the duplicate check in treaty-tree.ts to construct the message in shorter chunks (e.g., separate descriptive part and the JSON detail) so indentation + line length remain within the limit.
40-57: Consider Result-style returns for error handling.This function throws exceptions for invalid HTTP methods. As per coding guidelines for
packages/zenko/src/**: "Prefer Result-style returns for recoverable errors in library code rather than throwing exceptions."Malformed metadata (unsupported HTTP method) could be considered a recoverable error that callers might want to handle gracefully.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/zenko/src/utils/treaty-tree.ts` around lines 40 - 57, buildTreatyRouteTree currently throws on unsupported HTTP methods; change it to return a Result-style value instead of throwing so callers can handle recoverable metadata errors. Update the function signature (e.g., to return Result<TreatyRouteTree, Error>) and inside, when you detect an invalid method via HTTP_METHODS and meta.method, return a failure Result containing a clear error message referencing operationExport and meta.method rather than throwing; on success return an Ok Result with the built TreatyRouteTree. Keep the insertOperation usage and other logic the same, and update any callers of buildTreatyRouteTree to handle the Result (check for Ok/Err) instead of relying on exceptions.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@packages/zenko/src/utils/treaty-tree.ts`:
- Around line 83-87: The error string in the duplicate-check (bucket[method] !==
undefined) is longer than 80 chars; split the message across concatenated
strings or build it in parts so each source line stays under 80 chars while
preserving content and using JSON.stringify(bucket[method]) and the same
variables (method, segment, operationExport, bucket[method]); update the throw
in the function handling the duplicate check in treaty-tree.ts to construct the
message in shorter chunks (e.g., separate descriptive part and the JSON detail)
so indentation + line length remain within the limit.
- Around line 40-57: buildTreatyRouteTree currently throws on unsupported HTTP
methods; change it to return a Result-style value instead of throwing so callers
can handle recoverable metadata errors. Update the function signature (e.g., to
return Result<TreatyRouteTree, Error>) and inside, when you detect an invalid
method via HTTP_METHODS and meta.method, return a failure Result containing a
clear error message referencing operationExport and meta.method rather than
throwing; on success return an Ok Result with the built TreatyRouteTree. Keep
the insertOperation usage and other logic the same, and update any callers of
buildTreatyRouteTree to handle the Result (check for Ok/Err) instead of relying
on exceptions.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 35c415f8-56da-4dc6-8a24-aa425b161f60
📒 Files selected for processing (4)
packages/zenko/package.jsonpackages/zenko/src/__tests__/treaty-runtime.test.tspackages/zenko/src/treaty.tspackages/zenko/src/utils/treaty-tree.ts
✅ Files skipped from review due to trivial changes (1)
- packages/zenko/src/tests/treaty-runtime.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/zenko/package.json
- packages/zenko/src/treaty.ts
Summary by CodeRabbit
New Features
zenko treatyCLI command and atreatyOutputconfig option for generating treaty modules automatically.Tests
Documentation