Skip to content

Add an OpenAPI SDK generator for Hypervel Saloon - #808

Merged
binaryfire merged 5 commits into
0.4from
feature/sdk-generator
Dec 1, 2026
Merged

binaryfire merged 5 commits into
0.4from
feature/sdk-generator

Conversation

@binaryfire

@binaryfire binaryfire commented Dec 1, 2026 •

Copy link
Copy Markdown
Member

This adds hypervel/sdk-generator, a development dependency for building typed PHP clients from OpenAPI descriptions. The generated clients use Hypervel Saloon for requests, authentication, and pagination, and Hypervel Data for request and response objects. The generator runs from the command line without booting an application.

Generating a client

An SDK keeps a local copy of its OpenAPI description and a small sdk.php alongside its Composer manifest. The definition selects a source and the PHP namespace for the client. For example:

use Hypervel\SdkGenerator\SdkDefinition;

return SdkDefinition::make(
    source: 'resources/openapi/openapi.yaml',
    namespace: 'App\\Cloud',
);

Running vendor/bin/hypervel-sdk generate path/to/cloud writes the connector, resources, requests, and data objects under generated/. The definition can select operations, group them into resources, map provider types to application classes, and describe authentication, response handling, and pagination. Source corrections can live in the definition so the original provider description stays available for comparison.

The reader accepts local JSON and YAML files in Swagger 2.0 and OpenAPI 3.0 and 3.1. It also accepts OpenAPI 3.2 descriptions that use the supported 3.1 features and the QUERY method. Unsupported features in a selected operation are reported during generation.

Updating a client

Handwritten classes live in src/. A manifest in generated/ records the inputs and hashes of the files the generator owns. Regeneration checks those hashes before replacing output, so an unexpected edit, deletion, or extra file is reported before it can be overwritten.

Use generate --dry-run --diff to inspect a provider update, or generate --check in CI to detect drift without writing files.

Verification

The tests cover description loading, schema and operation compilation, rendering, CLI behavior, and output ownership. A committed example SDK exercises the generated client and its PHP types. The SDK generator suite, static analysis, and formatting checks passed locally. Regenerating the example produced no changes.

View guided diff Turn on auto-fix

Note

Add OpenAPI SDK generator for Hypervel Saloon

  • Adds a full sdk-generator component: OpenAPI source loading (JSON/YAML, Swagger 2.0 through OpenAPI 3.2), normalization, schema compilation, and generation of Saloon connectors, requests, resources, DTOs, enums, forms, authentication, OAuth, pagination, and wire helpers from an SdkDefinition file
  • Includes a hypervel-sdk CLI (generate command) with --dry-run, --diff, --check, and --only options, backed by a staged OutputManager that validates prior manifest ownership before replacing generated output
  • Configuration is expressed through fluent builders (SdkDefinition, OpenApiSource, TypeMapping, Authentication, Pagination, and others) that validate and freeze into immutable configurations
  • Adds extensive test coverage across normalization, generation, rendering, output management, and the CLI, plus an AnalysedSdk fixture used for end-to-end and PHPStan type checks
  • Behavioral Change: Connector::prefersUrlQuery() (default false) and UrlResolver::withQuery() change query merging so existing URL query pairs can win over connector defaults for designated fallback keys; withQueryParameters now replaces matching keys instead of appending
  • Risk: SdkGenerator::generate() reads $previousManifest before assigning it, causing an undefined-variable warning and a null value passed to stage() in SdkGenerator.php

Macroscope summarized efb019d.

Generate connectors, resources, requests and typed data objects from local OpenAPI descriptions and a PHP definition. Support customization of operation selection, authentication, pagination and response types.

Expose the hypervel-sdk executable for generation, dry runs, diffs and drift checks. Track generated files in a manifest so regeneration can validate output ownership before replacing files. Register the component, executable and dependencies in Composer.
Cover description normalization, schema and operation compilation, PHP rendering, CLI behavior and output ownership. Exercise generated clients and data objects against the fixture API.

Keep an example SDK under maximum-level type analysis and compare its generated files and manifest with fresh CLI output. Add the fixture autoload paths and preserve the renderer’s exact output during formatting.
Explain how to install the generator, pin OpenAPI descriptions, define an SDK and regenerate it with the CLI. Include examples of resource grouping, request bodies, authentication, pagination and testing generated clients.

Link the guide from the package README and the documentation index.
@coderabbitai

coderabbitai Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

Share

@binaryfire

Copy link
Copy Markdown
Member Author

@cubic-dev-ai review

@cubic-dev-ai

cubic-dev-ai Bot commented Dec 1, 2026

Copy link
Copy Markdown

@cubic-dev-ai review

@binaryfire cubic can't start this review because your workspace has reached its free monthly review limit. cubic has reviewed 164,098 of the 160,000 allowed lines of code this month. Reviews resume on 10 December 2026 (in 9 days). Paid plans include much higher monthly review limits. Upgrade now to resume reviews.

To help optimise your usage, you can tune cubic to get the most out of your usage limits:

Learn more →

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Add an OpenAPI SDK generator for Hypervel Saloon

✨ Enhancement 🧪 Tests 📝 Documentation ⚙️ Configuration changes 🕐 40+ Minutes

Grey Divider

AI Description

• Adds hypervel/sdk-generator, a CLI that builds typed Saloon clients from local OpenAPI files.
• Generated files are tracked in a hash manifest, so regeneration refuses to overwrite unexpected
 edits.
• Adds a unit and integration suite, a committed example SDK checked for drift, and a guide.
Merge Risk 🟡 Medium

Blast radius 🔴 High 💥 3 capabilities

  • 3 affected capabilities span independent functional scopes: OpenAPI SDK generation integration, Saloon outbound HTTP request construction.
  • The changed repository merge and URL resolver jointly determine one end-to-end outbound request URL; the connector and request classes are implementation hops in that same bounded HTTP-client behavior.
  • Source loading, operation/schema compilation, rendering, manifest production, and transactional replacement jointly deliver one bounded outcome: a generated SDK tree.
  • They are not independent capabilities merely because they are separate classes.
  • Generated connectors and requests are the consumer side of the same bounded SDK-generation integration; their user outcome is a usable client produced from the source contract.
  • The Saloon runtime is a separate library scope and is represented by the separate Saloon capability.
Sources

src/saloon/src/Http/UrlResolver.php[102-125]

            $replaced = false;

            foreach ($keys as $key) {
                if ($name !== $key && ! str_starts_with($name, $key . '[')) {
                    continue;
                }

                if ($fallbacks === []) {
                    continue 2;
                }

                if (array_key_exists($key, $fallbacks)) {
                    unset($parameters[$key]);
                } else {
                    $replaced = true;
                }
            }

            if (! $replaced) {
                $retained[] = $pair;
            }
        }

        $query = http_build_query(StructuredDataNormalizer::forUrlEncoding($parameters), '', '&', PHP_QUERY_RFC3986);

src/sdk-generator/src/Console/GenerateCommand.php[62-89]

            $definitions = $this->definitions($input->getArgument('definition'));
            $this->ensureSeparateOutputs($definitions);
            $changes = [];

            foreach ($definitions as $definition) {
                $staged[] = $this->generator->generate($definition, $only);
            }

            foreach ($staged as $index => $sdk) {
                $changes[$index] = $this->outputManager->changes($sdk);
                $drift = $drift || $changes[$index] !== [];
                $this->summary($sdk, $changes[$index], $output);

                if ($input->getOption('diff')) {
                    foreach ($this->outputManager->diff($sdk, $changes[$index]) as $diff) {
                        $output->write($diff, options: OutputInterface::OUTPUT_RAW);
                    }
                }
            }

            if (! $check && ! $input->getOption('dry-run') && $only === null) {
                foreach ($staged as $index => $sdk) {
                    if ($this->outputManager->install($sdk, $changes[$index])) {
                        $installed[] = $sdk->package->output;
                        $output->writeln('Installed ' . $sdk->package->output, OutputInterface::OUTPUT_RAW);
                    }
                }
            }
Behavioral complexity 🔴 High 🧩 Multiple interactions

  • Before, this repository had no SDK-generator pipeline.
  • After, source documents are normalized and resolved through references, operations are selected and compiled with variants, pagination, security, media, schemas, and naming policies, then rendered and installed.
  • New correctness conditions are that source references and schema identity remain consistent across compilation, generated names and imports remain valid, selected variants preserve compatible request/response behavior, manifests match every generated file, and replacement/rollback preserves ownership and prior output.
  • The transactional output protocol introduces additional states: staged, validated, concurrently changed, installed, restored, or cleanup-failed; these are coordinated rather than routine helper reuse.
Sources

src/sdk-generator/src/Console/GenerateCommand.php[62-89]

            $definitions = $this->definitions($input->getArgument('definition'));
            $this->ensureSeparateOutputs($definitions);
            $changes = [];

            foreach ($definitions as $definition) {
                $staged[] = $this->generator->generate($definition, $only);
            }

            foreach ($staged as $index => $sdk) {
                $changes[$index] = $this->outputManager->changes($sdk);
                $drift = $drift || $changes[$index] !== [];
                $this->summary($sdk, $changes[$index], $output);

                if ($input->getOption('diff')) {
                    foreach ($this->outputManager->diff($sdk, $changes[$index]) as $diff) {
                        $output->write($diff, options: OutputInterface::OUTPUT_RAW);
                    }
                }
            }

            if (! $check && ! $input->getOption('dry-run') && $only === null) {
                foreach ($staged as $index => $sdk) {
                    if ($this->outputManager->install($sdk, $changes[$index])) {
                        $installed[] = $sdk->package->output;
                        $output->writeln('Installed ' . $sdk->package->output, OutputInterface::OUTPUT_RAW);
                    }
                }
            }
Potential damage 🟡 Medium 🩹 Incorrect results

  • A malformed final query can select the wrong remote records, pagination window, filter, or action parameter.
  • Reverting restores the previous URL construction for new requests; any externally triggered request effects may require application-specific correction.
  • Reverting the code prevents new incorrect requests.
  • Persisted or external effects caused by an incorrect request are not automatically repaired.
Sources

src/saloon/src/Http/UrlResolver.php[102-125]

            $replaced = false;

            foreach ($keys as $key) {
                if ($name !== $key && ! str_starts_with($name, $key . '[')) {
                    continue;
                }

                if ($fallbacks === []) {
                    continue 2;
                }

                if (array_key_exists($key, $fallbacks)) {
                    unset($parameters[$key]);
                } else {
                    $replaced = true;
                }
            }

            if (! $replaced) {
                $retained[] = $pair;
            }
        }

        $query = http_build_query(StructuredDataNormalizer::forUrlEncoding($parameters), '', '&', PHP_QUERY_RFC3986);
Assessed commit efb019d
Diagram

graph TD
  CLI["hypervel-sdk CLI"] --> Def["sdk.php definition"] --> Gen["SdkGenerator"] --> Compile["ModelCompiler (OpenAPI)"] --> Artifacts["ArtifactGenerator"] --> Render["PhpRenderer"] --> OM["OutputManager (stage, install)"] --> Out[("generated/ + manifest")]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Use openapi-generator (Java CLI) with PHP templates
  • ➕ Mature and widely used across many languages
  • ➕ Large set of existing spec-compatibility fixes
  • ➖ Requires a Java runtime in CI and developer machines
  • ➖ Output does not target Saloon or Hypervel Data without custom templates
  • ➖ Ownership and drift detection would still need to be built
2. Adopt an existing PHP OpenAPI client generator
  • ➕ Less code for the project to maintain
  • ➕ Existing community usage
  • ➖ Targets Guzzle or framework-agnostic clients, not Saloon connectors
  • ➖ Limited control over pagination and authentication mapping
  • ➖ Hypervel Data integration would be an adapter layer
3. Hand-written clients per provider
  • ➕ No generator to maintain
  • ➕ Simplest review and debugging
  • ➖ Does not scale across many operations
  • ➖ Drifts from provider specs with no detection mechanism

Recommendation: The PR's approach is reasonable: a PHP-native generator fits Hypervel's Saloon and Data packages and needs no Java or Node runtime. Its ownership model (manifest hashes, staged output, backup and rollback) is the strongest part of the design. Consider splitting future provider-specific quirks into definition configuration rather than generator code to keep the core small.

Files changed (24) +5081 / -1

Enhancement (8) +1428 / -0
hypervel-sdkStandalone CLI entry point without application boot +44/-0

Standalone CLI entry point without application boot

• Loads Composer autoload and wires the generator, model compiler, renderer, package validator and output manager. Runs the console application and returns exit code 2 on uncaught errors.

src/sdk-generator/bin/hypervel-sdk

SdkDefinition.phpFluent builder for SDK definitions +443/-0

Fluent builder for SDK definitions

• Provides SdkDefinition::make() with source, namespace, and configuration methods for types, responses, pagination, parameters and authentication. Builder state is generation-owned and provider files are not read until generation.

src/sdk-generator/src/SdkDefinition.php

SdkGenerator.phpOrchestrates compile, render and staged output +113/-0

Orchestrates compile, render and staged output

• Loads sdk.php as trusted PHP and freezes the definition. Compiles the model, generates artifacts and renders them. Validates package ownership and stages output without touching the installed tree.

src/sdk-generator/src/SdkGenerator.php

GenerateCommand.phpgenerate command with dry-run, diff, check and only modes +205/-0

generate command with dry-run, diff, check and only modes

• Resolves all definitions, rejects overlapping output paths, and stages every target before any install. Supports --dry-run, --diff, --check (exit 1 on drift) and a diagnostic --only that is never installed.

src/sdk-generator/src/Console/GenerateCommand.php

OutputManager.phpStaged, ownership-checked replacement of SDK output +294/-0

Staged, ownership-checked replacement of SDK output

• Stages output in a hidden sibling directory and verifies existing files against the manifest before any change. Installs by moving the old tree to a backup and restoring it if the swap fails. Rejects symlinks and untracked or modified files.

src/sdk-generator/src/Output/OutputManager.php

Manifest.phpManifest recording inputs, hashes and generated file ownership +176/-0

Manifest recording inputs, hashes and generated file ownership

• Writes .hypervel-sdk.json with the OpenAPI version, document hashes, applied source patches and definition hash. Records per-file xxh128 hashes so regeneration can detect edits to generated output.

src/sdk-generator/src/Output/Manifest.php

DocumentLoader.phpLoads local JSON and YAML OpenAPI documents +96/-0

Loads local JSON and YAML OpenAPI documents

• Reads Swagger 2.0 and OpenAPI 3.0 to 3.2 files from local disk, delegating YAML parsing to YamlLoader. Remote references are not fetched.

src/sdk-generator/src/OpenApi/DocumentLoader.php

PhpRenderer.phpRenders compiled artifacts to PHP source with php-parser +57/-0

Renders compiled artifacts to PHP source with php-parser

• Converts each generated artifact into formatted PHP source. Package validation runs before any file is written.

src/sdk-generator/src/Rendering/PhpRenderer.php

Tests (10) +2216 / -0
GenerateCommandTest.phpCLI behavior tests for generate modes +161/-0

CLI behavior tests for generate modes

• Covers dry-run, diff, check, and --only behavior, plus rejection of overlapping output targets.

tests/SdkGenerator/Console/GenerateCommandTest.php

OutputManagerTest.phpOutput ownership and rollback tests +349/-0

Output ownership and rollback tests

• Checks that modified, untracked or missing files block replacement. Also verifies that failed installs restore the previous tree.

tests/SdkGenerator/Output/OutputManagerTest.php

SdkGeneratorTest.phpEnd-to-end generator tests +390/-0

End-to-end generator tests

• Exercises the full pipeline from definition to staged output against fixture APIs.

tests/SdkGenerator/SdkGeneratorTest.php

sdk.phpExample definition for the committed analysed SDK +34/-0

Example definition for the committed analysed SDK

• Defines type mappings, response modes, and pagination strategies for each fixture operation. Exercises the feature set the generator supports.

types/SdkGenerator/AnalysedSdk/sdk.php

.hypervel-sdk.jsonCommitted manifest for the example SDK +101/-0

Committed manifest for the example SDK

• Records the source document hash, definition hash, requirements and per-file hashes. Used to confirm that regeneration produces no diff.

types/SdkGenerator/AnalysedSdk/generated/.hypervel-sdk.json

AnalysedSdkConnector.phpGenerated Saloon connector for the example SDK +186/-0

Generated Saloon connector for the example SDK

• Generated connector class wiring base URL, authentication and resource accessors. Not hand-edited.

types/SdkGenerator/AnalysedSdk/generated/AnalysedSdkConnector.php

PayloadData.phpGenerated data object with nested payload types +486/-0

Generated data object with nested payload types

• Generated Hypervel Data class for a response payload. Covers nested and enum-typed fields. Generated, so review by spot-checking.

types/SdkGenerator/AnalysedSdk/generated/Data/PayloadData.php

ListNextPaginator.phpGenerated paginator for link-header-driven listing +232/-0

Generated paginator for link-header-driven listing

• Generated paginator that follows next-link responses from the example API. Generated, so review by spot-checking.

types/SdkGenerator/AnalysedSdk/generated/Pagination/Next/ListNextPaginator.php

openapi.jsonFixture OpenAPI document for analysed SDK +270/-0

Fixture OpenAPI document for analysed SDK

• Provides the 3.1 description covering pagination styles, multipart and form bodies, enums, streaming and OAuth flows.

types/SdkGenerator/AnalysedSdk/resources/openapi.json

sdk.phpFixture definition using external PHP types +7/-0

Fixture definition using external PHP types

• Defines an SDK that maps schemas to hand-written classes in the fixture src directory.

tests/SdkGenerator/Fixtures/ExternalSdk/sdk.php

Documentation (2) +1359 / -0
documentation.mdLink SDK Generator guide from documentation index +1/-0

Link SDK Generator guide from documentation index

• Adds an entry for the SDK Generator guide to the documentation table of contents.

src/docs/documentation.md

sdk-generator.mdGuide for installing, defining and regenerating SDKs +1358/-0

Guide for installing, defining and regenerating SDKs

• Covers pinning OpenAPI descriptions, defining an SDK, regenerating with the CLI, and resource grouping, request bodies, auth, pagination and testing generated clients.

src/docs/sdk-generator.md

Other (4) +78 / -1
composer.jsonRegister SDK generator, bump php-parser, add nette/php-generator and sebastian/diff +11/-1

Register SDK generator, bump php-parser, add nette/php-generator and sebastian/diff

• Adds hypervel/sdk-generator as a self-version dependency and autoload entry. Adds nette/php-generator and sebastian/diff, and raises nikic/php-parser to ^5.8. Maps the fixture AnalysedSdk and ExternalSdk namespaces for tests, and exposes the hypervel-sdk binary.

composer.json

composer.jsonNew package manifest for hypervel/sdk-generator +63/-0

New package manifest for hypervel/sdk-generator

• Defines the package with a PSR-4 namespace for Hypervel\SdkGenerator, the hypervel-sdk bin, and runtime deps on Saloon, Data, Filesystem, Yaml, Symfony Console, nette/php-generator and sebastian/diff. Dev deps are testbench and testing.

src/sdk-generator/composer.json

phpstan.neon.distInclude SDK binary in PHPStan analysis +1/-0

Include SDK binary in PHPStan analysis

• Adds src/sdk-generator/bin/hypervel-sdk to the analysed paths so the executable is type checked.

phpstan.neon.dist

.php-cs-fixer.phpExclude generated fixture and include binary in formatting +3/-0

Exclude generated fixture and include binary in formatting

• Excludes the generated AnalysedSdk tree from the fixer, since it must match generator output byte for byte. Adds the hypervel-sdk binary to the fixer name list.

.php-cs-fixer.php

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Concurrent edits to generated files are lost ✓ Resolved Bug Reliability
Description
OutputManager::install() moves the existing output to a backup without rechecking its contents
against the manifest after changes() validated it. If another process creates or edits files
between validation and installation, the changed tree is replaced and its backup is discarded
without reporting the unexpected files.

Grey Divider

Tip of the day
💡 Did you know, you can pick a display mode instead of tweaking every Display option by hand

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@greptile-apps

greptile-apps Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Confidence Score: 5/5 Tier: plusRetriggerView in Greptile

[Medium impact] The PR appears safe to merge; the added naming guidance matches the generator.

Summary

Adds a standalone OpenAPI SDK generator for Hypervel Saloon, with typed data objects, authentication, pagination, and guarded regeneration.

  • A local API description and PHP definition can produce a typed Hypervel client.
  • Saloon request query values take precedence over matching defaults.

Review used source inspection. No tests were run.

Reviews (3) · Last reviewed commit: "Document resource naming on a shared SDK..." · Reviewed by Greptile

Comment thread src/sdk-generator/LICENSE.md Resolved
Honor each source namespace when naming models, resources, requests and
paginators. Compare list arms when sharing model declarations, preserve
list and object values from typed serializers, and validate discriminator
tags on map-backed values. Count nullable enum arms through nested groups
while retaining the enclosing nullable policy used by provider schemas.

Apply stream media preferences in declaration order and check that the
selected range can accept a response. Let generated connector defaults
fill missing query parameters while preserving caller-supplied wire
encoding, repeated values and numeric names. Serialize only the defaults
that will be sent.

Coordinate SDK installation across the output swap, validate the actual
displaced tree, and restore it if a late edit or a competing generation
changed the output. Exercise these cases and the generated contracts
through the compiler and runtime tests.

Align the component and analysed fixture dependency constraints, remove
the unrelated YAML license notice, and give the CI formatter workers
enough memory to check the expanded source tree.
@binaryfire

Copy link
Copy Markdown
Member Author

The installer now checks the displaced tree and restores it if a file changed or another generation installed first.

Explain how source namespaces and connector method names interact when multiple descriptions use the same resource tag. Show how a naming override scoped to the billing source exposes both resources with distinct accessors on the shared connector.
@binaryfire
binaryfire merged commit fa35345 into 0.4 Dec 1, 2026
59 of 61 checks passed
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.

1 participant