Skip to content

feat(mock): add the mock serve and mock generate commands - #474

Draft
Shield-Jaguar wants to merge 18 commits into
devfrom
feat/mock-server
Draft

Shield-Jaguar wants to merge 18 commits into
devfrom
feat/mock-server

Conversation

@Shield-Jaguar

@Shield-Jaguar Shield-Jaguar commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Adds apimatic mock serve: a mock HTTP server that answers exactly the requests its stub files describe, for generated SDK tests to run against. It is the TypeScript port of the C# proof of concept in mock-server-poc-v4 (apimatic/codegen-v2#705), with the same stub format and wire contract, so the stub files of the proof of concept load as they are.

apimatic mock serve --stubs ./stubs --port 0

It also carries apimatic mock generate, which fetches the stub files mock serve reads. That command is hidden until its endpoint is live; it was #484, and is described in its own section below.

What it does

  • Exact matching. A request no stub describes is answered 418 with application/problem+json naming the closest stub and every difference from it, plus a one-line X-Mock-Mismatch header. It never guesses.
  • Declared errors and named examples are asked for with Prefer: code=<status> and Prefer: example=<name>.
  • An OAuth2 authorization server on the same origin, from an oauth2 stub: client credentials, authorization code with PKCE, refresh, password and implicit.
  • Streams and files from stub data: SSE and ndjson paced by chunkDelayMs, multipart and binary.
  • A request log at /__admin/requests (GET reads the newest 10,000, DELETE clears), so a retry test can count its attempts.
  • For a test harness: a line holding MOCKSERVER_URL=<origin> is printed once the mock listens. Exit code 130 means stopped, 1 means stub problems or a port that could not be opened, 2 means a bad flag.

Flags: -p, --port (default 4010; 0 picks a free loopback port; a busy port is an error), --host, -s, --stubs (default ./stubs), --token-ttl, --verbose.

How it is built

  • src/types/mock/** is the pure core: a strict JSON reader and writer, the stub format (schema check with ajv, then a typed parser that reports every problem with its JSON pointer), matching, the 418 report and the OAuth2 server. ESLint keeps fs, http, net, clack and oclif out of it, and bans regular expressions in the mock's folders and tests.
  • src/infrastructure/mock/** is the only I/O: the stubs directory and the host on node:http.
  • mock-stubs.schema.json ships in the package; ajv moves from devDependencies to dependencies.
  • docs/mock/stub-format.md is the format; docs/mock/generator-handoff.md says what a generator renders and how a generated test starts and stops the command, and lists what differs from the C# server on purpose (section 5).

How it was checked

  • Every behaviour the C# tests pin has a test here, including the seven wire mutations. The tests share one small stub set, held in code in test/helpers/mock-sample.ts; the reference's Spec S and TesterPoc stub sets belong with the SDKs that run against them and are not kept in this repository.
  • The reference's own Spec S and routing suites were run against this host: the only failures were the documented differences (a lower-case method answers 400 from Node's parser, the path is percent-decoded once, the request log has its own shape).
  • The C# SDK's contract suite (tests/TesterPoc.ContractTests, 103 tests) passes against apimatic mock serve on .NET 10 and .NET 8, with no request missed.
  • test/e2e/mock-serve.test.ts runs the built CLI: the marker line, exit codes 1 and 2, and exit 130 on SIGINT and SIGTERM (POSIX only).
  • The test matrix (Linux, Windows and macOS on Node 22.14, 22, 24 and 26) passes on the branch, signal cases included.

For the reviewer

  • The diff is about 20,200 lines: about 6,300 are source and about 12,000 are tests, 900 of them the shared sample stubs.
  • The CLI Reference rows in apimatic-docs are drafted in .ai/plans/mock-server.md (Phase 7 findings) and wait for the release.
  • Open choices are listed in that plan file's findings, among them: --host accepts localhost or an IP address only, stub problems go to stdout with the rest of the CLI's output, and the marker line sits inside the CLI's gutter rather than first on stdout.

mock generate (hidden)

apimatic mock generate sends the project's build to codegen, waits for the run, downloads the stub files and writes them to the folder apimatic mock serve reads. In a project directory the two commands work with no flags:

apimatic mock generate
apimatic mock serve

The endpoint it calls does not exist yet. The command is written against the planned /mock contract, which has the shape of /plugin, and is hidden until that endpoint is live, so a release cannot ship a command that always fails.

What it does

  • Uploads the build as plugin generate does: a zip of src/, to POST /mock. It asks for no language and needs no plugin block or metadata in apimatic.json.
  • Waits for the run on GET /mock/{id}/status with the shared pollUntilCompleted, then downloads GET /mock/{id}/download.
  • Checks the download before it writes. The zip is unpacked in a temporary folder and loaded with the loader mock serve uses. Stub files the mock would refuse are reported problem by problem, and the stubs directory is left as it was. So is a run that fails, and a download without a stub.
  • Replaces, never merges. mock serve loads every file in the folder, so one left from the last set would be served beside the new one. Only a .git folder is kept.
  • Asks before it replaces a destination that is not empty; --force skips the question.

Flags: --input (the project directory), --destination (default stubs in the project directory, so --input X writes to X/stubs), --force, --auth-key. Errors use the wording of plugin generate.

How it is built

  • It mirrors plugin generate layer by layer: commands/mock/generate.ts, actions/mock/generate.ts, prompts/mock/generate.ts, infrastructure/services/stub-generation-service.ts, with types/stubs-context.ts for the stubs directory.
  • Everything the contract fixes is in stub-generation-service.ts: the three routes, and the place of the stub files in the download (STUB_FILES_IN_DOWNLOAD). A change on the codegen side is an edit to that one file.
  • STUBS_DIRECTORY_NAME in types/project-layout.ts is now the one name both commands share; mock serve's default is built from it.
  • docs/mock/generator-handoff.md gains section 6, which states the contract as the CLI reads it. .ai/plans/mock-server.md records the work as phase 8, with what to do when the endpoint is live.

How it was checked

  • pnpm build, pnpm lint and pnpm test pass locally (3917 passing, 93 pending). 68 of the tests are new.
  • The service's tests run against a local HTTP stand-in for the endpoint (test/helpers/stub-generation-endpoint.ts), as plugin-service.test.ts does for /plugin.
  • One action test runs the whole path: the real service against the stand-in, the sample stub set as the download, then the mock host started on the folder it wrote (20 stubs, a request they describe answers 200).
  • The built CLI was run by hand against a stand-in: mock generate with only an auth key, then mock serve with no stubs flag, served the generated set; a second run with --force removed a file left from the first.
  • Four mutations (a wrong status route, a wrong layout constant, a merge in place of the replace, the loader check skipped) each made tests fail.

Not run: the real endpoint, since there is none, and the overwrite question in a real terminal.

For the reviewer

  • Assumptions about the endpoint, each one line to change: the names of the three routes, and stub files at the root of the zip. Codegen's ADR-0036 leaves their folder to the packaging change.
  • Also not known until the endpoint exists: its status values, the keys of a validation error, and that the gateway answers a finished run with 302 on this route as it does for /plugin.
  • The origin sent is APIMATIC CLI mock:generate, since oclif spells the command's id with a colon, as plugin generate sends plugin:generate.
  • Stricter than plugin generate in two places. The overwrite question counts hidden files, because the replace removes them. A run that returns no stub is a failure and leaves the folder as it was.
  • The download is received whole, not as a stream. A connection that drops or stalls part-way is then one more failed request, reported with the wording of an unexpected error, and the stubs directory is left as it was. plugin generate and sdk generate stream theirs, so the same break throws while they save it; they are not changed here.
  • stubs is not added to the folders quickstart puts in a project's .gitignore. Whether it should be is left for when the command is shown.
  • To show the command once the endpoint is live, follow the list at the end of the plan's phase 8 findings: run it against the live endpoint, remove hidden, widen the mock topic's description, run pnpm readme.

🤖 Generated with Claude Code

Shield-Jaguar and others added 10 commits November 10, 2026 18:01
The v4 mock server is being ported from C# (apimatic/mock-server-poc-v4) as
`apimatic mock serve`. This lays the ground and adds no behaviour:

- ajv moves to the runtime dependencies; the loader checks stub files with it
- mock-stubs.schema.json, the stub schema, is published with the package
- ESLint keeps src/types/mock free of file, process and network access and of
  imports from the rest of the CLI, and refuses regular expressions in the mock
- the three reference stub sets become fixtures under test/resources/mock

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The stub format of the v4 mock server, ported from its C# reference:

- a strict JSON reader and writer that keep a number as it was written, so an
  int64 beyond 2^53 or a decimal such as 250.00 is compared and served unchanged
- the stub model: path templates, value and JSON rules, responses with SSE,
  ndjson and multipart rendering, OAuth2 server settings
- StubSchema: ajv decides whether a file is valid, and a walk over the same
  schema says what is wrong and where, one problem per JSON pointer
- parseStub and loadStubs, which report every problem of every file in one run
- StubDirectoryService, which lists and reads a stubs directory

The three reference stub sets load with no problems.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The matching layer of the v4 mock server, ported from its C# reference:

- the request model, with query, cookie, Prefer and multipart/form-data reading
- the stub matcher: method, path, headers, cookies, credentials, the closed
  query set and the body, with Prefer: code= and Prefer: example=
- the closest-stub ranking and the 418 problem report with its X-Mock-Mismatch
  summary

The seven wire mutations are named without a server, and the report documents
the reference pins are reproduced as written.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
… stub

The authorization server an oauth2 stub describes: client credentials,
authorization code with PKCE (S256), refresh, password and implicit flows.
It is stateless (the code carries the challenge, scope and redirect URI;
refresh tokens are numbered) and refuses a wrong request with the same 418
report the stubs use.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The host on node:http. It loads a stubs directory, listens on a free
loopback port or a fixed host and port, hands every request to the router
(the OAuth2 servers first, then the stubs) and writes what was decided:
the stub's answer with its length stated, or the 418 report. Routing, the
request and the response as they cross the wire, and the body limit are
pure and live in src/types/mock/routing.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The mock is stateless, so a retry test counts its attempts in a log of
the newest 10,000 requests that reached the router: GET reads it, DELETE
clears it, and nothing else exists under /__admin. The paced body of a
stream moves into a module of its own with tests for the pause between
chunks and for a stream ended by a stop or by a client that leaves.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
apimatic mock serve loads a stubs directory and serves it until stopped,
printing MOCKSERVER_URL=<origin> for a test harness to read. Flags choose
the port (0 for a free one), the host, the stubs directory, the OAuth2
token lifetime and a request log on stderr. The command and its topic stay
hidden until the SDK contract suites pass against it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
docs/mock/stub-format.md is the format the mock loads, with the request
log's shape and the requests the mock answers itself.
docs/mock/generator-handoff.md says what a generator renders and how a
generated test starts the command, finds the origin and stops it, with a
table of what changed from the C# proof of concept. CONTEXT.md gains the
mock's terms, and the plan records the contract run and what is left.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The C# SDK's contract suite passes against it (103 of 103 on net10.0 and
net8.0 over the TesterPoc stubs, with no request missed), so the command
and its topic are no longer hidden and the README lists them.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
refreshTokenPrefix: 'ac-refresh-token-',
username: 'test-user',
password: 'test-password',
passwordAccessToken: 'pw-access-token',
clientCredentialsToken: 'cc-access-token',
username: 'test-user',
password: 'test-password',
passwordToken: 'pw-access-token',
Shield-Jaguar and others added 3 commits November 11, 2026 18:14
…loud asked for

The part names of a multipart form are sorted with the ordinal comparer
the rest of the mock uses, and the closest schema branch is folded from
the first one explicitly; neither changes what is returned. The two
fixed test passwords are marked as such for the analysis.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
apimatic mock generate zips the project's src folder, sends it to
codegen's /mock endpoint, waits for the run and replaces the stubs
directory with the stub files it downloads. The default destination is
the folder mock serve reads by default, so the two commands work in a
project directory with no flags.

The download is unpacked and loaded as mock serve would load it before
the stubs directory is touched, so a run that fails or returns stub
files the mock would refuse leaves the last set in place. The three
routes and the layout of the download are stated in
stub-generation-service.ts alone.

The endpoint does not exist yet, so the command is hidden and its tests
run against a local stand-in for it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
docs/mock/generator-handoff.md gains a section on the three /mock routes
the command calls, the statuses it reads, the layout it expects in the
download and the two points still open on the codegen side. The plan
records phase 8: what was built, how it differs from plugin generate,
what could not be run without the endpoint and what to do when it is
live. CONTEXT.md says what mock generate does to the stubs directory.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Shield-Jaguar and others added 3 commits November 20, 2026 11:28
mock generate took the download as a stream, so a connection that
dropped or stalled after the headers failed while the action saved it,
and the error was thrown out of the command. The service now receives
the download whole: a break is one more failed request, reported like
the others, and the stubs directory keeps the last set.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The Spec S and TesterPoc sets belong with the SDKs whose suites run
against them, not with the CLI. Both go, with the Spec S contract tests
that existed only to exercise them. The 20 sample stubs the unit and
host tests are built on move verbatim into test/helpers/mock-sample.ts;
a test that needs them on disk writes them to a temporary directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
String.raw stays only on the one sample file that holds a backslash,
and the stub helpers import the node: built-ins by their prefix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Shield-Jaguar Shield-Jaguar changed the title feat(mock): add the mock serve command feat(mock): add the mock serve and mock generate commands Nov 27, 2026
Shield-Jaguar and others added 2 commits November 27, 2026 19:02
Nested template literals and ternaries are pulled into named values or
small functions, the body reader of openStream into a function of its
own, and the stub loader sorts its problems in a statement of its own.
Static factories and the serve flags are readonly, the schema keyword
lists are Sets, tests assert undefined with to.be.undefined, and the
last item is read with at(-1).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
C Security Rating on New Code (required ≥ A)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants