skyward-api 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: a18b8e4d32a2a63f2fc6b92cd355834b77e2aecacf318df6f8aef501c8af2455
4
- data.tar.gz: 2c9ef850c2e8e7f468356d9be9fa192bd55c0ec6430382de4afce74358d3b24d
3
+ metadata.gz: '039ffb7a33af95928e5ce5068f752df1955cd10125e0b1db2259c1175a190109'
4
+ data.tar.gz: 2f89394fd909cd45274e5cc5042037f20e548746d162ec27947cecb9bd82d220
5
5
  SHA512:
6
- metadata.gz: 2ee0573f5a24f90e57aeade33b2358c01f6dc41b43405f217408d1b64e3a0e423f9cb4f8ca55edf5b655a956eb0a8d4d8ad0bdd892f3154330801d44aca6d538
7
- data.tar.gz: ae07e3a5b84e74596a83666f461060cc0eb3fce0283447f01ae1e324c75febc1d4afc98b3d07db61d1e0b135118b1fd89e25c80c2488ede26ede728ebc6adf7f
6
+ metadata.gz: 012d4896ea8fdacfb4177875f1a426003334b45ab94796defe98d622359cf63ed79bdb371d4529986a562dbce8cfec219a0d820e5ac5c421db1db66d881bb52d
7
+ data.tar.gz: 44e096875488c41b97a7fbd5343d59176b280c195271224248a2bd7c3d6c9afac04d79ee55e25bda6b9562c5fe726c0784ff1c824c47c6c388fc8639dbe5e2a2
data/README.md CHANGED
@@ -1,13 +1,13 @@
1
1
  # Skyward API
2
2
 
3
3
  > [!CAUTION]
4
- > **Work in progress: Skyward API is barely started.** Version 0.1 is a skeleton. The gems install and load, but only the parts listed under [Status](#status) are built. This README is the spec for what's coming, not documentation of what exists. Don't depend on it yet.
4
+ > Skyward API is pre-1.0. This README is its spec, most of it is built, and [Status](#status) lists exactly what is. Any release may change the API, so don't run it in production yet.
5
5
 
6
- A small, fast Ruby web framework where **an endpoint is a method**.
6
+ A Ruby web framework where **an endpoint is a method**, and its type signature is the API contract.
7
7
 
8
- Its inputs are keyword arguments. Its response is the return value. Add a type signature and Skyward API uses it to coerce and validate the request, check your code with Steep, and write your OpenAPI docs for you. Leave the signature off and it's still just Ruby.
8
+ Its inputs are keyword arguments and its response is the return value. Add an RBS signature and Skyward API coerces and validates the request against it, publishes it as your OpenAPI document, and Steep checks the method against it. Leave the signature off and it's plain Ruby.
9
9
 
10
- Skyward API is half of Skyward. The other half is [Skyward ORM](../skyward-orm/README.md), but each works without the other.
10
+ It's half of Skyward. The other half is [Skyward ORM](../skyward-orm/README.md), and you can use either without the other.
11
11
 
12
12
  ```ruby
13
13
  # config.ru
@@ -31,7 +31,7 @@ $ curl localhost:9292/hello/ruby?shout=true
31
31
  {"message":"HELLO, RUBY"}
32
32
  ```
33
33
 
34
- That's the whole framework. The rest of this README is detail.
34
+ The rest of this README is reference. If you only read one section, read [Types](#types).
35
35
 
36
36
  ---
37
37
 
@@ -41,7 +41,7 @@ That's the whole framework. The rest of this README is detail.
41
41
  - [Endpoints](#endpoints)
42
42
  - [Inputs](#inputs)
43
43
  - [Responses](#responses)
44
- - [Types: the bonus that pays rent](#types-the-bonus-that-pays-rent)
44
+ - [Types](#types)
45
45
  - [OpenAPI docs](#openapi-docs)
46
46
  - [Building an app](#building-an-app)
47
47
  - [Providers](#providers)
@@ -49,7 +49,7 @@ That's the whole framework. The rest of this README is detail.
49
49
  - [Testing](#testing)
50
50
  - [Production](#production)
51
51
  - [CLI](#cli)
52
- - [Coming from…](#coming-from)
52
+ - [Coming from other frameworks](#coming-from-other-frameworks)
53
53
  - [Design principles](#design-principles)
54
54
  - [Status](#status)
55
55
 
@@ -107,7 +107,7 @@ Skyward API fills each keyword argument by its name:
107
107
  | ----------------------------------------------- | --------------------------------------------------------------------------------- |
108
108
  | a path parameter (`id:` for `/:id`) | the URL path |
109
109
  | `body:` | the parsed JSON request body |
110
- | `request:` | the raw `Skyward::API::Request` (an escape hatch for headers, cookies and the IP) |
110
+ | `request:` | the raw `Skyward::API::Request`, for headers, cookies and the IP |
111
111
  | a [provided](#providers) name (`current_user:`) | your provider |
112
112
  | anything else | the query string |
113
113
 
@@ -126,7 +126,7 @@ def create(body:)
126
126
  end
127
127
  ```
128
128
 
129
- `request:` is the escape hatch for what typed inputs don't cover. It's a frozen `Skyward::API::Request`, built only when an endpoint or a provider asks for it, with the request's `headers` by lowercase name (`request.headers["authorization"]`), its `cookies`, the client's `ip`, its `request_id`, and `env`, the raw Rack env, for anything else. Its type is `Skyward::API::Request`, it never comes from the query string, and it never appears in the docs.
129
+ `request:` covers what typed inputs don't. It's a frozen `Skyward::API::Request`, built only when an endpoint or a provider asks for it, with the request's `headers` by lowercase name (`request.headers["authorization"]`), its `cookies`, the client's `ip`, its `request_id`, and `env`, the raw Rack env, for anything else. Its type is `Skyward::API::Request`, it never comes from the query string, and it never appears in the docs.
130
130
 
131
131
  ---
132
132
 
@@ -165,7 +165,7 @@ Error responses use [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457) `applicat
165
165
  }
166
166
  ```
167
167
 
168
- A Rack triple is the escape hatch for anything a value can't express: streaming, files, or a content type other than JSON. Its status, headers and body are sent as given, so a body that streams through `each` or `call` works. Rack 3 wants lowercase header names, and Skyward API doesn't rewrite them. A typed endpoint sends a triple only when its return type says so, with `Skyward::API::rack`, which is `[Integer, Hash[String, String], untyped]`, written `rack` under the [`# @rbs use` line](#types-the-bonus-that-pays-rent):
168
+ Return a Rack triple for anything a value can't express: streaming, files, or a content type other than JSON. Its status, headers and body are sent as given, so a body that streams through `each` or `call` works. Rack 3 wants lowercase header names, and Skyward API doesn't rewrite them. A typed endpoint sends a triple only when its return type says so, with `Skyward::API::rack`, which is `[Integer, Hash[String, String], untyped]`, written `rack` under the [`# @rbs use` line](#types):
169
169
 
170
170
  ```ruby
171
171
  # @rbs id: Integer
@@ -176,20 +176,20 @@ def export(id:)
176
176
  end
177
177
  ```
178
178
 
179
- Nothing checks what a triple sends: that's the point of an escape hatch, and why it's opt-in through the return type. An `Array[T]` return is always JSON, even with three items.
179
+ Nothing checks what a triple sends, which is why it's opt-in through the return type. An `Array[T]` return is always JSON, even with three items.
180
180
 
181
181
  ---
182
182
 
183
- ## Types: the bonus that pays rent
183
+ ## Types
184
184
 
185
- Everything above works without types. Add a signature and it does more:
185
+ Everything above works without types. Add a signature and:
186
186
 
187
- - **Coercion.** `"42"` in the path becomes `42` when the signature says `Integer`.
188
- - **Validation.** A body that doesn't match its type is rejected with a 422 that says exactly what was wrong, before your method runs.
189
- - **Docs.** The signature becomes the OpenAPI operation, including every possible response.
190
- - **Checking.** Steep checks your handlers like any other Ruby code, because they _are_ ordinary Ruby code.
187
+ - `"42"` in the path becomes `42` when the signature says `Integer`.
188
+ - A body that doesn't match its type gets a 422 saying exactly what's wrong, before your method runs.
189
+ - The signature becomes the OpenAPI operation, with every response it can return.
190
+ - Steep checks your handlers like any other Ruby, because that's all they are.
191
191
 
192
- Signatures are plain [RBS](https://github.com/ruby/rbs). Write them inline with [rbs-inline](https://github.com/soutaro/rbs-inline), or in `sig/*.rbs` files. Skyward API reads both, from the `.rbs` files under `sig/` (or the directory you pass as `Skyward.app(signatures:)`), so run rbs-inline before you boot. There's no schema DSL to learn and nothing to keep in sync: **the type you write for Steep is the API contract.**
192
+ Signatures are plain [RBS](https://github.com/ruby/rbs). Write them inline with [rbs-inline](https://github.com/soutaro/rbs-inline), or in `sig/*.rbs` files. Skyward API reads both, from the `.rbs` files under `sig/` (or the directory you pass as `Skyward.app(signatures:)`). `skyward serve`, `skyward routes` and `skyward openapi` regenerate `sig/generated` from your inline annotations first, so you never run rbs-inline yourself. There's no schema DSL to learn and nothing to keep in sync: **the type you write for Steep is the API contract.**
193
193
 
194
194
  A file whose signatures name Skyward API's types starts with `# @rbs use Skyward::API::*`, so they can write `Responses::NotFound`, `Responses::Created[Todo]` and `Request`: RBS doesn't look names up through the superclass, so without the line even an API class's signatures would need `Skyward::API::Responses::NotFound`. The line reaches only signatures, so Ruby code writes the full name, and so does a `#:` after an expression, which Steep also reads as Ruby.
195
195
 
@@ -363,7 +363,7 @@ end
363
363
 
364
364
  A `summary:` is one line, and Skyward API refuses to boot if it has a line break. A `description:` is Markdown.
365
365
 
366
- Comments are never read. They're for people reading the Ruby, and they never reach your docs, so documentation can't hide in a comment, and a comment can't change what you publish.
366
+ Comments are never read, so they never reach your docs, and changing one can't change what you publish.
367
367
 
368
368
  Docs are served only when you pass `docs: true`, so leave it out to hide them. With it, a route or a static file at `/openapi.json` or `/docs` fails boot. The document and the page at `/docs` are built once, at boot, and the same app always writes the same bytes. The document is your API's contract with the code that calls it. Skyward API doesn't write clients: write the document at build time, and generate a client from it with whatever tooling suits that code:
369
369
 
@@ -499,7 +499,7 @@ end
499
499
 
500
500
  ## Errors
501
501
 
502
- Skyward API checks your app thoroughly at boot, so mistakes surface when you start it, not at 3am:
502
+ Skyward API checks your app at boot, so mistakes show up when you start it, not at 3am:
503
503
 
504
504
  ```
505
505
  Skyward::Core::BootError: TodosAPI#show (GET /todos/:id)
@@ -555,7 +555,7 @@ describe TodosAPI do
555
555
  end
556
556
  ```
557
557
 
558
- No server, no Rack, no mocks. You pass the fake in through the front door.
558
+ There's no server or Rack in that test. The fake goes in through `initialize`.
559
559
 
560
560
  When you want the whole stack, including routing, coercion, providers and middleware, use the test client:
561
561
 
@@ -578,9 +578,9 @@ end
578
578
 
579
579
  ## Production
580
580
 
581
- Here's what you get without configuring anything:
581
+ Without any configuration, you get:
582
582
 
583
- - **Boot does the work. Requests don't.** Routes are compiled into a single matcher, and signatures are compiled into coercers and validators, all at boot. API objects are created once. A request is a route lookup, a coercion and a method call.
583
+ - **Work done at boot.** Routes are compiled into a single matcher, and signatures are compiled into coercers and validators, all at boot. API objects are created once. A request is a route lookup, a coercion and a method call.
584
584
  - **Bounded request bodies.** A body is read only for an endpoint that takes `body:`, and only up to `Skyward.app(max_body_size:)` bytes, 1 MiB (`1_048_576`) by default. A larger `Content-Length`, or a body that runs past the limit, answers 413 without reading the rest, and a body whose `Content-Type` isn't `application/json` or `*+json` answers 415.
585
585
  - **Bounded error lists.** A 422 lists at most 1,000 problems, and coercion stops once it has found them. Each message writes its expected type in at most 200 characters, worked out at boot, so a small body can't produce a large response.
586
586
  - **Bounded coercion.** A union's members only find whether a value fits, without writing errors, and a union nested in several members coerces each value once, so overlapping members don't multiply the cost of coercing a body by the type's depth.
@@ -654,29 +654,29 @@ No type error detected.
654
654
 
655
655
  ---
656
656
 
657
- ## Coming from…
657
+ ## Coming from other frameworks
658
658
 
659
- - **Sinatra.** The routes will feel familiar, but the handler is a named method rather than a block, so you can call it, test it and type it.
660
- - **Rails.** There's no controller instance per request and no `params` hash. Inputs arrive as arguments, and dependencies arrive through `initialize`.
661
- - **FastAPI.** It's the same big idea: the function signature is the API contract. Here it's in Ruby, with RBS instead of type hints.
659
+ - **Sinatra.** The routes will look familiar. The handler is a named method instead of a block, so you can call it, test it and type it.
660
+ - **Rails.** There's no controller instance per request and no `params` hash. Inputs arrive as arguments, and dependencies through `initialize`.
661
+ - **FastAPI.** Same idea: the function signature is the API contract. Here it's Ruby, with RBS for the type hints.
662
662
  - **Grape.** You get the docs without the DSL.
663
663
 
664
664
  ---
665
665
 
666
666
  ## Design principles
667
667
 
668
- 1. **It's just Ruby.** Classes, methods, keyword arguments and return values. If you can write a method, you can write an endpoint.
669
- 2. **Types are a bonus that pays rent.** Nothing requires them. Every signature you add buys coercion, validation, docs and type checking.
670
- 3. **One source of truth.** The signature is the contract, so there's no schema written twice.
671
- 4. **Responses are values.** You return what happened. Nothing is raised for an ordinary outcome.
672
- 5. **Dependencies come in through the front door.** Collaborators arrive through `initialize`, and per-request values through providers. Nothing reaches for globals.
673
- 6. **Boot does the work.** Skyward API fails at boot rather than in production, and pays the cost at boot rather than on each request.
668
+ 1. **Plain Ruby.** An endpoint is a method on a class you wrote, with keyword arguments in and a value out.
669
+ 2. **Optional types.** Nothing requires a signature. Each one you add gets you coercion, validation, docs and type checking for that endpoint.
670
+ 3. **One contract.** The signature is the schema, so nothing is written twice.
671
+ 4. **Responses are values.** You return what happened. Nothing is raised for an ordinary outcome like a 404.
672
+ 5. **Dependencies are passed in.** Collaborators arrive through `initialize`, and per-request values through providers. Nothing reaches for globals.
673
+ 6. **Boot does the work.** Mistakes stop the app from booting, and routes and types are compiled once, at boot, instead of on every request.
674
674
 
675
675
  ---
676
676
 
677
677
  ## Status
678
678
 
679
- This README is the spec. Skyward 0.1 is a skeleton: the gem installs and loads, and only the parts listed here are built. Skyward API is built first, and this section lists each part as it lands.
679
+ This README is the spec, and this section lists each part of it that's built, as it lands. Anything it describes that isn't listed here isn't built yet.
680
680
 
681
681
  - **Route declarations.** An API class subclasses `Skyward::API` and lists its routes with `get`, `post`, `put`, `patch` and `delete`, each with an optional `summary:` and `description:`, and describes itself with `description`. A subclass starts with its parent's routes. A path that doesn't start with `/`, a path parameter that isn't a valid keyword name or appears twice, or a `to:` that isn't a Symbol raises `ArgumentError` where it's declared. The rest is checked at boot, below.
682
682
  - **Building an app.** `Skyward.app` yields a builder and returns a frozen Rack app, and the builder is frozen once the block returns. `mount` attaches an API object at a prefix (`at:`, `/` by default), and raises `Skyward::Core::BootError` given anything but a `Skyward::API` instance. One object can be mounted at several prefixes. A request matches a route when its method and whole path match, trailing slash included, with each path parameter matching one non-empty segment, percent-decoded. Routes are tried in mount order, then declaration order. The method is called with its inputs, below, and its return value is answered by its return type, as Responses below describes. A request whose path no route matches gets a 404 problem+json.
@@ -684,14 +684,14 @@ This README is the spec. Skyward 0.1 is a skeleton: the gem installs and loads,
684
684
  - **Inputs.** Each endpoint's keywords are compiled into coercers at boot, and filled on each request before the method runs: a path parameter from the path, `body:` from the JSON body, `request:` with the request, below, a provided keyword from its provider, below, and any other keyword from the query string, each but `request:` and a provided keyword coerced to its type. In a path or query, `Integer` matches `-?\d+`, `Float` is parsed with `Float()` and must be finite, and `bool` takes `true`, `false`, `1` and `0`. In a body, a number or boolean must already be one, and an Integer is accepted as a Float. `Date` is `YYYY-MM-DD` and must exist, and `Time` is ISO 8601 with `T`, seconds, an optional fraction and `Z` or `±HH:MM`. A symbol union takes a symbol's name and gives the Symbol, and a union takes its first member that fits, in declared order. `Array[T]` in a query comes from repeated keys, one value is a one-item array, and `tag[]` is a different key; an `untyped` keyword takes the last value of a key given more than once, and any other keyword given more than once doesn't fit. A record becomes a Hash with Symbol keys, and a class with typed readers is built with `new(**fields)`, both ignoring undeclared keys. `Hash[String, T]` takes a JSON object, empty or not, and coerces each value by `T`, keeping its key a String. An `untyped` path or query value is its String, and an `untyped` part of a body, such as an untyped endpoint's `body:`, is the JSON as it's parsed, with Symbol keys at every level. An empty query value is a value, so `?limit=` doesn't fit `Integer`. A missing required keyword or field is `nil` when it's nullable, and otherwise `is required`. An absent optional keyword isn't passed, so Ruby's default applies, and an absent optional record field is left out. A request that doesn't fit answers a 422 problem+json titled `Unprocessable Content`, whose `errors` list every problem, up to the first 1,000, after which coercion stops, each with where it is (`path.id`, `query.limit`, `body.priority`, `body.tags[1]`, `body.scores["alice"]`, with a hash's key JSON-quoted so a dot or bracket in it is unambiguous, and a key longer than 200 characters cut to 200, ending `…`) and a message, such as `expected :low | :normal | :high, got "urgent"`, whose expected type, when longer than 200 characters, is cut to 200, ending `…`. A query string with unescaped bytes outside ASCII is a 422 at `query`, and a body that isn't JSON, or isn't UTF-8, is a 422 at `body`. The body is read only for an endpoint with `body:`, as [Production](#production) describes, and a missing or empty one is absent.
685
685
  - **The request.** An endpoint that takes `request:` is passed a frozen `Skyward::API::Request`, built from the Rack env once on each request, only for an endpoint that takes it or a provided keyword, and passed even when the keyword has a default. It wraps the env rather than subclassing `Rack::Request`, because Skyward API doesn't depend on Rack. `headers` is a frozen Hash of every `HTTP_` variable in the env, named in lowercase with dashes (`request.headers["authorization"]`), along with `content-type` and `content-length`. `cookies` is a frozen Hash read from the `cookie` header, each value percent-decoded with a `+` left as it is, and the first of two cookies with one name wins. `ip` is the client's address as Rack finds it: the remote address, unless it's a trusted proxy (a loopback or private address, `localhost` or a Unix socket), and otherwise the last `X-Forwarded-For` address that isn't one, or the first when every one is, or the remote address when there's no `X-Forwarded-For`, or `nil` with neither. The `Forwarded` header isn't read. `request_id` is the request's ID, and `env` is the env itself.
686
686
  - **Providers.** The builder's `provide(name, provider)` registers anything that responds to `call(request)`, such as an object, a lambda or a `Method`, under a Symbol name, and raises `Skyward::Core::BootError` for a name that's already provided, or for `body` or `request`, which Skyward API fills itself. A keyword with a provided name is filled by its provider, never from the query string, and passed even when it has a default. On each request, once a route matches, each provider the endpoint asks for runs once, in keyword order, with the request, the same `Skyward::API::Request` that `request:` gets, before the body is read or any input is coerced, so a caller a provider turns away gets its response rather than a 422 that shows the inputs' shape. When a provider returns a response value (`Skyward::API::Responses::NoContent`, `Skyward::API::Responses::BadRequest`, `Skyward::API::Responses::Unauthorized`, `Skyward::API::Responses::Forbidden`, `Skyward::API::Responses::NotFound`, `Skyward::API::Responses::Conflict`, `Skyward::API::Responses::Unprocessable` or `Skyward::API::Responses::Redirect`), no later provider runs, the method never runs, and the value is answered as Responses below describes, written by the provider's return type, or by its own status for a provider with no signature; anything else it returns, `nil` and a `Skyward::API::Responses::Created` included, is the keyword's value. At boot, Skyward API reads the provider's signature: the `call` of its class, which may be inherited, or a `Method`'s own name, in either case read from the module that defines it. A provider whose `call` is defined on a single object, such as a module with `extend self` or a class with `def self.call`, has no signature Skyward API can read, so boot refuses it: provide an instance of a class. The response values in its return type are added to the document's responses of every endpoint that asks for its name, and the rest of the return type's members must be exactly the keyword's type's members, compared as RBS types in any order, with a `T?` as `T` and `nil`, so several members are compared as their union, and a return type of only response values matches no keyword; boot refuses a keyword that doesn't match. A provider with no signature, or whose `call` returns `untyped`, as a lambda's does, adds no responses and its value isn't checked. A provider that raises is answered with a 500, as Errors below describes, and so is a typed provider's response value that its return type doesn't list, which raises `Skyward::API::ReturnTypeError` naming the provider. A keyword typed `untyped`, nullable or not, as each of an untyped endpoint's keywords is, takes any provider's value unchecked, since untyped code isn't checked anywhere else, and is still filled by its provider, never from the query string, with the provider's responses still added to the endpoint's. With `strict: true`, a signature that types a provided keyword as `untyped`, nullable or not, is refused like one that types any other keyword so, but a provider with no signature, or whose `call` returns `untyped`, doesn't make the endpoints that ask for it untyped, since `strict:` refuses untyped endpoints, not providers.
687
- - **Responses.** An API's instances have private helpers that return frozen response values, each taking `headers:`: `created(value)` returns a `Skyward::API::Responses::Created[T]`, `no_content` a `Skyward::API::Responses::NoContent`, `bad_request(detail)` a `Skyward::API::Responses::BadRequest`, `unauthorized(detail)` a `Skyward::API::Responses::Unauthorized`, `forbidden(detail)` a `Skyward::API::Responses::Forbidden`, `not_found(detail = nil)` a `Skyward::API::Responses::NotFound`, `conflict(detail)` a `Skyward::API::Responses::Conflict`, `unprocessable(detail)` a `Skyward::API::Responses::Unprocessable` and `redirect(to, status: 303)` a `Skyward::API::Responses::Redirect`. `bad_request`, `unauthorized`, `forbidden` and `redirect` are also public module functions on `Skyward`, such as `Skyward.unauthorized("Sign in first")`, for code outside an API class. `redirect` raises `ArgumentError` for a `status:` other than 301, 302, 303, 307 or 308, or a `to` with a line break. At boot, each endpoint compiles a serializer for every member of its return type, and a returned value goes to the first member it fits: by class for a class with typed readers and for a response value, and by shape otherwise. A class with typed readers is written by calling each reader it declares, never `to_h`, and a record is read from a Hash by its declared keys, leaving out an optional key that's absent, so nothing undeclared is ever written. Integers, Floats, Strings and booleans are written as JSON, an enum's Symbol as its name, a `Date` as `YYYY-MM-DD`, a `Time` in UTC as ISO 8601 with six fractional digits (`2026-10-18T09:30:00.123456Z`), and `nil` only where the type is nullable. A `Hash[String, T]` writes each value as `T`, so a value's undeclared fields are dropped too, and String or Symbol keys as strings; a Hash with any other key doesn't fit it. A plain value answers 200 with `content-type: application/json`; `Skyward::API::Responses::Created[T]` answers 201 with its value written as `T`; `Skyward::API::Responses::NoContent` answers 204 with no body; `Skyward::API::Responses::BadRequest`, `Skyward::API::Responses::Unauthorized`, `Skyward::API::Responses::Forbidden`, `Skyward::API::Responses::NotFound`, `Skyward::API::Responses::Conflict` and `Skyward::API::Responses::Unprocessable` answer 400, 401, 403, 404, 409 and 422 with RFC 9457 `application/problem+json`, whose `detail` appears only when given; and `Skyward::API::Responses::Redirect` answers its status with a `location` header and no body. A response value's `headers:` are added to its response, and Skyward adds no `WWW-Authenticate` to a 401, so pass it in `headers:`. A part typed `untyped` is written as untyped code's is: scalars as themselves, Symbols as their names, dates and times as above, Hashes and Arrays item by item, and anything else through `to_h`; a return type of `untyped` also answers each response value with its own status. A value, or any part of it, that doesn't fit its type raises `Skyward::API::ReturnTypeError` before anything is written, naming the endpoint's label, what came back (a scalar's value, or else only its class) and where, and the type it should have been, so it's answered with a 500 as Errors below describes. Skyward API's signatures declare `Skyward::API::rack` as `[Integer, Hash[String, String], untyped]`, and a member typed with it, or with that tuple written out, takes an Array of an Integer, a Hash and a body, and sends it as given, without checking or rewriting any of it, so a body that streams through `each` or `call` works. An `Array[T]` member is always JSON, even for three items. The request ID is still added to a triple, and `HEAD` drops its body, closing it when it responds to `close`. An untyped endpoint's return type is `untyped`, so it's answered the same way. An untyped endpoint's Rack triples are still to come.
687
+ - **Responses.** An API's instances have private helpers that return frozen response values, each taking `headers:`: `created(value)` returns a `Skyward::API::Responses::Created[T]`, `no_content` a `Skyward::API::Responses::NoContent`, `bad_request(detail)` a `Skyward::API::Responses::BadRequest`, `unauthorized(detail)` a `Skyward::API::Responses::Unauthorized`, `forbidden(detail)` a `Skyward::API::Responses::Forbidden`, `not_found(detail = nil)` a `Skyward::API::Responses::NotFound`, `conflict(detail)` a `Skyward::API::Responses::Conflict`, `unprocessable(detail)` a `Skyward::API::Responses::Unprocessable` and `redirect(to, status: 303)` a `Skyward::API::Responses::Redirect`. `bad_request`, `unauthorized`, `forbidden` and `redirect` are also public module functions on `Skyward`, such as `Skyward.unauthorized("Sign in first")`, for code outside an API class. `redirect` raises `ArgumentError` for a `status:` other than 301, 302, 303, 307 or 308, or a `to` with a line break. At boot, each endpoint compiles a serializer for every member of its return type, and a returned value goes to the first member it fits: by class for a class with typed readers and for a response value, and by shape otherwise. A class with typed readers is written by calling each reader it declares, never `to_h`, and a record is read from a Hash by its declared keys, leaving out an optional key that's absent, so nothing undeclared is ever written. Integers, Floats, Strings and booleans are written as JSON, an enum's Symbol as its name, a `Date` as `YYYY-MM-DD`, a `Time` in UTC as ISO 8601 with six fractional digits (`2026-10-18T09:30:00.123456Z`), and `nil` only where the type is nullable. JSON has no `Infinity` or `NaN`, so `Float` fits only a finite Float. A `Hash[String, T]` writes each value as `T`, so a value's undeclared fields are dropped too, and String or Symbol keys as strings; a Hash with any other key doesn't fit it. A plain value answers 200 with `content-type: application/json`; `Skyward::API::Responses::Created[T]` answers 201 with its value written as `T`; `Skyward::API::Responses::NoContent` answers 204 with no body; `Skyward::API::Responses::BadRequest`, `Skyward::API::Responses::Unauthorized`, `Skyward::API::Responses::Forbidden`, `Skyward::API::Responses::NotFound`, `Skyward::API::Responses::Conflict` and `Skyward::API::Responses::Unprocessable` answer 400, 401, 403, 404, 409 and 422 with RFC 9457 `application/problem+json`, whose `detail` appears only when given; and `Skyward::API::Responses::Redirect` answers its status with a `location` header and no body. A response value's `headers:` are added to its response, and Skyward adds no `WWW-Authenticate` to a 401, so pass it in `headers:`. A part typed `untyped` is written as untyped code's is: scalars as themselves, Symbols as their names, dates and times as above, Hashes and Arrays item by item, and anything else through `to_h`; a return type of `untyped` also answers each response value with its own status. A value, or any part of it, that doesn't fit its type raises `Skyward::API::ReturnTypeError` before anything is written, naming the endpoint's label, what came back (a scalar's value, or else only its class) and where, and the type it should have been, so it's answered with a 500 as Errors below describes. Skyward API's signatures declare `Skyward::API::rack` as `[Integer, Hash[String, String], untyped]`, and a member typed with it, or with that tuple written out, takes an Array of an Integer, a Hash and a body, and sends it as given, without checking or rewriting any of it, so a body that streams through `each` or `call` works. An `Array[T]` member is always JSON, even for three items. The request ID is still added to a triple, and `HEAD` drops its body, closing it when it responds to `close`. An untyped endpoint's return type is `untyped`, so it's answered the same way. An untyped endpoint's Rack triples are still to come.
688
688
  - **OpenAPI document.** With `Skyward.app(docs: true)`, the app builds its OpenAPI 3.1 document once, at boot, and answers GET and HEAD at `/openapi.json` with it as `application/json`, before any route or static file. The same app always writes the same bytes. Its `info` has `Skyward.app`'s `title:` (`"API"` by default), `version:` (`"0.1.0"` by default) and, when given, `description:`. Each API class is a tag, in mount order, with its `description`, and each route is an operation under its path, with each path parameter as `{name}`, tagged with its class, with its `summary:` and `description:` when given and the operation ID `<Tag>_<method>`; a tag is the class's constant path with `::` as `.`. A path keyword is a required parameter, and a query keyword is a parameter, required when the method requires it and it isn't nullable, whose schema leaves out `null`. `body:` is an `application/json` request body, required on the same terms. Each member of the return type is a response: a plain type a 200 `application/json`, `Skyward::API::Responses::Created[T]` a 201 of `T`, `Skyward::API::Responses::NoContent` a 204, each problem its status with the `Problem` schema as `application/problem+json`, `Skyward::API::Responses::Redirect` a `3XX` with a `location` header, and `Skyward::API::rack` a `default` with no schema. The response values of each provider the endpoint asks for are its responses too. Members with the same status are one response, `oneOf` their schemas. `request:` and a provided keyword aren't part of the HTTP contract, so neither is a parameter, schema or component, or counts as an input. An endpoint with other keywords also lists 422, and one with `body:` 413 and 415, and the responses are ordered by status. `Integer`, `Float`, `String` and `bool` are `integer`, `number`, `string` and `boolean`, `Date` and `Time` are strings of format `date` and `date-time`, `untyped` is any value, a literal is a `const`, an enum is a string `enum`, `Array[T]` is an `array` of `T`, `Hash[String, T]` is an `object` whose `additionalProperties` is `T`'s schema, so `{}` for `untyped`, a record is an inline `object` with `required` naming its required keys, a union is `oneOf` its members, and a nullable type adds `null` to its `type`, except that a nullable enum, literal, union, class or `untyped` is `anyOf` it and `null`. A class with typed readers is a `$ref` to an `object` component named by its constant path with `::` as `.`, or by `Skyward.app(schema_names:)`. A nullable field is required in a response but not in a request, and a class reached from any keyword gets the request form. The components are ordered by name, and always include `Problem`, with `type`, `title` and `status` required and an optional `detail` and `errors`. With `docs: true`, boot refuses a route whose path is `/openapi.json`, a static file there, two operations with the same ID (which two routes to one method, or a class mounted twice, have), a schema name with anything but letters, digits, `.`, `-` and `_`, and two types with the same schema name, including `Problem`. An `untyped` path or query keyword is a `string`, since that's all either carries, and an untyped endpoint's body and 200 response are any value, `{}`.
689
689
  - **API reference.** With `docs: true`, the app also answers GET and HEAD at `/docs`, before any route or static file, with an HTML page built once, at boot, as `text/html; charset=utf-8`. Its title is `Skyward.app`'s `title:`, HTML-escaped. It points Scalar at the document by the relative URL `openapi.json`, so it works under a prefix, and loads Scalar from jsDelivr, as `@scalar/api-reference` 1.75.1's `dist/browser/standalone.js` with its `sha384` integrity hash and `crossorigin="anonymous"`, or else from `Skyward.app(scalar_url:)`, HTML-escaped, with no hash. It has no inline JavaScript: Scalar is configured through `data-url` and `data-configuration`, which turns off its default fonts. Another method at `/docs` is answered as if there were no page, and `/docs/` isn't served. With `docs: true`, boot refuses a route whose path is `/docs`, and a static file there.
690
690
  - **Request IDs.** The app `Skyward.app` returns gives every request an ID: an incoming `X-Request-Id` of 1 to 200 visible ASCII characters with no spaces, or else a random UUID from `SecureRandom`. The ID is stored in the Rack env as `skyward.request_id` before anything else runs, and every response carries it as `x-request-id`, replacing one the app set.
691
691
  - **HTTP's own answers.** A path that matches routes only under other methods gets a 405 problem+json with an `allow` header listing the methods of every route matching it, in the order `GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS`, with `HEAD` wherever there's `GET` and always `OPTIONS`. `HEAD` runs the GET route and answers its status and headers with an empty body. `OPTIONS` on a routed path answers 204 with `allow`, and on any other path 404. CORS is still to come.
692
- - **`skyward serve`.** Skyward API registers it with the `skyward` command. It runs the current directory's `config.ru`, needing no `app.rb`, under one Falcon process bound to `localhost`, on `PORT` (9292 by default), with `RACK_ENV=development` unless it's already set. It writes no files. With no `config.ru`, or no Falcon in the bundle `skyward` runs in, it exits 1 saying what to do. Under `bundle exec` that's the app's bundle; run bare, `skyward` sees every installed gem. It reloads the app when a `.rb`, `.rbs` or `config.ru` file under the directory is added, changed or removed, outside `tmp/`, `log/`, `vendor/`, `node_modules/` and hidden directories such as `.git/` and `.bundle/`, polling modification times at most once every half second. The first request after a change clears the routes and description of every API class defined in those files, drops those files from `$LOADED_FEATURES` so their `require`s run again, unloads and unregisters each Zeitwerk loader that manages only directories there (so `config.ru` can set it up again), reloads any other Zeitwerk loader with reloading enabled, and builds a new app from `config.ru`. A loader of the app's own needs reloading enabled: Zeitwerk can't unload one without it, or enable it after setup, so the reload fails saying to call `loader.enable_reloading` in development and restart. One reload runs at a time and requests wait for it, while a request in flight finishes on the app it started with. A load that raises, at boot or on a reload, including a `Skyward::Core::BootError` or a `SyntaxError`, answers every request until the next change retries it with the development 500 described under Errors: `type`, `title`, `status`, `detail` and `backtrace`, and an empty body for `HEAD`. It has no `request_id`, because the app that assigns request IDs is the one that failed to load, and nothing is logged. Only `skyward serve` reloads.
693
- - **`skyward routes` and `skyward openapi`.** Skyward API registers them with the `skyward` command too. Each loads the current directory's `app.rb`, which must assign `App = Skyward.app { ... }`. With no `app.rb`, or no `App` that's a Skyward app, it exits 1 naming the file and what it must assign, and a `Skyward::Core::BootError` exits 1 with its message and no backtrace. `skyward routes` prints a line per endpoint, in mount order and then declaration order: its verb, full path, `Class#method` and its method type as the signature file writes it, with a type wrapped over several lines put on one, or for an untyped endpoint as `(id: untyped, ?done: untyped) -> untyped`. Each column but the last is as wide as its widest entry, then two spaces. An app with no routes prints nothing. `skyward openapi` writes the document the OpenAPI document bullet above describes, as pretty JSON with a trailing newline, whether or not the app passed `docs: true`, so the same app always writes the same bytes. Without `docs: true`, a route or static file at `/openapi.json` or `/docs` doesn't stop it, but the document's other problems exit 1 with their message.
694
- - **`skyward check`.** Skyward API registers it with the `skyward` command. It checks the current directory's app three ways, in this order, writing `Signatures:`, `Strict boot:` or `Steep:` and then `passed` or `failed` as each finishes, followed by what it found, and runs every check even after one fails, then exits 1 if any failed and 0 otherwise. rbs-inline, the boot and Steep each run in a Ruby of their own, in the app's directory, with the gems of the bundle `skyward` runs in, as `skyward serve` describes, and nothing is written to the directory. **Signatures** runs rbs-inline, in its default opt-in mode, which reads only files marked `# rbs_inline: enabled`, over every `.rb` file in the directory outside `test/`, `spec/`, `vendor/`, `tmp/` and hidden directories, into a temporary directory. It fails when there's no `sig/generated`, or when the result differs from it, listing each file under `sig/generated` that's missing, out of date or not generated from any file, and either way gives the rbs-inline command that regenerates `sig/generated`. It also fails when rbs-inline does, with its output. **Strict boot** loads `app.rb` as `skyward routes` does, with `SKYWARD_STRICT=1` in the environment, and fails where `skyward routes` would exit 1, with the same message, or on any other error, with its backtrace. It shows the boot's output even when it passes. **Steep** runs `steep check --no-daemon` with the app's `Steepfile`, and passes or fails as Steep does, with its output. Without rbs-inline or Steep in the bundle, or without a `Steepfile`, that check fails saying what to add.
692
+ - **`skyward serve`.** Skyward API registers it with the `skyward` command. It runs the current directory's `config.ru`, needing no `app.rb`, under one Falcon process bound to `localhost`, on `PORT` (9292 by default), with `RACK_ENV=development` unless it's already set. It writes no files but `sig/generated`. With no `config.ru`, or no Falcon in the bundle `skyward` runs in, it exits 1 saying what to do. Under `bundle exec` that's the app's bundle; run bare, `skyward` sees every installed gem. It reloads the app when a `.rb`, `.rbs` or `config.ru` file under the directory is added, changed or removed, outside `tmp/`, `log/`, `vendor/`, `node_modules/` and hidden directories such as `.git/` and `.bundle/`, polling modification times at most once every half second. The first request after a change clears the routes and description of every API class defined in those files, drops those files from `$LOADED_FEATURES` so their `require`s run again, unloads and unregisters each Zeitwerk loader that manages only directories there (so `config.ru` can set it up again), reloads any other Zeitwerk loader with reloading enabled, and builds a new app from `config.ru`. When it starts, it first regenerates `sig/generated` with `Skyward::Core::Signatures::Inline.generate`, using the rbs-inline in that bundle, so the app loads the types the Ruby has now. Then it polls the same files in the background, at most once every half second, and regenerates `sig/generated` as soon as it sees a `.rb` file added, changed or removed, without waiting for a request, so Steep in your editor checks the types you just wrote. The reload still waits for the first request after the change, which regenerates first only if the background hasn't yet: rbs-inline runs once for the `.rb` files as they are, and never twice at once. Without rbs-inline in the bundle, it uses `sig/generated` as it is, runs nothing in the background, and says nothing about it. Regenerating writes only the files whose content changed, so it brings at most one more reload, of `.rbs` files alone, which doesn't regenerate. When rbs-inline fails, `sig/generated` is left as it was. A loader of the app's own needs reloading enabled: Zeitwerk can't unload one without it, or enable it after setup, so the reload fails saying to call `loader.enable_reloading` in development and restart. One reload runs at a time and requests wait for it, while a request in flight finishes on the app it started with. A load that raises, at boot or on a reload, including a `Skyward::Core::BootError` or a `SyntaxError`, answers every request until the next change retries it with the development 500 described under Errors: `type`, `title`, `status`, `detail` and `backtrace`, and an empty body for `HEAD`. So does rbs-inline failing, as a `Skyward::Core::BootError` that carries its output, with an empty `backtrace`. It has no `request_id`, because the app that assigns request IDs is the one that failed to load, and nothing is logged. Only `skyward serve` reloads.
693
+ - **`skyward routes` and `skyward openapi`.** Skyward API registers them with the `skyward` command too. Each loads the current directory's `app.rb`, which must assign `App = Skyward.app { ... }`, after regenerating `sig/generated` as `skyward serve` does, or using it as it is without rbs-inline in the bundle. When rbs-inline fails, it exits 1 with rbs-inline's output, without loading `app.rb`. With no `app.rb`, or no `App` that's a Skyward app, it exits 1 naming the file and what it must assign, and a `Skyward::Core::BootError` exits 1 with its message and no backtrace. `skyward routes` prints a line per endpoint, in mount order and then declaration order: its verb, full path, `Class#method` and its method type as the signature file writes it, with a type wrapped over several lines put on one, or for an untyped endpoint as `(id: untyped, ?done: untyped) -> untyped`. Each column but the last is as wide as its widest entry, then two spaces. An app with no routes prints nothing. `skyward openapi` writes the document the OpenAPI document bullet above describes, as pretty JSON with a trailing newline, whether or not the app passed `docs: true`, so the same app always writes the same bytes. Without `docs: true`, a route or static file at `/openapi.json` or `/docs` doesn't stop it, but the document's other problems exit 1 with their message.
694
+ - **`skyward check`.** Skyward API registers it with the `skyward` command. It checks the current directory's app three ways, in this order, writing `Signatures:`, `Strict boot:` or `Steep:` and then `passed` or `failed` as each finishes, followed by what it found, and runs every check even after one fails, then exits 1 if any failed and 0 otherwise. rbs-inline, the boot and Steep each run in a Ruby of their own, in the app's directory, with the gems of the bundle `skyward` runs in, as `skyward serve` describes, and nothing is written to the directory. **Signatures** runs rbs-inline, in its default opt-in mode, which reads only files marked `# rbs_inline: enabled`, over every `.rb` file in the directory outside `test/`, `spec/`, `vendor/`, `tmp/` and hidden directories, into a temporary directory. It fails when there's no `sig/generated`, or when the result differs from it, listing each file under `sig/generated` that's missing, out of date or not generated from any file, and either way gives the rbs-inline command that regenerates `sig/generated`. It also fails when rbs-inline does, with its output. **Strict boot** loads `app.rb` as `skyward routes` does, without regenerating `sig/generated`, with `SKYWARD_STRICT=1` in the environment, and fails where `skyward routes` would exit 1, with the same message, or on any other error, with its backtrace. It shows the boot's output even when it passes. **Steep** runs `steep check --no-daemon` with the app's `Steepfile`, and passes or fails as Steep does, with its output. Without rbs-inline or Steep in the bundle, or without a `Steepfile`, that check fails saying what to add.
695
695
  - **The test client.** `Skyward::API::Test.client(app)` drives any object with `call(env)` in-process, with no server, and never loads Minitest or RSpec. Its `get`, `post`, `put`, `patch`, `delete`, `head` and `options` each take a path, which may include a query string. `json:` sends a JSON body with `content-type: application/json`, and without it no body is sent. `headers:` sends request headers by their HTTP names, and `cookies:` sends a Hash as a `cookie` header. Each returns a frozen response with `status`, `headers` as the app returned them, `body` as text, and `json`, the body parsed with Symbol keys when the content type is JSON or `+json` and the body isn't empty, and `nil` otherwise. The client reads the whole body and closes it when it responds to `close`.
696
696
  - **Middleware.** `use` adds Rack middleware, with the same arguments as `Rack::Builder#use`, so CORS comes from rack-cors. Middleware wraps the routes in declaration order, the first `use` outermost, wherever it sits relative to `mount`. Request IDs and request logs sit outside it, so a response from middleware still carries an ID and is logged. The stack is built once, at boot, and the app stays frozen, though the middleware objects themselves aren't frozen. Error handling sits outside it too, so an exception from middleware is still answered with a 500.
697
697
  - **Request logs.** Unless `Skyward.app` is given `logger: nil`, every request logs one JSON object on one line, whatever answered it, including a 404 or a 500: `time` (when the request arrived, ISO 8601 in UTC to the millisecond), `method`, `path` (Rack's `SCRIPT_NAME` and `PATH_INFO`, so never the query string), `status`, `duration_ms` (until the app returns its response, to two decimal places) and `request_id`. It writes to `$stdout`, or calls `info` on the `logger:` it's given.
@@ -7,10 +7,10 @@ module Skyward::API::CLI::AppFile
7
7
 
8
8
  ASSIGNMENT = "App = Skyward.app { ... }" #: String
9
9
 
10
- # @rbs (String directory, out: _Writer, kernel: singleton(Kernel)) { (Skyward::API::Assembly::Application) -> String }
11
- # -> void
12
- def run(directory, out:, kernel:, &)
13
- app = load(directory)
10
+ # @rbs (String directory, out: _Writer, kernel: singleton(Kernel), generate: ^() -> String?)
11
+ # { (Skyward::API::Assembly::Application) -> String } -> void
12
+ def run(directory, out:, kernel:, generate:, &)
13
+ app = load(directory, generate)
14
14
  case app
15
15
  when String then kernel.abort(app)
16
16
  else out.write(yield app)
@@ -22,13 +22,17 @@ module Skyward::API::CLI::AppFile
22
22
  end
23
23
 
24
24
  # @rbs directory: String
25
+ # @rbs generate: ^() -> String?
25
26
  # @rbs return: Skyward::API::Assembly::Application | String
26
- def load(directory)
27
+ def load(directory, generate)
27
28
  path = File.join(directory, FILE)
28
29
  unless File.file?(path)
29
30
  return "skyward: no #{FILE} in #{directory}. Run skyward where your app's #{FILE} assigns #{ASSIGNMENT}."
30
31
  end
31
32
 
33
+ failure = generate.call
34
+ return failure if failure
35
+
32
36
  require path
33
37
  app = Object.const_get(:App) if Object.const_defined?(:App)
34
38
  return app if app.is_a?(Skyward::API::Assembly::Application)
@@ -1,11 +1,9 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "tmpdir"
4
-
5
3
  module Skyward::API::CLI::Check
6
4
  extend self
7
5
 
8
- # @rbs! type capture = ^(Hash[String, String] env, Array[String] command, String chdir) -> [String, bool]
6
+ # @rbs! type capture = Skyward::Core::CLI::Executable::capture
9
7
 
10
8
  Outcome = Data.define(
11
9
  :passed, #: bool
@@ -14,19 +12,17 @@ module Skyward::API::CLI::Check
14
12
 
15
13
  PASSED = Outcome.new(passed: true, detail: "") #: Outcome
16
14
 
17
- GENERATED = "sig/generated" #: String
15
+ GENERATED = Skyward::Core::Signatures::Inline::OUTPUT #: String
18
16
 
19
17
  STEEPFILE = "Steepfile" #: String
20
18
 
21
- # None holds the app's contract: its tests, its installed gems and scratch.
22
- UNCHECKED = %w[test spec vendor tmp].freeze #: Array[String]
23
-
24
19
  # The strict boot's own Ruby runs it, so the forced strict mode, the app's
25
20
  # side effects and an exit or crash stay out of skyward check. The require
26
21
  # lives here because a `-r` on the command line runs before RUBYOPT's
27
22
  # `-rbundler/setup` on newer Rubies, before the bundle's gems are loadable.
23
+ # skyward check writes nothing, so the boot doesn't regenerate sig/generated.
28
24
  BOOT = 'require "skyward/api"; ' \
29
- 'Skyward::API::CLI::AppFile.run(Dir.pwd, out: $stdout, kernel: Kernel) { "" }' #: String
25
+ 'Skyward::API::CLI::AppFile.run(Dir.pwd, out: $stdout, kernel: Kernel, generate: -> {}) { "" }' #: String
30
26
 
31
27
  INSTALL_RBS_INLINE = "rbs-inline isn't installed. Add `gem \"rbs-inline\", require: false` to the Gemfile " \
32
28
  "and run `bundle install`.\n" #: String
@@ -56,19 +52,20 @@ module Skyward::API::CLI::Check
56
52
  def signatures(directory, capture:, rbs_inline:)
57
53
  return failed(INSTALL_RBS_INLINE) unless rbs_inline
58
54
 
59
- paths = sources(directory)
55
+ inline = Skyward::Core::Signatures::Inline
56
+ paths = inline.sources(directory)
60
57
  generate = "bundle exec rbs-inline --output=#{GENERATED} #{paths.join(" ")}"
61
58
  generated = File.join(directory, GENERATED)
62
59
  unless File.directory?(generated)
63
60
  return failed("There's no #{GENERATED}. Run `#{generate}` and commit the result.\n")
64
61
  end
65
62
 
66
- Dir.mktmpdir("skyward-check") do |output|
67
- log, ok = capture.call({}, [Gem.ruby, rbs_inline, "--output=#{output}", *paths], directory)
68
- next failed(log) unless ok
69
-
70
- stale = differences(rbs_files(generated), rbs_files(output))
71
- next PASSED if stale.empty?
63
+ expected = inline.run(directory, rbs_inline:, capture:)
64
+ case expected
65
+ when String then failed(expected)
66
+ else
67
+ stale = differences(inline.rbs_files(generated), expected)
68
+ return PASSED if stale.empty?
72
69
 
73
70
  failed(
74
71
  [
@@ -113,20 +110,6 @@ module Skyward::API::CLI::Check
113
110
  # @rbs return: Outcome
114
111
  def failed(detail) = Outcome.new(passed: false, detail:)
115
112
 
116
- # @rbs directory: String
117
- # @rbs return: Array[String]
118
- def sources(directory)
119
- roots = Dir.glob("*/", base: directory).map { |root| root.delete_suffix("/") } - UNCHECKED
120
- files = Dir.glob("*.rb", base: directory)
121
- [*files, *roots.reject { |root| Dir.glob("#{root}/**/*.rb", base: directory).empty? }].sort
122
- end
123
-
124
- # @rbs directory: String
125
- # @rbs return: Hash[String, String]
126
- def rbs_files(directory)
127
- Dir.glob("**/*.rbs", base: directory).to_h { |file| [file, File.read(File.join(directory, file))] }
128
- end
129
-
130
113
  # @rbs current: Hash[String, String]
131
114
  # @rbs expected: Hash[String, String]
132
115
  # @rbs return: Array[String]
@@ -7,22 +7,29 @@ class Skyward::API::CLI::Serve::Reloader
7
7
 
8
8
  # @rbs @watch: ^() -> Hash[String, Time]
9
9
  # @rbs @load: ^() -> Skyward::API::_RackApp
10
+ # @rbs @generate: ^() -> String?
10
11
  # @rbs @clock: ^() -> Float
11
12
  # @rbs @mutex: Thread::Mutex
12
13
  # @rbs @checked_at: Float
13
14
  # @rbs @files: Hash[String, Time]
15
+ # @rbs @sources: Hash[String, Time]
16
+ # @rbs @failure: String?
14
17
  # @rbs @app: Skyward::API::_RackApp
15
18
 
16
19
  # @rbs watch: ^() -> Hash[String, Time]
17
20
  # @rbs load: ^() -> Skyward::API::_RackApp
21
+ # @rbs generate: ^() -> String?
18
22
  # @rbs clock: ^() -> Float
19
23
  # @rbs return: void
20
- def initialize(watch:, load:, clock:)
24
+ def initialize(watch:, load:, generate:, clock:)
21
25
  @watch = watch
22
26
  @load = load
27
+ @generate = generate
23
28
  @clock = clock
24
29
  @mutex = Thread::Mutex.new
25
30
  @checked_at = clock.call
31
+ @sources = {}
32
+ @failure = nil
26
33
  @files = watch.call
27
34
  @app = attempt
28
35
  end
@@ -33,6 +40,17 @@ class Skyward::API::CLI::Serve::Reloader
33
40
  # @rbs return: Skyward::API::rack_response
34
41
  def call(env) = @mutex.synchronize { current }.call(env)
35
42
 
43
+ # Leaves the reload to the next request, which still sees the change.
44
+ # @rbs return: void
45
+ def regenerate
46
+ @mutex.synchronize { generate(@watch.call) }
47
+ # Runs on a thread of its own, which an exception would end. A file removed
48
+ # between listing and reading it raises, and a generate that raised is run
49
+ # again by the next reload, which answers with its error.
50
+ rescue StandardError
51
+ nil
52
+ end
53
+
36
54
  private
37
55
 
38
56
  # @rbs return: Skyward::API::_RackApp
@@ -50,10 +68,32 @@ class Skyward::API::CLI::Serve::Reloader
50
68
 
51
69
  # @rbs return: Skyward::API::_RackApp
52
70
  def attempt
71
+ failure = generate(@files)
72
+ return failed(Skyward::Core::BootError.new(failure)) if failure
73
+
53
74
  @load.call
54
75
  # A SyntaxError or LoadError is a ScriptError, not a StandardError.
55
76
  rescue StandardError, ScriptError => e
56
- ->(env) { failure(e, env) } #: ^(Hash[String, untyped]) -> Skyward::API::rack_response
77
+ failed(e)
78
+ end
79
+
80
+ # Runs rbs-inline once for the .rb files as they are, whether regenerate or
81
+ # a reload sees them first.
82
+ # @rbs files: Hash[String, Time]
83
+ # @rbs return: String?
84
+ def generate(files)
85
+ sources = files.select { |file, _time| file.end_with?(".rb") }
86
+ return @failure if sources == @sources
87
+
88
+ @failure = @generate.call
89
+ @sources = sources
90
+ @failure
91
+ end
92
+
93
+ # @rbs error: Exception
94
+ # @rbs return: Skyward::API::_RackApp
95
+ def failed(error)
96
+ ->(env) { failure(error, env) } #: ^(Hash[String, untyped]) -> Skyward::API::rack_response
57
97
  end
58
98
 
59
99
  # The development 500 that Skyward::API::Middleware::Rescue answers, without a request
@@ -69,7 +109,8 @@ class Skyward::API::CLI::Serve::Reloader
69
109
  title: "Internal Server Error",
70
110
  status: 500,
71
111
  detail: "#{error.class}: #{message}",
72
- backtrace: error.backtrace
112
+ # rbs-inline's failure is never raised, so has no backtrace.
113
+ backtrace: error.backtrace || []
73
114
  }
74
115
  body = env["REQUEST_METHOD"] == "HEAD" ? [] : [JSON.generate(problem)] #: Array[String]
75
116
  [500, { "content-type" => "application/problem+json" }, body]
@@ -45,22 +45,29 @@ module Skyward::API::CLI::Serve
45
45
  )
46
46
  end
47
47
 
48
+ # Without rbs-inline, generate is nil, and sig/generated is used as it is.
48
49
  # @rbs directory: String
49
50
  # @rbs build: ^(String config) -> Skyward::API::_RackApp
50
51
  # @rbs clock: ^() -> Float
51
52
  # @rbs apis: ^() -> Array[singleton(Skyward::API)]
52
53
  # @rbs features: Array[String]
53
54
  # @rbs loaders: ^() -> Array[Zeitwerk::Loader]
55
+ # @rbs generate: (^() -> String?)?
56
+ # @rbs every: ^(Float interval) { () -> void } -> void
54
57
  # @rbs return: Reloader
55
- def reloader(directory, build:, clock:, apis:, features:, loaders:)
56
- Reloader.new(
58
+ def reloader(directory, build:, clock:, apis:, features:, loaders:, generate:, every:)
59
+ reloader = Reloader.new(
57
60
  watch: -> { watch(directory) },
58
61
  load: lambda do
59
62
  unload(directory, apis: apis.call, features:, loaders: loaders.call)
60
63
  build.call(File.join(directory, CONFIG))
61
64
  end,
65
+ generate: generate || -> {},
62
66
  clock:
63
67
  )
68
+ # So the editor's Steep checks the types just written, before any request.
69
+ every.call(Reloader::INTERVAL) { reloader.regenerate } if generate
70
+ reloader
64
71
  end
65
72
 
66
73
  # @rbs directory: String
@@ -4,6 +4,11 @@
4
4
  # doesn't depend on it, and Falcon brings it.
5
5
  require "skyward/api"
6
6
 
7
+ rbs_inline = Skyward::Core::CLI::Executable.find("rbs-inline", feature: "rbs/inline")
8
+
9
+ capture = Skyward::Core::CLI::Executable::CAPTURE
10
+ generate = rbs_inline && -> { Skyward::Core::Signatures::Inline.generate(Dir.pwd, rbs_inline:, capture:) }
11
+
7
12
  run Skyward::API::CLI::Serve.reloader(
8
13
  Dir.pwd,
9
14
  build: ->(config) { Rack::Builder.parse_file(config) },
@@ -12,5 +17,15 @@ run Skyward::API::CLI::Serve.reloader(
12
17
  features: $LOADED_FEATURES,
13
18
  # Zeitwerk has no public list of its loaders, and ObjectSpace would go on
14
19
  # finding the ones serve unregisters until they're garbage collected.
15
- loaders: -> { Zeitwerk::Registry.loaders.enum_for(:each).to_a }
20
+ loaders: -> { Zeitwerk::Registry.loaders.enum_for(:each).to_a },
21
+ generate:,
22
+ # Ruby ends the thread when Falcon's worker exits.
23
+ every: lambda do |interval, &tick|
24
+ Thread.new do
25
+ loop do
26
+ sleep(interval)
27
+ tick.call
28
+ end
29
+ end
30
+ end
16
31
  )
@@ -3,11 +3,19 @@
3
3
  require "json"
4
4
  require "skyward/api"
5
5
 
6
+ generate = lambda do
7
+ Skyward::Core::Signatures::Inline.generate(
8
+ Dir.pwd,
9
+ rbs_inline: Skyward::Core::CLI::Executable.find("rbs-inline", feature: "rbs/inline"),
10
+ capture: Skyward::Core::CLI::Executable::CAPTURE
11
+ )
12
+ end
13
+
6
14
  Skyward::Core::CLI.register("serve", "Serve config.ru with Falcon in development, on PORT (default 9292)") do |_args|
7
15
  Skyward::API::CLI::Serve.run(
8
16
  Dir.pwd,
9
17
  env: ENV.to_h,
10
- falcon: Skyward::API::CLI::Executable.find("falcon"),
18
+ falcon: Skyward::Core::CLI::Executable.find("falcon"),
11
19
  kernel: Kernel
12
20
  )
13
21
  end
@@ -18,21 +26,20 @@ Skyward::Core::CLI.register("check", "Check signatures, boot app.rb in strict mo
18
26
  exit Skyward::API::CLI::Check.run(
19
27
  Dir.pwd,
20
28
  out: $stdout,
21
- capture: lambda do |env, command, chdir|
22
- # RBS doesn't list the [:child, :out] spelling of this redirect.
23
- output = IO.popen(env, command, chdir:, err: [:child, 1], &:read)
24
- # RBS doesn't declare Process.last_status, set by the popen above.
25
- [output, Process.last_status.success?] # steep:ignore NoMethod
26
- end,
27
- rbs_inline: Skyward::API::CLI::Executable.find("rbs-inline", feature: "rbs/inline"),
28
- steep: Skyward::API::CLI::Executable.find("steep")
29
+ capture: Skyward::Core::CLI::Executable::CAPTURE,
30
+ rbs_inline: Skyward::Core::CLI::Executable.find("rbs-inline", feature: "rbs/inline"),
31
+ steep: Skyward::Core::CLI::Executable.find("steep")
29
32
  )
30
33
  end
31
34
 
32
35
  Skyward::Core::CLI.register("routes", "Print every route with its handler and signature") do |_args|
33
- Skyward::API::CLI::AppFile.run(Dir.pwd, out: $stdout, kernel: Kernel) { |app| Skyward::API::CLI::Routes.table(app.endpoints) }
36
+ Skyward::API::CLI::AppFile.run(Dir.pwd, out: $stdout, kernel: Kernel, generate:) do |app|
37
+ Skyward::API::CLI::Routes.table(app.endpoints)
38
+ end
34
39
  end
35
40
 
36
41
  Skyward::Core::CLI.register("openapi", "Write the OpenAPI document to stdout") do |_args|
37
- Skyward::API::CLI::AppFile.run(Dir.pwd, out: $stdout, kernel: Kernel) { |app| "#{JSON.pretty_generate(app.openapi)}\n" }
42
+ Skyward::API::CLI::AppFile.run(Dir.pwd, out: $stdout, kernel: Kernel, generate:) do |app|
43
+ "#{JSON.pretty_generate(app.openapi)}\n"
44
+ end
38
45
  end
@@ -83,7 +83,7 @@ module Skyward::API::Serializer::Writers
83
83
  def scalar(name)
84
84
  case name
85
85
  when :integer then checked("Integer", ->(value) { value.is_a?(Integer) }, ->(value, _) { value })
86
- when :float then checked("Float", ->(value) { value.is_a?(Float) }, ->(value, _) { value })
86
+ when :float then checked("Float", ->(value) { value.is_a?(Float) && value.finite? }, ->(value, _) { value })
87
87
  when :string then checked("String", ->(value) { value.is_a?(String) }, ->(value, _) { value })
88
88
  when :bool then checked("bool", ->(value) { [true, false].include?(value) }, ->(value, _) { value })
89
89
  when :date then checked("Date", ->(value) { value.is_a?(Date) }, ->(value, _) { date(value) })
@@ -4,7 +4,7 @@ module Skyward
4
4
  class API
5
5
  # x-release-please-start-version
6
6
 
7
- VERSION = "0.2.0" #: String
7
+ VERSION = "0.3.0" #: String
8
8
 
9
9
  # x-release-please-end
10
10
  end
@@ -5,11 +5,12 @@ module Skyward::API::CLI::AppFile
5
5
 
6
6
  ASSIGNMENT: String
7
7
 
8
- # @rbs (String directory, out: _Writer, kernel: singleton(Kernel)) { (Skyward::API::Assembly::Application) -> String }
9
- # -> void
10
- def run: (String directory, out: _Writer, kernel: singleton(Kernel)) { (Skyward::API::Assembly::Application) -> String } -> void
8
+ # @rbs (String directory, out: _Writer, kernel: singleton(Kernel), generate: ^() -> String?)
9
+ # { (Skyward::API::Assembly::Application) -> String } -> void
10
+ def run: (String directory, out: _Writer, kernel: singleton(Kernel), generate: ^() -> String?) { (Skyward::API::Assembly::Application) -> String } -> void
11
11
 
12
12
  # @rbs directory: String
13
+ # @rbs generate: ^() -> String?
13
14
  # @rbs return: Skyward::API::Assembly::Application | String
14
- def load: (String directory) -> (Skyward::API::Assembly::Application | String)
15
+ def load: (String directory, ^() -> String? generate) -> (Skyward::API::Assembly::Application | String)
15
16
  end
@@ -1,7 +1,7 @@
1
1
  # Generated from lib/skyward/api/cli/check.rb with RBS::Inline
2
2
 
3
3
  module Skyward::API::CLI::Check
4
- type capture = ^(Hash[String, String] env, Array[String] command, String chdir) -> [ String, bool ]
4
+ type capture = Skyward::Core::CLI::Executable::capture
5
5
 
6
6
  class Outcome < Data
7
7
  attr_reader passed(): bool
@@ -22,13 +22,11 @@ module Skyward::API::CLI::Check
22
22
 
23
23
  STEEPFILE: String
24
24
 
25
- # None holds the app's contract: its tests, its installed gems and scratch.
26
- UNCHECKED: Array[String]
27
-
28
25
  # The strict boot's own Ruby runs it, so the forced strict mode, the app's
29
26
  # side effects and an exit or crash stay out of skyward check. The require
30
27
  # lives here because a `-r` on the command line runs before RUBYOPT's
31
28
  # `-rbundler/setup` on newer Rubies, before the bundle's gems are loadable.
29
+ # skyward check writes nothing, so the boot doesn't regenerate sig/generated.
32
30
  BOOT: String
33
31
 
34
32
  INSTALL_RBS_INLINE: String
@@ -61,14 +59,6 @@ module Skyward::API::CLI::Check
61
59
  # @rbs return: Outcome
62
60
  def failed: (String detail) -> Outcome
63
61
 
64
- # @rbs directory: String
65
- # @rbs return: Array[String]
66
- def sources: (String directory) -> Array[String]
67
-
68
- # @rbs directory: String
69
- # @rbs return: Hash[String, String]
70
- def rbs_files: (String directory) -> Hash[String, String]
71
-
72
62
  # @rbs current: Hash[String, String]
73
63
  # @rbs expected: Hash[String, String]
74
64
  # @rbs return: Array[String]
@@ -3,25 +3,32 @@
3
3
  class Skyward::API::CLI::Serve::Reloader
4
4
  INTERVAL: Float
5
5
 
6
- @watch: ^() -> Hash[String, Time]
6
+ @app: Skyward::API::_RackApp
7
7
 
8
- @load: ^() -> Skyward::API::_RackApp
8
+ @failure: String?
9
9
 
10
- @clock: ^() -> Float
10
+ @sources: Hash[String, Time]
11
11
 
12
- @mutex: Thread::Mutex
12
+ @files: Hash[String, Time]
13
13
 
14
14
  @checked_at: Float
15
15
 
16
- @files: Hash[String, Time]
16
+ @mutex: Thread::Mutex
17
17
 
18
- @app: Skyward::API::_RackApp
18
+ @clock: ^() -> Float
19
+
20
+ @generate: ^() -> String?
21
+
22
+ @load: ^() -> Skyward::API::_RackApp
23
+
24
+ @watch: ^() -> Hash[String, Time]
19
25
 
20
26
  # @rbs watch: ^() -> Hash[String, Time]
21
27
  # @rbs load: ^() -> Skyward::API::_RackApp
28
+ # @rbs generate: ^() -> String?
22
29
  # @rbs clock: ^() -> Float
23
30
  # @rbs return: void
24
- def initialize: (watch: ^() -> Hash[String, Time], load: ^() -> Skyward::API::_RackApp, clock: ^() -> Float) -> void
31
+ def initialize: (watch: ^() -> Hash[String, Time], load: ^() -> Skyward::API::_RackApp, generate: ^() -> String?, clock: ^() -> Float) -> void
25
32
 
26
33
  # The app is taken under the lock but called outside it, so a request in
27
34
  # flight finishes on the app it started with.
@@ -29,6 +36,10 @@ class Skyward::API::CLI::Serve::Reloader
29
36
  # @rbs return: Skyward::API::rack_response
30
37
  def call: (Hash[String, untyped] env) -> Skyward::API::rack_response
31
38
 
39
+ # Leaves the reload to the next request, which still sees the change.
40
+ # @rbs return: void
41
+ def regenerate: () -> void
42
+
32
43
  private
33
44
 
34
45
  # @rbs return: Skyward::API::_RackApp
@@ -37,6 +48,16 @@ class Skyward::API::CLI::Serve::Reloader
37
48
  # @rbs return: Skyward::API::_RackApp
38
49
  def attempt: () -> Skyward::API::_RackApp
39
50
 
51
+ # Runs rbs-inline once for the .rb files as they are, whether regenerate or
52
+ # a reload sees them first.
53
+ # @rbs files: Hash[String, Time]
54
+ # @rbs return: String?
55
+ def generate: (Hash[String, Time] files) -> String?
56
+
57
+ # @rbs error: Exception
58
+ # @rbs return: Skyward::API::_RackApp
59
+ def failed: (Exception error) -> Skyward::API::_RackApp
60
+
40
61
  # The development 500 that Skyward::API::Middleware::Rescue answers, without a request
41
62
  # ID: the app that assigns them is the one that failed to load.
42
63
  # @rbs error: Exception
@@ -18,14 +18,17 @@ module Skyward::API::CLI::Serve
18
18
  # @rbs return: void
19
19
  def run: (String directory, env: Hash[String, String], falcon: String?, kernel: singleton(Kernel)) -> void
20
20
 
21
+ # Without rbs-inline, generate is nil, and sig/generated is used as it is.
21
22
  # @rbs directory: String
22
23
  # @rbs build: ^(String config) -> Skyward::API::_RackApp
23
24
  # @rbs clock: ^() -> Float
24
25
  # @rbs apis: ^() -> Array[singleton(Skyward::API)]
25
26
  # @rbs features: Array[String]
26
27
  # @rbs loaders: ^() -> Array[Zeitwerk::Loader]
28
+ # @rbs generate: (^() -> String?)?
29
+ # @rbs every: ^(Float interval) { () -> void } -> void
27
30
  # @rbs return: Reloader
28
- def reloader: (String directory, build: ^(String config) -> Skyward::API::_RackApp, clock: ^() -> Float, apis: ^() -> Array[singleton(Skyward::API)], features: Array[String], loaders: ^() -> Array[Zeitwerk::Loader]) -> Reloader
31
+ def reloader: (String directory, build: ^(String config) -> Skyward::API::_RackApp, clock: ^() -> Float, apis: ^() -> Array[singleton(Skyward::API)], features: Array[String], loaders: ^() -> Array[Zeitwerk::Loader], generate: (^() -> String?)?, every: ^(Float interval) { () -> void } -> void) -> Reloader
29
32
 
30
33
  # @rbs directory: String
31
34
  # @rbs return: Hash[String, Time]
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: skyward-api
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.0
4
+ version: 0.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Jake Bottrall
@@ -15,14 +15,14 @@ dependencies:
15
15
  requirements:
16
16
  - - '='
17
17
  - !ruby/object:Gem::Version
18
- version: 0.2.0
18
+ version: 0.3.0
19
19
  type: :runtime
20
20
  prerelease: false
21
21
  version_requirements: !ruby/object:Gem::Requirement
22
22
  requirements:
23
23
  - - '='
24
24
  - !ruby/object:Gem::Version
25
- version: 0.2.0
25
+ version: 0.3.0
26
26
  - !ruby/object:Gem::Dependency
27
27
  name: zeitwerk
28
28
  requirement: !ruby/object:Gem::Requirement
@@ -54,7 +54,6 @@ files:
54
54
  - lib/skyward/api/cli.rb
55
55
  - lib/skyward/api/cli/app_file.rb
56
56
  - lib/skyward/api/cli/check.rb
57
- - lib/skyward/api/cli/executable.rb
58
57
  - lib/skyward/api/cli/routes.rb
59
58
  - lib/skyward/api/cli/serve.rb
60
59
  - lib/skyward/api/cli/serve.ru
@@ -103,7 +102,6 @@ files:
103
102
  - sig/generated/skyward/api/cli.rbs
104
103
  - sig/generated/skyward/api/cli/app_file.rbs
105
104
  - sig/generated/skyward/api/cli/check.rbs
106
- - sig/generated/skyward/api/cli/executable.rbs
107
105
  - sig/generated/skyward/api/cli/routes.rbs
108
106
  - sig/generated/skyward/api/cli/serve.rbs
109
107
  - sig/generated/skyward/api/cli/serve/reloader.rbs
@@ -145,7 +143,6 @@ files:
145
143
  - sig/manual/skyward/api/assembly/boot.rbs
146
144
  - sig/manual/skyward/api/cli/app_file.rbs
147
145
  - sig/manual/skyward/api/cli/check.rbs
148
- - sig/manual/skyward/api/cli/executable.rbs
149
146
  - sig/manual/skyward/api/cli/routes.rbs
150
147
  - sig/manual/skyward/api/cli/serve.rbs
151
148
  - sig/manual/skyward/api/inputs/coercer.rbs
@@ -1,15 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module Skyward::API::CLI::Executable
4
- extend self
5
-
6
- # Under Bundler, Gem.find_files and Gem.bin_path see only the bundle's gems,
7
- # so a gem installed outside the app's bundle isn't found. Checking first
8
- # spares rescuing the error bin_path raises for a missing gem.
9
- # @rbs name: String
10
- # @rbs feature: String
11
- # @rbs return: String?
12
- def find(name, feature: name)
13
- Gem.bin_path(name, name) unless Gem.find_files("#{feature}.rb").empty?
14
- end
15
- end
@@ -1,11 +0,0 @@
1
- # Generated from lib/skyward/api/cli/executable.rb with RBS::Inline
2
-
3
- module Skyward::API::CLI::Executable
4
- # Under Bundler, Gem.find_files and Gem.bin_path see only the bundle's gems,
5
- # so a gem installed outside the app's bundle isn't found. Checking first
6
- # spares rescuing the error bin_path raises for a missing gem.
7
- # @rbs name: String
8
- # @rbs feature: String
9
- # @rbs return: String?
10
- def find: (String name, ?feature: String) -> String?
11
- end
@@ -1,3 +0,0 @@
1
- module Skyward::API::CLI::Executable
2
- extend ::Skyward::API::CLI::Executable
3
- end