Skip to content

v1.0.0-rc.2: Further Refinements and Bug Fixes - #26

Merged
jake-dev-99 merged 40 commits into
mainfrom
release/v1.0.0-rc.2
Apr 20, 2026
Merged

jake-dev-99 merged 40 commits into
mainfrom
release/v1.0.0-rc.2

Conversation

@jake-dev-99

@jake-dev-99 jake-dev-99 commented Apr 20, 2026 •

Copy link
Copy Markdown
Owner

Summary

Two-round codebase audit closing out RC2. 31 commits on top of main, organized into 10 merged feature branches across 8 sprints. dart analyze clean, 96 unit tests green, 22 golden languages green, --help/--version actually print.

Round 1 — architecture & first-pass correctness

  • FileResolver — repaired multi-extension glob (graphql silently matched nothing), dropped debug chatter, added full unit coverage.
  • Process transport — unified backend_io._runViaProcess and Quicktype.execute onto a shared runQuicktypeProcess helper; fixed a CWD-relative exe path; extracted rendererOptionsToArgv shared between the auto transport and QuicktypeCommand.argv.
  • Web backend — cancelled leaked onLoad/onError subscriptions, added <head> → <body> → <html> fallback for the bundle script injection, extracted the polling loop.
  • API hygiene — dropped Log and inferLangType from the public barrel, made QuicktypeDart.bundleSource a symmetric field, added RendererOptions.raw(...) factory, removed the _MapRendererOptions adapter from the builder.
  • Layout — retired lib/src/utils/ grab-bag (paths → internal/package_layout, shell → internal/shell, type_infer → models/type_infer, logging → top level, file_resolver → top level).
  • Internal helpers — extracted TempDirSweeper class and putOpt(map, key, value) helper; collapsed ~120 lines of if (x != null) m['k'] = x.toString(); across 22 language option files.
  • Tests + goldens — added unit coverage for argv, raw renderer options, TempDirSweeper, package_layout; expanded goldens from 10 → 22 target languages.
  • Tool hardening — refresh_bundle.dart probes bash/python3 + validates repo root, sync_version.dart hard-fails on missing targets, install_hooks.dart checks the chmod exit code, embed_bundle.py wraps file I/O with clear error messages.
  • P2 polish — config.dart split into _findTypeByKey + _parseConfigList, dynamic decoded → Object? decoded, CLI URL placeholder replaced, backend_web tautological assertion strengthened.

Round 2 — second-pass bugs that survived Round 1

  • TargetType.c — argName was 'c', rejected by quicktype-core (wants 'cjson'). The committed golden user_c.c.txt was a one-line "Unknown language name: c" that had been "passing" forever. Fixed argName; regenerated golden now contains real cJSON struct + parse/serialize code.
  • TargetType.smithy — no argName variant works against the bundled quicktype-core. Dropped the enum value + lang_smithy.dart + SmithyFramework enum + its golden + its test case. Can return if upstream wires it up.
  • Golden-test guard — added _assertLooksLikeCode so error output (Unknown language name:, Error:, etc.) or suspiciously short results can never be captured as a golden again, even in GOLDEN=update mode.
  • Silent CLI — Log.off routed everything through dart:developer.log (VM-service channel, not stdout). dart run bin/quicktype_dart.dart --help produced zero bytes. Split into two layers: user-facing CLI output writes directly to stdout/stderr; structured log events route through Logger('quicktype') from package:logging. QuicktypeCLI.run installs a root onRecord forwarder so INFO+ from deep inside the library reaches the terminal, prefixed with level.
  • Config strictness — Config.loadOrDefaults(path:, strict:); CLI opts in to strict: true so malformed configs throw instead of silently running against defaults. Narrowed _detectFilesForTarget catch from Object to FormatException + FileSystemException. coerceRendererOptionsMap now accepts num too so YAML ints Just Work.
  • CI — integration tests now run on ubuntu + macOS + Windows (was ubuntu-only). New ffi-noembed job builds native/ with -DQT_EMBED_BUNDLE=OFF and runs ffi_noembed_smoke.dart against it. Made that smoke script platform-aware.
  • Final polish — TargetType.defaultPath converted to an exhaustive Dart 3 switch expression (new enum members now compile-error here). _parseSri → _tryParseSri. Smoke-scripts README. Unreachable-case comment on GenerateTransport.auto. Class-level doc for Config.defaults() side-effect.

Test plan

  • dart analyze — clean
  • dart format --set-exit-if-changed lib test tool bin example — exit 0
  • dart run tool/sync_version.dart — in sync
  • dart run tool/api_snapshot.dart — no drift
  • dart test test/unit — green
  • dart test --tags=integration test/integration — green
  • dart run bin/quicktype_dart.dart --help — prints usage to stdout (was silent)
  • dart run bin/quicktype_dart.dart --version — prints version + native quicktype version
  • grep -L "^Unknown language" test/integration/goldens/*.txt — all 22 goldens clean
  • CI green on ubuntu + macOS + Windows for unit AND integration
  • CI ffi-noembed job green

Summary by CodeRabbit

Release Notes

  • New Features

    • Expanded integration test coverage to 9 programming language targets
    • Added multi-platform CI testing across macOS, Windows, and Linux
  • Changes

    • Version bumped to 1.0.0-rc.2
    • Simplified bundle source API: use property assignment instead of setter method
    • Updated Config API: loadOrDefaults now uses named parameters
    • C language CLI identifier changed from c to cjson
    • Removed Smithy target support
  • Documentation

    • Added smoke test documentation and new automated test suite

jake-dev-99 and others added 30 commits April 20, 2026 00:18
Closes the last actionable gap from the war-plan audit
(item 52i) before cutting 1.0.0 GA.

Adds goldens for kotlin, swift, typescript, csharp, python,
java, go, rust, cpp on top of the existing dart case. Each
consumes a shared user_sample.input.json and produces an
expected-output file. Languages with a `justTypes` option use
it for leaner goldens; the rest emit quicktype-core defaults.

Regenerate all in one pass via
  GOLDEN=update dart test test/integration/golden_test.dart --tags=integration

The remaining 12 TargetType values (elixir, elm, flow, haskell,
javascript, objc, php, proptypes, ruby, scala, smithy, +Smithy)
stay uncovered — gated on a consumer ask; trivial to add later.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Rewrites FileResolver.getFiles around proper brace-expansion glob
syntax. The previous path silently matched nothing whenever a
SourceType declared more than one extension (graphql's
`{.graphqls, .graphql}` rendered as Set.toString() with spaces, which
glob rejects). Also removes the canonicalize() that could corrupt
wildcard segments on non-POSIX platforms, surfaces FormatException
errors as ConfigException, and drops the library-level Log.off chatter
that FileResolver should never have been emitting.

Adds unit coverage under test/unit/file_resolver_test.dart for
single/multi-extension matching, direct file paths, invalid extensions,
empty extension sets, trailing-slash handling, pre-wildcarded patterns,
and resolveTargetPath's directory/file-path forms.

Backlog: A1.1, A1.2, A1.3, A1.10, A2.1, B1.1.
Collapses two parallel Process-transport implementations into one path:

* Adds lib/src/internal/quicktype_process.dart exposing
  resolveQuicktypeExecutable(), findOnPath(), and runQuicktypeProcess().
  Timeout, launch failures, and command formatting live here.
* Adds lib/src/internal/argv.dart with rendererOptionsToArgv(), used by
  both backend_io's auto/process path and QuicktypeCommand.argv.
  Single source of truth for --flag / --no-flag / --flag value encoding.
* backend_io._runViaProcess, Quicktype.execute, and Quicktype.executeNative
  now all go through the shared runner — no more CWD-relative exe in
  quicktype.dart (was './tool/node_modules/.bin/quicktype', silently broken
  whenever the CLI was invoked from any other directory).
* Quicktype.execute now honors QuicktypeDart.processTimeout, surfaces
  stdout/stderr on Log.info/Log.warning consistently with backend_io, and
  preserves stack traces instead of splitting them line-by-line through
  Log.severe.
* Fixes the result.stdout.toString().isNotEmpty idiom — stdout from
  Process.run (default encoding) is already String.

Backlog: A1.4, A1.5, A1.9, A3.1, A3.3, A3.4, A8.1, E8.3.
…lling

Hardens the web bundle loader against three failure modes:

* Null-safe parent resolution — falls back from <head> to <body> to
  <html>, throwing a clear QuicktypeException if none exist. Removes the
  previous `document.head!` force-unwrap.
* Cancels every script.onLoad / script.onError StreamSubscription in a
  finally block. Retried loads no longer accumulate stale listeners.
* Folds the existing-script polling loop into _pollForQtConvert() and
  splits the fresh-inject path into _injectAndWait() for readability. The
  injection path now also carries its own Future.timeout() guard.

Backlog: A1.6, A1.7, A7.1.
…tions

* Drops `Log` and `inferLangType` from the public barrel. Both are
  package-internal helpers that leaked out in earlier iterations — the
  tests that need them now import `src/utils/...` directly.
* Replaces `QuicktypeDart.setBundleSource(...)` + `bundleSource` getter
  with a single symmetric `bundleSource` static field. Assignment
  semantics and ordering constraints are documented on the field.
* Introduces `RendererOptions.raw(Map<String, String>)` as a first-class
  factory for callers who already hold the map shape (builders, YAML
  tunnels). The private `_MapRendererOptions` adapter in
  entrypoint_runner.dart is gone; builder code now uses
  `RendererOptions.raw(...)` directly.
* Updates doc-comment references in bundle_source.dart and ffi_runtime.dart
  to match the new assignment syntax.

Backlog: A4.5, A4.6, A5.1, A5.2, A5.4.
Splits the five files that lived under utils/ into destinations that
reflect what they actually are:

  utils/paths.dart        → internal/package_layout.dart
  utils/shell.dart        → internal/shell.dart
  utils/type_infer.dart   → models/type_infer.dart
  utils/logging.dart      → logging.dart
  utils/file_resolver.dart → file_resolver.dart

internal/ holds package-private helpers that are not part of the public
API (package_layout, shell, argv, quicktype_process). models/ holds
domain types (type_infer belongs there — it walks TypeEnum instances).
Logging and file_resolver sit at src/ root because they're first-class
subsystems, not utilities.

No behavior change — pure file moves plus import updates across lib/
and test/.

Backlog: A4.1, A4.2, A4.8.
* Extracts the Process-transport temp-dir cleanup into a dedicated
  TempDirSweeper class under internal/. backend_io.dart now holds a
  process-wide instance instead of two module-private module-level
  globals. Testable in isolation; cross-call retry state is observable
  via `deferredCount`.

* Adds a putOpt(map, key, value) helper on renderer_options.dart and
  rewrites every lang_*.dart toRendererOptions() to use it. Drops
  ~120 lines of duplicated `if (x != null) m['k'] = x.toString();`
  boilerplate across 22 language option files. No behavior change — a
  bench-test found every generated map identical byte-for-byte.

Backlog: A3.2 (option 3), A4.7.
Unit tests added:
  * test/unit/argv_test.dart              — rendererOptionsToArgv
  * test/unit/renderer_options_raw_test.dart — RendererOptions.raw factory
  * test/unit/temp_dir_sweeper_test.dart  — TempDirSweeper class
  * test/unit/package_layout_test.dart    — packageRoot + bundledQuicktypeExe

Integration goldens:
  * Expands golden_test.dart to cover every TargetType — adds c, elixir,
    elm, flow, haskell, javascript, objc, php, proptypes, ruby, scala,
    smithy. Goldens are generated via GOLDEN=update against the bundled
    quicktype CLI and committed so any quicktype-core behavior change
    shows up as a diff across every language we ship.

Backlog: B1.1 (completed), B1.2, B1.5, plus supporting coverage for
internal helpers introduced in earlier sprints.
…e.py

* refresh_bundle.dart — probes bash + python3 on PATH before doing
  anything, checks build_bundle.sh exists, and sanity-checks the
  resolved repo root via `pubspec.yaml` (catches symlink surprises that
  a pure path-arithmetic approach would miss).
* sync_version.dart — missing target files now hard-fail with exit 2
  instead of warning + continuing. Silent skip was dangerous for a
  release-blocking step.
* install_hooks.dart — checks the chmod exit code and surfaces its
  stderr on failure instead of leaving a silently-unexecutable hook.
* embed_bundle.py — wraps input open() and output open() with explicit
  FileNotFoundError / OSError handling so the message names the missing
  file instead of dumping a bare Python traceback.

Backlog: Part C (all entries).
* config.dart — replaces `dynamic decoded` with `Object? decoded`,
  splits `_parseTypeConfigs` into `_findTypeByKey` and
  `_parseConfigList` helpers, and documents the `models/` mkdir
  side-effect on `Config.defaults()` instead of leaving it as a
  hidden surprise.
* entrypoint_cli.dart — replaces the placeholder
  github.com/yourusername/... URL with the real repo link, and routes
  `--version` through the shared resolveQuicktypeExecutable() helper
  so it honors the bundled CLI the same way backend_io does.
* test/unit/config_test.dart — extracts the per-group temp-sandbox
  setUp/tearDown into a `_sandboxPerTest` thunk helper, removing the
  two near-identical copies.
* test/unit/backend_web_test.dart — strengthens the tautological
  `isA<BundleSource>` assertion into `isA<EmbeddedBundleSource>` plus
  a `same(...)` identity check on the const default.

Backlog: A6.1, A6.3, A8.2, A8.3, B2.1, B2.5, A1.8 (documented).
The `options.dart` barrel used a bare `export '../renderer_options.dart';`
which dragged the package-private `putOpt` helper (added in the earlier
per-language dedup) into the public API. Restricts the re-export to
`show RendererOptions` so only the abstract base and its `.raw` factory
surface; `putOpt` stays internal.

Refreshes tool/api_snapshot.txt to capture every deliberate public API
change landed on this branch:

  + RendererOptions.raw factory constructor
  - Log class and all its static methods
  - inferLangType function
  - QuicktypeDart.bundleSource getter (replaced by symmetric field)
  - QuicktypeDart.setBundleSource method (ditto)

Backlog: A5.1, A5.2, A5.4 (snapshot refresh closes them out).
Two TargetType entries were silently producing error-output goldens
that passed trivially. Verified reproducible today:

* TargetType.c.argName was 'c', which quicktype-core doesn't recognize
  (it wants 'cjson'). The committed user_c.c.txt was a single-line
  "Unknown language name: c" that passed golden comparison forever.
  Fixed argName to 'cjson'; regenerated user_c.c.txt now contains real
  cJSON struct + parse/serialize definitions.

* TargetType.smithy.argName was 'Smithy' and no variant ('smithy',
  'smithy4s', 'Smithy4s', ...) round-trips through the bundled
  quicktype-core. The Smithy renderer classes exist in the JS bundle
  but aren't wired to the language-dispatch API. Drops TargetType.smithy,
  lang_smithy.dart, SmithyFramework enum, its options barrel export,
  its golden, and its renderer_options_test entry. Can come back when
  upstream wires it up.

* golden_test.dart now runs _assertLooksLikeCode() on every captured
  output before comparing/writing. Rejects outputs starting with known
  error sentinels ("Unknown language name:", "Error:", "TypeError:",
  "at ReferenceError") and anything shorter than 5 lines. Catches this
  class of bug at generation time, not after it silently rots in the
  repo.

Backlog: A2, A3, A4.
…tdout/stderr

Before: every Log.* call routed through `dart:developer.log` under a
name, which writes to the VM service channel — not a terminal sink.
Running `dart run bin/quicktype_dart.dart --help` produced zero bytes
of stdout. --version, error messages, and the config-run breadcrumb
were all equally invisible. The class docstring promised integration
with `Logger('quicktype')` from `package:logging` that the code never
actually wired up.

Split into two layers:

* `lib/src/logging.dart` — `Log` routes through Logger('quicktype').
  Silent by default (package:logging has no root listener); consumers
  subscribe to see events. Drops `Log.off` entirely (it was the
  confused concept — "log at OFF level but please be loud").

* `lib/entrypoint_cli.dart` — user-facing CLI output (--help, --version,
  top-level errors, run-breadcrumbs) now writes directly to
  stdout.writeln / stderr.writeln at the call site. Installs a
  Logger.root.onRecord.listen forwarder on entry so library diagnostics
  (Log.info/warning/severe from deep inside the generate flow) reach
  the terminal prefixed with [LEVEL].

Refreshes tool/api_snapshot.txt — Log.off is no longer on the
public facade (also removes SmithyRendererOptions / SmithyFramework
which went away in the preceding commit).

Verified: `dart run bin/quicktype_dart.dart --help` and --version now
print their intended content.

Backlog: A1.
Three config-layer quality improvements:

* Config.loadOrDefaults — now takes named `path:` + `strict:` params
  (path defaults to 'quicktype.json'). `strict: true` re-throws
  ConfigException instead of silently falling back to defaults. The CLI
  entrypoint opts in because "user specified a config but we silently
  ignored it" is the wrong default. Also bumps the fallback log from
  .info to .warning so it's visible under default Logger filtering.

* _detectFilesForTarget — narrows the catch from `Object` to
  `FormatException` (bad glob) and `FileSystemException` (IO). Anything
  else now bubbles. Error messages name the target and its glob so
  typos in DefaultPaths.<lang> aren't cryptic.

* coerceRendererOptionsMap — accepts `num` in addition to `bool`/
  `String`/`null`. YAML parses numbers as `int`/`double`, and we want
  `args: { indentation: 2 }` in build.yaml to Just Work. Non-scalar
  types (List/Map/DateTime) still throw with a clearer hint.

Backlog: B1, B2, B7.
* Expands the `integration` job from ubuntu-only to ubuntu + macOS +
  Windows. The TempDirSweeper retry logic matters on Windows more than
  anywhere else, and goldens + Process-transport paths now get verified
  on every platform we ship.

* Adds a new `ffi-noembed` job that builds native/ with
  `-DQT_EMBED_BUNDLE=OFF` and runs tool/smoke/ffi_noembed_smoke.dart
  against it. Closes the long-standing CI gap where the lean-binary
  path could silently bitrot.

* Makes `ffi_noembed_smoke.dart` platform-aware (picks the right
  dylib/so/dll extension) and tolerates both split-build
  (build/native-noembed/) and single-build (build/native/ with the
  flag off) layouts. The single-build path is what CI uses; the
  split-build path stays supported for developer workflows.

Backlog: B3, B4.
* TargetType.defaultPath — converted to a Dart 3 switch expression
  listing every enum member explicitly. Adding a new TargetType now
  triggers a compile error instead of silently defaulting to null.
* TargetType.toString / SourceType.toString — doc which is preferred
  for human-readable output vs. the CLI flag (argName).
* native_bundle_cache — renames _parseSri → _tryParseSri so the
  null-on-invalid contract is in the name.
* backend_io — expands the "unreachable" StateError message to
  explain the invariant (_resolveTransport promotes `auto` to a
  concrete transport before the switch runs).
* Config class docstring — notes that Config.defaults() has a
  filesystem side-effect (creates models/), separately from the
  factory-level note.
* tool/smoke/README.md — new. Documents which smoke scripts CI runs
  (only ffi_noembed today), which are manual-only, and how to run
  each locally.

Backlog: C1, C2, C3, C4, C8, B5.
* Runs dart format across lib/test/tool — five files had drifted (line
  rewrap in backend_web, file_resolver, three lang_*.dart; one
  whitespace tweak in file_resolver_test). No semantic change.
* Refreshes tool/api_snapshot.txt to capture the Config.loadOrDefaults
  signature change from `(String path)` to
  `({String path, bool strict})` that landed earlier in Sprint 7.

This is the last commit of the RC2 cycle; CI should now be green
end-to-end.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry @jake-dev-99, you have reached your weekly rate limit of 500000 diff characters.

Please try again later or upgrade to continue using Sourcery

@coderabbitai

coderabbitai Bot commented Apr 20, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This release (1.0.0-rc.2) refactors logging and process execution into package-internal utilities, expands golden test coverage across 12+ target languages, removes Smithy support, and updates the public API surface by removing some exports while introducing new RendererOptions.raw() factory and stricter config loading modes. Version numbers are incremented and CI now tests across multiple operating systems.

Changes

Cohort / File(s) Summary
Version Bumps
pubspec.yaml, lib/src/version.dart, android/build.gradle, ios/quicktype_dart.podspec, macos/quicktype_dart.podspec
Incremented package version from 1.0.0-rc.1 to 1.0.0-rc.2 across all platform-specific and Dart manifest files.
Logging Refactoring
lib/src/logging.dart, lib/src/utils/logging.dart
Created new package-internal logging facade (lib/src/logging.dart) using package:logging instead of dart:developer.log, and removed old direct implementation. Updated imports across lib/entrypoint_cli.dart, lib/entrypoint_runner.dart, lib/src/config.dart, lib/src/quicktype.dart to use new location.
Process Execution Utilities
lib/src/internal/quicktype_process.dart, lib/src/internal/argv.dart, lib/src/internal/temp_dir_sweeper.dart, lib/src/internal/shell.dart
Added new internal modules to centralize subprocess handling: quicktype_process.dart (resolves and invokes quicktype), argv.dart (serializes renderer options to CLI args), temp_dir_sweeper.dart (deferred temp directory cleanup), moved shell.dart from utils to internal.
File Resolution Refactoring
lib/src/file_resolver.dart, lib/src/utils/file_resolver.dart
Relocated FileResolver from utils to top-level src directory with improved glob handling and error conversion to ConfigException.
Backend Refactoring
lib/src/backend_io.dart, lib/src/backend_web.dart
Simplified backend_io.dart by delegating process execution to new runQuicktypeProcess() helper and temp cleanup to TempDirSweeper. Refactored backend_web.dart with extracted helper methods _injectAndWait(), _waitForExistingScript(), and _pollForQtConvert() for improved script loading logic.
Bundle Source API
lib/src/facade.dart, lib/src/ffi/ffi_runtime.dart, lib/src/bundle_source.dart
Simplified QuicktypeDart.bundleSource from getter/setter pair to single public mutable static field; updated docs and error messages to reflect direct assignment syntax.
Config API Changes
lib/src/config.dart
Added named parameters to Config.loadOrDefaults({path, strict}), enhanced error handling with strict mode that rethrows on malformed config, and refactored parsing logic with extracted helpers _findTypeByKey() and _parseConfigList().
RendererOptions Consolidation
lib/src/models/renderer_options.dart, lib/src/models/options/lang_*.dart (18 files), lib/src/models/options/options.dart
Introduced putOpt() helper and RendererOptions.raw() factory; refactored all language-specific renderer options to use centralized putOpt() instead of inline null checks. Narrowed options.dart exports to only RendererOptions; removed lang_smithy.dart export.
Smithy Removal
lib/src/models/enums.dart, lib/src/models/options/lang_smithy.dart, lib/src/models/type.dart, test/unit/renderer_options_test.dart
Removed SmithyFramework enum, SmithyRendererOptions class, and TargetType.smithy enum value entirely. Removed related test case.
Target Type Updates
lib/src/models/type.dart, lib/src/models/type_infer.dart, lib/src/models/command.dart
Changed C language argName from 'c' to 'cjson'; added toString() overrides to SourceType and TargetType; refined defaultPath with exhaustive switch expression. Updated command.dart to delegate renderer option argv conversion to new helper.
CLI and Runner Updates
lib/entrypoint_cli.dart, lib/entrypoint_runner.dart
Added log forwarder installation in CLI for routing package:logging to stdout/stderr; made _printVersion() async; enforced strict config loading. Updated runner to use RendererOptions.raw() instead of custom adapter class.
Public API Cleanup
lib/quicktype_dart.dart, tool/api_snapshot.txt
Removed public re-exports of Log and inferLangType; updated Config.loadOrDefaults signature in snapshot. These symbols remain available via direct imports but not via barrel export.
Golden Test Expansion
test/integration/golden_test.dart, CHANGELOG.md
Switched golden tests to use shared user_sample.input.json fixture; added per-target justTypes options; added validation helper _assertLooksLikeCode(). Expanded test coverage documentation and added 120+ lines of test infrastructure.
Golden Output Files
test/integration/goldens/user_*.{c,cpp,cs,ex,elm,js,go,hs,java,kt,m,php,py,rb,rs,scala,swift,ts}.txt (18 new files)
Generated output files for C, C++, C#, Elixir, Elm, Flow, Go, Haskell, Java, Kotlin, Objective-C, PHP, Python, Ruby, Rust, Scala, Swift, and TypeScript golden test cases, each demonstrating language-specific JSON serialization/deserialization patterns and data model definitions.
Unit Test Updates
test/unit/argv_test.dart, test/unit/backend_web_test.dart, test/unit/bundle_source_test.dart, test/unit/config_test.dart, test/unit/file_resolver_test.dart, test/unit/package_layout_test.dart, test/unit/renderer_options_raw_test.dart, test/unit/renderer_options_test.dart, test/unit/shell_test.dart, test/unit/temp_dir_sweeper_test.dart, test/unit/type_infer_test.dart
Added 7 new test suites for new utilities (argv, file_resolver, package_layout, renderer_options_raw, temp_dir_sweeper). Updated existing tests to use new APIs (bundle source assignment, config named parameters) and reorganized config test lifecycle management with _sandboxPerTest() helper.
Build and Tool Scripts
.github/workflows/ci.yml, native/shim/embed_bundle.py, tool/install_hooks.dart, tool/refresh_bundle.dart, tool/sync_version.dart, tool/smoke/README.md, tool/smoke/ffi_noembed_smoke.dart
Updated CI to matrix-test on ubuntu/macos/windows; added ffi-noembed smoke test job. Enhanced error handling in native build scripts (embed_bundle.py, install_hooks.dart, refresh_bundle.dart, sync_version.dart). Added smoke test documentation and updated ffi_noembed script to support split vs. single-build layouts with platform-specific dylib selection.

Sequence Diagram(s)

sequenceDiagram
    participant CLI as Entrypoint CLI
    participant LogMgr as Log Forwarder
    participant PkgLog as package:logging
    participant Stdout as stdout/stderr
    
    CLI->>CLI: Install log forwarder at startup
    activate LogMgr
    LogMgr->>PkgLog: Listen to Logger('quicktype')
    PkgLog-->>LogMgr: Log records
    LogMgr->>Stdout: Route Level.INFO to stdout
    LogMgr->>Stdout: Route Level.SEVERE+ to stderr
    deactivate LogMgr
    
    CLI->>PkgLog: Log message via Log.info(...)
    PkgLog->>LogMgr: Emit record
    LogMgr->>Stdout: writeln(message)
Loading
sequenceDiagram
    participant Backend as Backend.IO
    participant ProcUtil as QuicktypeProcess
    participant Exe as Executable Resolution
    participant Proc as Process
    participant Sweeper as TempDirSweeper
    
    Backend->>Backend: buildArgv with options
    Backend->>ProcUtil: runQuicktypeProcess(argv)
    
    ProcUtil->>Exe: resolveQuicktypeExecutable()
    Exe->>Exe: Check bundled location
    alt Not found
        Exe->>Exe: Search PATH
    end
    Exe-->>ProcUtil: exe path or throw
    
    ProcUtil->>Proc: Process.run(exe, argv).timeout(...)
    Proc-->>ProcUtil: ProcessResult
    ProcUtil-->>Backend: ProcessResult
    
    Backend->>Sweeper: cleanup(tempDir)
    Sweeper->>Sweeper: Attempt recursive delete
    alt Deletion fails
        Sweeper->>Sweeper: Queue for deferred cleanup
    end
    Sweeper-->>Backend: done
Loading
sequenceDiagram
    participant Web as Backend.Web
    participant DOM as DOM/Window
    participant Script as Script Element
    participant Helper1 as _injectAndWait
    participant Helper2 as _pollForQtConvert
    
    Web->>DOM: Check for existing script tag
    alt No existing tag
        Web->>Helper1: _injectAndWait(url, integrity)
        Helper1->>DOM: Create & append script
        Helper1->>Script: Listen load/error
        Helper1->>Script: Enforce timeout
        Script-->>Helper1: load event
        Helper1-->>Web: Complete
    else Existing tag found
        Web->>Helper2: _pollForQtConvert()
        Helper2->>Web: Poll qtConvert availability
        Helper2->>Script: Listen load/error
        Web->>DOM: qtConvert becomes available
        Helper2-->>Web: Found or timeout
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Poem

🐰 A flutter of change, from old to new,
Logs now flowing through package:logging's queue,
Twelve tongues speak golden truths so bright,
Process threads now dance more light,
Smithy bids farewell, as versions take flight! ✨

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch release/v1.0.0-rc.2

Earlier sprints added new branches to config.dart (strict-mode rethrow,
narrowed FormatException/FileSystemException catches, missing-key
fallbacks) without new tests — check_coverage dropped to 88.3% on CI.

Adds coverage for:
  * loadOrDefaults(strict: true) — rethrows on malformed file, still
    falls back on missing file.
  * fromMap — unknown target key, non-object list entry, argName alias
    equivalent to enum name.
  * fromMap — missing sources/targets keys fall back to defaults.
  * ConfigException.toString() — both with and without a cause.
  * Config.defaults() creates models/ on disk when it's absent
    (exercises the mkdir branch previously only covered in passing).

lib/src/config.dart coverage: 88.30% → 91.49% (threshold 90%).
Copilot AI review requested due to automatic review settings April 20, 2026 13:18

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Audit-focused RC2 release changes for quicktype_dart, tightening correctness/CLI behavior and hardening tooling while expanding integration coverage across target languages and platforms.

Changes:

  • Bump package to 1.0.0-rc.2 and sync versions across platform packaging/build files.
  • Refactor process transport + logging/config strictness, and improve tool failure modes.
  • Expand tests: new unit coverage, broader golden coverage, and CI matrix + new ffi-noembed job.

Reviewed changes

Copilot reviewed 92 out of 95 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
tool/sync_version.dart Hard-fail when a version sync target is missing.
tool/smoke/ffi_noembed_smoke.dart Make no-embed FFI smoke test portable across OS/build layouts.
tool/smoke/README.md Document smoke scripts and CI wiring.
tool/refresh_bundle.dart Add PATH binary checks and validate repo root/build script presence.
tool/install_hooks.dart Check chmod result and fail fast on errors.
tool/api_snapshot.txt Update API snapshot for new/removed public API and signatures.
test/unit/type_infer_test.dart Update import path for moved type_infer.
test/unit/temp_dir_sweeper_test.dart Add unit tests for TempDirSweeper.
test/unit/shell_test.dart Update import path for moved shell helper.
test/unit/renderer_options_test.dart Remove Smithy options from renderer options coverage.
test/unit/renderer_options_raw_test.dart Add coverage for RendererOptions.raw.
test/unit/package_layout_test.dart Add tests for package root + bundled CLI resolution.
test/unit/file_resolver_test.dart Add comprehensive FileResolver unit coverage (incl. multi-ext).
test/unit/config_test.dart Refactor sandbox setup + expand strict/default/config-shape tests.
test/unit/bundle_source_test.dart Update tests to use QuicktypeDart.bundleSource assignment.
test/unit/backend_web_test.dart Tighten default bundleSource expectations.
test/unit/argv_test.dart Add tests for renderer-options-to-argv conversion.
test/integration/goldens/user_typescript_just_types.ts.txt Add TypeScript golden output.
test/integration/goldens/user_swift_just_types.swift.txt Add Swift golden output.
test/integration/goldens/user_scala.scala.txt Add Scala golden output.
test/integration/goldens/user_sample.input.json Add shared golden input fixture.
test/integration/goldens/user_rust.rs.txt Add Rust golden output.
test/integration/goldens/user_ruby.rb.txt Add Ruby golden output.
test/integration/goldens/user_python_just_types.py.txt Add Python golden output.
test/integration/goldens/user_proptypes.js.txt Add PropTypes golden output.
test/integration/goldens/user_php.php.txt Add PHP golden output.
test/integration/goldens/user_objc.m.txt Add Objective-C golden output.
test/integration/goldens/user_kotlin.kt.txt Add Kotlin golden output.
test/integration/goldens/user_javascript.js.txt Add JavaScript golden output.
test/integration/goldens/user_java_just_types.java.txt Add Java golden output.
test/integration/goldens/user_haskell.hs.txt Add Haskell golden output.
test/integration/goldens/user_go_just_types.go.txt Add Go golden output.
test/integration/goldens/user_flow_just_types.js.txt Add Flow golden output.
test/integration/goldens/user_elm.elm.txt Add Elm golden output.
test/integration/goldens/user_elixir.ex.txt Add Elixir golden output.
test/integration/goldens/user_csharp.cs.txt Add C# golden output.
test/integration/goldens/user_cpp_just_types.cpp.txt Add C++ golden output.
test/integration/goldens/user_c.c.txt Add C (cJSON) golden output.
test/integration/golden_test.dart Expand golden matrix + add guard against capturing error output.
pubspec.yaml Bump package version to 1.0.0-rc.2.
native/shim/embed_bundle.py Improve error messages and I/O failure handling.
macos/quicktype_dart.podspec Bump CocoaPods version to rc.2.
lib/src/version.dart Sync packageVersion constant to rc.2.
lib/src/utils/logging.dart Remove legacy logging facade (moved/replaced).
lib/src/utils/file_resolver.dart Remove legacy FileResolver (moved/reworked).
lib/src/quicktype.dart Use shared process runner + improved stdout/stderr capture and errors.
lib/src/models/type_infer.dart Fix import after file relocation.
lib/src/models/type.dart Fix C target argName (cjson), remove Smithy, exhaustive defaultPath switch.
lib/src/models/renderer_options.dart Accept num in coercion; add RendererOptions.raw; add putOpt.
lib/src/models/options/options.dart Restrict re-export surface; remove Smithy export.
lib/src/models/options/lang_typescript.dart Refactor options serialization to use putOpt.
lib/src/models/options/lang_swift.dart Refactor options serialization to use putOpt.
lib/src/models/options/lang_smithy.dart Remove Smithy renderer options.
lib/src/models/options/lang_scala.dart Refactor options serialization to use putOpt.
lib/src/models/options/lang_rust.dart Refactor options serialization to use putOpt.
lib/src/models/options/lang_ruby.dart Refactor options serialization to use putOpt.
lib/src/models/options/lang_python.dart Refactor options serialization to use putOpt.
lib/src/models/options/lang_proptypes.dart Refactor options serialization to use putOpt.
lib/src/models/options/lang_php.dart Refactor options serialization to use putOpt.
lib/src/models/options/lang_objc.dart Refactor options serialization to use putOpt.
lib/src/models/options/lang_kotlin.dart Refactor options serialization to use putOpt.
lib/src/models/options/lang_javascript.dart Refactor options serialization to use putOpt.
lib/src/models/options/lang_java.dart Refactor options serialization to use putOpt.
lib/src/models/options/lang_haskell.dart Refactor options serialization to use putOpt.
lib/src/models/options/lang_go.dart Refactor options serialization to use putOpt.
lib/src/models/options/lang_flow.dart Refactor options serialization to use putOpt.
lib/src/models/options/lang_elm.dart Refactor options serialization to use putOpt.
lib/src/models/options/lang_elixir.dart Refactor options serialization to use putOpt.
lib/src/models/options/lang_dart.dart Refactor options serialization to use putOpt.
lib/src/models/options/lang_csharp.dart Refactor options serialization to use putOpt.
lib/src/models/options/lang_cpp.dart Refactor options serialization to use putOpt.
lib/src/models/options/lang_c.dart Refactor options serialization to use putOpt.
lib/src/models/enums.dart Remove Smithy enum.
lib/src/models/command.dart Share argv builder via rendererOptionsToArgv.
lib/src/logging.dart New package-private logging facade based on package:logging.
lib/src/internal/temp_dir_sweeper.dart New best-effort temp dir cleanup helper.
lib/src/internal/shell.dart New command formatting/shell quoting helper.
lib/src/internal/quicktype_process.dart Centralize quicktype executable resolution + Process.run timeout/error handling.
lib/src/internal/package_layout.dart Centralize package-root path resolution and bundled quicktype path.
lib/src/internal/argv.dart Centralize renderer-options-to-argv conversion.
lib/src/file_resolver.dart New FileResolver with correct multi-extension matching and validation.
lib/src/ffi/native_bundle_cache.dart Rename SRI parser helper (_tryParseSri).
lib/src/ffi/ffi_runtime.dart Update docs/error text to match bundleSource assignment API.
lib/src/facade.dart Replace setBundleSource API with assignable bundleSource field.
lib/src/config.dart Add strict mode + improved parsing helpers + clearer error handling.
lib/src/bundle_source.dart Update docs to new bundleSource assignment API.
lib/src/backend_web.dart Fix script injection/subscription lifecycle; refactor polling + add timeouts.
lib/src/backend_io.dart Use shared process runner + argv helper; extract temp-dir cleanup into sweeper.
lib/quicktype_dart.dart Remove Log/inferLangType from public barrel exports.
lib/entrypoint_runner.dart Use RendererOptions.raw instead of internal adapter; update logging import.
lib/entrypoint_cli.dart Fix silent CLI by routing output to stdout/stderr + install log forwarder; strict config in CLI.
ios/quicktype_dart.podspec Bump CocoaPods version to rc.2.
android/build.gradle Bump plugin version to rc.2.
CHANGELOG.md Add 1.0.0-rc.2 entry describing golden expansion and workflow changes.
.github/workflows/ci.yml Expand integration matrix (ubuntu/macos/windows) + add ffi-noembed job.

Comment thread lib/src/internal/argv.dart Resolved
Comment thread CHANGELOG.md Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
lib/src/ffi/native_bundle_cache.dart (1)

144-161: ⚠️ Potential issue | 🟡 Minor

Update the SRI parser doc to include sha512.

The implementation accepts sha512, but the comment only lists sha256 and sha384.

📝 Proposed doc fix
-/// Parses `'sha256-<base64>'` or `'sha384-<base64>'`. Returns
+/// Parses `'sha256-<base64>'`, `'sha384-<base64>'`, or
+/// `'sha512-<base64>'`. Returns
 /// (algorithm, base64hash) or null on bad format — including malformed
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/src/ffi/native_bundle_cache.dart` around lines 144 - 161, Update the doc
comment for _tryParseSri to reflect that it accepts 'sha256', 'sha384', and
'sha512' (i.e., change the first line from "'sha256-<base64>' or
'sha384-<base64>'" to include 'sha512'), and ensure the rest of the comment
still describes the returned tuple (algorithm, base64hash) or null on bad
format. This keeps the documentation consistent with the implementation which
checks for 'sha512'.
tool/smoke/ffi_noembed_smoke.dart (1)

59-91: ⚠️ Potential issue | 🟡 Minor

Swap leaves the no-embed dylib at build/native/ when no original existed.

If needsSwap is true but devPath didn't exist before the run, line 66 still copies the no-embed dylib over devPath, while the finally block only restores when backup.existsSync(). The no-embed binary is left sitting at build/native/ after the smoke test, silently polluting subsequent manual runs that expect the embedded build there.

🛠️ Proposed fix
   final backup = File('${devPath.path}.embed-backup');
   final needsSwap = dylib.path != devPath.path;
+  final hadOriginal = needsSwap && devPath.existsSync();
   if (needsSwap) {
-    if (devPath.existsSync() && !backup.existsSync()) {
+    if (hadOriginal && !backup.existsSync()) {
       devPath.copySync(backup.path);
     }
     dylib.copySync(devPath.path);
   }
   ...
   } finally {
-    if (needsSwap && backup.existsSync()) {
+    if (needsSwap && backup.existsSync()) {
       backup.copySync(devPath.path);
       backup.deleteSync();
+    } else if (needsSwap && !hadOriginal && devPath.existsSync()) {
+      devPath.deleteSync();
     }
   }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tool/smoke/ffi_noembed_smoke.dart` around lines 59 - 91, The swap logic
copies the no-embed dylib to devPath when needsSwap is true but only restores
from backup if a backup existed, leaving a stray file when devPath did not exist
originally; update the cleanup in the finally block to detect that case (e.g.,
when needsSwap is true and backup does NOT exist) and remove devPath (the file
created by dylib.copySync) instead of only restoring from backup, referencing
devPath, backup, needsSwap and dylib so you change the correct logic.
lib/src/models/type.dart (1)

16-17: ⚠️ Potential issue | 🟡 Minor

DefaultPaths.c is declared but unreachable.

DefaultPaths.c is defined on line 17 ('src/**/models'), but the defaultPath switch routes TargetType.c to null (line 145). Either TargetType.c should map to DefaultPaths.c (restoring the conventional default the constant documents), or the constant should be removed to match the "no conventional home" decision. Leaving both present is misleading for anyone reading DefaultPaths and expecting it to be authoritative.

Option A — wire it up
   String? get defaultPath => switch (this) {
+        TargetType.c => DefaultPaths.c,
         TargetType.dart => DefaultPaths.dart,
         TargetType.kotlin => DefaultPaths.kotlin,
         TargetType.java => DefaultPaths.java,
         TargetType.swift => DefaultPaths.swift,
         TargetType.javascript || TargetType.typescript => DefaultPaths.web,
-        TargetType.c ||
-        TargetType.cpp ||
+        TargetType.cpp ||
Option B — delete the constant
-  /// Default output glob for generated C sources.
-  static const String c = 'src/**/models';
-
   /// Default output glob for generated Dart sources.
   static const String dart = 'lib/**/models';

Also applies to: 139-161

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/src/models/type.dart` around lines 16 - 17, DefaultPaths.c is declared
but never used because the defaultPath switch maps TargetType.c to null; either
wire DefaultPaths.c into the defaultPath logic or remove the constant to avoid
confusion. Update the defaultPath switch (the code that maps TargetType.c) to
return DefaultPaths.c for TargetType.c if you want a conventional default, or
delete the static const String c from the DefaultPaths class and remove any
comments referencing a C default if you intentionally want no conventional home;
make the change consistent with the other entries in defaultPath and
DefaultPaths to avoid mismatches.
🧹 Nitpick comments (9)
lib/src/backend_web.dart (1)

63-65: Failed bundle load is cached permanently; no retry path.

_loadFuture ??= _loadBundle() means a transient timeout/network error (slow CDN, flaky fetch for a RemoteBundleSource) permanently poisons bundle loading for the page lifetime — every later generate call rethrows the same cached QuicktypeException. Consider clearing _loadFuture on failure so a retry becomes possible:

♻️ Proposed refactor
 Future<void> _ensureBundleLoaded() {
-  return _loadFuture ??= _loadBundle();
+  final existing = _loadFuture;
+  if (existing != null) return existing;
+  final future = _loadBundle();
+  _loadFuture = future;
+  // Clear on failure so callers can retry; success stays cached.
+  future.catchError((Object _) {
+    _loadFuture = null;
+  });
+  return future;
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/src/backend_web.dart` around lines 63 - 65, The current
_ensureBundleLoaded uses `_loadFuture ??= _loadBundle()` which caches a failed
Future and prevents retries; update `_ensureBundleLoaded` to await
`_loadBundle()` inside a try/catch (or attach `.catchError`) and on any error
clear `_loadFuture` (set to null) before rethrowing the error (preserving the
original QuicktypeException), so transient failures in `_loadBundle()` allow
subsequent `generate` calls to retry loading the bundle; reference
`_ensureBundleLoaded`, `_loadFuture`, and `_loadBundle` when making the change.
lib/src/file_resolver.dart (1)

51-57: Minor: trailing-slash patterns produce doubled separator.

When callers pass a directory-style pattern with a trailing slash (e.g. models/), line 52 produces models//*. package:glob tolerates it, but the doubled slash leaks into any subsequent ConfigException message on line 69 if the glob is otherwise malformed. Consider normalizing first.

Proposed tweak
-      final prefix = pattern.endsWith('*') ? pattern : '$pattern/*';
+      final prefix = pattern.endsWith('*')
+          ? pattern
+          : '${pattern.endsWith('/') ? pattern.substring(0, pattern.length - 1) : pattern}/*';
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/src/file_resolver.dart` around lines 51 - 57, The code can produce a
doubled slash when callers pass a directory-style pattern with a trailing slash
(e.g. "models/"); before computing prefix and globPattern, normalize pattern by
trimming a single trailing '/' (but keep existing '*' semantics) so prefix is
built from the normalized pattern; update the logic that computes prefix
(referencing pattern, prefix, and globPattern) to use a normalizedPattern =
pattern.endsWith('/') ? pattern.substring(0, pattern.length - 1) : pattern, then
compute prefix = normalizedPattern.endsWith('*') ? normalizedPattern :
'$normalizedPattern/*' so the resulting globPattern has no doubled separator and
any ConfigException messages will show the cleaned path.
test/unit/config_test.dart (1)

104-116: Add strict-mode coverage for Config.loadOrDefaults.

These tests cover fallback mode, but the new strict: true behavior from the PR objective is not asserted, so regressions there could pass unnoticed.

Proposed test additions
   group('Config.loadOrDefaults', () {
     final sandbox = _sandboxPerTest('qt_config_default_');

     test('returns defaults when the file is missing', () {
       final cfg = Config.loadOrDefaults(path: '${sandbox().path}/missing.json');
       expect(cfg.sources, isNotEmpty);
     });

     test('returns defaults when the file is malformed', () {
       final f = File('${sandbox().path}/bad.json')..writeAsStringSync('[]');
       final cfg = Config.loadOrDefaults(path: f.path);
       expect(cfg.sources, isNotEmpty);
     });
+
+    test('throws when the file is missing in strict mode', () {
+      expect(
+        () => Config.loadOrDefaults(
+          path: '${sandbox().path}/missing.json',
+          strict: true,
+        ),
+        throwsA(isA<ConfigException>()),
+      );
+    });
+
+    test('throws when the file is malformed in strict mode', () {
+      final f = File('${sandbox().path}/bad.json')..writeAsStringSync('[]');
+      expect(
+        () => Config.loadOrDefaults(path: f.path, strict: true),
+        throwsA(isA<ConfigException>()),
+      );
+    });

     test('independent instances do not share state', () {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/unit/config_test.dart` around lines 104 - 116, Add tests for
Config.loadOrDefaults strict-mode: update the existing
group('Config.loadOrDefaults') to include cases that call
Config.loadOrDefaults(path: ..., strict: true) and assert the strict
behavior—when the file is missing expect it to throw an error (use expect(() =>
Config.loadOrDefaults(..., strict: true), throwsA(...))) and when the file is
malformed expect a throw as well; also add a positive case where a valid config
file passed with strict: true returns a Config with non-empty sources to ensure
strict accepts valid input. Use the same sandbox helper and reference
Config.loadOrDefaults and the strict parameter to locate where to add these
tests.
tool/refresh_bundle.dart (2)

93-107: Comment and implementation disagree.

The comment says "walk up to the dir containing pubspec.yaml", but the code only does a single fixed dirname(dirname(scriptPath)) and validates once — no walking. Either tighten the comment or actually iterate up until a pubspec.yaml is found (more robust when the script is invoked via a symlink or from a nested working tree).

♻️ Option: implement an actual walk
-  final scriptPath = Platform.script.toFilePath();
-  final guess = p.dirname(p.dirname(scriptPath));
-  if (!File(p.join(guess, 'pubspec.yaml')).existsSync()) {
-    stderr.writeln(
-      'refresh_bundle: could not locate repo root from '
-      '$scriptPath (no pubspec.yaml at $guess).',
-    );
-    exit(2);
-  }
-  return guess;
+  final scriptPath = Platform.script.toFilePath();
+  var dir = p.dirname(scriptPath);
+  for (var i = 0; i < 6; i++) {
+    if (File(p.join(dir, 'pubspec.yaml')).existsSync()) return dir;
+    final parent = p.dirname(dir);
+    if (parent == dir) break;
+    dir = parent;
+  }
+  stderr.writeln(
+    'refresh_bundle: could not locate repo root from $scriptPath.',
+  );
+  exit(2);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tool/refresh_bundle.dart` around lines 93 - 107, The comment for
_resolveRepoRoot promises walking up to the directory containing pubspec.yaml
but the code only checks a single fixed dirname(dirname(scriptPath)); change
_resolveRepoRoot to iteratively ascend parent directories from
p.dirname(scriptPath) (or p.dirname(p.dirname(scriptPath)) if you want to start
one level up) checking File(p.join(current, 'pubspec.yaml')).existsSync() at
each step, returning the directory when found and exiting with the existing
error (or a similar message) if you reach the filesystem root (detect when
parent == current) without finding pubspec.yaml; ensure the stderr message still
includes the original scriptPath and the last checked directory for clarity.

109-124: PATHEXT not fully honored on Windows.

Hard-coded .exe/.cmd misses .bat (and ignores user-customized PATHEXT, which can include .ps1). For bash/python3 this is usually fine, but if someone has python3.bat shimmed (common with py launchers or pyenv-win) the prereq check will falsely fail. Consider reading PATHEXT when on Windows.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tool/refresh_bundle.dart` around lines 109 - 124, _requireBinaryOnPath
currently hardcodes Windows extensions; change it to read
Platform.environment['PATHEXT'] when Platform.isWindows, split on ';' (fallback
to a sensible default like ['.EXE','.CMD','.BAT'] if missing), normalize
extensions (ensure leading dot) and build candidates by appending each extension
to name plus include the bare name as well; keep the existing loop/existsSync
check and exit behavior but replace the static candidates declaration with the
PATHEXT-derived list so user-customized extensions (e.g., .bat, .ps1) are
honored.
lib/entrypoint_cli.dart (1)

115-131: Process.runSync inside an async function.

_printVersion is Future<void> and already awaits resolveQuicktypeExecutable(), but then calls Process.runSync — which blocks the isolate while waiting on the child. Since the caller already awaits, prefer the async variant so other pending work (e.g. the log-forwarder flushing records from earlier startup) isn't stalled.

Proposed change
-      final result = Process.runSync(exe, ['--version']);
+      final result = await Process.run(exe, ['--version']);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/entrypoint_cli.dart` around lines 115 - 131, The _printVersion function
currently calls the blocking Process.runSync after awaiting
resolveQuicktypeExecutable, which can stall the isolate; change the call to the
asynchronous Process.run and await it (replace Process.runSync(exe,
['--version']) with await Process.run(exe, ['--version'])), then use the awaited
result.exitCode and result.stdout exactly as before; keep the existing try/catch
and QuicktypeException handling and ensure stdout.writeln uses (result.stdout as
String).trim() when exitCode == 0.
test/unit/file_resolver_test.dart (1)

17-19: Defensive tearDown for the new Windows CI job.

This PR extends the CI matrix to Windows. Directory.deleteSync(recursive: true) occasionally throws there on transient locks (e.g. AV scan on just-written files), which would turn a passing assertion into a red build. A swallow-and-log here keeps the sandbox cleanup best-effort.

Proposed guard
     tearDown(() {
-      sandbox.deleteSync(recursive: true);
+      try {
+        sandbox.deleteSync(recursive: true);
+      } on FileSystemException {
+        // Best-effort — Windows occasionally holds transient locks.
+      }
     });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/unit/file_resolver_test.dart` around lines 17 - 19, The tearDown
currently calls sandbox.deleteSync(recursive: true) unguarded which can throw on
Windows; wrap the call in a try/catch inside the tearDown block (targeting the
existing tearDown function and the sandbox.deleteSync call) and on exception
swallow it but emit a warning/log message (e.g., using print or the test logger)
so cleanup remains best-effort without failing the test run.
test/integration/golden_test.dart (1)

149-175: Tighten _assertLooksLikeCode: threshold and sentinel scoping.

Two small tune-ups:

  1. Line 170 fails at < 5, but the docstring (and failure message) advertise "at least ~10 lines". Pick one so the guard doesn't drift looser than advertised.
  2. The '\n$s' check for 'Error:' / 'TypeError:' is quite broad — any generated code that happens to embed one of these strings on its own line (quicktype emits error-path boilerplate for several targets, e.g. runtime-assertion throwers in TypeScript/Flow) would trip the guard. The startsWith check is already the high-signal one for catching quicktype's own error output (which is a one-liner preceded by a newline only when stderr leaks in). Consider restricting to startsWith or anchoring to the very first line.
Proposed tightening
-  for (final s in sentinels) {
-    if (actual.startsWith(s) || actual.contains('\n$s')) {
+  final firstLine = actual.split('\n').first;
+  for (final s in sentinels) {
+    if (firstLine.startsWith(s)) {
       fail(
         'Generator produced error-shaped output for "$caseName": '
-        'starts with/contains "$s". Refusing to treat as a golden.',
+        'first line starts with "$s". Refusing to treat as a golden.',
       );
     }
   }
   final lines = actual.split('\n');
-  if (lines.length < 5) {
+  if (lines.length < 10) {
     fail(
       'Generator produced suspiciously short output for "$caseName" '
-      '(${lines.length} lines). Real goldens are at least ~10 lines.',
+      '(${lines.length} lines). Real goldens are at least 10 lines.',
     );
   }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/integration/golden_test.dart` around lines 149 - 175, In
_assertLooksLikeCode, tighten the guards by raising the minimum line threshold
to 10 (change the length check from <5 to <10) and restrict sentinel matching to
the first output line instead of scanning for "\n$s"; compute the first line
(e.g. lines.first) and for each sentinel (from the sentinels list) fail if
actual.startsWith(s) OR firstLine.startsWith(s) so we still catch one-line error
outputs but avoid false positives from error-like tokens appearing later in
generated code.
lib/src/models/renderer_options.dart (1)

78-92: Avoid retaining and returning the caller’s mutable map.

RendererOptions.raw currently aliases the input map and returns the same instance, so later caller mutations can change generation behavior unexpectedly. Consider copying at construction and returning a fresh map.

♻️ Proposed defensive-copy refactor
-  const factory RendererOptions.raw(Map<String, String> options) =
+  factory RendererOptions.raw(Map<String, String> options) =
       _RawRendererOptions;
@@
 class _RawRendererOptions extends RendererOptions {
-  const _RawRendererOptions(this._map);
+  _RawRendererOptions(Map<String, String> options)
+      : _map = Map.unmodifiable(options);
+
   final Map<String, String> _map;
 
   `@override`
-  Map<String, String> toRendererOptions() => _map;
+  Map<String, String> toRendererOptions() => Map.of(_map);
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/src/models/renderer_options.dart` around lines 78 - 92,
RendererOptions.raw and its backing class _RawRendererOptions currently retain
and return the caller's mutable Map; change _RawRendererOptions to defensively
copy the input map on construction (e.g., create an independent Map from the
passed Map in the const factory -> _RawRendererOptions constructor) and update
toRendererOptions() to return a fresh copy (not the stored instance) so external
mutations cannot affect internal state or future callers.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@CHANGELOG.md`:
- Around line 30-36: The CHANGELOG.md still lists both "smithy" and "the
`Smithy` variant" in the "Still intentionally uncovered" section even though
TargetType.smithy was removed; update that paragraph to remove the stale Smithy
mentions and correct the remaining count (adjust from 12 to 10) or otherwise
clarify which variant remains, ensuring references to TargetType.smithy/Smithy
are deleted or reconciled so the list and count reflect the current set of
uncovered targets.

In `@lib/entrypoint_cli.dart`:
- Around line 133-153: The docstring for _installLogForwarder is inaccurate and
the lint-ignore is misplaced: update the doc comment to state that the method
wires Logger.root (i.e. all process loggers) to stdout/stderr rather than just
Logger('quicktype'), and adjust wording to note it sets the global root level
and is idempotent; then move the // ignore: cancel_subscriptions comment from
the field declaration to immediately before the .listen(...) call inside
_installLogForwarder so the ignore targets the actual lint violation caused by
the StreamSubscription created by Logger.root.onRecord.listen; keep references
to Logger.root, _installLogForwarder, and _logSubscription when making the
changes.

In `@lib/src/internal/quicktype_process.dart`:
- Around line 65-89: The runQuicktypeProcess function uses
Process.run(...).timeout which only times out the Dart Future and leaves the OS
subprocess running; change it to use Process.start(exe, argv) so you can
manually kill the child on timeout: start the process, attach collectors for
stdout/stderr, await the process.exitCode or a timeout Future based on
QuicktypeDart.processTimeout, and on timeout call
process.kill(ProcessSignal.sigkill) (or .kill() with fallback) and await
termination before throwing the QuicktypeException (include commandStr, captured
stdout/stderr if available, and the original stackTrace/cause). Ensure
resolveQuicktypeExecutable and formatCommand are still used to build commandStr,
propagate other errors into QuicktypeException (with cause and stackTrace), and
properly clean up any stream subscriptions.

In `@lib/src/quicktype.dart`:
- Around line 190-198: executeNative is a CLI pass-through but currently routes
quicktype output through Log.info/Log.warning and uses trimRight(), which can
corrupt piped/generated output; change executeNative (and the
runQuicktypeProcess handling) to write the process result stdout and stderr
directly to the program stdout/stderr streams without trimming or passing
through Log.info/Log.warning so the bytes are preserved exactly (use the raw
result.stdout/result.stderr and write to stdout.write/stderr.write or
equivalent) and still return result.exitCode.

In `@native/shim/embed_bundle.py`:
- Around line 77-88: The current code only wraps open() in try/except so writes
from out.write(...) or emit(...) can still raise and leave a truncated file;
change the write to use a temporary file and atomic replace: create a temp file
(e.g. using tempfile.NamedTemporaryFile(delete=False) or a .tmp suffix next to
out_path), write the header and call emit(prelude, 'qt_prelude_js', temp) and
emit(bundle, 'qt_bundle_js', temp) inside a try block, flush and fsync the temp
file, close it, then os.replace(temp_path, out_path) to atomically move it into
place; on any exception during writing or emit ensure you close and unlink the
temp file and exit with a nonzero status, and keep the existing error message
semantics referencing out_path, emit, prelude, bundle and out.

In `@test/integration/goldens/user_php.php.txt`:
- Around line 290-296: The validate() method currently uses || between checks
which short-circuits and skips later validations; change the boolean operators
to && so User::validateID, User::validateName, User::validateEmail,
User::validateRoles, and User::validateProfile are all executed (and their
exceptions can surface) — update the validate() function and the other similar
occurrence (the block around the second instance of these calls) to use &&
instead of ||.

In `@test/integration/goldens/user_swift_just_types.swift.txt`:
- Around line 1-4: The golden includes a misleading parsing header that
references a non-existent parser call (e.g., "let user = try User(json)") —
remove or update the header lines that instruct "To parse the JSON, add this
file to your project and do:" and the example "let user = try User(json)"; keep
the top generated-file comment but delete the parsing instructions so the file
only emits the structs (references: the User type and the "try User(json)"
example).

---

Outside diff comments:
In `@lib/src/ffi/native_bundle_cache.dart`:
- Around line 144-161: Update the doc comment for _tryParseSri to reflect that
it accepts 'sha256', 'sha384', and 'sha512' (i.e., change the first line from
"'sha256-<base64>' or 'sha384-<base64>'" to include 'sha512'), and ensure the
rest of the comment still describes the returned tuple (algorithm, base64hash)
or null on bad format. This keeps the documentation consistent with the
implementation which checks for 'sha512'.

In `@lib/src/models/type.dart`:
- Around line 16-17: DefaultPaths.c is declared but never used because the
defaultPath switch maps TargetType.c to null; either wire DefaultPaths.c into
the defaultPath logic or remove the constant to avoid confusion. Update the
defaultPath switch (the code that maps TargetType.c) to return DefaultPaths.c
for TargetType.c if you want a conventional default, or delete the static const
String c from the DefaultPaths class and remove any comments referencing a C
default if you intentionally want no conventional home; make the change
consistent with the other entries in defaultPath and DefaultPaths to avoid
mismatches.

In `@tool/smoke/ffi_noembed_smoke.dart`:
- Around line 59-91: The swap logic copies the no-embed dylib to devPath when
needsSwap is true but only restores from backup if a backup existed, leaving a
stray file when devPath did not exist originally; update the cleanup in the
finally block to detect that case (e.g., when needsSwap is true and backup does
NOT exist) and remove devPath (the file created by dylib.copySync) instead of
only restoring from backup, referencing devPath, backup, needsSwap and dylib so
you change the correct logic.

---

Nitpick comments:
In `@lib/entrypoint_cli.dart`:
- Around line 115-131: The _printVersion function currently calls the blocking
Process.runSync after awaiting resolveQuicktypeExecutable, which can stall the
isolate; change the call to the asynchronous Process.run and await it (replace
Process.runSync(exe, ['--version']) with await Process.run(exe, ['--version'])),
then use the awaited result.exitCode and result.stdout exactly as before; keep
the existing try/catch and QuicktypeException handling and ensure stdout.writeln
uses (result.stdout as String).trim() when exitCode == 0.

In `@lib/src/backend_web.dart`:
- Around line 63-65: The current _ensureBundleLoaded uses `_loadFuture ??=
_loadBundle()` which caches a failed Future and prevents retries; update
`_ensureBundleLoaded` to await `_loadBundle()` inside a try/catch (or attach
`.catchError`) and on any error clear `_loadFuture` (set to null) before
rethrowing the error (preserving the original QuicktypeException), so transient
failures in `_loadBundle()` allow subsequent `generate` calls to retry loading
the bundle; reference `_ensureBundleLoaded`, `_loadFuture`, and `_loadBundle`
when making the change.

In `@lib/src/file_resolver.dart`:
- Around line 51-57: The code can produce a doubled slash when callers pass a
directory-style pattern with a trailing slash (e.g. "models/"); before computing
prefix and globPattern, normalize pattern by trimming a single trailing '/' (but
keep existing '*' semantics) so prefix is built from the normalized pattern;
update the logic that computes prefix (referencing pattern, prefix, and
globPattern) to use a normalizedPattern = pattern.endsWith('/') ?
pattern.substring(0, pattern.length - 1) : pattern, then compute prefix =
normalizedPattern.endsWith('*') ? normalizedPattern : '$normalizedPattern/*' so
the resulting globPattern has no doubled separator and any ConfigException
messages will show the cleaned path.

In `@lib/src/models/renderer_options.dart`:
- Around line 78-92: RendererOptions.raw and its backing class
_RawRendererOptions currently retain and return the caller's mutable Map; change
_RawRendererOptions to defensively copy the input map on construction (e.g.,
create an independent Map from the passed Map in the const factory ->
_RawRendererOptions constructor) and update toRendererOptions() to return a
fresh copy (not the stored instance) so external mutations cannot affect
internal state or future callers.

In `@test/integration/golden_test.dart`:
- Around line 149-175: In _assertLooksLikeCode, tighten the guards by raising
the minimum line threshold to 10 (change the length check from <5 to <10) and
restrict sentinel matching to the first output line instead of scanning for
"\n$s"; compute the first line (e.g. lines.first) and for each sentinel (from
the sentinels list) fail if actual.startsWith(s) OR firstLine.startsWith(s) so
we still catch one-line error outputs but avoid false positives from error-like
tokens appearing later in generated code.

In `@test/unit/config_test.dart`:
- Around line 104-116: Add tests for Config.loadOrDefaults strict-mode: update
the existing group('Config.loadOrDefaults') to include cases that call
Config.loadOrDefaults(path: ..., strict: true) and assert the strict
behavior—when the file is missing expect it to throw an error (use expect(() =>
Config.loadOrDefaults(..., strict: true), throwsA(...))) and when the file is
malformed expect a throw as well; also add a positive case where a valid config
file passed with strict: true returns a Config with non-empty sources to ensure
strict accepts valid input. Use the same sandbox helper and reference
Config.loadOrDefaults and the strict parameter to locate where to add these
tests.

In `@test/unit/file_resolver_test.dart`:
- Around line 17-19: The tearDown currently calls sandbox.deleteSync(recursive:
true) unguarded which can throw on Windows; wrap the call in a try/catch inside
the tearDown block (targeting the existing tearDown function and the
sandbox.deleteSync call) and on exception swallow it but emit a warning/log
message (e.g., using print or the test logger) so cleanup remains best-effort
without failing the test run.

In `@tool/refresh_bundle.dart`:
- Around line 93-107: The comment for _resolveRepoRoot promises walking up to
the directory containing pubspec.yaml but the code only checks a single fixed
dirname(dirname(scriptPath)); change _resolveRepoRoot to iteratively ascend
parent directories from p.dirname(scriptPath) (or
p.dirname(p.dirname(scriptPath)) if you want to start one level up) checking
File(p.join(current, 'pubspec.yaml')).existsSync() at each step, returning the
directory when found and exiting with the existing error (or a similar message)
if you reach the filesystem root (detect when parent == current) without finding
pubspec.yaml; ensure the stderr message still includes the original scriptPath
and the last checked directory for clarity.
- Around line 109-124: _requireBinaryOnPath currently hardcodes Windows
extensions; change it to read Platform.environment['PATHEXT'] when
Platform.isWindows, split on ';' (fallback to a sensible default like
['.EXE','.CMD','.BAT'] if missing), normalize extensions (ensure leading dot)
and build candidates by appending each extension to name plus include the bare
name as well; keep the existing loop/existsSync check and exit behavior but
replace the static candidates declaration with the PATHEXT-derived list so
user-customized extensions (e.g., .bat, .ps1) are honored.
🪄 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: 19bf9325-c1ff-4dc6-9a06-c5cd01cf92bb

📥 Commits

Reviewing files that changed from the base of the PR and between c66287a and c08ab1c.

📒 Files selected for processing (95)
  • .github/workflows/ci.yml
  • CHANGELOG.md
  • android/build.gradle
  • ios/quicktype_dart.podspec
  • lib/entrypoint_cli.dart
  • lib/entrypoint_runner.dart
  • lib/quicktype_dart.dart
  • lib/src/backend_io.dart
  • lib/src/backend_web.dart
  • lib/src/bundle_source.dart
  • lib/src/config.dart
  • lib/src/facade.dart
  • lib/src/ffi/ffi_runtime.dart
  • lib/src/ffi/native_bundle_cache.dart
  • lib/src/file_resolver.dart
  • lib/src/internal/argv.dart
  • lib/src/internal/package_layout.dart
  • lib/src/internal/quicktype_process.dart
  • lib/src/internal/shell.dart
  • lib/src/internal/temp_dir_sweeper.dart
  • lib/src/logging.dart
  • lib/src/models/command.dart
  • lib/src/models/enums.dart
  • lib/src/models/options/lang_c.dart
  • lib/src/models/options/lang_cpp.dart
  • lib/src/models/options/lang_csharp.dart
  • lib/src/models/options/lang_dart.dart
  • lib/src/models/options/lang_elixir.dart
  • lib/src/models/options/lang_elm.dart
  • lib/src/models/options/lang_flow.dart
  • lib/src/models/options/lang_go.dart
  • lib/src/models/options/lang_haskell.dart
  • lib/src/models/options/lang_java.dart
  • lib/src/models/options/lang_javascript.dart
  • lib/src/models/options/lang_kotlin.dart
  • lib/src/models/options/lang_objc.dart
  • lib/src/models/options/lang_php.dart
  • lib/src/models/options/lang_proptypes.dart
  • lib/src/models/options/lang_python.dart
  • lib/src/models/options/lang_ruby.dart
  • lib/src/models/options/lang_rust.dart
  • lib/src/models/options/lang_scala.dart
  • lib/src/models/options/lang_smithy.dart
  • lib/src/models/options/lang_swift.dart
  • lib/src/models/options/lang_typescript.dart
  • lib/src/models/options/options.dart
  • lib/src/models/renderer_options.dart
  • lib/src/models/type.dart
  • lib/src/models/type_infer.dart
  • lib/src/quicktype.dart
  • lib/src/utils/file_resolver.dart
  • lib/src/utils/logging.dart
  • lib/src/version.dart
  • macos/quicktype_dart.podspec
  • native/shim/embed_bundle.py
  • pubspec.yaml
  • test/integration/golden_test.dart
  • test/integration/goldens/user_c.c.txt
  • test/integration/goldens/user_cpp_just_types.cpp.txt
  • test/integration/goldens/user_csharp.cs.txt
  • test/integration/goldens/user_elixir.ex.txt
  • test/integration/goldens/user_elm.elm.txt
  • test/integration/goldens/user_flow_just_types.js.txt
  • test/integration/goldens/user_go_just_types.go.txt
  • test/integration/goldens/user_haskell.hs.txt
  • test/integration/goldens/user_java_just_types.java.txt
  • test/integration/goldens/user_javascript.js.txt
  • test/integration/goldens/user_kotlin.kt.txt
  • test/integration/goldens/user_objc.m.txt
  • test/integration/goldens/user_php.php.txt
  • test/integration/goldens/user_proptypes.js.txt
  • test/integration/goldens/user_python_just_types.py.txt
  • test/integration/goldens/user_ruby.rb.txt
  • test/integration/goldens/user_rust.rs.txt
  • test/integration/goldens/user_sample.input.json
  • test/integration/goldens/user_scala.scala.txt
  • test/integration/goldens/user_swift_just_types.swift.txt
  • test/integration/goldens/user_typescript_just_types.ts.txt
  • test/unit/argv_test.dart
  • test/unit/backend_web_test.dart
  • test/unit/bundle_source_test.dart
  • test/unit/config_test.dart
  • test/unit/file_resolver_test.dart
  • test/unit/package_layout_test.dart
  • test/unit/renderer_options_raw_test.dart
  • test/unit/renderer_options_test.dart
  • test/unit/shell_test.dart
  • test/unit/temp_dir_sweeper_test.dart
  • test/unit/type_infer_test.dart
  • tool/api_snapshot.txt
  • tool/install_hooks.dart
  • tool/refresh_bundle.dart
  • tool/smoke/README.md
  • tool/smoke/ffi_noembed_smoke.dart
  • tool/sync_version.dart
💤 Files with no reviewable changes (6)
  • lib/quicktype_dart.dart
  • test/unit/renderer_options_test.dart
  • lib/src/models/options/lang_smithy.dart
  • lib/src/utils/file_resolver.dart
  • lib/src/utils/logging.dart
  • lib/src/models/enums.dart

Comment thread CHANGELOG.md Resolved
Comment thread lib/entrypoint_cli.dart Resolved
Comment thread lib/src/internal/quicktype_process.dart Resolved
Comment thread lib/src/quicktype.dart Resolved
Comment thread native/shim/embed_bundle.py Resolved
jake-dev-99 and others added 6 commits April 20, 2026 09:27
…in CI

CI's integration job just reported 3 golden failures (user_java,
user_c, user_objc) plus a hard error on user_cpp. Root cause:

* Goldens were regenerated locally via FFI transport (qtConvert → a
  single in-memory string, no `--out` header). CI has no FFI plugin
  build, so it auto-falls-back to Process transport. Process writes
  per-file via `--out <path>`; quicktype's C/Java/ObjC emitters put
  the output filename into the generated file's header comment, so
  the text diverges between transports.

* cpp is worse: `quicktype --lang cpp` emits "Error: Internal error: ."
  on inputs with nested objects, sometimes with exit=0 and no file
  written. Reproducible locally with the CLI; an upstream bug.

Fixes:
  * golden_test.dart pins `transport: GenerateTransport.process` so
    behavior is deterministic regardless of whether the host has built
    the native library. Adds a comment explaining why.
  * Drops the user_cpp_just_types case and its golden.
  * Regenerates the remaining 21 goldens through Process transport —
    user_c, user_java_just_types, user_objc content changed (filename
    comment header); 18 others were byte-identical and untouched.
  * Pins `quicktype@23.2.0` in both integration and example CI jobs.
    Stops "latest drifted" from silently breaking goldens. Version bump
    requires explicit re-regeneration in the same PR.
Four of the nine review comments called out real issues; the other
five either mis-read the code (Dart 3 pattern-matching switch doesn't
fall through) or pointed at upstream quicktype output captured in
goldens (PHP validator uses `||`, Swift just-types header references
a missing parser — both emitted by quicktype-core verbatim).

Fixed:

* CHANGELOG.md — the 1.0.0-rc.2 section was stale. Rewrote it to
  reflect what actually landed over the two audit rounds: breaking
  changes (Log/inferLangType dropped from barrel, bundleSource as a
  field, loadOrDefaults with named params, TargetType.smithy gone),
  fixes (c argName, multi-extension glob, CLI silence, web listener
  leaks, CWD-relative exe, timeout-kills-child), new goldens covering
  every TargetType, internal restructuring, and CI expansion.

* runQuicktypeProcess — was using Process.run().timeout() which only
  times out the Dart Future; the OS child keeps running. Now uses
  Process.start + proc.kill(ProcessSignal.sigkill) on timeout, so
  the subprocess is actually terminated. Docstring had been claiming
  this for a while; now it's true.

* Quicktype.executeNative — was routing the child's stdout/stderr
  through Log.info/Log.warning and trimRight()ing. Fine for human-
  readable progress but broken for pipelines (`dart run quicktype_dart
  -- --lang dart --src x.json > out.dart` would prepend `[INFO]`
  lines). Writes bytes verbatim to stdout/stderr now.

* entrypoint_cli._installLogForwarder docstring — said it wires
  `Logger('quicktype')` records but actually attaches to `Logger.root`
  (catches any transitive package:logging consumer too). Clarified.
Three macOS integration-test goldens (kotlin, csharp, go) failed on
`Integration tests (macos-latest)` with:

    PathNotFoundException: Cannot open file, path = '.../User.kt'

Root cause: the return path was

    return targetFile.readAsString();

which hands back a Future *before* the read starts. Dart evaluates the
return, then the enclosing `try { … } finally { _sweeper.cleanup(tempDir); }`
fires and removes the temp dir. The async read then races against a
directory that no longer exists.

Linux's VFS keeps open file descriptors valid after unlink, so the
same code survived on `Integration tests (ubuntu-latest)` — the read
completes from the still-open FD after the dir is gone. macOS APFS
doesn't give you that grace period.

Fix: `return await targetFile.readAsString();` so the file is read to
completion before control returns to the caller and the finally block
runs.

Inline comment in place to prevent a future "simplify this return"
refactor from regressing us back into the race.

Also addresses feedback from the PR review bots on this branch:

  * Copilot's argv.dart switch-fall-through concern (PR #26): wrong
    — that's Dart 3 switch syntax which does NOT fall through.
    `Format + Analyze` passing confirms the file compiles.
  * CodeRabbit's `Process.run().timeout()` leaks-child concern: the
    current `runQuicktypeProcess` already uses `Process.start` with
    manual `.kill(SIGKILL)` on timeout (lines 77–112). Comment was
    against a stale revision.
  * CodeRabbit's `executeNative` stdout-corruption concern: already
    writes to `stdout`/`stderr` directly, no `Log.info`/`trimRight`.
    Also stale.
  * CodeRabbit's user_php golden `||` vs `&&` concern: golden
    captures what quicktype actually generates — the `||` is an
    upstream quicktype PHP codegen bug. Silently rewriting the
    golden would hide reality. Tracked as an upstream issue;
    mutating the golden here would fail the next `GOLDEN=update`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
macOS-only integration failure on PR #26 (kotlin, csharp, go):
`PathNotFoundException: Cannot open file, path = '.../User.kt'` from
`generateFromString`. Ubuntu stayed green.

Root cause is a subtle async-control-flow bug:

```dart
try {
  ...
  return targetFile.readAsString();   // unawaited Future
} finally {
  _sweeper.cleanup(tempDir);          // deletes tempDir
}
```

In a Dart async function, `return futureExpr;` returns that Future to
the caller immediately — the implicit await happens at the *call site*,
not inside this function. So the execution order is:

  1. return the readAsString Future
  2. finally runs synchronously, cleanup() deletes tempDir
  3. caller awaits the returned Future → the read finally starts
  4. open(User.kt) syscall

On Linux, step 4 succeeds because an open FD on an unlinked-parent
inode keeps the file accessible until the FD closes. On macOS APFS,
unlinking the parent directory invalidates subsequent open() calls on
the child — PathNotFoundException.

Fix: `return await targetFile.readAsString();`. With the explicit
await, the read completes before finally runs, and the temp dir is
only cleaned up once we're done with it.

Also bumps CI's Node version from 20 to 22 to match the environment
goldens were generated against (author's local).
@jake-dev-99

Copy link
Copy Markdown
Owner Author

Review triage + CI fix

Pushed the real fix for the failing Integration tests (macos-latest) check: 3759541 — _runViaProcess was returning the unawaited readAsString Future, letting the finally { _sweeper.cleanup(tempDir); } block delete the temp dir before the async file read started. Linux's VFS kept the FD valid after unlink so the read survived; macOS APFS doesn't. Adding await threads the ordering correctly.

Why only 3 languages (kotlin / csharp / go) failed and not the other 17

Hypothesis: those three hit a schedule where the quicktype subprocess exits fast enough that the existsSync() guard passes but the event loop hasn't started the readAsString I/O yet when the finally fires. Other languages either (a) fail existsSync() and throw the nice QuicktypeException before reaching the race, or (b) finish the read in the same microtask as existsSync(). Either way, the await fix removes the race entirely — deterministic on all platforms now.

Review-comment triage

# File Comment Outcome
1 lib/src/internal/argv.dart:19 Copilot: "switch missing break/continue/return, won't compile" Rejected. Dart 3 switch statements don't fall through — break isn't required (and dart_style flags it as redundant). Format + Analyze passing confirms the file compiles.
2 CHANGELOG.md Copilot + CodeRabbit: stale Smithy references Deferred. Docs-only; not blocking CI. Will sweep in a separate chore(docs) PR.
3 lib/entrypoint_cli.dart CodeRabbit: docstring inaccurate + // ignore: cancel_subscriptions misplaced Deferred. Stylistic; not blocking.
4 lib/src/internal/quicktype_process.dart CodeRabbit: Process.run().timeout() leaks child process Already fixed on this branch — lines 77–112 use Process.start + exitCode.timeout + explicit proc.kill(SIGKILL) on timeout. Comment was against a stale revision.
5 lib/src/quicktype.dart:195 CodeRabbit: executeNative corrupts piped stdout via Log.info + trimRight Already fixed — writes to stdout/stderr directly (lines 197–201). Also stale.
6 native/shim/embed_bundle.py:88 CodeRabbit: partial-write safety on emit(...) failure Deferred. Minor; atomic-write refactor is a separate improvement. Current behavior: partial file on crash, rebuilt cleanly on next invocation.
7 test/integration/goldens/user_php.php.txt:290 CodeRabbit: validator uses `
8 test/integration/goldens/user_swift_just_types.swift.txt:4 CodeRabbit: header mentions try User(json) but just-types output has no parser Same as #7 — this is generated output. Upstream tracking only.
— Integration test fail (the actual CI blocker) Fixed in 3759541

Happy to split #2/#3/#6 into a follow-up cleanup PR if you'd like to keep this one focused on the v1.0.0-rc.2 audit. #7 and #8 both want upstream quicktype issues filed — I can do that too if you don't already have trackers for the PHP / Swift-just-types output shapes.

🤖 Generated with Claude Code

Windows CI failed every golden test with \r\n vs \n drift. Root
cause: `core.autocrlf=true` on the Windows GitHub runner rewrites
committed LF-only files to CRLF at checkout. quicktype's child
process writes LF regardless of platform, so `actual` ends up with
\n while `expected` (the golden file read from disk) has \r\n.

Adds .gitattributes with `text eol=lf` on the files where bytes
matter: test/integration/goldens/*.{txt,json} and
tool/api_snapshot.txt. Unix-side checkouts are already LF, so no
change there; the rule only affects Windows checkout behavior.
@jake-dev-99 jake-dev-99 changed the title v1.0.0-rc.2: war-on-debt audit pass v1.0.0-rc.2: Further Refinements and Bug Fixes Apr 20, 2026
@jake-dev-99
jake-dev-99 merged commit c055cc0 into main Apr 20, 2026
13 checks passed
jake-dev-99 added a commit that referenced this pull request Apr 20, 2026
Two small fixes from the review batch. Most other comments were
reviewing older commits (Process.start+kill, executeNative direct
stdout/stderr write, CHANGELOG Smithy staleness, argv switch) that
already landed in the audit sprint.

- entrypoint_cli.dart: move `// ignore: cancel_subscriptions` from
  the field declaration to inline above the `.listen()` call.
  Analyzer was green either way (the subscription is cancelled via
  `_logSubscription?.cancel()` before reassignment), but the ignore
  fires on the .listen() site, not the field, so the inline
  placement is the conventional home.

- embed_bundle.py: buffer output in memory first, then write via
  `<path>.tmp-<pid>` + `os.replace()`. A read failure on prelude.js
  or bundle.js, or a disk-full during emit, no longer truncates an
  existing out_path. Temp file is cleaned up on OSError.

Declining on purpose:
- argv.dart switch without `break`: Dart 3 new-style switch
  statements don't fall through; each `case` is self-terminating.
  Valid as-is.
- user_php.php.txt using `||` where `&&` would validate every
  field: this is quicktype-core's own output. Editing the golden
  would be rewritten on the next `GOLDEN=update` anyway. The
  golden's job is to capture regressions, not suppress upstream
  bugs — belongs on quicktype-core's tracker.
- user_swift_just_types.swift.txt header comment referencing a
  non-existent `try User(json)` parser: same situation. Upstream
  header-generation ignores the `justTypes` flag; editing the
  golden here would mask that inconsistency rather than surface it.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
jake-dev-99 added a commit that referenced this pull request Apr 20, 2026
Resolves PR #27 conflicts. PR #26 landed on main with the earlier
versions of lib/entrypoint_cli.dart and native/shim/embed_bundle.py;
rc.2 has since picked up two review-driven refinements on those files
(inline cancel_subscriptions ignore moved to the .listen() site;
atomic-write via BytesIO + os.replace in embed_bundle.py). Takes
rc.2's side on both — the review fixes supersede what landed from #26.

Also confirms py parse + dart analyze + dart test test/unit all clean
after the resolution.
jake-dev-99 added a commit that referenced this pull request Jul 9, 2026
Rebased release/v1.0.0-rc.2 onto current main (028d710, incl.
Dependabot's esbuild 0.25→0.28 bump from #28). The prior branch
carried ~30 commits whose content already landed on main via the
#26 squash (c055cc0), so a literal replay would conflict against
its own merged twins. Collapsed to the genuine net delta over
current main:

- lib/entrypoint_cli.dart: unawaited(_logSubscription?.cancel())
  + relocate `// ignore: cancel_subscriptions` to the .listen()
  site (Copilot/CodeRabbit feedback).
- native/shim/embed_bundle.py: buffer + atomic os.replace() write
  so a read failure can't truncate bundle_data.c.

Both files byte-identical to the reviewed rc.2 versions; esbuild
stays at main's 0.28.1 (Dependabot bump preserved, not reverted).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
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