From cb2681fbeeb1385502fd8bed5c03211f55ebacdb Mon Sep 17 00:00:00 2001 From: Karina Munoz Gonzalez Date: Wed, 18 Nov 2026 10:35:06 -0600 Subject: [PATCH 1/5] feat(core): add the version negotiation headers to every route (#1401) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### Summary - Fixes #1386 - Time to review: 20 minutes Adds protocol version 0.6.0 and the version headers from ADR 0032 (API version negotiation) to the core library. Clients can ask for a version with `CG-Version`, and every response confirms the version it was served in with `CG-Version-Served`. The docs mock API now serves 0.6.0 so the website build stays green. The version errors (#1388), the discovery route (#1387, PR #1399), the docs (#1389, #1391) and moving the mock to the version header (#1393) are separate tickets. > [!IMPORTANT] > This PR and #1399 both add `Versions.v0_6` and `Types.protocolVersion`. Whichever merges second drops its copy. Once both land, the discovery route needs its own 200 response without the version headers, because ADR 0032 says discovery carries neither `CG-Version-Served` nor `Vary`. ### Changes proposed - Protocol version 0.6.0: - `lib/core/lib/main.tsp`: adds `v0_6: "0.6.0"` to `Versions`. - `lib/core/lib/core/types.tsp`: adds `Types.protocolVersion`, a full `MAJOR.MINOR.PATCH` version with no `v` prefix, no short forms and no leading zeros. - `lib/core/lib/core/headers.tsp`: new `CommonGrants.Headers` namespace, not emitted as JSON Schema. - `VersionRequest`: optional `CG-Version` request header. - `VersionResponse`: required `CG-Version-Served`, plus optional `Vary`, `Deprecation` (RFC 9745 `@`), `Sunset` (RFC 8594 HTTP-date) and `Link`. - `VersionResponseAuth`: the same headers with `CG-Version-Served` optional, for 401 and 403, because authentication can run before version selection. - The namespace example shows `...Headers.VersionRequest` on a hand-declared protocol route, since custom routes ignore `CG-Version`. - `lib/core/lib/core/index.tsp`: imports `headers.tsp`. - Request header on every route: `lib/core/lib/core/routes/{opportunities,awards,orgs,competitions,applications,form-responses,forms}.tsp` spread `...Headers.VersionRequest` as the last parameter of every operation, so adopters inherit it through `op x is Router.y`. - Response headers on every response: - `lib/core/lib/core/responses/success.tsp`: spreads `...Headers.VersionResponse` into `OkT`, `PaginatedT`, `SortedT`, `FilteredT`, `CreatedT` and `AcceptedT`. The emitted non-template models are untouched. - `lib/core/lib/core/responses/error.tsp`: `NotFound` intersects `VersionResponse`. `Unauthorized` and `Forbidden` intersect `VersionResponseAuth`. - `lib/core/lib/core/routes/applications.tsp`: `submitApplication` returns a new `ApplicationSubmissionErrorResponse` wrapper with an explicit `@body`, so the submission error keeps `@error` and its body reference while gaining the headers. - Generated: `website/public/openapi/openapi.0.6.0.yaml` and `website/public/schemas/yaml/protocolVersion.yaml`. - Docs mock API serves 0.6.0: - `website/src/lib/mock/data/fixtures.ts`: adds `0.6.0` to `SUPPORTED_VERSIONS`. It shapes responses the same as 0.5.0, because 0.6.0 adds only headers. - `website/__tests__/lib/mock/**` and `website/__tests__/scripts/inject-mock-server.spec.ts`: cover 0.6.0, and use 0.7.0 as the unsupported version. - `lib/python-sdk/tests/schemas/test_award_inventory.py`: moves the Core baseline tripwire from 0.5.0 to 0.6.0. 0.6.0 adds no fields to the Award closure. ### Context for reviewers The part worth the closest look is how the headers stay out of the 0.1.0 to 0.5.0 documents and out of the JSON Schemas. - **Versioning on spreads.** Every header property carries its own `@added(v0_6)`. Spreading a model copies its properties without the model's versioning, so a model-level `@added` alone leaked the headers into older documents. - **Submission error wrapper.** It lives in `Routes`, not `Responses`, because `Responses` is `@jsonSchema` and would emit the headers as schema fields. Intersecting the headers onto `ApplicationSubmissionError` dropped `@error` and moved it into the 200 response. The wrapper's explanation is a `//` comment because a doc comment replaced the response description in older documents. - **`Vary` is optional in OpenAPI.** ADR 0032 requires it only on cacheable responses, which OpenAPI can't express, so the rule lives in the header description. - **CI is green.** Adding `Versions.v0_6` used to break two checks: the website's mock server guard and the Python SDK's Core baseline tripwire. This PR updates both. The mock still selects the version from the URL path; #1393 moves it to `CG-Version`. To verify: 1. Run core CI. It should pass. ```bash pnpm --filter @common-grants/core run ci ``` 2. Regenerate the website outputs. `git status` should show no changes under `website/public`. ```bash pnpm --filter website run typespec && git status --short website/public ``` 3. Confirm the older documents are unchanged. The output should be empty. ```bash git diff --stat origin/CORE-v0.6.0 -- website/public/openapi/openapi.0.{1,2,3,4,5}.0.yaml ``` 4. Confirm the only JSON Schema change is the new `protocolVersion.yaml`. ```bash git diff --stat origin/CORE-v0.6.0 -- website/public/schemas ``` 5. Count the headers in 0.6.0. Expect 21 request header references, one per operation, and 47 `CG-Version-Served` headers, one per response. ```bash grep -c "Headers.VersionRequest'" website/public/openapi/openapi.0.6.0.yaml grep -c "CG-Version-Served:" website/public/openapi/openapi.0.6.0.yaml ``` ### Additional information Core CI: ``` $ tsp compile lib/main.tsp TypeSpec compiler v1.17.0 ✔ Compiling ✔ @typespec/json-schema 68ms tsp-output/@typespec/json-schema/ ✔ @typespec/openapi3 397ms tsp-output/@typespec/openapi3/ Compilation completed successfully. ``` Every response in `openapi.0.6.0.yaml`, grouped by status code (count, then whether each header is required or optional): ``` 19 200 | CG-Version-Served:req Vary:opt Deprecation:opt Sunset:opt Link:opt 1 201 | CG-Version-Served:req Vary:opt Deprecation:opt Sunset:opt Link:opt 1 202 | CG-Version-Served:req Vary:opt Deprecation:opt Sunset:opt Link:opt 10 404 | CG-Version-Served:req Vary:opt Deprecation:opt Sunset:opt Link:opt 1 default | CG-Version-Served:req Vary:opt Deprecation:opt Sunset:opt Link:opt 9 401 | CG-Version-Served:opt Vary:opt Deprecation:opt Sunset:opt Link:opt 6 403 | CG-Version-Served:opt Vary:opt Deprecation:opt Sunset:opt Link:opt Sunset schema: {"type":"string","format":"http-date"} Deprecation schema: {"type":"string","pattern":"^@-?[0-9]+$"} CG-Version-Served schema: {"$ref":"#/components/schemas/CommonGrants.Types.protocolVersion"} CG-Version params: 21 of 21 operations ``` Every 0.5.0 response compared against 0.6.0 for body, description, pre-existing headers (such as `Location` on 202) and request bodies: ``` checked 47 responses, 0 differences component schemas added in 0.6.0: [ 'CommonGrants.Types.protocolVersion' ] ``` Adopter quickstarts still compile against the new route interfaces: ``` ✓ Getting Started (First steps) quickstart compiles ✓ Getting Started (after Customization) quickstart compiles ✓ lib/core/README.md quickstart compiles ``` --- lib/core/lib/core/headers.tsp | 97 + lib/core/lib/core/index.tsp | 1 + lib/core/lib/core/responses/error.tsp | 14 +- lib/core/lib/core/responses/success.tsp | 10 + lib/core/lib/core/routes/applications.tsp | 19 +- lib/core/lib/core/routes/awards.tsp | 5 + lib/core/lib/core/routes/competitions.tsp | 4 + lib/core/lib/core/routes/form-responses.tsp | 4 + lib/core/lib/core/routes/forms.tsp | 3 + lib/core/lib/core/routes/opportunities.tsp | 5 + lib/core/lib/core/routes/orgs.tsp | 11 + lib/core/lib/core/types.tsp | 9 + lib/core/lib/main.tsp | 1 + .../tests/schemas/test_award_inventory.py | 6 +- .../mock/__fixtures__/golden-envelopes.json | 4 +- .../lib/mock/__fixtures__/request-matrix.ts | 2 +- .../applications-vs-openapi.spec.ts | 2 + .../__tests__/lib/mock/data/fixtures.spec.ts | 9 +- .../lib/mock/handlers/applications.spec.ts | 2 + .../scripts/inject-mock-server.spec.ts | 4 +- website/public/openapi/openapi.0.6.0.yaml | 7973 +++++++++++++++++ .../public/schemas/yaml/protocolVersion.yaml | 10 + website/src/lib/mock/data/fixtures.ts | 3 + 23 files changed, 8182 insertions(+), 16 deletions(-) create mode 100644 lib/core/lib/core/headers.tsp create mode 100644 website/public/openapi/openapi.0.6.0.yaml create mode 100644 website/public/schemas/yaml/protocolVersion.yaml diff --git a/lib/core/lib/core/headers.tsp b/lib/core/lib/core/headers.tsp new file mode 100644 index 000000000..b2d63c4b7 --- /dev/null +++ b/lib/core/lib/core/headers.tsp @@ -0,0 +1,97 @@ +import "@typespec/http"; +import "@typespec/versioning"; +import "./types.tsp"; + +/** Version negotiation headers (ADR 0032), added in protocol version 0.6.0 + * + * @example How to add the version request header to a declared protocol route + * + * ```typespec + * import "@typespec/http"; + * import "@common-grants/core"; + * + * using CommonGrants; // exposes the Headers namespace + * using TypeSpec.Http; + * using TypeSpec.Versioning; + * + * @service + * @useDependency(CommonGrants.Versions.v0_6) + * namespace MyApi; + * + * @route("/common-grants/opportunities") + * @get + * op listOpportunities( + * ...Pagination.PaginatedQueryParams, + * ...Headers.VersionRequest, + * ): Responses.PaginatedT; + * ``` + */ +namespace CommonGrants.Headers; + +/** Request headers a client sends to select a protocol version */ +@Versioning.added(CommonGrants.Versions.v0_6) +model VersionRequest { + /** The protocol version the client wants, such as `0.6.0` + * + * Servers match on major and minor version. When absent, the server responds + * in its default version. + */ + @Http.header("CG-Version") + // Spreading drops model-level `@added`, so each property repeats it + @Versioning.added(CommonGrants.Versions.v0_6) + cgVersion?: Types.protocolVersion; +} + +/** Response headers that report the protocol version a response was served in */ +@Versioning.added(CommonGrants.Versions.v0_6) +model VersionResponse { + /** The full protocol version this response was served in, such as `0.5.1` + * + * Can differ from the requested version in the patch number only. + */ + @Http.header("CG-Version-Served") + @Versioning.added(CommonGrants.Versions.v0_6) + cgVersionServed: Types.protocolVersion; + + ...VersionLifecycle; +} + +/** Version headers for 401 and 403 responses */ +@Versioning.added(CommonGrants.Versions.v0_6) +model VersionResponseAuth { + /** The full protocol version this response was served in, such as `0.5.1` + * + * Optional because authentication can run before a version is selected. + */ + @Http.header("CG-Version-Served") + @Versioning.added(CommonGrants.Versions.v0_6) + cgVersionServed?: Types.protocolVersion; + + ...VersionLifecycle; +} + +/** Caching and retirement headers shared by `VersionResponse` and `VersionResponseAuth` */ +@Versioning.added(CommonGrants.Versions.v0_6) +model VersionLifecycle { + /** Request headers that caches must key this response on, such as `CG-Version` */ + @Http.header("Vary") + @Versioning.added(CommonGrants.Versions.v0_6) + vary?: string; + + /** When the served version was or will be deprecated (RFC 9745), such as `@1796083200` */ + @pattern("^@-?[0-9]+$") + @Http.header("Deprecation") + @Versioning.added(CommonGrants.Versions.v0_6) + deprecation?: string; + + /** When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` */ + @encode(DateTimeKnownEncoding.rfc7231) + @Http.header("Sunset") + @Versioning.added(CommonGrants.Versions.v0_6) + sunset?: utcDateTime; + + /** Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` */ + @Http.header("Link") + @Versioning.added(CommonGrants.Versions.v0_6) + link?: string; +} diff --git a/lib/core/lib/core/index.tsp b/lib/core/lib/core/index.tsp index f3884c3c1..3b27c6279 100644 --- a/lib/core/lib/core/index.tsp +++ b/lib/core/lib/core/index.tsp @@ -1,4 +1,5 @@ import "./types.tsp"; +import "./headers.tsp"; import "./fields/index.tsp"; import "./models/index.tsp"; import "./routes/index.tsp"; diff --git a/lib/core/lib/core/responses/error.tsp b/lib/core/lib/core/responses/error.tsp index 57caa364a..7a5a9167c 100644 --- a/lib/core/lib/core/responses/error.tsp +++ b/lib/core/lib/core/responses/error.tsp @@ -1,3 +1,4 @@ +import "../headers.tsp"; import "@typespec/http"; namespace CommonGrants.Responses; @@ -10,6 +11,11 @@ namespace CommonGrants.Responses; * import "@typespec/http" * * alias Unauthorized = Error & Http.UnauthorizedResponse + * + * // From protocol version 0.6.0, also carry the version response headers + * alias VersionedUnauthorized = Error & + * Http.UnauthorizedResponse & + * Headers.VersionResponseAuth * ``` */ @error @@ -27,9 +33,11 @@ model Error { errors: Array; } -alias Unauthorized = Error & Http.UnauthorizedResponse; -alias Forbidden = Error & Http.ForbiddenResponse; -alias NotFound = Error & Http.NotFoundResponse; +alias Unauthorized = Error & + Http.UnauthorizedResponse & + Headers.VersionResponseAuth; +alias Forbidden = Error & Http.ForbiddenResponse & Headers.VersionResponseAuth; +alias NotFound = Error & Http.NotFoundResponse & Headers.VersionResponse; @example(#{ status: 400, diff --git a/lib/core/lib/core/responses/success.tsp b/lib/core/lib/core/responses/success.tsp index 32a104abb..e6c13588c 100644 --- a/lib/core/lib/core/responses/success.tsp +++ b/lib/core/lib/core/responses/success.tsp @@ -1,3 +1,4 @@ +import "../headers.tsp"; import "../pagination.tsp"; import "../sorting.tsp"; import "@typespec/http"; @@ -57,6 +58,8 @@ model OkT extends Success { // Inherit the 200 status code ...Http.OkResponse; + ...Headers.VersionResponse; + /** Response data */ data: T; } @@ -111,6 +114,7 @@ model PaginatedT extends Success { // Inherit the 200 status code ...Http.OkResponse; + ...Headers.VersionResponse; ...PaginatedBase; } @@ -162,6 +166,7 @@ model SortedT extends Success { // Inherit the 200 status code ...Http.OkResponse; + ...Headers.VersionResponse; ...SortedBase; } @@ -225,6 +230,7 @@ model FilteredT extends Success { // Inherit the 200 status code ...Http.OkResponse; + ...Headers.VersionResponse; ...FilteredBase; } @@ -253,6 +259,8 @@ model CreatedT extends Success { // Inherit the 201 status code ...Http.CreatedResponse; + ...Headers.VersionResponse; + /** Response data */ data: T; } @@ -286,6 +294,8 @@ model AcceptedT extends Success { // Inherit the 202 status code ...Http.AcceptedResponse; + ...Headers.VersionResponse; + /** URL where the accepted resource can be retrieved */ @Http.header("Location") location?: url; diff --git a/lib/core/lib/core/routes/applications.tsp b/lib/core/lib/core/routes/applications.tsp index 52dcbb500..3204123c3 100644 --- a/lib/core/lib/core/routes/applications.tsp +++ b/lib/core/lib/core/routes/applications.tsp @@ -33,6 +33,8 @@ interface Applications { /** The title of the application */ @Versioning.renamedFrom(Versions.v0_4, "name") title: string, + + ...Headers.VersionRequest, ): Responses.CreatedT | Responses.Unauthorized; // ############################### @@ -46,6 +48,8 @@ interface Applications { getApplication( /** The ID of the application to get */ @path appId: Types.uuid, + + ...Headers.VersionRequest, ): | Responses.OkT | Responses.NotFound @@ -62,9 +66,11 @@ interface Applications { submitApplication( /** The ID of the application to submit */ @path appId: Types.uuid, + + ...Headers.VersionRequest, ): | Responses.OkT - | Responses.ApplicationSubmissionError + | ApplicationSubmissionErrorResponse | Responses.NotFound | Responses.Unauthorized; @@ -82,5 +88,16 @@ interface Applications { /** The sorting to apply to the search */ @query sorting: Models.AppSorting, + + ...Headers.VersionRequest, ): Responses.FilteredT; } + +// Lives here, not in `Responses`, so the headers stay out of the JSON Schemas +@error +model ApplicationSubmissionErrorResponse { + ...Headers.VersionResponse; + + /** The submission error */ + @body body: Responses.ApplicationSubmissionError; +} diff --git a/lib/core/lib/core/routes/awards.tsp b/lib/core/lib/core/routes/awards.tsp index 5ceb453db..6eb4b9e04 100644 --- a/lib/core/lib/core/routes/awards.tsp +++ b/lib/core/lib/core/routes/awards.tsp @@ -51,6 +51,7 @@ interface Awards { @list list( ...Pagination.PaginatedQueryParams, + ...Headers.VersionRequest, ): Responses.PaginatedT; // ############################## @@ -69,6 +70,8 @@ interface Awards { /** The ID of the award to view */ @path awdId: Types.uuid, + + ...Headers.VersionRequest, ): Responses.OkT | Responses.NotFound; // ############################### @@ -101,5 +104,7 @@ interface Awards { /** Pagination instructions for the results */ pagination?: Pagination.PaginatedBodyParams, + + ...Headers.VersionRequest, ): Responses.FilteredT; } diff --git a/lib/core/lib/core/routes/competitions.tsp b/lib/core/lib/core/routes/competitions.tsp index 69b42b848..53cc4396f 100644 --- a/lib/core/lib/core/routes/competitions.tsp +++ b/lib/core/lib/core/routes/competitions.tsp @@ -30,6 +30,8 @@ interface Competitions { read( /** The ID of the competition to view */ @path compId: Types.uuid, + + ...Headers.VersionRequest, ): Responses.OkT | Responses.NotFound; // ############################### @@ -46,6 +48,8 @@ interface Competitions { /** The application to apply to the competition */ @body application: Models.ApplicationBase, + + ...Headers.VersionRequest, ): | Responses.CreatedT | Responses.NotFound diff --git a/lib/core/lib/core/routes/form-responses.tsp b/lib/core/lib/core/routes/form-responses.tsp index fba2dd948..69fe0a0b4 100644 --- a/lib/core/lib/core/routes/form-responses.tsp +++ b/lib/core/lib/core/routes/form-responses.tsp @@ -32,6 +32,8 @@ interface FormResponses { /** The response to the form */ @body response: Record, + + ...Headers.VersionRequest, ): Responses.OkT; // ############################### @@ -48,5 +50,7 @@ interface FormResponses { /** The ID of the form whose response is being retrieved */ @path formId: Types.uuid, + + ...Headers.VersionRequest, ): Responses.OkT; } diff --git a/lib/core/lib/core/routes/forms.tsp b/lib/core/lib/core/routes/forms.tsp index 55d20f4dc..ecae469f5 100644 --- a/lib/core/lib/core/routes/forms.tsp +++ b/lib/core/lib/core/routes/forms.tsp @@ -24,6 +24,7 @@ interface Forms { @get list( ...Pagination.PaginatedQueryParams, + ...Headers.VersionRequest, ): Responses.PaginatedT; // ############################### @@ -36,5 +37,7 @@ interface Forms { read( /** The ID of the form to view */ @path formId: Types.uuid, + + ...Headers.VersionRequest, ): Responses.OkT; } diff --git a/lib/core/lib/core/routes/opportunities.tsp b/lib/core/lib/core/routes/opportunities.tsp index 86b99411e..a114657a9 100644 --- a/lib/core/lib/core/routes/opportunities.tsp +++ b/lib/core/lib/core/routes/opportunities.tsp @@ -50,6 +50,7 @@ interface Opportunities { @list list( ...Pagination.PaginatedQueryParams, + ...Headers.VersionRequest, ): Responses.PaginatedT; // ############################## @@ -74,6 +75,8 @@ interface Opportunities { @path @added(Versions.v0_2) oppId: Types.uuid, + + ...Headers.VersionRequest, ): Responses.OkT | Responses.NotFound; // ############################### @@ -106,5 +109,7 @@ interface Opportunities { /** Pagination instructions for the results */ pagination?: Pagination.PaginatedBodyParams, + + ...Headers.VersionRequest, ): Responses.FilteredT; } diff --git a/lib/core/lib/core/routes/orgs.tsp b/lib/core/lib/core/routes/orgs.tsp index ba93ae04b..6a2d823f3 100644 --- a/lib/core/lib/core/routes/orgs.tsp +++ b/lib/core/lib/core/routes/orgs.tsp @@ -61,6 +61,8 @@ interface Organizations { /** Identifier value within the given registry to filter by */ @query id?: string, + + ...Headers.VersionRequest, ): Responses.PaginatedT | Responses.Unauthorized | Responses.Forbidden; // ############################## @@ -85,6 +87,8 @@ interface Organizations { /** Return the profile as of the given point in time */ @query at?: utcDateTime, + + ...Headers.VersionRequest, ): | Responses.OkT | Responses.NotFound @@ -112,6 +116,8 @@ interface Organizations { /** JSON Merge Patch body for the organization profile */ @body patch: Models.OrgPatchData, + + ...Headers.VersionRequest, ): | Responses.OkT | Responses.NotFound @@ -141,6 +147,8 @@ interface Organizations { /** JSON Merge Patch body for the organization profile */ @body patch: Models.OrgPatchData, + + ...Headers.VersionRequest, ): | Responses.AcceptedT | Responses.NotFound @@ -168,6 +176,7 @@ interface Organizations { orgId: Types.uuid, ...Pagination.PaginatedQueryParams, + ...Headers.VersionRequest, ): | Responses.PaginatedT | Responses.NotFound @@ -197,6 +206,8 @@ interface Organizations { /** The id of the change to view */ @path changeId: Types.uuid, + + ...Headers.VersionRequest, ): | Responses.OkT | Responses.NotFound diff --git a/lib/core/lib/core/types.tsp b/lib/core/lib/core/types.tsp index 006fec8c4..e94ac965f 100644 --- a/lib/core/lib/core/types.tsp +++ b/lib/core/lib/core/types.tsp @@ -61,6 +61,15 @@ scalar duns extends string; @Versioning.added(CommonGrants.Versions.v0_5) scalar nonEmptyString extends string; +/** A published CommonGrants protocol version, such as `0.6.0` + * + * A full `MAJOR.MINOR.PATCH` version with no `v` prefix and no leading zeros. + */ +@example("0.6.0") +@pattern("^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$") +@Versioning.added(CommonGrants.Versions.v0_6) +scalar protocolVersion extends string; + // ######################################## // Numeric types // ######################################## diff --git a/lib/core/lib/main.tsp b/lib/core/lib/main.tsp index 364e20f1e..853625b5b 100644 --- a/lib/core/lib/main.tsp +++ b/lib/core/lib/main.tsp @@ -21,4 +21,5 @@ enum Versions { v0_3: "0.3.0", v0_4: "0.4.0", v0_5: "0.5.0", + v0_6: "0.6.0", } diff --git a/lib/python-sdk/tests/schemas/test_award_inventory.py b/lib/python-sdk/tests/schemas/test_award_inventory.py index 0206da88a..3e7e5dff7 100644 --- a/lib/python-sdk/tests/schemas/test_award_inventory.py +++ b/lib/python-sdk/tests/schemas/test_award_inventory.py @@ -195,9 +195,9 @@ def wire_shape(model: type[BaseModel]) -> tuple[set[str], set[str]]: return keys, required -def test_core_baseline_is_v0_5(): - assert (SCHEMA_DIR.parents[1] / "openapi" / "openapi.0.5.0.yaml").exists() - assert not list((SCHEMA_DIR.parents[1] / "openapi").glob("openapi.0.[6-9]*.yaml")) +def test_core_baseline_is_v0_6(): + assert (SCHEMA_DIR.parents[1] / "openapi" / "openapi.0.6.0.yaml").exists() + assert not list((SCHEMA_DIR.parents[1] / "openapi").glob("openapi.0.[7-9]*.yaml")) def test_inventory_classifies_the_whole_award_closure(): diff --git a/website/__tests__/lib/mock/__fixtures__/golden-envelopes.json b/website/__tests__/lib/mock/__fixtures__/golden-envelopes.json index c6ee0b3ab..689f27679 100644 --- a/website/__tests__/lib/mock/__fixtures__/golden-envelopes.json +++ b/website/__tests__/lib/mock/__fixtures__/golden-envelopes.json @@ -137,12 +137,12 @@ "version-unsupported": { "status": 404, "contentType": "application/json", - "body": "{\"status\":404,\"message\":\"Unsupported protocol version\",\"errors\":[{\"field\":\"version\",\"message\":\"Version 9.9.9 is not served by this mock; supported versions are 0.1.0, 0.2.0, 0.3.0, 0.4.0, 0.5.0\"}]}" + "body": "{\"status\":404,\"message\":\"Unsupported protocol version\",\"errors\":[{\"field\":\"version\",\"message\":\"Version 9.9.9 is not served by this mock; supported versions are 0.1.0, 0.2.0, 0.3.0, 0.4.0, 0.5.0, 0.6.0\"}]}" }, "version-malformed": { "status": 404, "contentType": "application/json", - "body": "{\"status\":404,\"message\":\"Unsupported protocol version\",\"errors\":[{\"field\":\"version\",\"message\":\"Version abc is not served by this mock; supported versions are 0.1.0, 0.2.0, 0.3.0, 0.4.0, 0.5.0\"}]}" + "body": "{\"status\":404,\"message\":\"Unsupported protocol version\",\"errors\":[{\"field\":\"version\",\"message\":\"Version abc is not served by this mock; supported versions are 0.1.0, 0.2.0, 0.3.0, 0.4.0, 0.5.0, 0.6.0\"}]}" }, "route-miss-unsupported-method": { "status": 404, diff --git a/website/__tests__/lib/mock/__fixtures__/request-matrix.ts b/website/__tests__/lib/mock/__fixtures__/request-matrix.ts index 9156556db..d774d51ff 100644 --- a/website/__tests__/lib/mock/__fixtures__/request-matrix.ts +++ b/website/__tests__/lib/mock/__fixtures__/request-matrix.ts @@ -55,7 +55,7 @@ const REPRESENTATIVE_SEARCH = JSON.stringify({ * once the Worker serves every entry in `SUPPORTED_VERSIONS` again. */ const GOLDEN_VERSIONS = SUPPORTED_VERSIONS.filter( - (version) => version !== "0.5.0", + (version) => version !== "0.5.0" && version !== "0.6.0", ); /** The three endpoints across every version the golden corpus covers. */ diff --git a/website/__tests__/lib/mock/conformance/applications-vs-openapi.spec.ts b/website/__tests__/lib/mock/conformance/applications-vs-openapi.spec.ts index ef7a62e70..8c0081584 100644 --- a/website/__tests__/lib/mock/conformance/applications-vs-openapi.spec.ts +++ b/website/__tests__/lib/mock/conformance/applications-vs-openapi.spec.ts @@ -115,6 +115,7 @@ describe("shaped applications against the per-version OpenAPI documents", () => "0.3.0": "name", "0.4.0": "title", "0.5.0": "title", + "0.6.0": "title", }); const hasOpportunityId = Object.fromEntries( @@ -132,6 +133,7 @@ describe("shaped applications against the per-version OpenAPI documents", () => "0.3.0": true, "0.4.0": true, "0.5.0": true, + "0.6.0": true, }); }); }); diff --git a/website/__tests__/lib/mock/data/fixtures.spec.ts b/website/__tests__/lib/mock/data/fixtures.spec.ts index a68123380..dae83b64a 100644 --- a/website/__tests__/lib/mock/data/fixtures.spec.ts +++ b/website/__tests__/lib/mock/data/fixtures.spec.ts @@ -14,6 +14,7 @@ import { allForVersion, type Opportunity, } from "@/lib/mock/data/fixtures"; +import { isAtLeastVersion } from "@/lib/mock/data/availability"; const STATUS_VALUES = ["forecasted", "open", "closed", "custom"]; @@ -296,7 +297,7 @@ describe("shapeOpportunityForVersion", () => { it("strips identifiers for every version below 0.5.0, both variants", () => { const olderVersions = SUPPORTED_VERSIONS.filter( - (version) => version !== "0.5.0", + (version) => !isAtLeastVersion(version, "0.5.0"), ); for (const version of olderVersions) { @@ -340,7 +341,7 @@ describe("shapeOpportunityForVersion", () => { it("strips funders for every version below 0.5.0, both variants", () => { const olderVersions = SUPPORTED_VERSIONS.filter( - (version) => version !== "0.5.0", + (version) => !isAtLeastVersion(version, "0.5.0"), ); for (const version of olderVersions) { @@ -388,7 +389,7 @@ describe("shapeOpportunityForVersion", () => { it("strips awards for every version below 0.5.0, both variants", () => { const olderVersions = SUPPORTED_VERSIONS.filter( - (version) => version !== "0.5.0", + (version) => !isAtLeastVersion(version, "0.5.0"), ); for (const version of olderVersions) { @@ -432,6 +433,6 @@ describe("isSupportedVersion", () => { }); it("rejects a version the fixture cannot shape", () => { - expect(isSupportedVersion("0.6.0")).toBe(false); + expect(isSupportedVersion("0.7.0")).toBe(false); }); }); diff --git a/website/__tests__/lib/mock/handlers/applications.spec.ts b/website/__tests__/lib/mock/handlers/applications.spec.ts index d49fcd62f..d66fbeb32 100644 --- a/website/__tests__/lib/mock/handlers/applications.spec.ts +++ b/website/__tests__/lib/mock/handlers/applications.spec.ts @@ -871,6 +871,7 @@ describe("per-version application response shape", () => { "0.3.0": "name", "0.4.0": "title", "0.5.0": "title", + "0.6.0": "title", }; /** Versions whose `ApplicationBase` declares `opportunityId`. */ @@ -880,6 +881,7 @@ describe("per-version application response shape", () => { "0.3.0": true, "0.4.0": true, "0.5.0": true, + "0.6.0": true, }; /** The applications routes start at v0.2; v0.1 never reaches a handler. */ diff --git a/website/__tests__/scripts/inject-mock-server.spec.ts b/website/__tests__/scripts/inject-mock-server.spec.ts index 27eef52f4..b45b218ec 100644 --- a/website/__tests__/scripts/inject-mock-server.spec.ts +++ b/website/__tests__/scripts/inject-mock-server.spec.ts @@ -118,8 +118,8 @@ describe("assertMockServesVersion", () => { // docs page whose every Execute answers 404. it("throws for a spec version the router does not serve", () => { expect(() => - assertMockServesVersion("0.6.0", "openapi.0.6.0.yaml"), - ).toThrow(/openapi\.0\.6\.0\.yaml.*does not serve/s); + assertMockServesVersion("0.7.0", "openapi.0.7.0.yaml"), + ).toThrow(/openapi\.0\.7\.0\.yaml.*does not serve/s); }); }); diff --git a/website/public/openapi/openapi.0.6.0.yaml b/website/public/openapi/openapi.0.6.0.yaml new file mode 100644 index 000000000..3cbbeb359 --- /dev/null +++ b/website/public/openapi/openapi.0.6.0.yaml @@ -0,0 +1,7973 @@ +openapi: 3.0.0 +info: + title: CommonGrants Base API + description: |- + The base OpenAPI specification for a CommonGrants API + + In order for an API to be "compliant" with the CommonGrants protocol, + it must implement all of the routes with the "required" tag in this specification. + version: 0.6.0 +tags: + - name: Opportunities + description: Endpoints related to funding opportunities + - name: Competitions + description: Endpoints related to competitions, which are distinct application processes for the same funding opportunity + - name: Applications + description: Endpoints related to submitting applications for a given competition + - name: Application Reviews + description: Endpoints related to reviewing applications for a given competition + - name: Organizations + description: Endpoints related to viewing and syncing organization profiles + - name: Awards + description: Endpoints related to grant awards + - name: Forms + description: Endpoints related to forms + - name: required + description: Endpoints that MUST be implemented by all CommonGrants APIs + - name: optional + description: Endpoints that MAY be implemented by CommonGrants APIs + - name: experimental + description: Endpoints that MAY be implemented by CommonGrants APIs, but are not guaranteed to be stable +paths: + /common-grants/applications/search: + post: + operationId: Applications_searchApplications + summary: Search applications + description: 'Search for applications. Note: The search results for a given query will depend on the scopes attached to the API token used to make the request.' + parameters: + - name: filters + in: query + required: true + description: The filters to apply to the search + schema: + $ref: '#/components/schemas/CommonGrants.Models.AppFilters' + explode: false + - name: sorting + in: query + required: true + description: The sorting to apply to the search + schema: + $ref: '#/components/schemas/CommonGrants.Models.AppSorting' + explode: false + - $ref: '#/components/parameters/CommonGrants.Headers.VersionRequest' + responses: + '200': + description: A paginated list of typed items with a typed filter + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + type: object + required: + - items + - paginationInfo + - sortInfo + - filterInfo + properties: + items: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Models.ApplicationBase' + description: Items from the current page + paginationInfo: + allOf: + - $ref: '#/components/schemas/CommonGrants.Pagination.PaginatedResultsInfo' + description: Details about the paginated results + sortInfo: + allOf: + - $ref: '#/components/schemas/CommonGrants.Sorting.SortedResultsInfo' + description: The sort order of the items + filterInfo: + type: object + properties: + filters: + $ref: '#/components/schemas/CommonGrants.Models.AppFilters' + errors: + type: array + items: + type: string + description: Non-fatal errors that occurred during filtering + required: + - filters + description: The filters applied to the response items + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A paginated list of typed items with a typed filter + tags: + - Applications + - experimental + - Application Reviews + /common-grants/applications/start: + post: + operationId: Applications_startApplication + summary: Start an application + description: Start a new application for a given competition. + parameters: + - $ref: '#/components/parameters/CommonGrants.Headers.VersionRequest' + responses: + '201': + description: A 201 response with typed data + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + type: object + required: + - data + properties: + data: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.ApplicationBase' + description: Response data + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A 201 response with typed data + '401': + description: Access is unauthorized. + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Optional because authentication can run before a version is selected. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.Error' + tags: + - Applications + - experimental + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + competitionId: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.uuid' + description: The ID of the competition to start an application for + organizationId: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.uuid' + description: The ID of the organization to start an application for, if applying on behalf of an organization + title: + type: string + description: The title of the application + required: + - competitionId + - title + /common-grants/applications/{appId}: + get: + operationId: Applications_getApplication + summary: View an application + description: View an application for a given competition, along with its form responses and validation errors. + parameters: + - name: appId + in: path + required: true + description: The ID of the application to get + schema: + $ref: '#/components/schemas/CommonGrants.Types.uuid' + - $ref: '#/components/parameters/CommonGrants.Headers.VersionRequest' + responses: + '200': + description: A 200 response with typed data + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + type: object + required: + - data + properties: + data: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.ApplicationBase' + description: Response data + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A 200 response with typed data + '401': + description: Access is unauthorized. + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Optional because authentication can run before a version is selected. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.Error' + '404': + description: The server cannot find the requested resource. + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.Error' + tags: + - Applications + - experimental + /common-grants/applications/{appId}/forms/{formId}: + put: + operationId: Applications_setFormResponse + summary: Respond to a form + description: Set or update the response to a given form in an application. + parameters: + - name: appId + in: path + required: true + description: The ID of the application to whose form response is being updated + schema: + $ref: '#/components/schemas/CommonGrants.Types.uuid' + - name: formId + in: path + required: true + description: The ID of the form whose response is being updated + schema: + $ref: '#/components/schemas/CommonGrants.Types.uuid' + - $ref: '#/components/parameters/CommonGrants.Headers.VersionRequest' + responses: + '200': + description: A 200 response with typed data + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + type: object + required: + - data + properties: + data: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.AppFormResponse' + description: Response data + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A 200 response with typed data + tags: + - Applications + - experimental + requestBody: + required: true + content: + application/json: + schema: + type: object + additionalProperties: {} + description: The response to the form + get: + operationId: Applications_getFormResponse + summary: Get a form response + description: Get the response to a given form in an application. + parameters: + - name: appId + in: path + required: true + description: The ID of the application to whose form response is being retrieved + schema: + $ref: '#/components/schemas/CommonGrants.Types.uuid' + - name: formId + in: path + required: true + description: The ID of the form whose response is being retrieved + schema: + $ref: '#/components/schemas/CommonGrants.Types.uuid' + - $ref: '#/components/parameters/CommonGrants.Headers.VersionRequest' + responses: + '200': + description: A 200 response with typed data + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + type: object + required: + - data + properties: + data: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.AppFormResponse' + description: Response data + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A 200 response with typed data + tags: + - Applications + - experimental + /common-grants/applications/{appId}/submit: + put: + operationId: Applications_submitApplication + summary: Submit an application + description: Submit an application to a competition. Applications that have validation errors will be blocked from submitting until the errors are fixed. + parameters: + - name: appId + in: path + required: true + description: The ID of the application to submit + schema: + $ref: '#/components/schemas/CommonGrants.Types.uuid' + - $ref: '#/components/parameters/CommonGrants.Headers.VersionRequest' + responses: + '200': + description: A 200 response with typed data + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + type: object + required: + - data + properties: + data: + description: Response data + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A 200 response with typed data + '401': + description: Access is unauthorized. + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Optional because authentication can run before a version is selected. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.Error' + '404': + description: The server cannot find the requested resource. + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.Error' + default: + description: An unexpected error response. + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.ApplicationSubmissionError' + tags: + - Applications + - experimental + /common-grants/awards: + get: + operationId: Awards_list + summary: List awards + description: Get a paginated list of awards, sorted by `lastModifiedAt` with most recent first. + parameters: + - $ref: '#/components/parameters/CommonGrants.Pagination.PaginatedQueryParams.page' + - $ref: '#/components/parameters/CommonGrants.Pagination.PaginatedQueryParams.pageSize' + - $ref: '#/components/parameters/CommonGrants.Headers.VersionRequest' + responses: + '200': + description: A 200 response with a paginated list of typed items + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + type: object + required: + - items + - paginationInfo + properties: + items: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Models.AwardBase' + description: Items from the current page + paginationInfo: + allOf: + - $ref: '#/components/schemas/CommonGrants.Pagination.PaginatedResultsInfo' + description: Details about the paginated results + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A 200 response with a paginated list of typed items + tags: + - Awards + - optional + /common-grants/awards/search: + post: + operationId: Awards_search + summary: Search awards + description: Search for awards based on the provided filters. + parameters: + - $ref: '#/components/parameters/CommonGrants.Headers.VersionRequest' + responses: + '200': + description: A paginated list of typed items with a typed filter + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + type: object + required: + - items + - paginationInfo + - sortInfo + - filterInfo + properties: + items: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Models.AwardBase' + description: Items from the current page + paginationInfo: + allOf: + - $ref: '#/components/schemas/CommonGrants.Pagination.PaginatedResultsInfo' + description: Details about the paginated results + sortInfo: + allOf: + - $ref: '#/components/schemas/CommonGrants.Sorting.SortedResultsInfo' + description: The sort order of the items + filterInfo: + type: object + properties: + filters: + $ref: '#/components/schemas/CommonGrants.Models.AwdFilters' + errors: + type: array + items: + type: string + description: Non-fatal errors that occurred during filtering + required: + - filters + description: The filters applied to the response items + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A paginated list of typed items with a typed filter + tags: + - Awards + - optional + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + search: + type: string + description: Award search query + example: Community health center + filters: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.AwdFilters' + description: |- + Filters to apply to the award search + + Multiple filter conditions will be combined with AND logic, so that + results only include awards that match all of the provided filters. + sorting: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.AwdSorting' + description: The sort order to apply to the results + pagination: + allOf: + - $ref: '#/components/schemas/CommonGrants.Pagination.PaginatedBodyParams' + description: Pagination instructions for the results + /common-grants/awards/{awdId}: + get: + operationId: Awards_read + summary: View award details + description: View details about an award. + parameters: + - name: awdId + in: path + required: true + description: The ID of the award to view + schema: + $ref: '#/components/schemas/CommonGrants.Types.uuid' + - $ref: '#/components/parameters/CommonGrants.Headers.VersionRequest' + responses: + '200': + description: A 200 response with typed data + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + type: object + required: + - data + properties: + data: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.AwardBase' + description: Response data + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A 200 response with typed data + '404': + description: The server cannot find the requested resource. + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.Error' + tags: + - Awards + - optional + /common-grants/competitions/{compId}: + get: + operationId: Competitions_read + summary: View competition details + description: |- + View details about a competition for a given funding opportunity. + + Each competition may have a distinct set of forms, be limited to a + certain types of applicants, or have a different application period. + parameters: + - name: compId + in: path + required: true + description: The ID of the competition to view + schema: + $ref: '#/components/schemas/CommonGrants.Types.uuid' + - $ref: '#/components/parameters/CommonGrants.Headers.VersionRequest' + responses: + '200': + description: A 200 response with typed data + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + type: object + required: + - data + properties: + data: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.CompetitionBase' + description: Response data + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A 200 response with typed data + '404': + description: The server cannot find the requested resource. + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.Error' + tags: + - Competitions + - experimental + /common-grants/forms: + get: + operationId: Forms_list + summary: List forms + description: Get a paginated list of forms, sorted by `lastModifiedAt` with most recent first. + parameters: + - $ref: '#/components/parameters/CommonGrants.Pagination.PaginatedQueryParams.page' + - $ref: '#/components/parameters/CommonGrants.Pagination.PaginatedQueryParams.pageSize' + - $ref: '#/components/parameters/CommonGrants.Headers.VersionRequest' + responses: + '200': + description: A 200 response with a paginated list of typed items + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + type: object + required: + - items + - paginationInfo + properties: + items: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Models.FormBase' + description: Items from the current page + paginationInfo: + allOf: + - $ref: '#/components/schemas/CommonGrants.Pagination.PaginatedResultsInfo' + description: Details about the paginated results + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A 200 response with a paginated list of typed items + tags: + - Forms + - experimental + /common-grants/forms/{formId}: + get: + operationId: Forms_read + summary: View form details + description: View details about a given form. + parameters: + - name: formId + in: path + required: true + description: The ID of the form to view + schema: + $ref: '#/components/schemas/CommonGrants.Types.uuid' + - $ref: '#/components/parameters/CommonGrants.Headers.VersionRequest' + responses: + '200': + description: A 200 response with typed data + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + type: object + required: + - data + properties: + data: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.FormBase' + description: Response data + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A 200 response with typed data + tags: + - Forms + - experimental + /common-grants/opportunities: + get: + operationId: Opportunities_list + summary: List opportunities + description: Get a paginated list of opportunities, sorted by `lastModifiedAt` with most recent first. + parameters: + - $ref: '#/components/parameters/CommonGrants.Pagination.PaginatedQueryParams.page' + - $ref: '#/components/parameters/CommonGrants.Pagination.PaginatedQueryParams.pageSize' + - $ref: '#/components/parameters/CommonGrants.Headers.VersionRequest' + responses: + '200': + description: A 200 response with a paginated list of typed items + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + type: object + required: + - items + - paginationInfo + properties: + items: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Models.OpportunityBase' + description: Items from the current page + paginationInfo: + allOf: + - $ref: '#/components/schemas/CommonGrants.Pagination.PaginatedResultsInfo' + description: Details about the paginated results + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A 200 response with a paginated list of typed items + tags: + - Opportunities + - required + /common-grants/opportunities/search: + post: + operationId: Opportunities_search + summary: Search opportunities + description: Search for opportunities based on the provided filters. + parameters: + - $ref: '#/components/parameters/CommonGrants.Headers.VersionRequest' + responses: + '200': + description: A paginated list of typed items with a typed filter + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + type: object + required: + - items + - paginationInfo + - sortInfo + - filterInfo + properties: + items: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Models.OpportunityBase' + description: Items from the current page + paginationInfo: + allOf: + - $ref: '#/components/schemas/CommonGrants.Pagination.PaginatedResultsInfo' + description: Details about the paginated results + sortInfo: + allOf: + - $ref: '#/components/schemas/CommonGrants.Sorting.SortedResultsInfo' + description: The sort order of the items + filterInfo: + type: object + properties: + filters: + $ref: '#/components/schemas/CommonGrants.Models.OppFilters' + errors: + type: array + items: + type: string + description: Non-fatal errors that occurred during filtering + required: + - filters + description: The filters applied to the response items + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A paginated list of typed items with a typed filter + tags: + - Opportunities + - optional + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + search: + type: string + description: Opportunity search query + example: Pre-school education + filters: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OppFilters' + description: |- + Filters to apply to the opportunity search + + Multiple filter conditions will be combined with AND logic, so that + results only include opportunities that match all of the provided filters. + sorting: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OppSorting' + description: The sort order to apply to the results + pagination: + allOf: + - $ref: '#/components/schemas/CommonGrants.Pagination.PaginatedBodyParams' + description: Pagination instructions for the results + /common-grants/opportunities/{oppId}: + get: + operationId: Opportunities_read + summary: View opportunity details + description: View details about an opportunity. + parameters: + - name: oppId + in: path + required: true + description: The ID of the opportunity to view + schema: + $ref: '#/components/schemas/CommonGrants.Types.uuid' + - $ref: '#/components/parameters/CommonGrants.Headers.VersionRequest' + responses: + '200': + description: A 200 response with typed data + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + type: object + required: + - data + properties: + data: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OpportunityDetails' + description: Response data + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A 200 response with typed data + '404': + description: The server cannot find the requested resource. + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.Error' + tags: + - Opportunities + - required + /common-grants/orgs: + get: + operationId: Organizations_list + summary: List organizations + description: Get a paginated list of organizations. Requires the `org:read` scope. + parameters: + - $ref: '#/components/parameters/CommonGrants.Pagination.PaginatedQueryParams.page' + - $ref: '#/components/parameters/CommonGrants.Pagination.PaginatedQueryParams.pageSize' + - name: registry + in: query + required: false + description: Registry code of an external identifier to filter by (e.g. `org:us:ein`) + schema: + type: string + explode: false + - name: id + in: query + required: false + description: Identifier value within the given registry to filter by + schema: + type: string + explode: false + - $ref: '#/components/parameters/CommonGrants.Headers.VersionRequest' + responses: + '200': + description: A 200 response with a paginated list of typed items + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + type: object + required: + - items + - paginationInfo + properties: + items: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Models.OrganizationBase' + description: Items from the current page + paginationInfo: + allOf: + - $ref: '#/components/schemas/CommonGrants.Pagination.PaginatedResultsInfo' + description: Details about the paginated results + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A 200 response with a paginated list of typed items + '401': + description: Access is unauthorized. + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Optional because authentication can run before a version is selected. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.Error' + '403': + description: Access is forbidden. + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Optional because authentication can run before a version is selected. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.Error' + tags: + - Organizations + - experimental + security: + - OAuth2Auth: + - org:read + /common-grants/orgs/{orgId}: + get: + operationId: Organizations_read + summary: View an organization profile + description: View an organization profile by its UUID. Requires the `org:read` scope. + parameters: + - name: orgId + in: path + required: true + description: The UUID of the organization to view + schema: + $ref: '#/components/schemas/CommonGrants.Types.uuid' + - name: at + in: query + required: false + description: Return the profile as of the given point in time + schema: + type: string + format: date-time + explode: false + - $ref: '#/components/parameters/CommonGrants.Headers.VersionRequest' + responses: + '200': + description: A 200 response with typed data + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + type: object + required: + - data + properties: + data: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrganizationBase' + description: Response data + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A 200 response with typed data + '401': + description: Access is unauthorized. + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Optional because authentication can run before a version is selected. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.Error' + '403': + description: Access is forbidden. + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Optional because authentication can run before a version is selected. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.Error' + '404': + description: The server cannot find the requested resource. + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.Error' + tags: + - Organizations + - experimental + security: + - OAuth2Auth: + - org:read + patch: + operationId: Organizations_update + summary: Update an organization profile + description: Apply a direct JSON Merge Patch edit to an organization profile, recorded as an accepted change. Requires the `org:write` scope. + parameters: + - name: orgId + in: path + required: true + description: The UUID of the organization to update + schema: + $ref: '#/components/schemas/CommonGrants.Types.uuid' + - $ref: '#/components/parameters/CommonGrants.Headers.VersionRequest' + responses: + '200': + description: A 200 response with typed data + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + type: object + required: + - data + properties: + data: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgRevision' + description: Response data + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A 200 response with typed data + '401': + description: Access is unauthorized. + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Optional because authentication can run before a version is selected. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.Error' + '403': + description: Access is forbidden. + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Optional because authentication can run before a version is selected. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.Error' + '404': + description: The server cannot find the requested resource. + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.Error' + tags: + - Organizations + - experimental + requestBody: + required: true + content: + application/merge-patch+json: + schema: + $ref: '#/components/schemas/CommonGrants.Models.OrgPatchData' + description: JSON Merge Patch body for the organization profile + security: + - OAuth2Auth: + - org:write + /common-grants/orgs/{orgId}/changes: + post: + operationId: Organizations_submitChange + summary: Submit an organization profile change + description: Submit a change to an organization profile, which a receiver may apply immediately or queue for review. Requires the `org.changes:write` scope. + parameters: + - name: orgId + in: path + required: true + description: The UUID of the organization to change + schema: + $ref: '#/components/schemas/CommonGrants.Types.uuid' + - $ref: '#/components/parameters/CommonGrants.Headers.VersionRequest' + responses: + '202': + description: A 202 response with typed data + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + Location: + required: false + description: URL where the accepted resource can be retrieved + schema: + type: string + format: uri + content: + application/json: + schema: + type: object + required: + - data + properties: + data: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgRevision' + description: Response data + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A 202 response with typed data + '401': + description: Access is unauthorized. + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Optional because authentication can run before a version is selected. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.Error' + '403': + description: Access is forbidden. + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Optional because authentication can run before a version is selected. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.Error' + '404': + description: The server cannot find the requested resource. + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.Error' + tags: + - Organizations + - experimental + requestBody: + required: true + content: + application/merge-patch+json: + schema: + $ref: '#/components/schemas/CommonGrants.Models.OrgPatchData' + description: JSON Merge Patch body for the organization profile + security: + - OAuth2Auth: + - org.changes:write + get: + operationId: Organizations_listChanges + summary: List organization profile changes + description: Get a paginated list of changes to an organization profile, newest first. Requires the `org.changes:read` scope. + parameters: + - name: orgId + in: path + required: true + description: The UUID of the organization whose changes to list + schema: + $ref: '#/components/schemas/CommonGrants.Types.uuid' + - $ref: '#/components/parameters/CommonGrants.Pagination.PaginatedQueryParams.page' + - $ref: '#/components/parameters/CommonGrants.Pagination.PaginatedQueryParams.pageSize' + - $ref: '#/components/parameters/CommonGrants.Headers.VersionRequest' + responses: + '200': + description: A 200 response with a paginated list of typed items + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + type: object + required: + - items + - paginationInfo + properties: + items: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Models.OrgRevision' + description: Items from the current page + paginationInfo: + allOf: + - $ref: '#/components/schemas/CommonGrants.Pagination.PaginatedResultsInfo' + description: Details about the paginated results + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A 200 response with a paginated list of typed items + '401': + description: Access is unauthorized. + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Optional because authentication can run before a version is selected. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.Error' + '403': + description: Access is forbidden. + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Optional because authentication can run before a version is selected. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.Error' + '404': + description: The server cannot find the requested resource. + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.Error' + tags: + - Organizations + - experimental + security: + - OAuth2Auth: + - org.changes:read + /common-grants/orgs/{orgId}/changes/{changeId}: + get: + operationId: Organizations_viewChange + summary: View an organization profile change + description: View a single change to an organization profile by its id. Requires the `org.changes:read` scope. + parameters: + - name: orgId + in: path + required: true + description: The UUID of the organization the change belongs to + schema: + $ref: '#/components/schemas/CommonGrants.Types.uuid' + - name: changeId + in: path + required: true + description: The id of the change to view + schema: + $ref: '#/components/schemas/CommonGrants.Types.uuid' + - $ref: '#/components/parameters/CommonGrants.Headers.VersionRequest' + responses: + '200': + description: A 200 response with typed data + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + type: object + required: + - data + properties: + data: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgRevision' + description: Response data + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A 200 response with typed data + '401': + description: Access is unauthorized. + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Optional because authentication can run before a version is selected. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.Error' + '403': + description: Access is forbidden. + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Optional because authentication can run before a version is selected. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.Error' + '404': + description: The server cannot find the requested resource. + headers: + CG-Version-Served: + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.Error' + tags: + - Organizations + - experimental + security: + - OAuth2Auth: + - org.changes:read +components: + parameters: + CommonGrants.Headers.VersionRequest: + name: CG-Version + in: header + required: false + description: |- + The protocol version the client wants, such as `0.6.0` + + Servers match on major and minor version. When absent, the server responds + in its default version. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + CommonGrants.Pagination.PaginatedQueryParams.page: + name: page + in: query + required: false + description: The page to return + schema: + type: integer + format: int32 + minimum: 1 + default: 1 + explode: false + CommonGrants.Pagination.PaginatedQueryParams.pageSize: + name: pageSize + in: query + required: false + description: The number of items to return per page + schema: + type: integer + format: int32 + minimum: 1 + default: 100 + explode: false + schemas: + CommonGrants.Fields.Address: + type: object + required: + - street1 + - city + - stateOrProvince + - country + - postalCode + properties: + street1: + type: string + description: The primary street address line. + street2: + type: string + description: Additional street address information (e.g., apartment number, suite, etc.). + city: + type: string + description: The city or municipality name. + stateOrProvince: + type: string + description: The state, province, or region name. + country: + type: string + description: The country name or ISO country code. + postalCode: + type: string + description: The postal or ZIP code for the address. + latitude: + type: number + description: The latitude coordinate of the address location. + longitude: + type: number + description: The longitude coordinate of the address location. + geography: + type: object + additionalProperties: {} + description: Additional geospatial data in GeoJSON format. + description: A mailing address. + example: + street1: 123 Main St + city: Anytown + stateOrProvince: CA + country: US + postalCode: '12345' + CommonGrants.Fields.AddressCollection: + type: object + required: + - primary + properties: + primary: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.Address' + description: The primary address for a person or organization. + otherAddresses: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Fields.Address' + description: Additional addresses keyed by a descriptive label (e.g., "work", "home", "international"). + description: A collection of addresses. + example: + primary: + street1: 456 Main St + street2: Suite 100 + city: Anytown + stateOrProvince: CA + country: US + postalCode: '12345' + otherAddresses: + satellite: + street1: 456 Main St + street2: Suite 100 + city: Anytown + stateOrProvince: CA + country: US + postalCode: '12345' + international: + street1: 123 Rue Principale + city: Montreal + stateOrProvince: QC + country: CA + postalCode: H2Y 1C6 + CommonGrants.Fields.CustomField: + type: object + required: + - name + - fieldType + - value + properties: + name: + type: string + description: Name of the custom field + fieldType: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.CustomFieldType' + description: The JSON schema type to use when de-serializing the `value` field + schema: + type: string + format: uri + description: Link to the full JSON schema for this custom field + value: + description: Value of the custom field + description: + type: string + description: Description of the custom field's purpose + description: A custom field on a model + example: + name: eligibilityType + fieldType: array + value: + - nonprofit + - academic + description: Types of eligible organizations + CommonGrants.Fields.CustomFieldType: + type: string + enum: + - string + - number + - integer + - boolean + - object + - array + description: The set of JSON schema types supported by a custom field + CommonGrants.Fields.DateRangeEvent: + type: object + required: + - eventType + - startDate + - endDate + properties: + eventType: + type: string + enum: + - dateRange + description: Type of event + startDate: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.isoDate' + description: 'Start date of the event in ISO 8601 format: YYYY-MM-DD' + startTime: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.isoTime' + description: 'Start time of the event in ISO 8601 format: HH:MM:SS' + endDate: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.isoDate' + description: 'End date of the event in ISO 8601 format: YYYY-MM-DD' + endTime: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.isoTime' + description: 'End time of the event in ISO 8601 format: HH:MM:SS' + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.EventBase' + description: Description of an event that has a start and end date (and possible time) associated with it + example: + name: Application period + eventType: dateRange + startDate: '2024-01-01' + endDate: '2024-01-31' + endTime: '17:00:00' + description: Primary application period for the grant opportunity + CommonGrants.Fields.EmailCollection: + type: object + required: + - primary + properties: + primary: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.email' + description: The primary email address for a person or organization. + otherEmails: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Types.email' + description: Additional email addresses keyed by a descriptive label (e.g., "work", "personal", "support"). + description: A collection of email addresses. + example: + primary: john.doe@example.com + otherEmails: + work: john.doe@work.com + personal: john.doe@gmail.com + school: john.doe@school.edu + CommonGrants.Fields.Event: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Fields.SingleDateEvent' + - $ref: '#/components/schemas/CommonGrants.Fields.DateRangeEvent' + - $ref: '#/components/schemas/CommonGrants.Fields.OtherEvent' + description: Union of all event types + CommonGrants.Fields.EventBase: + type: object + required: + - name + - eventType + properties: + name: + type: string + description: Human-readable name of the event (e.g., 'Application posted', 'Question deadline') + eventType: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.EventType' + description: Type of event + description: + type: string + description: Description of what this event represents + discriminator: + propertyName: eventType + mapping: + dateRange: '#/components/schemas/CommonGrants.Fields.DateRangeEvent' + other: '#/components/schemas/CommonGrants.Fields.OtherEvent' + singleDate: '#/components/schemas/CommonGrants.Fields.SingleDateEvent' + description: Base model for all events + CommonGrants.Fields.EventType: + type: string + enum: + - singleDate + - dateRange + - other + description: |- + Type of event (e.g., a single date, a date range, or a custom event) + + - singleDate: A single date (and possible time) + - dateRange: A period of time with a start and end date + - other: Other event type (e.g., a recurring event) + CommonGrants.Fields.File: + type: object + required: + - downloadUrl + - name + - createdAt + - lastModifiedAt + properties: + downloadUrl: + type: string + format: uri + description: The file's download URL. + name: + type: string + description: The file's name. + description: + type: string + description: The file's description. + sizeInBytes: + type: number + description: The file's size in bytes. + mimeType: + type: string + description: The file's MIME type. + createdAt: + type: string + format: date-time + description: The timestamp (in UTC) at which the record was created. + readOnly: true + lastModifiedAt: + type: string + format: date-time + description: The timestamp (in UTC) at which the record was last modified. + readOnly: true + description: A field representing a downloadable file. + example: + downloadUrl: https://example.com/file.pdf + name: example.pdf + description: A PDF file with instructions + sizeInBytes: 1000 + mimeType: application/pdf + createdAt: '2025-01-01T17:01:01Z' + lastModifiedAt: '2025-01-02T17:30:00Z' + CommonGrants.Fields.Identifier: + type: object + properties: + registry: + type: object + properties: + code: + type: string + description: Canonical CommonGrants registry code, `::` (e.g. `org:us:ein`). + url: + type: string + format: uri + description: Link to the catalog entry for this registry. + description: Registry-level facts shared by every record in this registry. + id: + type: string + description: |- + The primary identifier string, when the registry has a single canonical value. + + May be omitted for registries with no natural primary; consumers should read + `allIds` in that case. + allIds: + type: array + items: + type: object + properties: + id: + type: string + description: The identifier string. + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.IdentifierStatus' + description: Whether the identifier is currently valid or retired. + required: + - id + - status + description: Every known identifier for this record in this registry, including archived values. + description: |- + An identifier issued to a record by a registry. + + Accepts any string value and any registry code. Model-specific collections use + registry-typed instantiations of `IdentifierT` (e.g. `OrgIdEin`) for their base + identifiers, and this generic form for extension identifiers under `otherIds`. + example: + registry: + code: org:us:ein + url: https://commongrants.org/registries/org-us-ein + id: '123456789' + allIds: + - id: '123456789' + status: active + - id: '987654321' + status: archived + CommonGrants.Fields.IdentifierCollection: + type: object + properties: + systemId: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.SystemId' + description: The hosting system's own identifier for this record. + otherIds: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Fields.Identifier' + description: |- + Additional identifiers keyed by their registry code, for registries the + protocol does not define as a base identifier on the model. + description: A collection of identifiers associated with a record. + example: + systemId: + registry: + code: org:grants.gov:system + url: https://commongrants.org/registries/org-grants-gov-system + id: 01912a8b-7c3d-7890-abcd-ef1234567890 + otherIds: + org:candid:bridge: + registry: + code: org:candid:bridge + id: '1234567' + CommonGrants.Fields.IdentifierStatus: + type: string + enum: + - active + - archived + description: The lifecycle status of an identifier value. + CommonGrants.Fields.Money: + type: object + required: + - amount + - currency + properties: + amount: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.decimalString' + description: The amount of money + currency: + type: string + description: The ISO 4217 currency code in which the amount is denominated + description: A monetary amount and the currency in which it's denominated + example: + amount: '-50.50' + currency: USD + CommonGrants.Fields.Name: + type: object + required: + - firstName + - lastName + properties: + prefix: + type: string + description: Honorific prefix (e.g., Mr., Mrs., Dr., Prof.). + firstName: + type: string + description: The person's first or given name. + middleName: + type: string + description: The person's middle name or names. + lastName: + type: string + description: The person's last name or family name. + suffix: + type: string + description: Name suffix (e.g., Jr., Sr., III, Ph.D.). + description: A person's name. + example: + prefix: Dr. + firstName: Jane + middleName: Edward + lastName: Doe + suffix: Jr. + CommonGrants.Fields.OrgPatchAddressOrCreate: + type: object + properties: + street1: + type: string + description: The primary street address line. + street2: + type: string + nullable: true + description: Additional street address information (e.g., apartment number, suite, etc.). + city: + type: string + description: The city or municipality name. + stateOrProvince: + type: string + description: The state, province, or region name. + country: + type: string + description: The country name or ISO country code. + postalCode: + type: string + description: The postal or ZIP code for the address. + latitude: + type: number + nullable: true + description: The latitude coordinate of the address location. + longitude: + type: number + nullable: true + description: The longitude coordinate of the address location. + geography: + type: object + additionalProperties: {} + nullable: true + description: Additional geospatial data in GeoJSON format. + description: A mailing address. + example: + street1: 123 Main St + city: Anytown + stateOrProvince: CA + country: US + postalCode: '12345' + CommonGrants.Fields.OrgPatchCustomFieldOrCreate: + type: object + properties: + name: + type: string + description: Name of the custom field + fieldType: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.CustomFieldType' + description: The JSON schema type to use when de-serializing the `value` field + schema: + type: string + format: uri + nullable: true + description: Link to the full JSON schema for this custom field + value: + description: Value of the custom field + description: + type: string + nullable: true + description: Description of the custom field's purpose + description: A custom field on a model + example: + name: eligibilityType + fieldType: array + value: + - nonprofit + - academic + description: Types of eligible organizations + CommonGrants.Fields.OrgPatchIdentifierOrCreate: + type: object + properties: + registry: + type: object + properties: + code: + type: string + nullable: true + description: Canonical CommonGrants registry code, `::` (e.g. `org:us:ein`). + url: + type: string + format: uri + nullable: true + description: Link to the catalog entry for this registry. + nullable: true + description: Registry-level facts shared by every record in this registry. + id: + type: string + nullable: true + description: |- + The primary identifier string, when the registry has a single canonical value. + + May be omitted for registries with no natural primary; consumers should read + `allIds` in that case. + allIds: + type: array + items: + type: object + properties: + id: + type: string + description: The identifier string. + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.IdentifierStatus' + description: Whether the identifier is currently valid or retired. + required: + - id + - status + nullable: true + description: Every known identifier for this record in this registry, including archived values. + description: |- + An identifier issued to a record by a registry. + + Accepts any string value and any registry code. Model-specific collections use + registry-typed instantiations of `IdentifierT` (e.g. `OrgIdEin`) for their base + identifiers, and this generic form for extension identifiers under `otherIds`. + example: + registry: + code: org:us:ein + url: https://commongrants.org/registries/org-us-ein + id: '123456789' + allIds: + - id: '123456789' + status: active + - id: '987654321' + status: archived + CommonGrants.Fields.OrgPatchPhoneOrCreate: + type: object + properties: + countryCode: + type: string + pattern: ^\+[1-9][0-9]{0,3}$ + description: The international country code (e.g., "+1" for US/Canada). + number: + type: string + description: The local phone number without the country code. + extension: + type: string + nullable: true + description: Optional extension number for the phone line. + isMobile: + type: boolean + nullable: true + description: Indicates whether this is a mobile/cell phone number. + description: A phone number. + example: + countryCode: '+1' + number: 555-123-4567 + extension: '123' + isMobile: false + CommonGrants.Fields.OrgPatchSystemIdOrCreate: + type: object + properties: + registry: + type: object + properties: + code: + type: string + nullable: true + description: Canonical CommonGrants registry code, `::` (e.g. `org:us:ein`). + url: + type: string + format: uri + nullable: true + description: Link to the catalog entry for this registry. + nullable: true + description: Registry-level facts shared by every record in this registry. + id: + type: string + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.uuid' + nullable: true + description: |- + The primary identifier string, when the registry has a single canonical value. + + May be omitted for registries with no natural primary; consumers should read + `allIds` in that case. + allIds: + type: array + items: + type: object + properties: + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.uuid' + description: The identifier string. + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.IdentifierStatus' + description: Whether the identifier is currently valid or retired. + required: + - id + - status + nullable: true + description: Every known identifier for this record in this registry, including archived values. + description: |- + The hosting system's own identifier for a record. + + The identifier value is the record's UUID within the hosting system; the + registry code names that system (e.g. `org:grants.gov:system`). + example: + registry: + code: org:grants.gov:system + url: https://commongrants.org/registries/org-grants-gov-system + id: 01912a8b-7c3d-7890-abcd-ef1234567890 + CommonGrants.Fields.OtherEvent: + type: object + required: + - eventType + properties: + eventType: + type: string + enum: + - other + description: Type of event + details: + type: string + description: Details of the event's timeline (e.g. "Every other Tuesday") + description: + type: string + description: Description of the event + example: Applications begin being accepted + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.EventBase' + description: Description of an event that is not a single date or date range + example: + name: Info sessions + eventType: other + details: Every other Tuesday at 10:00 AM during the application period + description: Info sessions for the opportunity + CommonGrants.Fields.PCSClass: + type: string + enum: + - Organization types + - Subjects + - Population groups + - Transaction types + - Support strategies + description: The class to which the PCS term belongs. + CommonGrants.Fields.PCSOrgType: + type: object + required: + - class + properties: + class: + type: string + enum: + - Organization types + description: The PCS term for the organization type. + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.PCSTerm' + description: |- + A Philanthropy Classification System (PCS) term for organization types. + + See https://taxonomy.candid.org/organization-type for more information. + CommonGrants.Fields.PCSPopulation: + type: object + required: + - class + properties: + class: + type: string + enum: + - Population groups + description: The PCS term for the population. + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.PCSTerm' + description: |- + A Philanthropy Classification System (PCS) term for populations served. + + See https://taxonomy.candid.org/populations for more information. + CommonGrants.Fields.PCSSubject: + type: object + required: + - class + properties: + class: + type: string + enum: + - Subjects + description: The PCS term for the subject. + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.PCSTerm' + description: |- + A Philanthropy Classification System (PCS) term for the subject of the grant. + + See https://taxonomy.candid.org/subjects for more information. + CommonGrants.Fields.PCSSupportStrategy: + type: object + required: + - class + properties: + class: + type: string + enum: + - Support strategies + description: The PCS term for the support strategy. + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.PCSTerm' + description: |- + A Philanthropy Classification System (PCS) term for support strategies. + + See https://taxonomy.candid.org/support-strategies for more information. + CommonGrants.Fields.PCSTerm: + type: object + required: + - term + - class + - code + properties: + term: + type: string + description: The plain language PCS term. + class: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.PCSClass' + description: The class to which the PCS term belongs. + code: + type: string + pattern: ^[A-Z]{2}[0-9]{6}$ + description: The code for this PCS term. + example: UC000000 + description: + type: string + description: Description of the PCS term + description: |- + A Philanthropy Classification System (PCS) term. + + The PCS is a hierarchical classification system for categorizing data related to + philanthropic activities. It supports the following classes: + - Organization types + - Subjects + - Population groups + - Transaction types + - Support strategies + + See https://taxonomy.candid.org/ for more information. + example: + term: Hospital + class: Organization types + description: Institutions with the primary purpose of providing in-patient physical and mental health services... + code: EO000000 + CommonGrants.Fields.PCSTransactionType: + type: object + required: + - class + properties: + class: + type: string + enum: + - Transaction types + description: The PCS term for the transaction type. + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.PCSTerm' + description: |- + A Philanthropy Classification System (PCS) term for transaction types. + + See https://taxonomy.candid.org/transaction-types for more information. + CommonGrants.Fields.Phone: + type: object + required: + - countryCode + - number + properties: + countryCode: + type: string + pattern: ^\+[1-9][0-9]{0,3}$ + description: The international country code (e.g., "+1" for US/Canada). + number: + type: string + description: The local phone number without the country code. + extension: + type: string + description: Optional extension number for the phone line. + isMobile: + type: boolean + description: Indicates whether this is a mobile/cell phone number. + default: false + description: A phone number. + example: + countryCode: '+1' + number: 555-123-4567 + extension: '123' + isMobile: false + CommonGrants.Fields.PhoneCollection: + type: object + required: + - primary + properties: + primary: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.Phone' + description: The person's primary phone number. + fax: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.Phone' + description: The person's fax number, if applicable. + otherPhones: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Fields.Phone' + description: Additional phone numbers not covered by the standard fields. + description: A collection of phone numbers for a person. + example: + primary: + countryCode: '+1' + number: 444-456-1230 + isMobile: true + fax: + countryCode: '+1' + number: 555-123-4567 + extension: '123' + isMobile: false + otherPhones: + support: + countryCode: '+1' + number: 333-456-1230 + isMobile: false + marketing: + countryCode: '+1' + number: 444-456-1230 + isMobile: true + CommonGrants.Fields.SingleDateEvent: + type: object + required: + - eventType + - date + properties: + eventType: + type: string + enum: + - singleDate + description: Type of event + date: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.isoDate' + description: 'Date of the event in in ISO 8601 format: YYYY-MM-DD' + time: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.isoTime' + description: 'Time of the event in ISO 8601 format: HH:MM:SS' + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.EventBase' + description: Description of an event that has a date (and possible time) associated with it + example: + name: Opportunity close date + eventType: singleDate + date: '2024-12-31' + time: '17:00:00' + description: Opportunity closes for all applications + CommonGrants.Fields.SystemId: + type: object + properties: + registry: + type: object + properties: + code: + type: string + description: Canonical CommonGrants registry code, `::` (e.g. `org:us:ein`). + url: + type: string + format: uri + description: Link to the catalog entry for this registry. + description: Registry-level facts shared by every record in this registry. + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.uuid' + description: |- + The primary identifier string, when the registry has a single canonical value. + + May be omitted for registries with no natural primary; consumers should read + `allIds` in that case. + allIds: + type: array + items: + type: object + properties: + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.uuid' + description: The identifier string. + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.IdentifierStatus' + description: Whether the identifier is currently valid or retired. + required: + - id + - status + description: Every known identifier for this record in this registry, including archived values. + description: |- + The hosting system's own identifier for a record. + + The identifier value is the record's UUID within the hosting system; the + registry code names that system (e.g. `org:grants.gov:system`). + example: + registry: + code: org:grants.gov:system + url: https://commongrants.org/registries/org-grants-gov-system + id: 01912a8b-7c3d-7890-abcd-ef1234567890 + CommonGrants.Filters.AllOperators: + type: string + enum: + - eq + - neq + - gt + - gte + - lt + - lte + - in + - notIn + - between + - outside + - like + - notLike + CommonGrants.Filters.ArrayOperators: + type: string + enum: + - in + - notIn + description: Operators that filter a field based on an array of values + CommonGrants.Filters.ComparisonOperators: + type: string + enum: + - gt + - gte + - lt + - lte + description: Operators that filter a field based on a comparison to a value + CommonGrants.Filters.DateRangeFilter: + type: object + required: + - operator + - value + properties: + operator: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.RangeOperators' + description: The operator to apply to the filter value + value: + type: object + properties: + min: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Types.isoDate' + - type: string + format: date-time + - type: string + format: date-time + max: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Types.isoDate' + - type: string + format: date-time + - type: string + format: date-time + required: + - min + - max + description: The value to use for the filter operation + example: + min: '2021-01-01' + max: '2021-01-02' + description: Filters by comparing a field to a range of date values + CommonGrants.Filters.DefaultFilter: + type: object + required: + - operator + - value + properties: + operator: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Filters.EquivalenceOperators' + - $ref: '#/components/schemas/CommonGrants.Filters.ComparisonOperators' + - $ref: '#/components/schemas/CommonGrants.Filters.ArrayOperators' + - $ref: '#/components/schemas/CommonGrants.Filters.StringOperators' + - $ref: '#/components/schemas/CommonGrants.Filters.RangeOperators' + - $ref: '#/components/schemas/CommonGrants.Filters.AllOperators' + description: The operator to apply to the filter value + value: + description: The value to use for the filter operation + description: A base filter model that can be used to create more specific filter models + CommonGrants.Filters.EquivalenceOperators: + type: string + enum: + - eq + - neq + description: Operators that filter a field based on an exact match to a value + CommonGrants.Filters.MoneyRangeFilter: + type: object + required: + - operator + - value + properties: + operator: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.RangeOperators' + description: The operator to apply to the filter value + value: + type: object + properties: + min: + $ref: '#/components/schemas/CommonGrants.Fields.Money' + max: + $ref: '#/components/schemas/CommonGrants.Fields.Money' + required: + - min + - max + description: The value to use for the filter operation + example: + min: + amount: '1000' + currency: USD + max: + amount: '10000' + currency: USD + description: Filters by comparing a field to a range of monetary values + CommonGrants.Filters.RangeOperators: + type: string + enum: + - between + - outside + description: Operators that filter a field based on a range of values + CommonGrants.Filters.StringArrayFilter: + type: object + required: + - operator + - value + properties: + operator: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.ArrayOperators' + description: The operator to apply to the filter value + value: + type: array + items: + type: string + description: The value to use for the filter operation + example: + - value1 + - value2 + description: Filters by comparing a field to an array of string values + CommonGrants.Filters.StringOperators: + type: string + enum: + - like + - notLike + description: Operators that filter a field based on a string value + CommonGrants.Models.AppDefaultFilters: + type: object + properties: + opportunityId: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.StringArrayFilter' + description: '`opportunityId` matches one of the following values' + example: + operator: in + value: + - ad3b469a-d89a-42d3-c439-6c1234567890 + competitionId: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.StringArrayFilter' + description: '`competitionId` matches one of the following values' + example: + operator: in + value: + - 123e4567-e89b-12d3-a456-426614174000 + submittedAtRange: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.DateRangeFilter' + description: '`submittedAt` is between the given range' + example: + operator: between + value: + min: '2025-01-01' + max: '2025-01-30' + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.StringArrayFilter' + description: '`status.value` matches one of the following values' + example: + operator: in + value: + - submitted + - accepted + allOf: + - type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Filters.DefaultFilter' + description: The standard set of filters supported for application searches + CommonGrants.Models.AppFilters: + type: object + properties: + opportunityId: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.StringArrayFilter' + description: '`opportunityId` matches one of the following values' + example: + operator: in + value: + - ad3b469a-d89a-42d3-c439-6c1234567890 + competitionId: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.StringArrayFilter' + description: '`competitionId` matches one of the following values' + example: + operator: in + value: + - 123e4567-e89b-12d3-a456-426614174000 + submittedAtRange: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.DateRangeFilter' + description: '`submittedAt` is between the given range' + example: + operator: between + value: + min: '2025-01-01' + max: '2025-01-30' + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.StringArrayFilter' + description: '`status.value` matches one of the following values' + example: + operator: in + value: + - submitted + - accepted + customFilters: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Filters.DefaultFilter' + description: Additional implementation-defined filters to apply to the search + description: Filters to apply when searching for applications + CommonGrants.Models.AppFormResponse: + type: object + required: + - applicationId + - id + - formId + - response + - status + - createdAt + - lastModifiedAt + properties: + applicationId: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.uuid' + description: The unique identifier for the application + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.uuid' + description: The unique identifier for the form response + formId: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.uuid' + description: The form being responded to + response: + type: object + additionalProperties: {} + description: The response to the form + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.FormResponseStatus' + description: The status of the form response + validationErrors: + type: array + items: {} + description: The validation errors for the form response + customFields: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Fields.CustomField' + description: Custom attributes about the form response + createdAt: + type: string + format: date-time + description: The timestamp (in UTC) at which the record was created. + readOnly: true + lastModifiedAt: + type: string + format: date-time + description: The timestamp (in UTC) at which the record was last modified. + readOnly: true + description: The model for a form response included in an application + example: + applicationId: 123e4567-e89b-12d3-a456-426614174000 + id: 123e4567-e89b-12d3-a456-426614174000 + formId: 123e4567-e89b-12d3-a456-426614174000 + response: + firstName: John + lastName: Doe + email: john.doe@example.com + phone: 123-456-7890 + address: + street: 123 Main St + city: Anytown + state: CA + zip: '12345' + country: null + status: + value: inProgress + description: The form response is in progress + validationErrors: + - field: address.country + message: Country is required + createdAt: '2021-01-01T00:00:00Z' + lastModifiedAt: '2021-01-01T00:00:00Z' + CommonGrants.Models.AppRef: + type: object + required: + - id + - title + properties: + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.uuid' + description: The unique identifier for the application + readOnly: true + title: + type: string + description: The title of the application + description: |- + A reference to an application, previewing the key fields a consumer needs + to identify it and look it up or join it to another response. Appears + wherever another record points to an application, such as the application + an award resulted from. + example: + id: 123e4567-e89b-12d3-a456-426614174000 + title: My Application + CommonGrants.Models.AppSortBy: + type: string + enum: + - lastModifiedAt + - createdAt + - submittedAt + - status.value + - opportunityId + - competitionId + - custom + description: The fields that can be used to sort applications + CommonGrants.Models.AppSorting: + type: object + required: + - sortBy + properties: + sortBy: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.AppSortBy' + description: The field to sort by + example: opportunityId + allOf: + - $ref: '#/components/schemas/CommonGrants.Sorting.SortBodyParams' + description: Sorting parameters for applications + CommonGrants.Models.AppStatus: + type: object + required: + - value + properties: + value: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.AppStatusOptions' + description: The selected value, from a predefined set of options + customValue: + type: string + description: A custom value, used when the selected value is the `custom` option + description: + type: string + description: A human-readable description of the value + description: The status of the application + example: + value: submitted + description: The application has been submitted. + CommonGrants.Models.AppStatusOptions: + type: string + enum: + - inProgress + - submitted + - accepted + - rejected + - custom + description: |- + The default set of values accepted for application status: + - `inProgress`: The application is in progress + - `submitted`: The application has been submitted and is being reviewed + - `accepted`: The application has been accepted + - `rejected`: The application has been rejected + - `custom`: A custom status + CommonGrants.Models.ApplicantType: + type: object + required: + - value + properties: + value: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.ApplicantTypeOptions' + description: The selected value, from a predefined set of options + customValue: + type: string + description: A custom value, used when the selected value is the `custom` option + description: + type: string + description: A human-readable description of the value + description: The type of applicant eligible to apply for funding + example: + value: individual + description: An individual applicant + CommonGrants.Models.ApplicantTypeOptions: + type: string + enum: + - individual + - organization + - government_state + - government_county + - government_municipal + - government_special_district + - government_tribal + - organization_tribal_other + - school_district_independent + - higher_education_public + - higher_education_private + - non_profit_with_501c3 + - nonprofit_without_501c3 + - for_profit_small_business + - for_profit_not_small_business + - unrestricted + - custom + description: The set of possible applicant types + CommonGrants.Models.ApplicationBase: + type: object + required: + - id + - title + - competitionId + - opportunityId + - formResponses + - status + - createdAt + - lastModifiedAt + properties: + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.uuid' + description: The unique identifier for the application + readOnly: true + title: + type: string + description: The title of the application + competitionId: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.uuid' + description: The unique identifier for the competition + opportunityId: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.uuid' + description: The unique identifier for the opportunity being applied to + formResponses: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Models.AppFormResponse' + description: The form responses for the application + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.AppStatus' + description: The status of the application + submittedAt: + type: string + format: date-time + nullable: true + description: The date and time the application was submitted + validationErrors: + type: array + items: {} + description: The validation errors for the application and form responses + customFields: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Fields.CustomField' + description: The custom fields about the application + createdAt: + type: string + format: date-time + description: The timestamp (in UTC) at which the record was created. + readOnly: true + lastModifiedAt: + type: string + format: date-time + description: The timestamp (in UTC) at which the record was last modified. + readOnly: true + description: The base model for an application to a competition for a funding opportunity + example: + id: 123e4567-e89b-12d3-a456-426614174000 + title: My Application + competitionId: 123e4567-e89b-12d3-a456-426614174000 + opportunityId: ad3b469a-d89a-42d3-c439-6c1234567890 + formResponses: + formA: + applicationId: 123e4567-e89b-12d3-a456-426614174000 + id: 123e4567-e89b-12d3-a456-426614174000 + formId: 123e4567-e89b-12d3-a456-426614174000 + response: + firstName: John + lastName: Doe + email: john.doe@example.com + phone: 123-456-7890 + address: + street: 123 Main St + city: Anytown + state: CA + zip: '12345' + country: null + status: + value: inProgress + description: The form response is in progress + validationErrors: + - field: address.country + message: Country is required + createdAt: '2021-01-01T00:00:00Z' + lastModifiedAt: '2021-01-01T00:00:00Z' + status: + value: inProgress + description: The application is in progress. + submittedAt: null + createdAt: '2021-01-01T00:00:00Z' + lastModifiedAt: '2021-01-01T00:00:00Z' + customFields: + attachments: + name: attachments + fieldType: object + value: + contacts: + downloadUrl: https://example.com/file.pdf + name: example.pdf + description: A PDF file with instructions + sizeInBytes: 1000 + mimeType: application/pdf + createdAt: '2025-01-01T17:01:01Z' + lastModifiedAt: '2025-01-02T17:30:00Z' + budget: + downloadUrl: https://example.com/excel.xlsx + name: excel.xlsx + description: The excel file for the application + sizeInBytes: 1000 + mimeType: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet + createdAt: '2025-01-01T17:01:01Z' + lastModifiedAt: '2025-01-02T17:30:00Z' + description: The attachments for the application + applicationZipFile: + name: applicationZipFile + fieldType: object + value: + downloadUrl: https://example.com/application.zip + name: application.zip + description: The zip file for the application + sizeInBytes: 50000 + mimeType: application/zip + createdAt: '2025-01-01T17:01:01Z' + lastModifiedAt: '2025-01-02T17:30:00Z' + description: The zip file for the application + CommonGrants.Models.AwardBase: + type: object + required: + - id + - title + - description + - status + - createdAt + - lastModifiedAt + properties: + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.uuid' + description: Globally unique id for the award + readOnly: true + title: + type: string + description: Title or name of the award + example: Community Health Center Capital Improvement Grant + identifiers: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.AwdIds' + description: System and registry-specific identifiers for the award + description: + type: string + description: Description of the award's purpose + example: Supports facility upgrades at federally qualified health centers. + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.AwdStatus' + description: Lifecycle status of the award + funding: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.AwdFunding' + description: Requested, awarded, and disbursed amounts + keyDates: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.AwdTimeline' + description: Award date and period of performance + opportunity: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OppRef' + description: The opportunity this award resulted from + application: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.AppRef' + description: The application this award resulted from + funders: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgRefCollection' + description: Organization(s) that funded the award + recipientOrganizations: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgRefCollection' + description: Organization(s) that received the award, if the recipient is an organization + recipientIndividual: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.AwdRecipientIndividual' + description: The individual who received the award, if the recipient is a person + parent: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.AwdRef' + description: Parent award, for amendments or multi-tranche awards + source: + type: string + format: uri + description: URL for the canonical source record of the award + createdAt: + type: string + format: date-time + description: The timestamp (in UTC) at which the record was created. + readOnly: true + lastModifiedAt: + type: string + format: date-time + description: The timestamp (in UTC) at which the record was last modified. + readOnly: true + description: A grant award + example: + id: 01912a8b-7c3d-7894-abcd-ef1234567890 + title: Community Health Center Capital Improvement Grant + identifiers: + systemId: + registry: + code: awd:grants.gov:system + id: 01912a8b-7c3d-7894-abcd-ef1234567890 + awd:us:fain: + registry: + code: awd:us:fain + url: https://commongrants.org/registries/awd-us-fain + id: H80CS00001 + description: Supports facility upgrades at federally qualified health centers. + status: + value: awarded + description: Award has been issued and funds are being disbursed. + funding: + requestedAmount: + amount: '500000.00' + currency: USD + awardedAmount: + amount: '450000.00' + currency: USD + disbursedAmount: + amount: '150000.00' + currency: USD + keyDates: + awardDate: + name: Award date + eventType: singleDate + date: '2026-03-01' + description: The date the award was issued. + periodOfPerformance: + name: Period of performance + eventType: dateRange + startDate: '2026-04-01' + endDate: '2027-03-31' + description: The period during which the funded work is performed. + opportunity: + id: 018f2e77-3a4b-7c1d-9e2f-abcdef123456 + title: Health Center Capital Improvement Program + identifiers: + opp:us:fon: + registry: + code: opp:us:fon + url: https://commongrants.org/registries/opp-us-fon + id: HHS-2026-ACF-OCC-YD-0001 + funders: + primary: + id: 018f2e77-4b5c-7d2e-9f3a-bcdef1234567 + name: Health Resources and Services Administration + identifiers: + otherIds: + org:grants.gov:agency: + registry: + code: org:grants.gov:agency + id: HRSA + recipientOrganizations: + primary: + id: 018f2e77-6d7e-7f4a-9b5c-def123456789 + name: Riverside Community Health Center + identifiers: + org:us:ein: + registry: + code: org:us:ein + id: '582345679' + source: https://www.usaspending.gov/award/ASST_NON_H80CS00001 + createdAt: '2026-03-01T00:00:00Z' + lastModifiedAt: '2026-06-01T00:00:00Z' + CommonGrants.Models.AwdDefaultFilters: + type: object + properties: + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.StringArrayFilter' + description: '`status.value` matches one of the following values' + example: + operator: in + value: + - awarded + - completed + opportunityId: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.StringArrayFilter' + description: '`opportunity.id` matches one of the following values' + example: + operator: in + value: + - 018f2e77-3a4b-7c1d-9e2f-abcdef123456 + awardDateRange: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.DateRangeFilter' + description: '`keyDates.awardDate` is between the given range' + example: + operator: between + value: + min: '2026-01-01' + max: '2026-12-31' + awardedAmountRange: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.MoneyRangeFilter' + description: |- + `funding.awardedAmount` is between the given range + + Funding amounts that are denominated in a different currency will + be excluded from the search. + example: + operator: between + value: + min: + amount: '100000' + currency: USD + max: + amount: '500000' + currency: USD + allOf: + - type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Filters.DefaultFilter' + description: The standard set of filters supported for award searches + CommonGrants.Models.AwdFilters: + type: object + properties: + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.StringArrayFilter' + description: '`status.value` matches one of the following values' + example: + operator: in + value: + - awarded + - completed + opportunityId: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.StringArrayFilter' + description: '`opportunity.id` matches one of the following values' + example: + operator: in + value: + - 018f2e77-3a4b-7c1d-9e2f-abcdef123456 + awardDateRange: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.DateRangeFilter' + description: '`keyDates.awardDate` is between the given range' + example: + operator: between + value: + min: '2026-01-01' + max: '2026-12-31' + awardedAmountRange: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.MoneyRangeFilter' + description: |- + `funding.awardedAmount` is between the given range + + Funding amounts that are denominated in a different currency will + be excluded from the search. + example: + operator: between + value: + min: + amount: '100000' + currency: USD + max: + amount: '500000' + currency: USD + customFilters: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Filters.DefaultFilter' + description: Additional implementation-defined filters to apply to the search + description: Filters to apply when searching for awards + CommonGrants.Models.AwdFunding: + type: object + properties: + details: + type: string + description: Details about the award's funding that don't fit other fields + requestedAmount: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.Money' + description: Amount of funding requested by the recipient + awardedAmount: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.Money' + description: Amount of funding awarded to the recipient + disbursedAmount: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.Money' + description: Amount of funding disbursed to the recipient so far + description: Financial details about the award, including the amounts requested, awarded, and disbursed + example: + requestedAmount: + amount: '500000.00' + currency: USD + awardedAmount: + amount: '450000.00' + currency: USD + disbursedAmount: + amount: '150000.00' + currency: USD + CommonGrants.Models.AwdIdFain: + type: object + properties: + registry: + type: object + properties: + code: + type: string + enum: + - awd:us:fain + description: Canonical CommonGrants registry code, `::` (e.g. `org:us:ein`). + url: + type: string + format: uri + description: Link to the catalog entry for this registry. + description: Registry-level facts shared by every record in this registry. + id: + type: string + description: |- + The primary identifier string, when the registry has a single canonical value. + + May be omitted for registries with no natural primary; consumers should read + `allIds` in that case. + allIds: + type: array + items: + type: object + properties: + id: + type: string + description: The identifier string. + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.IdentifierStatus' + description: Whether the identifier is currently valid or retired. + required: + - id + - status + description: Every known identifier for this record in this registry, including archived values. + description: An award's Federal Award Identification Number (FAIN), assigned by the awarding agency. + example: + registry: + code: awd:us:fain + url: https://commongrants.org/registries/awd-us-fain + id: H80CS00001 + CommonGrants.Models.AwdIds: + type: object + properties: + awd:us:fain: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.AwdIdFain' + description: The award's Federal Award Identification Number (FAIN). + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.IdentifierCollection' + description: |- + A collection of identifiers associated with an award. + + Extends the generic identifier collection with the base identifiers CommonGrants + defines for awards. Additional registries can be published under `otherIds`. + example: + systemId: + registry: + code: awd:grants.gov:system + id: 01912a8b-7c3d-7894-abcd-ef1234567890 + awd:us:fain: + registry: + code: awd:us:fain + url: https://commongrants.org/registries/awd-us-fain + id: H80CS00001 + CommonGrants.Models.AwdRecipientIndividual: + type: object + properties: + name: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.Name' + description: The individual's name. + identifiers: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.IdentifierCollection' + description: Identifiers associated with the individual, keyed by registry code. + customFields: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Fields.CustomField' + description: Custom fields about the individual recipient. + description: An individual who received an award, when the recipient is a person rather than an organization. + CommonGrants.Models.AwdRef: + type: object + required: + - id + - title + properties: + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.uuid' + description: Globally unique id for the award + readOnly: true + title: + type: string + description: Title or name of the award + example: Community Health Center Capital Improvement Grant + identifiers: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.AwdIds' + description: System and registry-specific identifiers for the award + description: |- + A reference to an award, previewing the key fields a consumer needs to + identify it and look it up or join it to another response. Appears wherever + another record points to an award, such as a parent award for an amendment + or tranche. + example: + id: 01912a8b-7c3d-7894-abcd-ef1234567890 + title: Community Health Center Capital Improvement Grant + identifiers: + systemId: + registry: + code: awd:grants.gov:system + id: 01912a8b-7c3d-7894-abcd-ef1234567890 + awd:us:fain: + registry: + code: awd:us:fain + url: https://commongrants.org/registries/awd-us-fain + id: H80CS00001 + CommonGrants.Models.AwdSortBy: + type: string + enum: + - lastModifiedAt + - createdAt + - title + - status.value + - keyDates.awardDate + - funding.awardedAmount + - custom + CommonGrants.Models.AwdSorting: + type: object + required: + - sortBy + properties: + sortBy: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.AwdSortBy' + description: The field to sort by + example: lastModifiedAt + allOf: + - $ref: '#/components/schemas/CommonGrants.Sorting.SortBodyParams' + CommonGrants.Models.AwdStatus: + type: object + required: + - value + properties: + value: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.AwdStatusOptions' + description: The selected value, from a predefined set of options + customValue: + type: string + description: A custom value, used when the selected value is the `custom` option + description: + type: string + description: A human-readable description of the value + description: The status of the award + example: + value: awarded + description: Award has been issued and funds are being disbursed. + CommonGrants.Models.AwdStatusOptions: + type: string + enum: + - awarded + - completed + - cancelled + - custom + description: |- + The set of values accepted for award status: + - `awarded`: The award has been issued and funds are being disbursed + - `completed`: The award's period of performance has ended + - `cancelled`: The award was cancelled or terminated + - `custom`: A custom status + CommonGrants.Models.AwdTimeline: + type: object + properties: + awardDate: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.Event' + description: The date (and time) on which the award was issued + periodOfPerformance: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.Event' + description: The period during which the funded work is expected to be performed + otherDates: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Fields.Event' + description: |- + An optional map of other key dates or events in the award timeline + + Examples might include a reporting deadline, close-out date, etc. + description: Key dates in the award's timeline, such as the award date and period of performance + example: + awardDate: + name: Award date + eventType: singleDate + date: '2026-03-01' + description: The date the award was issued. + periodOfPerformance: + name: Period of performance + eventType: dateRange + startDate: '2026-04-01' + endDate: '2027-03-31' + description: The period during which the funded work is performed. + CommonGrants.Models.CompetitionBase: + type: object + required: + - id + - opportunity + - title + - status + - forms + - createdAt + - lastModifiedAt + properties: + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.uuid' + description: Globally unique id for the competition + opportunity: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OppRef' + description: The opportunity this competition is for + title: + type: string + description: The title of the competition + description: + type: string + description: The description of the competition + instructions: + anyOf: + - type: string + - type: array + items: + $ref: '#/components/schemas/CommonGrants.Fields.File' + description: The instructions for the competition + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.CompetitionStatus' + description: The status of the competition + keyDates: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.CompetitionTimeline' + description: The key dates in the competition timeline + forms: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.CompetitionForms' + description: The forms for the competition + acceptedApplicantTypes: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Models.ApplicantType' + description: Accepted applicant types for the competition + customFields: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Fields.CustomField' + description: The custom fields for the competition + createdAt: + type: string + format: date-time + description: The timestamp (in UTC) at which the record was created. + readOnly: true + lastModifiedAt: + type: string + format: date-time + description: The timestamp (in UTC) at which the record was last modified. + readOnly: true + description: |- + The base model for a competition. + + A competition is an application process for a funding opportunity. It often has a + distinct application period and set of application forms. + example: + id: b7c1e2f4-8a3d-4e2a-9c5b-1f2e3d4c5b6a + opportunity: + id: b7c1e2f4-8a3d-4e2a-9c5b-1f2e3d4c5b6b + title: Small business grant program + title: Competition 1 + description: Competition 1 description + instructions: Competition 1 instructions + status: + value: open + description: Competition is open for applications + keyDates: + openDate: + name: Open Date + eventType: singleDate + date: '2025-01-01' + closeDate: + name: Close Date + eventType: singleDate + date: '2025-01-30' + otherDates: + reviewPeriod: + name: Application Review Period + eventType: dateRange + startDate: '2025-02-01' + endDate: '2025-02-28' + forms: + forms: + formA: + id: b7c1e2f4-8a3d-4e2a-9c5b-1f2e3d4c5b6a + title: Form A + description: Form A description + instructions: Form A instructions + jsonSchema: + $id: formA.json + type: object + properties: + name: + first: + type: string + last: + type: string + email: + type: string + phone: + type: string + uiSchema: + type: VerticalLayout + elements: + - type: Group + label: Name + elements: + - type: Control + scope: '#/properties/name/first' + - type: Control + scope: '#/properties/name/last' + - type: Control + scope: '#/properties/email' + - type: Control + scope: '#/properties/phone' + mappingToCommonGrants: + name: + firstName: + field: name.first + lastName: + field: name.last + emails: + primary: + field: email + phones: + primary: + field: phone + mappingFromCommonGrants: + name: + first: + field: name.firstName + last: + field: name.lastName + email: + field: emails.primary + phone: + field: phones.primary + createdAt: '2025-01-01T17:01:01Z' + lastModifiedAt: '2025-01-02T17:30:00Z' + formB: + id: b7c1e2f4-8a3d-4e2a-9c5b-1f2e3d4c5b6a + title: Form A + description: Form A description + instructions: Form A instructions + jsonSchema: + $id: formA.json + type: object + properties: + name: + first: + type: string + last: + type: string + email: + type: string + phone: + type: string + uiSchema: + type: VerticalLayout + elements: + - type: Group + label: Name + elements: + - type: Control + scope: '#/properties/name/first' + - type: Control + scope: '#/properties/name/last' + - type: Control + scope: '#/properties/email' + - type: Control + scope: '#/properties/phone' + mappingToCommonGrants: + name: + firstName: + field: name.first + lastName: + field: name.last + emails: + primary: + field: email + phones: + primary: + field: phone + mappingFromCommonGrants: + name: + first: + field: name.firstName + last: + field: name.lastName + email: + field: emails.primary + phone: + field: phones.primary + createdAt: '2025-01-01T17:01:01Z' + lastModifiedAt: '2025-01-02T17:30:00Z' + validation: + required: + - formA + - formB + createdAt: '2025-01-01T00:00:00Z' + lastModifiedAt: '2025-01-01T00:00:00Z' + CommonGrants.Models.CompetitionForms: + type: object + required: + - forms + properties: + forms: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Models.FormBase' + description: The forms for the competition + validation: + type: object + additionalProperties: {} + description: The validation rules for the competition forms + description: Set of forms that need to be completed to apply to the competition. + example: + forms: + formA: + id: b7c1e2f4-8a3d-4e2a-9c5b-1f2e3d4c5b6a + title: Form A + description: Form A description + instructions: Form A instructions + jsonSchema: + $id: formA.json + type: object + properties: + name: + first: + type: string + last: + type: string + email: + type: string + phone: + type: string + uiSchema: + type: VerticalLayout + elements: + - type: Group + label: Name + elements: + - type: Control + scope: '#/properties/name/first' + - type: Control + scope: '#/properties/name/last' + - type: Control + scope: '#/properties/email' + - type: Control + scope: '#/properties/phone' + mappingToCommonGrants: + name: + firstName: + field: name.first + lastName: + field: name.last + emails: + primary: + field: email + phones: + primary: + field: phone + mappingFromCommonGrants: + name: + first: + field: name.firstName + last: + field: name.lastName + email: + field: emails.primary + phone: + field: phones.primary + createdAt: '2025-01-01T17:01:01Z' + lastModifiedAt: '2025-01-02T17:30:00Z' + formB: + id: b7c1e2f4-8a3d-4e2a-9c5b-1f2e3d4c5b6a + title: Form A + description: Form A description + instructions: Form A instructions + jsonSchema: + $id: formA.json + type: object + properties: + name: + first: + type: string + last: + type: string + email: + type: string + phone: + type: string + uiSchema: + type: VerticalLayout + elements: + - type: Group + label: Name + elements: + - type: Control + scope: '#/properties/name/first' + - type: Control + scope: '#/properties/name/last' + - type: Control + scope: '#/properties/email' + - type: Control + scope: '#/properties/phone' + mappingToCommonGrants: + name: + firstName: + field: name.first + lastName: + field: name.last + emails: + primary: + field: email + phones: + primary: + field: phone + mappingFromCommonGrants: + name: + first: + field: name.firstName + last: + field: name.lastName + email: + field: emails.primary + phone: + field: phones.primary + createdAt: '2025-01-01T17:01:01Z' + lastModifiedAt: '2025-01-02T17:30:00Z' + validation: + required: + - formA + - formB + CommonGrants.Models.CompetitionStatus: + type: object + required: + - value + properties: + value: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.CompetitionStatusOptions' + description: The selected value, from a predefined set of options + customValue: + type: string + description: A custom value, used when the selected value is the `custom` option + description: + type: string + description: A human-readable description of the value + description: The status of the competition + example: + value: open + description: Competition is open for applications + CommonGrants.Models.CompetitionStatusOptions: + type: string + enum: + - open + - closed + - custom + description: |- + The set of values accepted for competition status + - `open`: The competition is open for applications + - `closed`: The competition is no longer accepting applications + - `custom`: A custom status + CommonGrants.Models.CompetitionTimeline: + type: object + properties: + openDate: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.Event' + description: The start date of the competition + closeDate: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.Event' + description: The end date of the competition + otherDates: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Fields.Event' + description: The date the competition was created + description: Key dates in the competition's timeline. + example: + openDate: + name: Open Date + eventType: singleDate + date: '2025-01-01' + closeDate: + name: Close Date + eventType: singleDate + date: '2025-01-30' + otherDates: + reviewPeriod: + name: Application Review Period + eventType: dateRange + startDate: '2025-02-01' + endDate: '2025-02-28' + CommonGrants.Models.FormBase: + type: object + required: + - id + - title + - createdAt + - lastModifiedAt + properties: + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.uuid' + description: The form's unique identifier. + title: + type: string + description: The form's title. + description: + type: string + description: The form's description. + version: + type: string + instructions: + anyOf: + - type: string + - type: array + items: + $ref: '#/components/schemas/CommonGrants.Fields.File' + description: The form's instructions. + jsonSchema: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.FormJsonSchema' + description: The form's JSON schema used to render the form and validate responses. + uiSchema: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.FormUISchema' + description: The form's UI schema used to render the form in the browser. + mappingToCommonGrants: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.MappingSchema' + description: A mapping from form schema to CommonGrants schema. + mappingFromCommonGrants: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.MappingSchema' + description: A mapping from CommonGrants schema to form schema. + customFields: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Fields.CustomField' + description: Custom attributes about the form itself, not custom fields within the form. + createdAt: + type: string + format: date-time + description: The timestamp (in UTC) at which the record was created. + readOnly: true + lastModifiedAt: + type: string + format: date-time + description: The timestamp (in UTC) at which the record was last modified. + readOnly: true + description: A form for collecting data from a user. + example: + id: b7c1e2f4-8a3d-4e2a-9c5b-1f2e3d4c5b6a + title: Form A + description: Form A description + instructions: Form A instructions + jsonSchema: + $id: formA.json + type: object + properties: + name: + first: + type: string + last: + type: string + email: + type: string + phone: + type: string + uiSchema: + type: VerticalLayout + elements: + - type: Group + label: Name + elements: + - type: Control + scope: '#/properties/name/first' + - type: Control + scope: '#/properties/name/last' + - type: Control + scope: '#/properties/email' + - type: Control + scope: '#/properties/phone' + mappingToCommonGrants: + name: + firstName: + field: name.first + lastName: + field: name.last + emails: + primary: + field: email + phones: + primary: + field: phone + mappingFromCommonGrants: + name: + first: + field: name.firstName + last: + field: name.lastName + email: + field: emails.primary + phone: + field: phones.primary + createdAt: '2025-01-01T17:01:01Z' + lastModifiedAt: '2025-01-02T17:30:00Z' + CommonGrants.Models.FormJsonSchema: + type: object + additionalProperties: {} + description: A JSON schema used to validate form responses. + example: + $id: formA.json + type: object + properties: + name: + first: + type: string + last: + type: string + email: + type: string + phone: + type: string + CommonGrants.Models.FormResponseStatus: + type: object + required: + - value + properties: + value: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.FormResponseStatusOptions' + description: The selected value, from a predefined set of options + customValue: + type: string + description: A custom value, used when the selected value is the `custom` option + description: + type: string + description: A human-readable description of the value + description: The status of the form response + example: + value: inProgress + description: The form response is in progress + CommonGrants.Models.FormResponseStatusOptions: + type: string + enum: + - notStarted + - inProgress + - complete + - custom + description: |- + The set of values accepted for form response status: + - `notStarted`: The form response has not been started + - `inProgress`: The form response is in progress + - `complete`: The form response is complete, meaning all required fields have been filled out and there are no validation errors + - `custom`: A custom status + CommonGrants.Models.FormUISchema: + type: object + additionalProperties: {} + description: A UI schema used to render the form in the browser. + example: + type: VerticalLayout + elements: + - type: Group + label: Name + elements: + - type: Control + scope: '#/properties/name/first' + - type: Control + scope: '#/properties/name/last' + - type: Control + scope: '#/properties/email' + - type: Control + scope: '#/properties/phone' + CommonGrants.Models.MappingConstantFunction: + type: object + required: + - const + properties: + const: {} + description: Returns a constant value. + example: + const: '123' + CommonGrants.Models.MappingFieldFunction: + type: object + required: + - field + properties: + field: + type: string + description: Returns the value of a field in the source data. + example: + field: summary.opportunity_amount + CommonGrants.Models.MappingFunction: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Models.MappingConstantFunction' + - $ref: '#/components/schemas/CommonGrants.Models.MappingFieldFunction' + - $ref: '#/components/schemas/CommonGrants.Models.MappingSwitchFunction' + description: The set of supported mapping functions. + example: + switch: + field: summary.opportunity_status + case: + active: open + inactive: closed + default: custom + CommonGrants.Models.MappingSchema: + type: object + additionalProperties: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Models.MappingFunction' + - $ref: '#/components/schemas/CommonGrants.Models.MappingSchema' + description: |- + A mapping format for translating data from one schema to another. + + Example: + + The following mapping: + + ```json + { + "id": { "const": "123" }, + "opportunity": { + "status": { + "switch": { + "field": "summary.opportunity_status", + "case": { "active": "open", "inactive": "closed" }, + "default": "custom", + }, + }, + "amount": { "field": "summary.opportunity_amount" }, + } + } + ``` + + Will translate the following data: + + ```json + { + "id": "123", + "summary": { + "opportunity_status": "active", + "opportunity_amount": 100, + }, + } + ``` + + To the following data: + + ```json + { + "id": "123", + "opportunity": { "status": "open", "amount": 100 }, + } + ``` + example: + id: + const: '123' + opportunity: + status: + switch: + field: summary.opportunity_status + case: + active: open + inactive: closed + default: custom + amount: + field: summary.opportunity_amount + CommonGrants.Models.MappingSwitchFunction: + type: object + required: + - switch + properties: + switch: + type: object + properties: + field: + type: string + description: The field in the source data to switch on. + case: + type: object + additionalProperties: {} + description: An object mapping source field values to desired output values. + default: + description: The default value to output if no case matches the source field value. + required: + - field + - case + description: Returns a new value based on the value of a field in the source data using a switch statement. + example: + switch: + field: summary.opportunity_status + case: + active: open + inactive: closed + default: custom + CommonGrants.Models.OppDefaultFilters: + type: object + properties: + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.StringArrayFilter' + description: '`status.value` matches one of the following values' + example: + operator: in + value: + - forecasted + - open + closeDateRange: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.DateRangeFilter' + description: '`keyDates.closeDate` is between the given range' + example: + operator: between + value: + min: '2021-01-01' + max: '2021-01-02' + totalFundingAvailableRange: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.MoneyRangeFilter' + description: |- + `funding.totalAmountAvailable` is between the given range + + Funding amounts that are denominated in a different currency will + be excluded from the search. + example: + operator: between + value: + min: + amount: '1000000' + currency: USD + max: + amount: '2000000' + currency: USD + minAwardAmountRange: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.MoneyRangeFilter' + description: |- + `funding.minAwardAmount` is between the given range + + Funding amounts that are denominated in a different currency will + be excluded from the search. + example: + operator: between + value: + min: + amount: '1000000' + currency: USD + max: + amount: '2000000' + currency: USD + maxAwardAmountRange: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.MoneyRangeFilter' + description: |- + `funding.maxAwardAmount` is between the given range. + + Funding amounts that are denominated in a different currency will + be excluded from the search. + example: + operator: between + value: + min: + amount: '1000000' + currency: USD + max: + amount: '2000000' + currency: USD + allOf: + - type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Filters.DefaultFilter' + description: The standard set of filters supported for opportunity searches + CommonGrants.Models.OppFilters: + type: object + properties: + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.StringArrayFilter' + description: '`status.value` matches one of the following values' + example: + operator: in + value: + - forecasted + - open + closeDateRange: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.DateRangeFilter' + description: '`keyDates.closeDate` is between the given range' + example: + operator: between + value: + min: '2021-01-01' + max: '2021-01-02' + totalFundingAvailableRange: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.MoneyRangeFilter' + description: |- + `funding.totalAmountAvailable` is between the given range + + Funding amounts that are denominated in a different currency will + be excluded from the search. + example: + operator: between + value: + min: + amount: '1000000' + currency: USD + max: + amount: '2000000' + currency: USD + minAwardAmountRange: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.MoneyRangeFilter' + description: |- + `funding.minAwardAmount` is between the given range + + Funding amounts that are denominated in a different currency will + be excluded from the search. + example: + operator: between + value: + min: + amount: '1000000' + currency: USD + max: + amount: '2000000' + currency: USD + maxAwardAmountRange: + allOf: + - $ref: '#/components/schemas/CommonGrants.Filters.MoneyRangeFilter' + description: |- + `funding.maxAwardAmount` is between the given range. + + Funding amounts that are denominated in a different currency will + be excluded from the search. + example: + operator: between + value: + min: + amount: '1000000' + currency: USD + max: + amount: '2000000' + currency: USD + customFilters: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Filters.DefaultFilter' + description: Additional implementation-defined filters to apply to the search + description: Filters to apply when searching for opportunities + CommonGrants.Models.OppFunding: + type: object + properties: + details: + type: string + description: Details about the funding available for this opportunity that don't fit other fields + totalAmountAvailable: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.Money' + description: Total amount of funding available for this opportunity + minAwardAmount: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.Money' + description: Minimum amount of funding granted per award + maxAwardAmount: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.Money' + description: Maximum amount of funding granted per award + minAwardCount: + type: integer + description: Minimum number of awards granted + maxAwardCount: + type: integer + description: Maximum number of awards granted + estimatedAwardCount: + type: integer + description: Estimated number of awards that will be granted + description: Details about the funding available for this opportunity + example: + totalAmountAvailable: + amount: '1000000.00' + currency: USD + minAwardAmount: + amount: '10000.00' + currency: USD + maxAwardAmount: + amount: '50000.00' + currency: USD + minAwardCount: 5 + maxAwardCount: 20 + estimatedAwardCount: 10 + CommonGrants.Models.OppIdAln: + type: object + properties: + registry: + type: object + properties: + code: + type: string + enum: + - opp:us:aln + description: Canonical CommonGrants registry code, `::` (e.g. `org:us:ein`). + url: + type: string + format: uri + description: Link to the catalog entry for this registry. + description: Registry-level facts shared by every record in this registry. + id: + type: string + description: |- + The primary identifier string, when the registry has a single canonical value. + + May be omitted for registries with no natural primary; consumers should read + `allIds` in that case. + allIds: + type: array + items: + type: object + properties: + id: + type: string + description: The identifier string. + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.IdentifierStatus' + description: Whether the identifier is currently valid or retired. + required: + - id + - status + description: Every known identifier for this record in this registry, including archived values. + description: An opportunity's Assistance Listing Number (ALN), formerly the CFDA number. + example: + registry: + code: opp:us:aln + url: https://commongrants.org/registries/opp-us-aln + id: '93.575' + CommonGrants.Models.OppIdFon: + type: object + properties: + registry: + type: object + properties: + code: + type: string + enum: + - opp:us:fon + description: Canonical CommonGrants registry code, `::` (e.g. `org:us:ein`). + url: + type: string + format: uri + description: Link to the catalog entry for this registry. + description: Registry-level facts shared by every record in this registry. + id: + type: string + description: |- + The primary identifier string, when the registry has a single canonical value. + + May be omitted for registries with no natural primary; consumers should read + `allIds` in that case. + allIds: + type: array + items: + type: object + properties: + id: + type: string + description: The identifier string. + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.IdentifierStatus' + description: Whether the identifier is currently valid or retired. + required: + - id + - status + description: Every known identifier for this record in this registry, including archived values. + description: An opportunity's Funding Opportunity Number (FON), assigned by the awarding agency. + example: + registry: + code: opp:us:fon + url: https://commongrants.org/registries/opp-us-fon + id: HHS-2026-ACF-OCC-YD-0001 + CommonGrants.Models.OppIds: + type: object + properties: + opp:us:fon: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OppIdFon' + description: The opportunity's Funding Opportunity Number (FON). + opp:us:aln: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OppIdAln' + description: The opportunity's Assistance Listing Number (ALN). + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.IdentifierCollection' + description: |- + A collection of identifiers associated with an opportunity. + + Extends the generic identifier collection with the base identifiers CommonGrants + defines for opportunities. Additional registries can be published under `otherIds`. + example: + systemId: + registry: + code: opp:grants.gov:system + id: 018f2e77-3a4b-7c1d-9e2f-abcdef123456 + opp:us:fon: + registry: + code: opp:us:fon + url: https://commongrants.org/registries/opp-us-fon + id: HHS-2026-ACF-OCC-YD-0001 + opp:us:aln: + registry: + code: opp:us:aln + url: https://commongrants.org/registries/opp-us-aln + id: '93.575' + CommonGrants.Models.OppRef: + type: object + required: + - id + - title + properties: + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.uuid' + description: Globally unique id for the opportunity + readOnly: true + title: + type: string + description: Title or name of the funding opportunity + example: Small business grant program + identifiers: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OppIds' + description: System and registry-specific identifiers for the opportunity + description: |- + A reference to an opportunity, previewing the key fields a consumer needs + to identify it and look it up or join it to another response. Appears + wherever another record points to an opportunity, such as the opportunity + an award resulted from. + example: + id: 018f2e77-3a4b-7c1d-9e2f-abcdef123456 + title: Health Center Capital Improvement Program + identifiers: + opp:us:fon: + registry: + code: opp:us:fon + url: https://commongrants.org/registries/opp-us-fon + id: HHS-2026-ACF-OCC-YD-0001 + CommonGrants.Models.OppSortBy: + type: string + enum: + - lastModifiedAt + - createdAt + - title + - status.value + - keyDates.closeDate + - funding.maxAwardAmount + - funding.minAwardAmount + - funding.totalAmountAvailable + - funding.estimatedAwardCount + - custom + CommonGrants.Models.OppSorting: + type: object + required: + - sortBy + properties: + sortBy: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OppSortBy' + description: The field to sort by + example: lastModifiedAt + allOf: + - $ref: '#/components/schemas/CommonGrants.Sorting.SortBodyParams' + CommonGrants.Models.OppStatus: + type: object + required: + - value + properties: + value: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OppStatusOptions' + description: The selected value, from a predefined set of options + customValue: + type: string + description: A custom value, used when the selected value is the `custom` option + description: + type: string + description: A human-readable description of the value + description: The status of the opportunity + example: + value: open + description: The opportunity is currently accepting applications + CommonGrants.Models.OppStatusOptions: + type: string + enum: + - forecasted + - open + - closed + - custom + description: |- + The set of values accepted for opportunity status: + - `forecasted`: The opportunity is forecasted and not yet open for applications + - `open`: The opportunity is open for applications + - `closed`: The opportunity is no longer accepting applications + - `custom`: A custom status + CommonGrants.Models.OppTimeline: + type: object + properties: + postDate: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.Event' + description: The date (and time) at which the opportunity is posted + closeDate: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.Event' + description: The date (and time) at which the opportunity closes + otherDates: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Fields.Event' + description: |- + An optional map of other key dates or events in the opportunity timeline + + Examples might include a deadline for questions, anticipated award date, etc. + description: Key dates and events in the opportunity's timeline, such as when the opportunity is posted and closes + example: + postDate: + name: Opportunity posted date + eventType: singleDate + date: '2024-01-15' + description: Opportunity is posted publicly + closeDate: + name: Opportunity close date + eventType: singleDate + date: '2024-12-31' + time: '17:00:00' + description: Opportunity closes for all applications + otherDates: + anticipatedAward: + name: Anticipated award date + eventType: singleDate + date: '2025-03-15' + description: When we expect to announce awards for this opportunity. + applicationPeriod: + name: Application period + eventType: dateRange + startDate: '2024-01-01' + endDate: '2024-01-31' + endTime: '17:00:00' + description: Primary application period for the grant opportunity + performancePeriod: + name: Period of Performance + eventType: dateRange + startDate: '2024-01-01' + endDate: '2024-12-31' + description: Period of performance for the grant + infoSessions: + name: Info sessions + eventType: other + details: Every other Tuesday + description: Info sessions for the opportunity + CommonGrants.Models.OpportunityBase: + type: object + required: + - id + - title + - status + - description + - createdAt + - lastModifiedAt + properties: + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.uuid' + description: Globally unique id for the opportunity + readOnly: true + title: + type: string + description: Title or name of the funding opportunity + example: Small business grant program + identifiers: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OppIds' + description: System and registry-specific identifiers for the opportunity + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OppStatus' + description: Status of the opportunity + description: + type: string + description: Description of the opportunity's purpose and scope + example: This program provides funding to small businesses to help them grow and create jobs + funding: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OppFunding' + description: Details about the funding available + funders: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgRefCollection' + description: Organization(s) offering the funding for this opportunity + example: + primary: + id: 018f2e77-4b5c-7d2e-9f3a-bcdef1234567 + name: Health Resources and Services Administration + identifiers: + otherIds: + org:grants.gov:agency: + registry: + code: org:grants.gov:agency + id: HRSA + keyDates: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OppTimeline' + description: Key dates for the opportunity, such as when the application opens and closes + acceptedApplicantTypes: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Models.ApplicantType' + description: The type of applicant for the opportunity + source: + type: string + format: uri + description: URL for the original source of the opportunity + customFields: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Fields.CustomField' + description: Additional custom fields specific to this opportunity + createdAt: + type: string + format: date-time + description: The timestamp (in UTC) at which the record was created. + readOnly: true + lastModifiedAt: + type: string + format: date-time + description: The timestamp (in UTC) at which the record was last modified. + readOnly: true + description: A funding opportunity + CommonGrants.Models.OpportunityDetails: + type: object + properties: + competitions: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Models.CompetitionBase' + description: The competitions associated with the opportunity + awards: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Models.AwdRef' + description: |- + Awards that resulted from this opportunity, as references. + + Each entry references an award that resulted from this opportunity; the + award's `opportunity.id`, when it is published, is this record's `id`. + An entry is a reference, not the award record: `GET /awards/` is the + canonical record only where an implementation serves the award routes, + and otherwise the entry's `identifiers`, where the publisher supplies + them, are the key for joining the award in another system. A consumer + must not assume a reference can be dereferenced through this API. + + Absent means the implementation does not publish this link for the + record, and an empty array means the link is published and no awards are + known. Entries carry no ordering guarantee. + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OpportunityBase' + description: A funding opportunity with additional details, like available competitions. + CommonGrants.Models.OrgHierarchyKindOptions: + type: string + enum: + - chapter + - department + - branch + - subsidiary + - fiscalSponsor + - dba + - custom + description: |- + The standard subtypes of a parent or child relationship: + - `chapter`: The child is a chapter of the parent + - `department`: The child is an internal unit of the parent + - `branch`: The child is a branch of the parent + - `subsidiary`: The child is a subsidiary of the parent + - `fiscalSponsor`: The parent fiscally sponsors the child + - `dba`: The child is a record for a name the parent, a legal entity, does business under + - `custom`: Another subtype, named in `customValue` + CommonGrants.Models.OrgHierarchyRelationship: + type: object + required: + - org + properties: + org: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgRef' + description: The other organization. + kind: + type: object + properties: + value: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgHierarchyKindOptions' + description: The selected value, from a predefined set of options + customValue: + type: string + description: A custom value, used when the selected value is the `custom` option + description: + type: string + description: A human-readable description of the value + required: + - value + description: The relationship's subtype within the category its list names. + startDate: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.isoDate' + description: 'When the relationship started, in ISO 8601 format: YYYY-MM-DD' + endDate: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.isoDate' + description: 'When the relationship ended, in ISO 8601 format: YYYY-MM-DD' + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgRelationshipStatus' + description: Whether the relationship is in effect, as stated by the provider. + description: A parent or child relationship. + example: + org: + id: 01912a8b-7c3d-7892-abcd-ef1234567892 + name: Riverside Community Foundation + identifiers: + org:us:ein: + registry: + code: org:us:ein + id: '472345678' + kind: + value: fiscalSponsor + startDate: '2024-07-01' + status: active + CommonGrants.Models.OrgIdDuns: + type: object + properties: + registry: + type: object + properties: + code: + type: string + enum: + - org:xi:duns + description: Canonical CommonGrants registry code, `::` (e.g. `org:us:ein`). + url: + type: string + format: uri + description: Link to the catalog entry for this registry. + description: Registry-level facts shared by every record in this registry. + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.duns' + description: |- + The primary identifier string, when the registry has a single canonical value. + + May be omitted for registries with no natural primary; consumers should read + `allIds` in that case. + allIds: + type: array + items: + type: object + properties: + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.duns' + description: The identifier string. + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.IdentifierStatus' + description: Whether the identifier is currently valid or retired. + required: + - id + - status + description: Every known identifier for this record in this registry, including archived values. + description: An organization's Data Universal Numbering System (DUNS) number. + example: + registry: + code: org:xi:duns + url: https://commongrants.org/registries/org-xi-duns + id: '123456789' + CommonGrants.Models.OrgIdEin: + type: object + properties: + registry: + type: object + properties: + code: + type: string + enum: + - org:us:ein + description: Canonical CommonGrants registry code, `::` (e.g. `org:us:ein`). + url: + type: string + format: uri + description: Link to the catalog entry for this registry. + description: Registry-level facts shared by every record in this registry. + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.employerTaxId' + description: |- + The primary identifier string, when the registry has a single canonical value. + + May be omitted for registries with no natural primary; consumers should read + `allIds` in that case. + allIds: + type: array + items: + type: object + properties: + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.employerTaxId' + description: The identifier string. + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.IdentifierStatus' + description: Whether the identifier is currently valid or retired. + required: + - id + - status + description: Every known identifier for this record in this registry, including archived values. + description: An organization's Employer Identification Number (EIN), assigned by the IRS. + example: + registry: + code: org:us:ein + url: https://commongrants.org/registries/org-us-ein + id: '123456789' + CommonGrants.Models.OrgIdUei: + type: object + properties: + registry: + type: object + properties: + code: + type: string + enum: + - org:us:uei + description: Canonical CommonGrants registry code, `::` (e.g. `org:us:ein`). + url: + type: string + format: uri + description: Link to the catalog entry for this registry. + description: Registry-level facts shared by every record in this registry. + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.samUEI' + description: |- + The primary identifier string, when the registry has a single canonical value. + + May be omitted for registries with no natural primary; consumers should read + `allIds` in that case. + allIds: + type: array + items: + type: object + properties: + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.samUEI' + description: The identifier string. + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.IdentifierStatus' + description: Whether the identifier is currently valid or retired. + required: + - id + - status + description: Every known identifier for this record in this registry, including archived values. + description: An organization's Unique Entity Identifier (UEI) from SAM.gov. + example: + registry: + code: org:us:uei + url: https://commongrants.org/registries/org-us-uei + id: AB0123456789 + CommonGrants.Models.OrgIds: + type: object + properties: + org:us:ein: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgIdEin' + description: The organization's Employer Identification Number (EIN), assigned by the IRS. + org:us:uei: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgIdUei' + description: The organization's Unique Entity Identifier (UEI) from SAM.gov. + org:xi:duns: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgIdDuns' + description: The organization's Data Universal Numbering System (DUNS) number. + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.IdentifierCollection' + description: |- + A collection of identifiers associated with an organization. + + Extends the generic identifier collection with the base identifiers CommonGrants + defines for organizations. Additional registries can be published under `otherIds`. + CommonGrants.Models.OrgOtherKindOptions: + type: string + enum: + - custom + description: Other relationships define no standard subtypes, so a stated subtype is `custom`. + CommonGrants.Models.OrgOtherRelationship: + type: object + required: + - org + properties: + org: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgRef' + description: The other organization. + kind: + type: object + properties: + value: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgOtherKindOptions' + description: The selected value, from a predefined set of options + customValue: + type: string + description: A custom value, used when the selected value is the `custom` option + description: + type: string + description: A human-readable description of the value + required: + - value + description: The relationship's subtype within the category its list names. + startDate: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.isoDate' + description: 'When the relationship started, in ISO 8601 format: YYYY-MM-DD' + endDate: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.isoDate' + description: 'When the relationship ended, in ISO 8601 format: YYYY-MM-DD' + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgRelationshipStatus' + description: Whether the relationship is in effect, as stated by the provider. + description: A relationship outside the named categories, which need not have a direction. + example: + org: + id: 01912a8b-7c3d-7895-abcd-ef1234567895 + name: Riverside Literacy Coalition + CommonGrants.Models.OrgPatchData: + type: object + properties: + name: + type: string + description: The name this organization is known by; for a legal entity, its legal name. + status: + type: object + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgPatchOrgStatusOrCreate' + nullable: true + description: Whether the organization exists and operates, or has dissolved or ceased operating. + mission: + type: string + nullable: true + description: The organization's mission statement. + yearFounded: + type: string + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.calendarYear' + nullable: true + description: The calendar year the organization was founded. + aliases: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Types.nonEmptyString' + nullable: true + uniqueItems: true + description: Other names this organization goes by, such as a trading name or a short form of its legal name. Not a history of former names. Don't list a name that has its own live trading-name record linked to this organization by a `dba` entry in either record; see the organization relationships guide. + identifiers: + type: object + allOf: + - $ref: '#/components/schemas/CommonGrants.Patch.OrgPatchOrgIdsOrCreate' + nullable: true + description: Identifiers associated with the organization, keyed by registry code. + orgType: + type: object + allOf: + - $ref: '#/components/schemas/CommonGrants.Patch.OrgPatchPCSOrgTypeOrCreate' + nullable: true + description: The organization's type within the Philanthropy Classification System (PCS). + addresses: + type: object + allOf: + - $ref: '#/components/schemas/CommonGrants.Patch.OrgPatchAddressCollectionOrCreate' + nullable: true + description: Collection of physical addresses associated with the organization. + phones: + type: object + allOf: + - $ref: '#/components/schemas/CommonGrants.Patch.OrgPatchPhoneCollectionOrCreate' + nullable: true + description: Collection of phone numbers associated with the organization. + emails: + type: object + allOf: + - $ref: '#/components/schemas/CommonGrants.Patch.OrgPatchEmailCollectionOrCreate' + nullable: true + description: Collection of email addresses associated with the organization. + socials: + type: object + allOf: + - $ref: '#/components/schemas/CommonGrants.Patch.OrgPatchOrgSocialLinksOrCreate' + nullable: true + description: Collection of the organization's social media and web presence links. + relationships: + type: object + properties: + parents: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Patch.OrgPatchOrgHierarchyRelationshipReplaceOnly' + nullable: true + description: Organizations above this one, such as a containing organization or a fiscal sponsor. + children: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Patch.OrgPatchOrgHierarchyRelationshipReplaceOnly' + nullable: true + description: Organizations below this one, such as its chapters or sponsored projects. + succeededBy: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Patch.OrgPatchOrgSuccessionRelationshipReplaceOnly' + nullable: true + description: Organizations that carry on all or part of this one. + succeeds: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Patch.OrgPatchOrgSuccessionRelationshipReplaceOnly' + nullable: true + description: Organizations whose work this one carries on in whole or in part. + recordReplacedBy: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Patch.OrgPatchOrgRecordRelationshipReplaceOnly' + nullable: true + description: Records to use instead of this record. + recordReplaces: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Patch.OrgPatchOrgRecordRelationshipReplaceOnly' + nullable: true + description: Records that this record is used instead of. + otherRelationships: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Patch.OrgPatchOrgOtherRelationshipReplaceOnly' + nullable: true + description: Connections outside the categories above, which need not have a direction. + nullable: true + description: The organization's relationships to other organizations. + customFields: + type: object + additionalProperties: + type: object + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.OrgPatchCustomFieldOrCreate' + nullable: true + nullable: true + description: Custom fields for the organization. + description: |- + A JSON Merge Patch (RFC 7396) body for updating an organization profile. + + Derived from `OrganizationBase`: every field is optional, fields that can + be cleared accept `null` to unset them, record keys can be deleted by + setting them to `null`, and read-only fields like `id` are excluded. + Sent as `application/merge-patch+json`. + example: + name: Example Nonprofit (Renamed) + mission: To expand access to community health resources. + yearFounded: null + socials: + website: null + emails: + primary: info@example.org + customFields: + legacyCode: null + CommonGrants.Models.OrgPatchOrgIdDunsOrCreate: + type: object + properties: + registry: + type: object + properties: + code: + type: string + enum: + - org:xi:duns + nullable: true + description: Canonical CommonGrants registry code, `::` (e.g. `org:us:ein`). + url: + type: string + format: uri + nullable: true + description: Link to the catalog entry for this registry. + nullable: true + description: Registry-level facts shared by every record in this registry. + id: + type: string + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.duns' + nullable: true + description: |- + The primary identifier string, when the registry has a single canonical value. + + May be omitted for registries with no natural primary; consumers should read + `allIds` in that case. + allIds: + type: array + items: + type: object + properties: + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.duns' + description: The identifier string. + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.IdentifierStatus' + description: Whether the identifier is currently valid or retired. + required: + - id + - status + nullable: true + description: Every known identifier for this record in this registry, including archived values. + description: An organization's Data Universal Numbering System (DUNS) number. + example: + registry: + code: org:xi:duns + url: https://commongrants.org/registries/org-xi-duns + id: '123456789' + CommonGrants.Models.OrgPatchOrgIdEinOrCreate: + type: object + properties: + registry: + type: object + properties: + code: + type: string + enum: + - org:us:ein + nullable: true + description: Canonical CommonGrants registry code, `::` (e.g. `org:us:ein`). + url: + type: string + format: uri + nullable: true + description: Link to the catalog entry for this registry. + nullable: true + description: Registry-level facts shared by every record in this registry. + id: + type: string + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.employerTaxId' + nullable: true + description: |- + The primary identifier string, when the registry has a single canonical value. + + May be omitted for registries with no natural primary; consumers should read + `allIds` in that case. + allIds: + type: array + items: + type: object + properties: + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.employerTaxId' + description: The identifier string. + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.IdentifierStatus' + description: Whether the identifier is currently valid or retired. + required: + - id + - status + nullable: true + description: Every known identifier for this record in this registry, including archived values. + description: An organization's Employer Identification Number (EIN), assigned by the IRS. + example: + registry: + code: org:us:ein + url: https://commongrants.org/registries/org-us-ein + id: '123456789' + CommonGrants.Models.OrgPatchOrgIdUeiOrCreate: + type: object + properties: + registry: + type: object + properties: + code: + type: string + enum: + - org:us:uei + nullable: true + description: Canonical CommonGrants registry code, `::` (e.g. `org:us:ein`). + url: + type: string + format: uri + nullable: true + description: Link to the catalog entry for this registry. + nullable: true + description: Registry-level facts shared by every record in this registry. + id: + type: string + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.samUEI' + nullable: true + description: |- + The primary identifier string, when the registry has a single canonical value. + + May be omitted for registries with no natural primary; consumers should read + `allIds` in that case. + allIds: + type: array + items: + type: object + properties: + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.samUEI' + description: The identifier string. + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.IdentifierStatus' + description: Whether the identifier is currently valid or retired. + required: + - id + - status + nullable: true + description: Every known identifier for this record in this registry, including archived values. + description: An organization's Unique Entity Identifier (UEI) from SAM.gov. + example: + registry: + code: org:us:uei + url: https://commongrants.org/registries/org-us-uei + id: AB0123456789 + CommonGrants.Models.OrgPatchOrgStatusOrCreate: + type: object + properties: + value: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgStatusOptions' + description: The selected value, from a predefined set of options + customValue: + type: string + nullable: true + description: A custom value, used when the selected value is the `custom` option + description: + type: string + nullable: true + description: A human-readable description of the value + description: The status of the organization + example: + value: active + description: The organization exists and operates + CommonGrants.Models.OrgRecordKindOptions: + type: string + enum: + - duplicate + - merged + - custom + description: |- + The standard subtypes of record replacement. A provider's workflow may + treat them alike; they need not be exclusive. + - `duplicate`: The records duplicate each other + - `merged`: The provider combined the records + - `custom`: Another subtype, named in `customValue` + CommonGrants.Models.OrgRecordRelationship: + type: object + required: + - org + properties: + org: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgRef' + description: The other organization. + kind: + type: object + properties: + value: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgRecordKindOptions' + description: The selected value, from a predefined set of options + customValue: + type: string + description: A custom value, used when the selected value is the `custom` option + description: + type: string + description: A human-readable description of the value + required: + - value + description: The relationship's subtype within the category its list names. + startDate: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.isoDate' + description: 'When the relationship started, in ISO 8601 format: YYYY-MM-DD' + endDate: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.isoDate' + description: 'When the relationship ended, in ISO 8601 format: YYYY-MM-DD' + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgRelationshipStatus' + description: Whether the relationship is in effect, as stated by the provider. + description: A record replacement relationship. + example: + org: + id: 01912a8b-7c3d-7894-abcd-ef1234567894 + name: Riverside Reading Project + kind: + value: duplicate + CommonGrants.Models.OrgRef: + type: object + required: + - id + - name + properties: + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.uuid' + description: The organization's unique identifier. + readOnly: true + name: + type: string + description: The name this organization is known by; for a legal entity, its legal name. + identifiers: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgIds' + description: Identifiers associated with the organization, keyed by registry code. + description: |- + A reference to an organization, previewing the key fields a consumer needs + to identify it and look it up or join it to another response. Appears + wherever another record points to an organization, such as an award's funder + or recipient. + example: + id: 018f2e77-4b5c-7d2e-9f3a-bcdef1234567 + name: Health Resources and Services Administration + identifiers: + otherIds: + org:grants.gov:agency: + registry: + code: org:grants.gov:agency + id: HRSA + CommonGrants.Models.OrgRefCollection: + type: object + required: + - primary + properties: + primary: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgRef' + description: The primary organization in the collection. + otherOrgs: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Models.OrgRef' + description: Other organizations in the collection, keyed by an implementation-defined role. + description: |- + A group of organization references, with a primary organization and + optional others. Appears wherever several organizations share a role on a + record, such as an award's funders or recipient organizations. + example: + primary: + id: 018f2e77-4b5c-7d2e-9f3a-bcdef1234567 + name: Health Resources and Services Administration + identifiers: + otherIds: + org:grants.gov:agency: + registry: + code: org:grants.gov:agency + id: HRSA + CommonGrants.Models.OrgRelationshipStatus: + type: string + enum: + - active + - inactive + description: Whether a relationship is in effect, as stated by the provider. + CommonGrants.Models.OrgRelationships: + type: object + properties: + parents: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Models.OrgHierarchyRelationship' + description: Organizations above this one, such as a containing organization or a fiscal sponsor. + children: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Models.OrgHierarchyRelationship' + description: Organizations below this one, such as its chapters or sponsored projects. + succeededBy: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Models.OrgSuccessionRelationship' + description: Organizations that carry on all or part of this one. + succeeds: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Models.OrgSuccessionRelationship' + description: Organizations whose work this one carries on in whole or in part. + recordReplacedBy: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Models.OrgRecordRelationship' + description: Records to use instead of this record. + recordReplaces: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Models.OrgRecordRelationship' + description: Records that this record is used instead of. + otherRelationships: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Models.OrgOtherRelationship' + description: Connections outside the categories above, which need not have a direction. + description: |- + An organization's relationships to other organizations. + + Each named list holds relationships of one category and direction; + `otherRelationships` holds connections outside those categories. Every list + is optional, list order carries no meaning, and a provider may state a + relationship from either organization's record. A relationship confers no + authority over the other organization. + example: + parents: + - org: + id: 01912a8b-7c3d-7891-abcd-ef1234567891 + name: National Reading Network + kind: + value: chapter + - org: + id: 01912a8b-7c3d-7892-abcd-ef1234567892 + name: Riverside Community Foundation + identifiers: + org:us:ein: + registry: + code: org:us:ein + id: '472345678' + kind: + value: fiscalSponsor + startDate: '2024-07-01' + status: active + CommonGrants.Models.OrgRevision: + type: object + required: + - id + - status + - createdAt + - lastModifiedAt + properties: + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.uuid' + description: Globally unique id for the revision + readOnly: true + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.RevisionStatus' + description: The lifecycle status of the change + source: + type: string + description: The source system the change came from + patch: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgPatchData' + description: The merge patch that was submitted + snapshot: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrganizationBase' + description: A full snapshot of the record with the change applied + createdAt: + type: string + format: date-time + description: The timestamp (in UTC) at which the record was created. + readOnly: true + lastModifiedAt: + type: string + format: date-time + description: The timestamp (in UTC) at which the record was last modified. + readOnly: true + description: |- + A single change to an organization profile, recorded in the change ledger. + + The `patch` is an `OrgPatchData` merge patch, and the `snapshot` is the + organization profile with that change applied. + example: + id: 01912a8b-7c3d-7890-abcd-ef1234567890 + status: + value: accepted + description: The change was applied. + source: grants.gov + patch: + mission: To provide support and resources to the community. + snapshot: + id: 083b4567-e89d-42c8-a439-6c1234567890 + name: Example Organization + orgType: + term: Hospital + class: Organization types + description: Institutions with the primary purpose of providing in-patient physical and mental health services... + code: EO000000 + status: + value: active + description: The organization exists and operates + identifiers: + org:us:ein: + registry: + code: org:us:ein + url: https://commongrants.org/registries/org-us-ein + id: '123456789' + org:us:uei: + registry: + code: org:us:uei + url: https://commongrants.org/registries/org-us-uei + id: AB0123456789 + addresses: + primary: + street1: 456 Main St + street2: Suite 100 + city: Anytown + stateOrProvince: CA + country: US + postalCode: '12345' + otherAddresses: + satellite: + street1: 456 Main St + street2: Suite 100 + city: Anytown + stateOrProvince: CA + country: US + postalCode: '12345' + international: + street1: 123 Rue Principale + city: Montreal + stateOrProvince: QC + country: CA + postalCode: H2Y 1C6 + phones: + primary: + countryCode: '+1' + number: 444-456-1230 + isMobile: true + fax: + countryCode: '+1' + number: 555-123-4567 + extension: '123' + isMobile: false + otherPhones: + support: + countryCode: '+1' + number: 333-456-1230 + isMobile: false + marketing: + countryCode: '+1' + number: 444-456-1230 + isMobile: true + emails: + primary: info@example.com + otherEmails: + support: support@example.com + marketing: marketing@example.com + mission: To provide support and resources to the community. + yearFounded: '2024' + socials: + website: https://www.example.com + facebook: https://www.facebook.com/example + twitterOrX: https://x.com/example + instagram: https://www.instagram.com/example + linkedin: https://www.linkedin.com/company/example + otherSocials: + youtube: https://www.youtube.com/example + aliases: + - Example Org + relationships: + parents: + - org: + id: 01912a8b-7c3d-7891-abcd-ef1234567891 + name: National Reading Network + kind: + value: chapter + createdAt: '2026-06-20T14:30:00Z' + lastModifiedAt: '2026-06-20T14:30:00Z' + CommonGrants.Models.OrgSocialLinks: + type: object + properties: + website: + type: string + format: uri + description: The organization's primary website URL. + facebook: + type: string + format: uri + description: The organization's Facebook profile URL. + twitterOrX: + type: string + format: uri + description: The organization's Twitter/X profile URL. + bluesky: + type: string + format: uri + description: The organization's BlueSky profile URL. + instagram: + type: string + format: uri + description: The organization's Instagram profile URL. + linkedin: + type: string + format: uri + description: The organization's LinkedIn profile URL. + otherSocials: + type: object + additionalProperties: + type: string + format: uri + description: Additional social media profiles not covered by the standard fields. + description: A collection of social media and web presence links for an organization. + example: + website: https://www.example.com + facebook: https://www.facebook.com/example + twitterOrX: https://x.com/example + instagram: https://www.instagram.com/example + linkedin: https://www.linkedin.com/company/example + otherSocials: + youtube: https://www.youtube.com/example + CommonGrants.Models.OrgStatus: + type: object + required: + - value + properties: + value: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgStatusOptions' + description: The selected value, from a predefined set of options + customValue: + type: string + description: A custom value, used when the selected value is the `custom` option + description: + type: string + description: A human-readable description of the value + description: The status of the organization + example: + value: active + description: The organization exists and operates + CommonGrants.Models.OrgStatusOptions: + type: string + enum: + - active + - inactive + - custom + description: |- + The set of values accepted for organization status: + - `active`: The organization exists and operates + - `inactive`: The organization has dissolved or ceased operating; loss of tax-exempt status alone does not make an organization inactive + - `custom`: A status not covered by the other options, described in `customValue` + CommonGrants.Models.OrgSuccessionKindOptions: + type: string + enum: + - merger + - acquisition + - divestiture + - split + - custom + description: |- + The standard subtypes of organizational succession: + - `merger`: Succession through a merger + - `acquisition`: Succession through an acquisition + - `divestiture`: Succession through a divestiture + - `split`: Succession through a split into several organizations + - `custom`: Another subtype, named in `customValue` + CommonGrants.Models.OrgSuccessionRelationship: + type: object + required: + - org + properties: + org: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgRef' + description: The other organization. + kind: + type: object + properties: + value: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgSuccessionKindOptions' + description: The selected value, from a predefined set of options + customValue: + type: string + description: A custom value, used when the selected value is the `custom` option + description: + type: string + description: A human-readable description of the value + required: + - value + description: The relationship's subtype within the category its list names. + startDate: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.isoDate' + description: 'When the relationship started, in ISO 8601 format: YYYY-MM-DD' + endDate: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.isoDate' + description: 'When the relationship ended, in ISO 8601 format: YYYY-MM-DD' + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgRelationshipStatus' + description: Whether the relationship is in effect, as stated by the provider. + description: A succession relationship. + example: + org: + id: 01912a8b-7c3d-7893-abcd-ef1234567893 + name: Riverside Reading East + kind: + value: split + startDate: '2026-01-01' + CommonGrants.Models.OrganizationBase: + type: object + required: + - id + - name + properties: + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.uuid' + description: The organization's unique identifier. + readOnly: true + name: + type: string + description: The name this organization is known by; for a legal entity, its legal name. + identifiers: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgIds' + description: Identifiers associated with the organization, keyed by registry code. + orgType: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.PCSOrgType' + description: The organization's type within the Philanthropy Classification System (PCS). + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgStatus' + description: Whether the organization exists and operates, or has dissolved or ceased operating. + addresses: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.AddressCollection' + description: Collection of physical addresses associated with the organization. + phones: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.PhoneCollection' + description: Collection of phone numbers associated with the organization. + emails: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.EmailCollection' + description: Collection of email addresses associated with the organization. + mission: + type: string + description: The organization's mission statement. + yearFounded: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.calendarYear' + description: The calendar year the organization was founded. + socials: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgSocialLinks' + description: Collection of the organization's social media and web presence links. + aliases: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Types.nonEmptyString' + uniqueItems: true + description: Other names this organization goes by, such as a trading name or a short form of its legal name. Not a history of former names. Don't list a name that has its own live trading-name record linked to this organization by a `dba` entry in either record; see the organization relationships guide. + relationships: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgRelationships' + description: The organization's relationships to other organizations. + customFields: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Fields.CustomField' + description: Custom fields for the organization. + description: An organization that can apply for grants. + example: + id: 083b4567-e89d-42c8-a439-6c1234567890 + name: Example Organization + orgType: + term: Hospital + class: Organization types + description: Institutions with the primary purpose of providing in-patient physical and mental health services... + code: EO000000 + status: + value: active + description: The organization exists and operates + identifiers: + org:us:ein: + registry: + code: org:us:ein + url: https://commongrants.org/registries/org-us-ein + id: '123456789' + org:us:uei: + registry: + code: org:us:uei + url: https://commongrants.org/registries/org-us-uei + id: AB0123456789 + addresses: + primary: + street1: 456 Main St + street2: Suite 100 + city: Anytown + stateOrProvince: CA + country: US + postalCode: '12345' + otherAddresses: + satellite: + street1: 456 Main St + street2: Suite 100 + city: Anytown + stateOrProvince: CA + country: US + postalCode: '12345' + international: + street1: 123 Rue Principale + city: Montreal + stateOrProvince: QC + country: CA + postalCode: H2Y 1C6 + phones: + primary: + countryCode: '+1' + number: 444-456-1230 + isMobile: true + fax: + countryCode: '+1' + number: 555-123-4567 + extension: '123' + isMobile: false + otherPhones: + support: + countryCode: '+1' + number: 333-456-1230 + isMobile: false + marketing: + countryCode: '+1' + number: 444-456-1230 + isMobile: true + emails: + primary: info@example.com + otherEmails: + support: support@example.com + marketing: marketing@example.com + mission: To provide support and resources to the community. + yearFounded: '2024' + socials: + website: https://www.example.com + facebook: https://www.facebook.com/example + twitterOrX: https://x.com/example + instagram: https://www.instagram.com/example + linkedin: https://www.linkedin.com/company/example + otherSocials: + youtube: https://www.youtube.com/example + aliases: + - Example Org + relationships: + parents: + - org: + id: 01912a8b-7c3d-7891-abcd-ef1234567891 + name: National Reading Network + kind: + value: chapter + CommonGrants.Models.RevisionStatus: + type: object + required: + - value + properties: + value: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.RevisionStatusOptions' + description: The selected value, from a predefined set of options + customValue: + type: string + description: A custom value, used when the selected value is the `custom` option + description: + type: string + description: A human-readable description of the value + description: |- + The status of a revision, including its lifecycle state and an optional + human-readable description. + example: + value: custom + customValue: escalated + description: The change was escalated for additional review. + CommonGrants.Models.RevisionStatusOptions: + type: string + enum: + - pending + - accepted + - denied + - superseded + - custom + description: |- + The set of values accepted for a revision's status: + - `pending`: Non-terminal. The change is queued for review. + - `accepted`: Terminal. The change was applied, either immediately via a + direct `PATCH` or after a `pending` change was approved. + - `denied`: Terminal. The change was rejected, with a reason. + - `superseded`: Terminal. A competing change was accepted first, so this + change no longer applies. + - `custom`: An implementation-defined status. The receiver documents whether + it is terminal. + + A revision moves once from `pending` into a terminal state; a terminal + revision is never restated. How a receiver resolves a `pending` change (a + human review, a policy engine, a batch job) is out of scope for this contract. + CommonGrants.Pagination.PaginatedBodyParams: + type: object + properties: + page: + type: integer + format: int32 + minimum: 1 + description: The page to return + default: 1 + pageSize: + type: integer + format: int32 + minimum: 1 + description: The number of items to return per page + default: 100 + description: Body parameters for paginated routes + CommonGrants.Pagination.PaginatedResultsInfo: + type: object + required: + - page + - pageSize + properties: + page: + type: integer + format: int32 + minimum: 1 + description: Current page number (indexing starts at 1) + example: 1 + pageSize: + type: integer + minimum: 1 + description: Number of items per page + example: 20 + totalItems: + type: integer + description: Total number of items across all pages + example: 100 + totalPages: + type: integer + description: Total number of pages + example: 5 + description: Details about the paginated results + CommonGrants.Patch.OrgPatchAddressCollectionOrCreate: + type: object + properties: + primary: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.OrgPatchAddressOrCreate' + description: The primary address for a person or organization. + otherAddresses: + type: object + additionalProperties: + type: object + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.OrgPatchAddressOrCreate' + nullable: true + nullable: true + description: Additional addresses keyed by a descriptive label (e.g., "work", "home", "international"). + description: A collection of addresses. + CommonGrants.Patch.OrgPatchEmailCollectionOrCreate: + type: object + properties: + primary: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.email' + description: The primary email address for a person or organization. + otherEmails: + type: object + additionalProperties: + type: string + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.email' + nullable: true + nullable: true + description: Additional email addresses keyed by a descriptive label (e.g., "work", "personal", "support"). + description: A collection of email addresses. + CommonGrants.Patch.OrgPatchOrgHierarchyRelationshipReplaceOnly: + type: object + required: + - org + properties: + org: + allOf: + - $ref: '#/components/schemas/CommonGrants.Patch.OrgPatchOrgTargetRefReplaceOnly' + description: The other organization, which a writer can name by `id` alone. + kind: + type: object + properties: + value: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgHierarchyKindOptions' + description: The selected value, from a predefined set of options + customValue: + type: string + description: A custom value, used when the selected value is the `custom` option + description: + type: string + description: A human-readable description of the value + required: + - value + description: The relationship's subtype within the category its list names. + startDate: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.isoDate' + description: 'When the relationship started, in ISO 8601 format: YYYY-MM-DD' + endDate: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.isoDate' + description: 'When the relationship ended, in ISO 8601 format: YYYY-MM-DD' + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgRelationshipStatus' + description: Whether the relationship is in effect, as stated by the provider. + description: A parent or child relationship, as written. + CommonGrants.Patch.OrgPatchOrgIdsOrCreate: + type: object + properties: + org:us:ein: + type: object + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgPatchOrgIdEinOrCreate' + nullable: true + description: The organization's Employer Identification Number (EIN), assigned by the IRS. + org:us:uei: + type: object + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgPatchOrgIdUeiOrCreate' + nullable: true + description: The organization's Unique Entity Identifier (UEI) from SAM.gov. + org:xi:duns: + type: object + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgPatchOrgIdDunsOrCreate' + nullable: true + description: The organization's Data Universal Numbering System (DUNS) number. + systemId: + type: object + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.OrgPatchSystemIdOrCreate' + nullable: true + description: The hosting system's own identifier for this record. + otherIds: + type: object + additionalProperties: + type: object + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.OrgPatchIdentifierOrCreate' + nullable: true + nullable: true + description: |- + Additional identifiers keyed by their registry code, for registries the + protocol does not define as a base identifier on the model. + description: |- + A collection of identifiers associated with an organization. + + Extends the generic identifier collection with the base identifiers CommonGrants + defines for organizations. Additional registries can be published under `otherIds`. + CommonGrants.Patch.OrgPatchOrgOtherRelationshipReplaceOnly: + type: object + required: + - org + properties: + org: + allOf: + - $ref: '#/components/schemas/CommonGrants.Patch.OrgPatchOrgTargetRefReplaceOnly' + description: The other organization, which a writer can name by `id` alone. + kind: + type: object + properties: + value: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgOtherKindOptions' + description: The selected value, from a predefined set of options + customValue: + type: string + description: A custom value, used when the selected value is the `custom` option + description: + type: string + description: A human-readable description of the value + required: + - value + description: The relationship's subtype within the category its list names. + startDate: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.isoDate' + description: 'When the relationship started, in ISO 8601 format: YYYY-MM-DD' + endDate: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.isoDate' + description: 'When the relationship ended, in ISO 8601 format: YYYY-MM-DD' + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgRelationshipStatus' + description: Whether the relationship is in effect, as stated by the provider. + description: A relationship outside the named categories, as written. + CommonGrants.Patch.OrgPatchOrgRecordRelationshipReplaceOnly: + type: object + required: + - org + properties: + org: + allOf: + - $ref: '#/components/schemas/CommonGrants.Patch.OrgPatchOrgTargetRefReplaceOnly' + description: The other organization, which a writer can name by `id` alone. + kind: + type: object + properties: + value: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgRecordKindOptions' + description: The selected value, from a predefined set of options + customValue: + type: string + description: A custom value, used when the selected value is the `custom` option + description: + type: string + description: A human-readable description of the value + required: + - value + description: The relationship's subtype within the category its list names. + startDate: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.isoDate' + description: 'When the relationship started, in ISO 8601 format: YYYY-MM-DD' + endDate: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.isoDate' + description: 'When the relationship ended, in ISO 8601 format: YYYY-MM-DD' + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgRelationshipStatus' + description: Whether the relationship is in effect, as stated by the provider. + description: A record replacement relationship, as written. + CommonGrants.Patch.OrgPatchOrgSocialLinksOrCreate: + type: object + properties: + website: + type: string + format: uri + nullable: true + description: The organization's primary website URL. + facebook: + type: string + format: uri + nullable: true + description: The organization's Facebook profile URL. + twitterOrX: + type: string + format: uri + nullable: true + description: The organization's Twitter/X profile URL. + bluesky: + type: string + format: uri + nullable: true + description: The organization's BlueSky profile URL. + instagram: + type: string + format: uri + nullable: true + description: The organization's Instagram profile URL. + linkedin: + type: string + format: uri + nullable: true + description: The organization's LinkedIn profile URL. + otherSocials: + type: object + additionalProperties: + type: string + format: uri + nullable: true + nullable: true + description: Additional social media profiles not covered by the standard fields. + description: A collection of social media and web presence links for an organization. + CommonGrants.Patch.OrgPatchOrgSuccessionRelationshipReplaceOnly: + type: object + required: + - org + properties: + org: + allOf: + - $ref: '#/components/schemas/CommonGrants.Patch.OrgPatchOrgTargetRefReplaceOnly' + description: The other organization, which a writer can name by `id` alone. + kind: + type: object + properties: + value: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgSuccessionKindOptions' + description: The selected value, from a predefined set of options + customValue: + type: string + description: A custom value, used when the selected value is the `custom` option + description: + type: string + description: A human-readable description of the value + required: + - value + description: The relationship's subtype within the category its list names. + startDate: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.isoDate' + description: 'When the relationship started, in ISO 8601 format: YYYY-MM-DD' + endDate: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.isoDate' + description: 'When the relationship ended, in ISO 8601 format: YYYY-MM-DD' + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgRelationshipStatus' + description: Whether the relationship is in effect, as stated by the provider. + description: A succession relationship, as written. + CommonGrants.Patch.OrgPatchOrgTargetRefReplaceOnly: + type: object + required: + - id + properties: + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.uuid' + description: The other organization's unique identifier. + name: + type: string + description: "The other organization's name. Ignored if supplied: the receiver fills it in from its own record." + identifiers: + type: object + properties: + org:us:ein: + type: object + properties: + registry: + type: object + properties: + code: + type: string + enum: + - org:us:ein + description: Canonical CommonGrants registry code, `::` (e.g. `org:us:ein`). + url: + type: string + format: uri + description: Link to the catalog entry for this registry. + description: Registry-level facts shared by every record in this registry. + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.employerTaxId' + description: |- + The primary identifier string, when the registry has a single canonical value. + + May be omitted for registries with no natural primary; consumers should read + `allIds` in that case. + allIds: + type: array + items: + type: object + properties: + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.employerTaxId' + description: The identifier string. + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.IdentifierStatus' + description: Whether the identifier is currently valid or retired. + required: + - id + - status + description: Every known identifier for this record in this registry, including archived values. + description: The organization's Employer Identification Number (EIN), assigned by the IRS. + org:us:uei: + type: object + properties: + registry: + type: object + properties: + code: + type: string + enum: + - org:us:uei + description: Canonical CommonGrants registry code, `::` (e.g. `org:us:ein`). + url: + type: string + format: uri + description: Link to the catalog entry for this registry. + description: Registry-level facts shared by every record in this registry. + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.samUEI' + description: |- + The primary identifier string, when the registry has a single canonical value. + + May be omitted for registries with no natural primary; consumers should read + `allIds` in that case. + allIds: + type: array + items: + type: object + properties: + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.samUEI' + description: The identifier string. + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.IdentifierStatus' + description: Whether the identifier is currently valid or retired. + required: + - id + - status + description: Every known identifier for this record in this registry, including archived values. + description: The organization's Unique Entity Identifier (UEI) from SAM.gov. + org:xi:duns: + type: object + properties: + registry: + type: object + properties: + code: + type: string + enum: + - org:xi:duns + description: Canonical CommonGrants registry code, `::` (e.g. `org:us:ein`). + url: + type: string + format: uri + description: Link to the catalog entry for this registry. + description: Registry-level facts shared by every record in this registry. + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.duns' + description: |- + The primary identifier string, when the registry has a single canonical value. + + May be omitted for registries with no natural primary; consumers should read + `allIds` in that case. + allIds: + type: array + items: + type: object + properties: + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.duns' + description: The identifier string. + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.IdentifierStatus' + description: Whether the identifier is currently valid or retired. + required: + - id + - status + description: Every known identifier for this record in this registry, including archived values. + description: The organization's Data Universal Numbering System (DUNS) number. + systemId: + type: object + properties: + registry: + type: object + properties: + code: + type: string + description: Canonical CommonGrants registry code, `::` (e.g. `org:us:ein`). + url: + type: string + format: uri + description: Link to the catalog entry for this registry. + description: Registry-level facts shared by every record in this registry. + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.uuid' + description: |- + The primary identifier string, when the registry has a single canonical value. + + May be omitted for registries with no natural primary; consumers should read + `allIds` in that case. + allIds: + type: array + items: + type: object + properties: + id: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.uuid' + description: The identifier string. + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.IdentifierStatus' + description: Whether the identifier is currently valid or retired. + required: + - id + - status + description: Every known identifier for this record in this registry, including archived values. + description: The hosting system's own identifier for this record. + otherIds: + type: object + additionalProperties: + type: object + properties: + registry: + type: object + properties: + code: + type: string + description: Canonical CommonGrants registry code, `::` (e.g. `org:us:ein`). + url: + type: string + format: uri + description: Link to the catalog entry for this registry. + description: Registry-level facts shared by every record in this registry. + id: + type: string + description: |- + The primary identifier string, when the registry has a single canonical value. + + May be omitted for registries with no natural primary; consumers should read + `allIds` in that case. + allIds: + type: array + items: + type: object + properties: + id: + type: string + description: The identifier string. + status: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.IdentifierStatus' + description: Whether the identifier is currently valid or retired. + required: + - id + - status + description: Every known identifier for this record in this registry, including archived values. + description: |- + Additional identifiers keyed by their registry code, for registries the + protocol does not define as a base identifier on the model. + description: 'Identifiers associated with the other organization, keyed by registry code. Ignored if supplied: the receiver fills them in from its own record.' + description: |- + A writable reference to a relationship's other organization. + + Unlike `Models.OrgRef`, whose `id` is read-only, `id` is writable here so a + patch can name the other organization, and the rest is optional so it can + be named by `id` alone. The receiver identifies the target by `id` and + rejects an `id` it doesn't recognize. It ignores a supplied `name` and + `identifiers` and fills both in from its own record on reads and revision + snapshots. They stay accepted, rather than read-only, so a writer can + resend entries copied from a read: read-only members would be dropped + from this closed schema, which would then reject them. Schema validation + checks only this shape; it does not look up or fill in the target. + CommonGrants.Patch.OrgPatchPCSOrgTypeOrCreate: + type: object + properties: + class: + type: string + enum: + - Organization types + description: The PCS term for the organization type. + term: + type: string + description: The plain language PCS term. + code: + type: string + pattern: ^[A-Z]{2}[0-9]{6}$ + description: The code for this PCS term. + example: UC000000 + description: + type: string + nullable: true + description: Description of the PCS term + description: |- + A Philanthropy Classification System (PCS) term for organization types. + + See https://taxonomy.candid.org/organization-type for more information. + CommonGrants.Patch.OrgPatchPhoneCollectionOrCreate: + type: object + properties: + primary: + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.OrgPatchPhoneOrCreate' + description: The person's primary phone number. + fax: + type: object + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.OrgPatchPhoneOrCreate' + nullable: true + description: The person's fax number, if applicable. + otherPhones: + type: object + additionalProperties: + type: object + allOf: + - $ref: '#/components/schemas/CommonGrants.Fields.OrgPatchPhoneOrCreate' + nullable: true + nullable: true + description: Additional phone numbers not covered by the standard fields. + description: A collection of phone numbers for a person. + CommonGrants.Responses.Accepted: + type: object + required: + - data + properties: + data: + description: Response data + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A 202 response with data + CommonGrants.Responses.ApplicationSubmissionError: + type: object + required: + - status + properties: + status: + type: number + enum: + - 400 + example: 400 + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Error' + description: A failure to submit an application due to validation errors + example: + status: 400 + message: Application submission failed due to validation errors + errors: + - field: formA.name + message: Name is required + CommonGrants.Responses.Created: + type: object + required: + - data + properties: + data: + description: Response data + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A 201 response with data + CommonGrants.Responses.Error: + type: object + required: + - status + - message + - errors + properties: + status: + type: integer + format: int32 + example: 400 + message: + type: string + description: Human-readable error message + example: Error + errors: + type: array + items: {} + description: List of errors + description: A non-2xx response schema + CommonGrants.Responses.Filtered: + type: object + required: + - items + - paginationInfo + - sortInfo + - filterInfo + properties: + items: + type: array + items: {} + description: Items from the current page + paginationInfo: + allOf: + - $ref: '#/components/schemas/CommonGrants.Pagination.PaginatedResultsInfo' + description: Details about the paginated results + sortInfo: + allOf: + - $ref: '#/components/schemas/CommonGrants.Sorting.SortedResultsInfo' + description: The sort order of the items + filterInfo: + type: object + properties: + filters: {} + errors: + type: array + items: + type: string + description: Non-fatal errors that occurred during filtering + required: + - filters + description: The filters applied to the response items + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A paginated list of items with a filter + CommonGrants.Responses.Ok: + type: object + required: + - data + properties: + data: + description: Response data + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A 200 response with data + CommonGrants.Responses.Paginated: + type: object + required: + - items + - paginationInfo + properties: + items: + type: array + items: {} + description: Items from the current page + paginationInfo: + allOf: + - $ref: '#/components/schemas/CommonGrants.Pagination.PaginatedResultsInfo' + description: Details about the paginated results + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A 200 response with a paginated list of items + CommonGrants.Responses.Sorted: + type: object + required: + - items + - paginationInfo + - sortInfo + properties: + items: + type: array + items: {} + description: Items from the current page + paginationInfo: + allOf: + - $ref: '#/components/schemas/CommonGrants.Pagination.PaginatedResultsInfo' + description: Details about the paginated results + sortInfo: + allOf: + - $ref: '#/components/schemas/CommonGrants.Sorting.SortedResultsInfo' + description: The sort order of the items + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A paginated list of items with a sort order + CommonGrants.Responses.Success: + type: object + required: + - status + - message + properties: + status: + type: integer + format: int32 + example: 200 + message: + type: string + example: Success + CommonGrants.Sorting.SortBodyParams: + type: object + required: + - sortBy + properties: + sortBy: + description: The field to sort by + example: lastModifiedAt + customSortBy: + type: string + description: Implementation-defined sort key + example: customField + sortOrder: + allOf: + - $ref: '#/components/schemas/CommonGrants.Sorting.SortOrder' + description: The order to sort by + example: asc + description: Sorting parameters included in the request body + CommonGrants.Sorting.SortOrder: + type: string + enum: + - asc + - desc + CommonGrants.Sorting.SortedResultsInfo: + type: object + required: + - sortBy + - sortOrder + properties: + sortBy: + type: string + description: The field results are sorted by, or "custom" if an implementation-defined sort key is used + example: lastModifiedAt + customSortBy: + type: string + description: Implementation-defined sort key used to sort the results, if applicable + example: customField + sortOrder: + allOf: + - $ref: '#/components/schemas/CommonGrants.Sorting.SortOrder' + description: The order in which the results are sorted, e.g. ascending or descending + example: asc + errors: + type: array + items: + type: string + description: Non-fatal errors that occurred during sorting + description: Information about the sort order of the items returned + CommonGrants.Types.calendarYear: + type: string + pattern: ^[0-9]{4}$ + description: A calendar year + example: '2025' + CommonGrants.Types.decimalString: + type: string + pattern: ^-?[0-9]+\.?[0-9]*$ + description: A decimal number (with variable scale) encoded as a string, to avoid floating point issues + example: '-100.5' + CommonGrants.Types.duns: + type: string + pattern: ^[0-9]{9}$ + description: A Data Universal Numbering System (DUNS) number, normalized to nine digits + example: '123456789' + CommonGrants.Types.email: + type: string + format: email + description: An email address + example: test@example.com + CommonGrants.Types.employerTaxId: + type: string + pattern: ^[0-9]{9}$ + description: An Employer Identification Number (EIN) issued by the IRS, normalized to nine digits + example: '123456789' + CommonGrants.Types.isoDate: + type: string + format: date + description: A date on a calendar in ISO 8601 format YYYY-MM-DD + example: '2025-01-01' + CommonGrants.Types.isoTime: + type: string + format: time + description: A time on a clock, without a timezone, in ISO 8601 format HH:mm:ss + example: '17:00:00' + CommonGrants.Types.nonEmptyString: + type: string + minLength: 1 + description: A string with at least one character + example: Example + CommonGrants.Types.protocolVersion: + type: string + pattern: ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ + description: |- + A published CommonGrants protocol version, such as `0.6.0` + + A full `MAJOR.MINOR.PATCH` version with no `v` prefix and no leading zeros. + example: 0.6.0 + CommonGrants.Types.samUEI: + type: string + pattern: ^[A-HJ-NP-Z0-9]{12}$ + description: A Unique Entity Identifier (UEI) issued by SAM.gov + example: AB0123456789 + CommonGrants.Types.uuid: + type: string + format: uuid + description: A universally unique identifier + example: 30a12e5e-5940-4c08-921c-17a8960fcf4b + securitySchemes: + OAuth2Auth: + type: oauth2 + flows: + clientCredentials: + tokenUrl: https://auth.example.com/oauth/token + scopes: + org:read: '' + org:write: '' + org.changes:write: '' + org.changes:read: '' + authorizationCode: + authorizationUrl: https://auth.example.com/authorize + tokenUrl: https://auth.example.com/oauth/token + scopes: + org:read: '' + org:write: '' + org.changes:write: '' + org.changes:read: '' diff --git a/website/public/schemas/yaml/protocolVersion.yaml b/website/public/schemas/yaml/protocolVersion.yaml new file mode 100644 index 000000000..ed837e13c --- /dev/null +++ b/website/public/schemas/yaml/protocolVersion.yaml @@ -0,0 +1,10 @@ +$schema: https://json-schema.org/draft/2020-12/schema +$id: protocolVersion.yaml +type: string +examples: + - 0.6.0 +pattern: ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ +description: |- + A published CommonGrants protocol version, such as `0.6.0` + + A full `MAJOR.MINOR.PATCH` version with no `v` prefix and no leading zeros. diff --git a/website/src/lib/mock/data/fixtures.ts b/website/src/lib/mock/data/fixtures.ts index ed7a17f9f..abc5f1001 100644 --- a/website/src/lib/mock/data/fixtures.ts +++ b/website/src/lib/mock/data/fixtures.ts @@ -33,6 +33,8 @@ import { orgRefCollection, HRSA_ORG_ID, NSF_ORG_ID } from "./organizations"; * identically to v0.3.0. v0.5.0 adds `OppRef.identifiers`, which * `shapeOpportunityForVersion` strips for every earlier version, and replaces * each nested competition's `opportunityId` with an `opportunity` reference. + * v0.6.0 adds only the version negotiation headers, so it shapes identically + * to v0.5.0. */ export const SUPPORTED_VERSIONS = [ "0.1.0", @@ -40,6 +42,7 @@ export const SUPPORTED_VERSIONS = [ "0.3.0", "0.4.0", "0.5.0", + "0.6.0", ] as const; /** A protocol version the opportunity handlers can shape responses for. */ From 31897d65de01a76b44ca2b63e4273f44440703b5 Mon Sep 17 00:00:00 2001 From: Karina Munoz Gonzalez Date: Thu, 19 Nov 2026 15:00:14 -0600 Subject: [PATCH 2/5] feat(core): add the version errors to every route (#1414) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### Summary - Fixes #1388 - Time to review: 20 minutes Adds the ADR 0032 version errors (`version.malformed`, `version.conflict`, `version.unsupported`, `version.retired`) to the core library and to every protocol route, in 0.6.0 only. SDK support, a docs page for the errors, and the discovery route (#1399) are out of scope. ### Changes proposed - `lib/core/lib/core/responses/version-errors.tsp` (new): - `VersionErrorScope` enum and a `VersionErrorDetail` base with `field`, `message`, `supported`, `defaultVersion` and optional `discovery` - One detail model per code: `requested` is omitted on conflict, `scope` is required on unsupported and retired, `sunset` is required on retired - Detail models accept unknown fields (`...Record`), like the discovery models in #1399: a version error is returned when negotiation fails, so clients must tolerate fields added later - Four error bodies extending `Error` (400: malformed, conflict; 406: unsupported, retired), each with an ADR-based example; `errors` requires at least one entry - Status-code aliases (`Http.BadRequestResponse`, `Http.Response<406>`), so status codes stay out of the JSON Schemas; version errors carry no version headers, per the ADR - `WithVersionErrors` union: keeps a route's responses and adds the errors as two `@added(v0_6)` variants, one per status code - A generic `BadRequest` alias joins the 400 variant, with an optional `CG-Version-Served` and the lifecycle headers - `lib/core/lib/core/routes/*.tsp`: every protocol route's return type is wrapped in `Responses.WithVersionErrors<...>` (22 operations) - Doc examples: - `lib/core/lib/core/responses/index.tsp`: example of a declared protocol route (`listOpportunities`) using the wrapper - `lib/core/lib/core/headers.tsp`: the existing custom route example now uses the wrapper - Generated: - `website/public/openapi/openapi.0.6.0.yaml`: 400 and 406 on every `/common-grants/` operation, plus the new schemas - `website/public/schemas/yaml/Version*.yaml`: 10 new JSON Schemas ### Context for reviewers Look most closely at `WithVersionErrors` in `version-errors.tsp`. Its docs are on the error variants, not the union, because `@typespec/http` copies a union's doc onto every response it flattens (it was overwriting the 200 and 404 descriptions, including in 0.2.0 to 0.5.0). Every route's 0.6.0 400 also accepts an ordinary `Error` with an optional `CG-Version-Served` header, so a body that fails validation in the requested version (ADR 0032 scenarios) and `submitApplication`'s submission error still match the documented 400. To verify: 1. Regenerate the outputs: `pnpm --filter website run typespec`. Then `git status --short website/public` should print nothing. 2. Check that only the 0.6.0 document changed: `git diff --stat origin/CORE-v0.6.0 -- website/public/openapi/` 3. Open `website/public/openapi/openapi.0.6.0.yaml` and find `/common-grants/opportunities/{oppId}`. It should list `400` (malformed, conflict, or a generic `Error` with an optional `CG-Version-Served`) and `406` (unsupported or retired, with no headers). 4. Run the core checks: `pnpm --filter @common-grants/core run checks` ### Additional information Preview deploy: https://pr-1414-common-grants.agile6.workers.dev. The 0.6.0 document is at `/openapi/openapi.0.6.0.yaml`; it lists `VersionUnsupportedError` on all 21 operations. Only the 0.6.0 document changes. The 0.1.0 to 0.5.0 documents are byte-identical: ``` $ git diff --stat origin/CORE-v0.6.0 -- website/public/openapi/ website/public/openapi/openapi.0.6.0.yaml | 1298 ++++++++++++++++++++++++++++- 1 file changed, 1281 insertions(+), 17 deletions(-) ``` A script over the 0.6.0 document confirmed that every `/common-grants/` operation lists 400 and 406, references all four error schemas, and carries no version headers on them: ``` operations checked: 21 | missing version errors: 0 ``` (`Competitions.apply` is wrapped too but isn't exposed in `lib/api.tsp`, same as on `main`.) `GET /common-grants/opportunities/{oppId}` in 0.6.0: ```yaml '400': description: The `CG-Version` value is malformed or was sent more than once content: application/json: schema: anyOf: - $ref: '#/components/schemas/CommonGrants.Responses.VersionMalformedError' - $ref: '#/components/schemas/CommonGrants.Responses.VersionConflictError' '406': description: The requested version isn't served by this server or this route content: application/json: schema: anyOf: - $ref: '#/components/schemas/CommonGrants.Responses.VersionUnsupportedError' - $ref: '#/components/schemas/CommonGrants.Responses.VersionRetiredError' ``` An implementer who reuses a route op gets the errors only when targeting 0.6.0. For a test service with `read is Routes.Opportunities.read`: ``` v0.5 statuses: 200 404 v0.6 statuses: 200 400 404 406 ``` Core checks: ``` All matched files use Prettier code style! ✔ 58 formatted All 25 utcDateTime.fromISO examples have a UTC offset. ``` --- lib/core/lib/core/headers.tsp | 2 +- lib/core/lib/core/responses/index.tsp | 12 + .../lib/core/responses/version-errors.tsp | 242 +++ lib/core/lib/core/routes/applications.tsp | 17 +- lib/core/lib/core/routes/awards.tsp | 6 +- lib/core/lib/core/routes/competitions.tsp | 8 +- lib/core/lib/core/routes/form-responses.tsp | 4 +- lib/core/lib/core/routes/forms.tsp | 4 +- lib/core/lib/core/routes/opportunities.tsp | 6 +- lib/core/lib/core/routes/orgs.tsp | 25 +- website/public/openapi/openapi.0.6.0.yaml | 1298 ++++++++++++++++- .../schemas/yaml/VersionConflictDetail.yaml | 14 + .../schemas/yaml/VersionConflictError.yaml | 34 + .../schemas/yaml/VersionErrorDetail.yaml | 33 + .../schemas/yaml/VersionErrorScope.yaml | 7 + .../schemas/yaml/VersionMalformedDetail.yaml | 18 + .../schemas/yaml/VersionMalformedError.yaml | 35 + .../schemas/yaml/VersionRetiredDetail.yaml | 27 + .../schemas/yaml/VersionRetiredError.yaml | 38 + .../yaml/VersionUnsupportedDetail.yaml | 22 + .../schemas/yaml/VersionUnsupportedError.yaml | 36 + 21 files changed, 1840 insertions(+), 48 deletions(-) create mode 100644 lib/core/lib/core/responses/version-errors.tsp create mode 100644 website/public/schemas/yaml/VersionConflictDetail.yaml create mode 100644 website/public/schemas/yaml/VersionConflictError.yaml create mode 100644 website/public/schemas/yaml/VersionErrorDetail.yaml create mode 100644 website/public/schemas/yaml/VersionErrorScope.yaml create mode 100644 website/public/schemas/yaml/VersionMalformedDetail.yaml create mode 100644 website/public/schemas/yaml/VersionMalformedError.yaml create mode 100644 website/public/schemas/yaml/VersionRetiredDetail.yaml create mode 100644 website/public/schemas/yaml/VersionRetiredError.yaml create mode 100644 website/public/schemas/yaml/VersionUnsupportedDetail.yaml create mode 100644 website/public/schemas/yaml/VersionUnsupportedError.yaml diff --git a/lib/core/lib/core/headers.tsp b/lib/core/lib/core/headers.tsp index b2d63c4b7..5467e9558 100644 --- a/lib/core/lib/core/headers.tsp +++ b/lib/core/lib/core/headers.tsp @@ -23,7 +23,7 @@ import "./types.tsp"; * op listOpportunities( * ...Pagination.PaginatedQueryParams, * ...Headers.VersionRequest, - * ): Responses.PaginatedT; + * ): Responses.WithVersionErrors>; * ``` */ namespace CommonGrants.Headers; diff --git a/lib/core/lib/core/responses/index.tsp b/lib/core/lib/core/responses/index.tsp index 1648d5c0b..6aae3dc8f 100644 --- a/lib/core/lib/core/responses/index.tsp +++ b/lib/core/lib/core/responses/index.tsp @@ -2,6 +2,7 @@ import "@typespec/http"; import "./error.tsp"; import "./success.tsp"; +import "./version-errors.tsp"; using TypeSpec.JsonSchema; @@ -22,6 +23,17 @@ using TypeSpec.JsonSchema; * op getPets(): Responses.OkT | Responses.Unauthorized; * } * ``` + * + * @example How to add the version errors to a protocol route + * + * ```typespec + * @route("/common-grants/opportunities") + * @get + * op listOpportunities( + * ...Pagination.PaginatedQueryParams, + * ...Headers.VersionRequest, + * ): Responses.WithVersionErrors>; + * ``` */ @jsonSchema namespace CommonGrants.Responses; diff --git a/lib/core/lib/core/responses/version-errors.tsp b/lib/core/lib/core/responses/version-errors.tsp new file mode 100644 index 000000000..0c41f343f --- /dev/null +++ b/lib/core/lib/core/responses/version-errors.tsp @@ -0,0 +1,242 @@ +import "@typespec/http"; +import "../types.tsp"; +import "./error.tsp"; + +namespace CommonGrants.Responses; + +// ############################################################################ +// Version error details +// ############################################################################ + +/** Whether a version is unavailable on the whole server or only on the route called */ +@Versioning.added(CommonGrants.Versions.v0_6) +enum VersionErrorScope { + /** The server doesn't serve the version on any route */ + deployment, + + /** The server serves the version, but not on this route */ + operation, +} + +/** Details shared by every version error, describing the route that was called */ +@Versioning.added(CommonGrants.Versions.v0_6) +model VersionErrorDetail { + /** The request header the error is about */ + field: "CG-Version"; + + /** Human-readable description of the problem */ + message: string; + + /** The versions this route serves */ + @minItems(1) + supported: Types.protocolVersion[]; + + /** The version this route serves when a request doesn't name one */ + defaultVersion: Types.protocolVersion; + + /** The server's version discovery URL + * + * Omitted by servers that serve one version and don't publish discovery. + */ + discovery?: url; +} + +/** The `CG-Version` value isn't a full `MAJOR.MINOR.PATCH` version */ +@Versioning.added(CommonGrants.Versions.v0_6) +model VersionMalformedDetail extends VersionErrorDetail { + /** Stable error code that clients branch on */ + code: "version.malformed"; + + /** The value received, as sent */ + requested: string; + + // Version errors are returned outside version selection, so new fields must be tolerated + ...Record; +} + +/** The request sent more than one `CG-Version` value */ +@Versioning.added(CommonGrants.Versions.v0_6) +model VersionConflictDetail extends VersionErrorDetail { + /** Stable error code that clients branch on */ + code: "version.conflict"; + + ...Record; +} + +/** The requested version isn't served by this server or this route */ +@Versioning.added(CommonGrants.Versions.v0_6) +model VersionUnsupportedDetail extends VersionErrorDetail { + /** Stable error code that clients branch on */ + code: "version.unsupported"; + + /** The version requested */ + requested: Types.protocolVersion; + + /** Whether the server or only this route doesn't serve the version */ + scope: VersionErrorScope; + + ...Record; +} + +/** The requested version was retired from this server or this route */ +@Versioning.added(CommonGrants.Versions.v0_6) +model VersionRetiredDetail extends VersionErrorDetail { + /** Stable error code that clients branch on */ + code: "version.retired"; + + /** The version requested */ + requested: Types.protocolVersion; + + /** Whether the server or only this route doesn't serve the version */ + scope: VersionErrorScope; + + /** When the version stopped being served */ + sunset: utcDateTime; + + ...Record; +} + +// ############################################################################ +// Version error responses +// ############################################################################ + +@example(#{ + status: 400, + message: "The CG-Version header is not a valid CommonGrants version", + errors: #[ + #{ + field: "CG-Version", + code: "version.malformed", + message: "Version 0.5 is not a full MAJOR.MINOR.PATCH version", + requested: "0.5", + supported: #["0.5.0", "0.6.0"], + defaultVersion: "0.5.0", + discovery: "https://grants.example.org/common-grants/versions", + } + ], +}) +@error +@doc("A `CG-Version` header that isn't a full `MAJOR.MINOR.PATCH` version") +@Versioning.added(CommonGrants.Versions.v0_6) +model VersionMalformedError extends Error { + @example(400) + status: 400; + + @minItems(1) + errors: VersionMalformedDetail[]; +} + +@example(#{ + status: 400, + message: "The request sent more than one CG-Version value", + errors: #[ + #{ + field: "CG-Version", + code: "version.conflict", + message: "Received CG-Version values 0.5.0 and 0.6.0", + supported: #["0.5.0", "0.6.0"], + defaultVersion: "0.5.0", + discovery: "https://grants.example.org/common-grants/versions", + } + ], +}) +@error +@doc("A request that sent more than one `CG-Version` value, even the same value twice") +@Versioning.added(CommonGrants.Versions.v0_6) +model VersionConflictError extends Error { + @example(400) + status: 400; + + @minItems(1) + errors: VersionConflictDetail[]; +} + +@example(#{ + status: 406, + message: "The requested CommonGrants version is not available for this route", + errors: #[ + #{ + field: "CG-Version", + code: "version.unsupported", + message: "Version 0.4.0 is not served by GET /common-grants/forms. Supported versions: 0.5.0, 0.6.0", + requested: "0.4.0", + supported: #["0.5.0", "0.6.0"], + scope: VersionErrorScope.operation, + defaultVersion: "0.5.0", + discovery: "https://grants.example.org/common-grants/versions", + } + ], +}) +@error +@doc("A requested version that this server or route doesn't serve") +@Versioning.added(CommonGrants.Versions.v0_6) +model VersionUnsupportedError extends Error { + @example(406) + status: 406; + + @minItems(1) + errors: VersionUnsupportedDetail[]; +} + +@example(#{ + status: 406, + message: "The requested CommonGrants version has been retired", + errors: #[ + #{ + field: "CG-Version", + code: "version.retired", + message: "Version 0.3.0 was retired on 2027-06-01. Supported versions: 0.4.0, 0.5.0, 0.6.0", + requested: "0.3.0", + supported: #["0.4.0", "0.5.0", "0.6.0"], + scope: VersionErrorScope.deployment, + defaultVersion: "0.4.0", + discovery: "https://grants.example.org/common-grants/versions", + sunset: utcDateTime.fromISO("2027-06-01T00:00:00Z"), + } + ], +}) +@error +@doc("A requested version that was retired from this server or route") +@Versioning.added(CommonGrants.Versions.v0_6) +model VersionRetiredError extends Error { + @example(406) + status: 406; + + @minItems(1) + errors: VersionRetiredDetail[]; +} + +// Status codes live on these aliases, not the models, so they stay out of the +// JSON Schemas. Version errors carry no version response headers (ADR 0032). +alias VersionMalformed = VersionMalformedError & Http.BadRequestResponse; +alias VersionConflict = VersionConflictError & Http.BadRequestResponse; +alias VersionUnsupported = VersionUnsupportedError & Http.Response<406>; +alias VersionRetired = VersionRetiredError & Http.Response<406>; + +// Any other 400, such as a body that fails validation in the requested version. +// The served version is optional because version errors share this status. +alias BadRequest = Error & + Http.BadRequestResponse & { + /** The full protocol version this response was served in, such as `0.5.1` + * + * Sent on every 400 except the version errors. + */ + @Http.header("CG-Version-Served") + cgVersionServed?: Types.protocolVersion; + + ...Headers.VersionLifecycle; + }; + +// Adds the version errors to a route's responses from protocol version 0.6.0. +// Docs go on the variants: a union-level doc would replace every response description. +union WithVersionErrors { + response: R, + + /** The request is invalid, or its `CG-Version` value is malformed or was sent more than once */ + @Versioning.added(CommonGrants.Versions.v0_6) + badRequest: VersionMalformed | VersionConflict | BadRequest, + + /** The requested version isn't served by this server or this route */ + @Versioning.added(CommonGrants.Versions.v0_6) + notAcceptable: VersionUnsupported | VersionRetired, +} diff --git a/lib/core/lib/core/routes/applications.tsp b/lib/core/lib/core/routes/applications.tsp index 3204123c3..4a9a2bbdd 100644 --- a/lib/core/lib/core/routes/applications.tsp +++ b/lib/core/lib/core/routes/applications.tsp @@ -35,7 +35,9 @@ interface Applications { title: string, ...Headers.VersionRequest, - ): Responses.CreatedT | Responses.Unauthorized; + ): Responses.WithVersionErrors< + | Responses.CreatedT + | Responses.Unauthorized>; // ############################### // Get an application @@ -50,10 +52,10 @@ interface Applications { @path appId: Types.uuid, ...Headers.VersionRequest, - ): + ): Responses.WithVersionErrors< | Responses.OkT | Responses.NotFound - | Responses.Unauthorized; + | Responses.Unauthorized>; // ############################### // Submit an application @@ -68,11 +70,11 @@ interface Applications { @path appId: Types.uuid, ...Headers.VersionRequest, - ): + ): Responses.WithVersionErrors< | Responses.OkT | ApplicationSubmissionErrorResponse | Responses.NotFound - | Responses.Unauthorized; + | Responses.Unauthorized>; // ############################### // Search applications @@ -90,7 +92,10 @@ interface Applications { @query sorting: Models.AppSorting, ...Headers.VersionRequest, - ): Responses.FilteredT; + ): Responses.WithVersionErrors>; } // Lives here, not in `Responses`, so the headers stay out of the JSON Schemas diff --git a/lib/core/lib/core/routes/awards.tsp b/lib/core/lib/core/routes/awards.tsp index 6eb4b9e04..b90c215c9 100644 --- a/lib/core/lib/core/routes/awards.tsp +++ b/lib/core/lib/core/routes/awards.tsp @@ -52,7 +52,7 @@ interface Awards { list( ...Pagination.PaginatedQueryParams, ...Headers.VersionRequest, - ): Responses.PaginatedT; + ): Responses.WithVersionErrors>; // ############################## // View an award @@ -72,7 +72,7 @@ interface Awards { awdId: Types.uuid, ...Headers.VersionRequest, - ): Responses.OkT | Responses.NotFound; + ): Responses.WithVersionErrors | Responses.NotFound>; // ############################### // Search awards @@ -106,5 +106,5 @@ interface Awards { pagination?: Pagination.PaginatedBodyParams, ...Headers.VersionRequest, - ): Responses.FilteredT; + ): Responses.WithVersionErrors>; } diff --git a/lib/core/lib/core/routes/competitions.tsp b/lib/core/lib/core/routes/competitions.tsp index 53cc4396f..442ad94fd 100644 --- a/lib/core/lib/core/routes/competitions.tsp +++ b/lib/core/lib/core/routes/competitions.tsp @@ -32,7 +32,9 @@ interface Competitions { @path compId: Types.uuid, ...Headers.VersionRequest, - ): Responses.OkT | Responses.NotFound; + ): Responses.WithVersionErrors< + | Responses.OkT + | Responses.NotFound>; // ############################### // Apply to a competition @@ -50,8 +52,8 @@ interface Competitions { @body application: Models.ApplicationBase, ...Headers.VersionRequest, - ): + ): Responses.WithVersionErrors< | Responses.CreatedT | Responses.NotFound - | Responses.Unauthorized; + | Responses.Unauthorized>; } diff --git a/lib/core/lib/core/routes/form-responses.tsp b/lib/core/lib/core/routes/form-responses.tsp index 69fe0a0b4..fe0db0e51 100644 --- a/lib/core/lib/core/routes/form-responses.tsp +++ b/lib/core/lib/core/routes/form-responses.tsp @@ -34,7 +34,7 @@ interface FormResponses { @body response: Record, ...Headers.VersionRequest, - ): Responses.OkT; + ): Responses.WithVersionErrors>; // ############################### // Get form response @@ -52,5 +52,5 @@ interface FormResponses { @path formId: Types.uuid, ...Headers.VersionRequest, - ): Responses.OkT; + ): Responses.WithVersionErrors>; } diff --git a/lib/core/lib/core/routes/forms.tsp b/lib/core/lib/core/routes/forms.tsp index ecae469f5..4e7a0ea09 100644 --- a/lib/core/lib/core/routes/forms.tsp +++ b/lib/core/lib/core/routes/forms.tsp @@ -25,7 +25,7 @@ interface Forms { list( ...Pagination.PaginatedQueryParams, ...Headers.VersionRequest, - ): Responses.PaginatedT; + ): Responses.WithVersionErrors>; // ############################### // View form details @@ -39,5 +39,5 @@ interface Forms { @path formId: Types.uuid, ...Headers.VersionRequest, - ): Responses.OkT; + ): Responses.WithVersionErrors>; } diff --git a/lib/core/lib/core/routes/opportunities.tsp b/lib/core/lib/core/routes/opportunities.tsp index a114657a9..a934312d3 100644 --- a/lib/core/lib/core/routes/opportunities.tsp +++ b/lib/core/lib/core/routes/opportunities.tsp @@ -51,7 +51,7 @@ interface Opportunities { list( ...Pagination.PaginatedQueryParams, ...Headers.VersionRequest, - ): Responses.PaginatedT; + ): Responses.WithVersionErrors>; // ############################## // View an opportunity (v0.1.0) @@ -77,7 +77,7 @@ interface Opportunities { oppId: Types.uuid, ...Headers.VersionRequest, - ): Responses.OkT | Responses.NotFound; + ): Responses.WithVersionErrors | Responses.NotFound>; // ############################### // Search opportunities @@ -111,5 +111,5 @@ interface Opportunities { pagination?: Pagination.PaginatedBodyParams, ...Headers.VersionRequest, - ): Responses.FilteredT; + ): Responses.WithVersionErrors>; } diff --git a/lib/core/lib/core/routes/orgs.tsp b/lib/core/lib/core/routes/orgs.tsp index 6a2d823f3..e83263845 100644 --- a/lib/core/lib/core/routes/orgs.tsp +++ b/lib/core/lib/core/routes/orgs.tsp @@ -63,7 +63,10 @@ interface Organizations { @query id?: string, ...Headers.VersionRequest, - ): Responses.PaginatedT | Responses.Unauthorized | Responses.Forbidden; + ): Responses.WithVersionErrors< + | Responses.PaginatedT + | Responses.Unauthorized + | Responses.Forbidden>; // ############################## // View an organization @@ -89,11 +92,11 @@ interface Organizations { @query at?: utcDateTime, ...Headers.VersionRequest, - ): + ): Responses.WithVersionErrors< | Responses.OkT | Responses.NotFound | Responses.Unauthorized - | Responses.Forbidden; + | Responses.Forbidden>; // ############################### // Update an organization @@ -118,11 +121,11 @@ interface Organizations { patch: Models.OrgPatchData, ...Headers.VersionRequest, - ): + ): Responses.WithVersionErrors< | Responses.OkT | Responses.NotFound | Responses.Unauthorized - | Responses.Forbidden; + | Responses.Forbidden>; // ############################### // Submit a change @@ -149,11 +152,11 @@ interface Organizations { patch: Models.OrgPatchData, ...Headers.VersionRequest, - ): + ): Responses.WithVersionErrors< | Responses.AcceptedT | Responses.NotFound | Responses.Unauthorized - | Responses.Forbidden; + | Responses.Forbidden>; // ############################### // List changes @@ -177,11 +180,11 @@ interface Organizations { ...Pagination.PaginatedQueryParams, ...Headers.VersionRequest, - ): + ): Responses.WithVersionErrors< | Responses.PaginatedT | Responses.NotFound | Responses.Unauthorized - | Responses.Forbidden; + | Responses.Forbidden>; // ############################### // View a change @@ -208,9 +211,9 @@ interface Organizations { changeId: Types.uuid, ...Headers.VersionRequest, - ): + ): Responses.WithVersionErrors< | Responses.OkT | Responses.NotFound | Responses.Unauthorized - | Responses.Forbidden; + | Responses.Forbidden>; } diff --git a/website/public/openapi/openapi.0.6.0.yaml b/website/public/openapi/openapi.0.6.0.yaml index 3cbbeb359..3adb2e665 100644 --- a/website/public/openapi/openapi.0.6.0.yaml +++ b/website/public/openapi/openapi.0.6.0.yaml @@ -123,6 +123,54 @@ paths: allOf: - $ref: '#/components/schemas/CommonGrants.Responses.Success' description: A paginated list of typed items with a typed filter + '400': + description: The request is invalid, or its `CG-Version` value is malformed or was sent more than once + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Sent on every 400 except the version errors. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionMalformedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionConflictError' + - $ref: '#/components/schemas/CommonGrants.Responses.Error' + '406': + description: The requested version isn't served by this server or this route + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionUnsupportedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionRetiredError' tags: - Applications - experimental @@ -182,6 +230,46 @@ paths: allOf: - $ref: '#/components/schemas/CommonGrants.Responses.Success' description: A 201 response with typed data + '400': + description: The request is invalid, or its `CG-Version` value is malformed or was sent more than once + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Sent on every 400 except the version errors. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionMalformedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionConflictError' + - $ref: '#/components/schemas/CommonGrants.Responses.Error' '401': description: Access is unauthorized. headers: @@ -219,6 +307,14 @@ paths: application/json: schema: $ref: '#/components/schemas/CommonGrants.Responses.Error' + '406': + description: The requested version isn't served by this server or this route + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionUnsupportedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionRetiredError' tags: - Applications - experimental @@ -304,6 +400,46 @@ paths: allOf: - $ref: '#/components/schemas/CommonGrants.Responses.Success' description: A 200 response with typed data + '400': + description: The request is invalid, or its `CG-Version` value is malformed or was sent more than once + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Sent on every 400 except the version errors. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionMalformedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionConflictError' + - $ref: '#/components/schemas/CommonGrants.Responses.Error' '401': description: Access is unauthorized. headers: @@ -378,6 +514,14 @@ paths: application/json: schema: $ref: '#/components/schemas/CommonGrants.Responses.Error' + '406': + description: The requested version isn't served by this server or this route + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionUnsupportedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionRetiredError' tags: - Applications - experimental @@ -448,6 +592,54 @@ paths: allOf: - $ref: '#/components/schemas/CommonGrants.Responses.Success' description: A 200 response with typed data + '400': + description: The request is invalid, or its `CG-Version` value is malformed or was sent more than once + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Sent on every 400 except the version errors. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionMalformedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionConflictError' + - $ref: '#/components/schemas/CommonGrants.Responses.Error' + '406': + description: The requested version isn't served by this server or this route + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionUnsupportedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionRetiredError' tags: - Applications - experimental @@ -525,6 +717,54 @@ paths: allOf: - $ref: '#/components/schemas/CommonGrants.Responses.Success' description: A 200 response with typed data + '400': + description: The request is invalid, or its `CG-Version` value is malformed or was sent more than once + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Sent on every 400 except the version errors. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionMalformedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionConflictError' + - $ref: '#/components/schemas/CommonGrants.Responses.Error' + '406': + description: The requested version isn't served by this server or this route + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionUnsupportedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionRetiredError' tags: - Applications - experimental @@ -587,6 +827,46 @@ paths: allOf: - $ref: '#/components/schemas/CommonGrants.Responses.Success' description: A 200 response with typed data + '400': + description: The request is invalid, or its `CG-Version` value is malformed or was sent more than once + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Sent on every 400 except the version errors. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionMalformedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionConflictError' + - $ref: '#/components/schemas/CommonGrants.Responses.Error' '401': description: Access is unauthorized. headers: @@ -661,6 +941,14 @@ paths: application/json: schema: $ref: '#/components/schemas/CommonGrants.Responses.Error' + '406': + description: The requested version isn't served by this server or this route + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionUnsupportedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionRetiredError' default: description: An unexpected error response. headers: @@ -764,6 +1052,54 @@ paths: allOf: - $ref: '#/components/schemas/CommonGrants.Responses.Success' description: A 200 response with a paginated list of typed items + '400': + description: The request is invalid, or its `CG-Version` value is malformed or was sent more than once + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Sent on every 400 except the version errors. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionMalformedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionConflictError' + - $ref: '#/components/schemas/CommonGrants.Responses.Error' + '406': + description: The requested version isn't served by this server or this route + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionUnsupportedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionRetiredError' tags: - Awards - optional @@ -847,10 +1183,58 @@ paths: allOf: - $ref: '#/components/schemas/CommonGrants.Responses.Success' description: A paginated list of typed items with a typed filter - tags: - - Awards - - optional - requestBody: + '400': + description: The request is invalid, or its `CG-Version` value is malformed or was sent more than once + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Sent on every 400 except the version errors. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionMalformedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionConflictError' + - $ref: '#/components/schemas/CommonGrants.Responses.Error' + '406': + description: The requested version isn't served by this server or this route + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionUnsupportedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionRetiredError' + tags: + - Awards + - optional + requestBody: required: true content: application/json: @@ -938,6 +1322,46 @@ paths: allOf: - $ref: '#/components/schemas/CommonGrants.Responses.Success' description: A 200 response with typed data + '400': + description: The request is invalid, or its `CG-Version` value is malformed or was sent more than once + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Sent on every 400 except the version errors. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionMalformedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionConflictError' + - $ref: '#/components/schemas/CommonGrants.Responses.Error' '404': description: The server cannot find the requested resource. headers: @@ -975,6 +1399,14 @@ paths: application/json: schema: $ref: '#/components/schemas/CommonGrants.Responses.Error' + '406': + description: The requested version isn't served by this server or this route + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionUnsupportedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionRetiredError' tags: - Awards - optional @@ -1043,6 +1475,46 @@ paths: allOf: - $ref: '#/components/schemas/CommonGrants.Responses.Success' description: A 200 response with typed data + '400': + description: The request is invalid, or its `CG-Version` value is malformed or was sent more than once + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Sent on every 400 except the version errors. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionMalformedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionConflictError' + - $ref: '#/components/schemas/CommonGrants.Responses.Error' '404': description: The server cannot find the requested resource. headers: @@ -1080,6 +1552,14 @@ paths: application/json: schema: $ref: '#/components/schemas/CommonGrants.Responses.Error' + '406': + description: The requested version isn't served by this server or this route + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionUnsupportedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionRetiredError' tags: - Competitions - experimental @@ -1146,6 +1626,54 @@ paths: allOf: - $ref: '#/components/schemas/CommonGrants.Responses.Success' description: A 200 response with a paginated list of typed items + '400': + description: The request is invalid, or its `CG-Version` value is malformed or was sent more than once + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Sent on every 400 except the version errors. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionMalformedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionConflictError' + - $ref: '#/components/schemas/CommonGrants.Responses.Error' + '406': + description: The requested version isn't served by this server or this route + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionUnsupportedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionRetiredError' tags: - Forms - experimental @@ -1210,6 +1738,54 @@ paths: allOf: - $ref: '#/components/schemas/CommonGrants.Responses.Success' description: A 200 response with typed data + '400': + description: The request is invalid, or its `CG-Version` value is malformed or was sent more than once + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Sent on every 400 except the version errors. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionMalformedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionConflictError' + - $ref: '#/components/schemas/CommonGrants.Responses.Error' + '406': + description: The requested version isn't served by this server or this route + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionUnsupportedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionRetiredError' tags: - Forms - experimental @@ -1276,6 +1852,54 @@ paths: allOf: - $ref: '#/components/schemas/CommonGrants.Responses.Success' description: A 200 response with a paginated list of typed items + '400': + description: The request is invalid, or its `CG-Version` value is malformed or was sent more than once + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Sent on every 400 except the version errors. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionMalformedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionConflictError' + - $ref: '#/components/schemas/CommonGrants.Responses.Error' + '406': + description: The requested version isn't served by this server or this route + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionUnsupportedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionRetiredError' tags: - Opportunities - required @@ -1359,6 +1983,54 @@ paths: allOf: - $ref: '#/components/schemas/CommonGrants.Responses.Success' description: A paginated list of typed items with a typed filter + '400': + description: The request is invalid, or its `CG-Version` value is malformed or was sent more than once + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Sent on every 400 except the version errors. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionMalformedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionConflictError' + - $ref: '#/components/schemas/CommonGrants.Responses.Error' + '406': + description: The requested version isn't served by this server or this route + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionUnsupportedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionRetiredError' tags: - Opportunities - optional @@ -1450,6 +2122,46 @@ paths: allOf: - $ref: '#/components/schemas/CommonGrants.Responses.Success' description: A 200 response with typed data + '400': + description: The request is invalid, or its `CG-Version` value is malformed or was sent more than once + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Sent on every 400 except the version errors. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionMalformedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionConflictError' + - $ref: '#/components/schemas/CommonGrants.Responses.Error' '404': description: The server cannot find the requested resource. headers: @@ -1487,6 +2199,14 @@ paths: application/json: schema: $ref: '#/components/schemas/CommonGrants.Responses.Error' + '406': + description: The requested version isn't served by this server or this route + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionUnsupportedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionRetiredError' tags: - Opportunities - required @@ -1567,6 +2287,46 @@ paths: allOf: - $ref: '#/components/schemas/CommonGrants.Responses.Success' description: A 200 response with a paginated list of typed items + '400': + description: The request is invalid, or its `CG-Version` value is malformed or was sent more than once + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Sent on every 400 except the version errors. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionMalformedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionConflictError' + - $ref: '#/components/schemas/CommonGrants.Responses.Error' '401': description: Access is unauthorized. headers: @@ -1641,6 +2401,14 @@ paths: application/json: schema: $ref: '#/components/schemas/CommonGrants.Responses.Error' + '406': + description: The requested version isn't served by this server or this route + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionUnsupportedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionRetiredError' tags: - Organizations - experimental @@ -1716,6 +2484,46 @@ paths: allOf: - $ref: '#/components/schemas/CommonGrants.Responses.Success' description: A 200 response with typed data + '400': + description: The request is invalid, or its `CG-Version` value is malformed or was sent more than once + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Sent on every 400 except the version errors. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionMalformedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionConflictError' + - $ref: '#/components/schemas/CommonGrants.Responses.Error' '401': description: Access is unauthorized. headers: @@ -1827,6 +2635,14 @@ paths: application/json: schema: $ref: '#/components/schemas/CommonGrants.Responses.Error' + '406': + description: The requested version isn't served by this server or this route + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionUnsupportedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionRetiredError' tags: - Organizations - experimental @@ -1850,11 +2666,58 @@ paths: description: A 200 response with typed data headers: CG-Version-Served: - required: true + required: true + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Can differ from the requested version in the patch number only. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + type: object + required: + - data + properties: + data: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.OrgRevision' + description: Response data + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A 200 response with typed data + '400': + description: The request is invalid, or its `CG-Version` value is malformed or was sent more than once + headers: + CG-Version-Served: + required: false description: |- The full protocol version this response was served in, such as `0.5.1` - Can differ from the requested version in the patch number only. + Sent on every 400 except the version errors. schema: $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' Vary: @@ -1882,17 +2745,10 @@ paths: content: application/json: schema: - type: object - required: - - data - properties: - data: - allOf: - - $ref: '#/components/schemas/CommonGrants.Models.OrgRevision' - description: Response data - allOf: - - $ref: '#/components/schemas/CommonGrants.Responses.Success' - description: A 200 response with typed data + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionMalformedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionConflictError' + - $ref: '#/components/schemas/CommonGrants.Responses.Error' '401': description: Access is unauthorized. headers: @@ -2004,6 +2860,14 @@ paths: application/json: schema: $ref: '#/components/schemas/CommonGrants.Responses.Error' + '406': + description: The requested version isn't served by this server or this route + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionUnsupportedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionRetiredError' tags: - Organizations - experimental @@ -2084,6 +2948,46 @@ paths: allOf: - $ref: '#/components/schemas/CommonGrants.Responses.Success' description: A 202 response with typed data + '400': + description: The request is invalid, or its `CG-Version` value is malformed or was sent more than once + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Sent on every 400 except the version errors. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionMalformedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionConflictError' + - $ref: '#/components/schemas/CommonGrants.Responses.Error' '401': description: Access is unauthorized. headers: @@ -2195,6 +3099,14 @@ paths: application/json: schema: $ref: '#/components/schemas/CommonGrants.Responses.Error' + '406': + description: The requested version isn't served by this server or this route + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionUnsupportedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionRetiredError' tags: - Organizations - experimental @@ -2276,6 +3188,46 @@ paths: allOf: - $ref: '#/components/schemas/CommonGrants.Responses.Success' description: A 200 response with a paginated list of typed items + '400': + description: The request is invalid, or its `CG-Version` value is malformed or was sent more than once + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Sent on every 400 except the version errors. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionMalformedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionConflictError' + - $ref: '#/components/schemas/CommonGrants.Responses.Error' '401': description: Access is unauthorized. headers: @@ -2387,6 +3339,14 @@ paths: application/json: schema: $ref: '#/components/schemas/CommonGrants.Responses.Error' + '406': + description: The requested version isn't served by this server or this route + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionUnsupportedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionRetiredError' tags: - Organizations - experimental @@ -2460,6 +3420,46 @@ paths: allOf: - $ref: '#/components/schemas/CommonGrants.Responses.Success' description: A 200 response with typed data + '400': + description: The request is invalid, or its `CG-Version` value is malformed or was sent more than once + headers: + CG-Version-Served: + required: false + description: |- + The full protocol version this response was served in, such as `0.5.1` + + Sent on every 400 except the version errors. + schema: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + Vary: + required: false + description: Request headers that caches must key this response on, such as `CG-Version` + schema: + type: string + Deprecation: + required: false + description: When the served version was or will be deprecated (RFC 9745), such as `@1796083200` + schema: + type: string + pattern: ^@-?[0-9]+$ + Sunset: + required: false + description: When the served version stops responding (RFC 8594), such as `Tue, 01 Jun 2027 00:00:00 GMT` + schema: + type: string + format: http-date + Link: + required: false + description: Links about the served version's lifecycle (RFC 8288), such as `rel="sunset"` + schema: + type: string + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionMalformedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionConflictError' + - $ref: '#/components/schemas/CommonGrants.Responses.Error' '401': description: Access is unauthorized. headers: @@ -2571,6 +3571,14 @@ paths: application/json: schema: $ref: '#/components/schemas/CommonGrants.Responses.Error' + '406': + description: The requested version isn't served by this server or this route + content: + application/json: + schema: + anyOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionUnsupportedError' + - $ref: '#/components/schemas/CommonGrants.Responses.VersionRetiredError' tags: - Organizations - experimental @@ -7846,6 +8854,262 @@ components: message: type: string example: Success + CommonGrants.Responses.VersionConflictDetail: + type: object + required: + - code + properties: + code: + type: string + enum: + - version.conflict + description: Stable error code that clients branch on + additionalProperties: {} + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionErrorDetail' + description: The request sent more than one `CG-Version` value + CommonGrants.Responses.VersionConflictError: + type: object + required: + - status + - errors + properties: + status: + type: number + enum: + - 400 + example: 400 + errors: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Responses.VersionConflictDetail' + minItems: 1 + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Error' + description: A request that sent more than one `CG-Version` value, even the same value twice + example: + status: 400 + message: The request sent more than one CG-Version value + errors: + - field: CG-Version + code: version.conflict + message: Received CG-Version values 0.5.0 and 0.6.0 + supported: + - 0.5.0 + - 0.6.0 + defaultVersion: 0.5.0 + discovery: https://grants.example.org/common-grants/versions + CommonGrants.Responses.VersionErrorDetail: + type: object + required: + - field + - message + - supported + - defaultVersion + properties: + field: + type: string + enum: + - CG-Version + description: The request header the error is about + message: + type: string + description: Human-readable description of the problem + supported: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + minItems: 1 + description: The versions this route serves + defaultVersion: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + description: The version this route serves when a request doesn't name one + discovery: + type: string + format: uri + description: |- + The server's version discovery URL + + Omitted by servers that serve one version and don't publish discovery. + description: Details shared by every version error, describing the route that was called + CommonGrants.Responses.VersionErrorScope: + type: string + enum: + - deployment + - operation + description: Whether a version is unavailable on the whole server or only on the route called + CommonGrants.Responses.VersionMalformedDetail: + type: object + required: + - code + - requested + properties: + code: + type: string + enum: + - version.malformed + description: Stable error code that clients branch on + requested: + type: string + description: The value received, as sent + additionalProperties: {} + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionErrorDetail' + description: The `CG-Version` value isn't a full `MAJOR.MINOR.PATCH` version + CommonGrants.Responses.VersionMalformedError: + type: object + required: + - status + - errors + properties: + status: + type: number + enum: + - 400 + example: 400 + errors: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Responses.VersionMalformedDetail' + minItems: 1 + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Error' + description: A `CG-Version` header that isn't a full `MAJOR.MINOR.PATCH` version + example: + status: 400 + message: The CG-Version header is not a valid CommonGrants version + errors: + - field: CG-Version + code: version.malformed + message: Version 0.5 is not a full MAJOR.MINOR.PATCH version + requested: '0.5' + supported: + - 0.5.0 + - 0.6.0 + defaultVersion: 0.5.0 + discovery: https://grants.example.org/common-grants/versions + CommonGrants.Responses.VersionRetiredDetail: + type: object + required: + - code + - requested + - scope + - sunset + properties: + code: + type: string + enum: + - version.retired + description: Stable error code that clients branch on + requested: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + description: The version requested + scope: + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionErrorScope' + description: Whether the server or only this route doesn't serve the version + sunset: + type: string + format: date-time + description: When the version stopped being served + additionalProperties: {} + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionErrorDetail' + description: The requested version was retired from this server or this route + CommonGrants.Responses.VersionRetiredError: + type: object + required: + - status + - errors + properties: + status: + type: number + enum: + - 406 + example: 406 + errors: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Responses.VersionRetiredDetail' + minItems: 1 + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Error' + description: A requested version that was retired from this server or route + example: + status: 406 + message: The requested CommonGrants version has been retired + errors: + - field: CG-Version + code: version.retired + message: 'Version 0.3.0 was retired on 2027-06-01. Supported versions: 0.4.0, 0.5.0, 0.6.0' + requested: 0.3.0 + supported: + - 0.4.0 + - 0.5.0 + - 0.6.0 + scope: deployment + defaultVersion: 0.4.0 + discovery: https://grants.example.org/common-grants/versions + sunset: '2027-06-01T00:00:00Z' + CommonGrants.Responses.VersionUnsupportedDetail: + type: object + required: + - code + - requested + - scope + properties: + code: + type: string + enum: + - version.unsupported + description: Stable error code that clients branch on + requested: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + description: The version requested + scope: + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionErrorScope' + description: Whether the server or only this route doesn't serve the version + additionalProperties: {} + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.VersionErrorDetail' + description: The requested version isn't served by this server or this route + CommonGrants.Responses.VersionUnsupportedError: + type: object + required: + - status + - errors + properties: + status: + type: number + enum: + - 406 + example: 406 + errors: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Responses.VersionUnsupportedDetail' + minItems: 1 + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Error' + description: A requested version that this server or route doesn't serve + example: + status: 406 + message: The requested CommonGrants version is not available for this route + errors: + - field: CG-Version + code: version.unsupported + message: 'Version 0.4.0 is not served by GET /common-grants/forms. Supported versions: 0.5.0, 0.6.0' + requested: 0.4.0 + supported: + - 0.5.0 + - 0.6.0 + scope: operation + defaultVersion: 0.5.0 + discovery: https://grants.example.org/common-grants/versions CommonGrants.Sorting.SortBodyParams: type: object required: diff --git a/website/public/schemas/yaml/VersionConflictDetail.yaml b/website/public/schemas/yaml/VersionConflictDetail.yaml new file mode 100644 index 000000000..a53e88832 --- /dev/null +++ b/website/public/schemas/yaml/VersionConflictDetail.yaml @@ -0,0 +1,14 @@ +$schema: https://json-schema.org/draft/2020-12/schema +$id: VersionConflictDetail.yaml +type: object +properties: + code: + type: string + const: version.conflict + description: Stable error code that clients branch on +required: + - code +allOf: + - $ref: VersionErrorDetail.yaml +unevaluatedProperties: {} +description: The request sent more than one `CG-Version` value diff --git a/website/public/schemas/yaml/VersionConflictError.yaml b/website/public/schemas/yaml/VersionConflictError.yaml new file mode 100644 index 000000000..7a64d5826 --- /dev/null +++ b/website/public/schemas/yaml/VersionConflictError.yaml @@ -0,0 +1,34 @@ +$schema: https://json-schema.org/draft/2020-12/schema +$id: VersionConflictError.yaml +type: object +properties: + status: + type: number + const: 400 + examples: + - 400 + errors: + type: array + items: + $ref: VersionConflictDetail.yaml + minItems: 1 +required: + - status + - errors +allOf: + - $ref: Error.yaml +unevaluatedProperties: + not: {} +examples: + - status: 400 + message: The request sent more than one CG-Version value + errors: + - field: CG-Version + code: version.conflict + message: Received CG-Version values 0.5.0 and 0.6.0 + supported: + - 0.5.0 + - 0.6.0 + defaultVersion: 0.5.0 + discovery: https://grants.example.org/common-grants/versions +description: A request that sent more than one `CG-Version` value, even the same value twice diff --git a/website/public/schemas/yaml/VersionErrorDetail.yaml b/website/public/schemas/yaml/VersionErrorDetail.yaml new file mode 100644 index 000000000..e529bb7e8 --- /dev/null +++ b/website/public/schemas/yaml/VersionErrorDetail.yaml @@ -0,0 +1,33 @@ +$schema: https://json-schema.org/draft/2020-12/schema +$id: VersionErrorDetail.yaml +type: object +properties: + field: + type: string + const: CG-Version + description: The request header the error is about + message: + type: string + description: Human-readable description of the problem + supported: + type: array + items: + $ref: protocolVersion.yaml + minItems: 1 + description: The versions this route serves + defaultVersion: + $ref: protocolVersion.yaml + description: The version this route serves when a request doesn't name one + discovery: + type: string + format: uri + description: |- + The server's version discovery URL + + Omitted by servers that serve one version and don't publish discovery. +required: + - field + - message + - supported + - defaultVersion +description: Details shared by every version error, describing the route that was called diff --git a/website/public/schemas/yaml/VersionErrorScope.yaml b/website/public/schemas/yaml/VersionErrorScope.yaml new file mode 100644 index 000000000..045ca61e2 --- /dev/null +++ b/website/public/schemas/yaml/VersionErrorScope.yaml @@ -0,0 +1,7 @@ +$schema: https://json-schema.org/draft/2020-12/schema +$id: VersionErrorScope.yaml +type: string +enum: + - deployment + - operation +description: Whether a version is unavailable on the whole server or only on the route called diff --git a/website/public/schemas/yaml/VersionMalformedDetail.yaml b/website/public/schemas/yaml/VersionMalformedDetail.yaml new file mode 100644 index 000000000..da41caec0 --- /dev/null +++ b/website/public/schemas/yaml/VersionMalformedDetail.yaml @@ -0,0 +1,18 @@ +$schema: https://json-schema.org/draft/2020-12/schema +$id: VersionMalformedDetail.yaml +type: object +properties: + code: + type: string + const: version.malformed + description: Stable error code that clients branch on + requested: + type: string + description: The value received, as sent +required: + - code + - requested +allOf: + - $ref: VersionErrorDetail.yaml +unevaluatedProperties: {} +description: The `CG-Version` value isn't a full `MAJOR.MINOR.PATCH` version diff --git a/website/public/schemas/yaml/VersionMalformedError.yaml b/website/public/schemas/yaml/VersionMalformedError.yaml new file mode 100644 index 000000000..27d5358a5 --- /dev/null +++ b/website/public/schemas/yaml/VersionMalformedError.yaml @@ -0,0 +1,35 @@ +$schema: https://json-schema.org/draft/2020-12/schema +$id: VersionMalformedError.yaml +type: object +properties: + status: + type: number + const: 400 + examples: + - 400 + errors: + type: array + items: + $ref: VersionMalformedDetail.yaml + minItems: 1 +required: + - status + - errors +allOf: + - $ref: Error.yaml +unevaluatedProperties: + not: {} +examples: + - status: 400 + message: The CG-Version header is not a valid CommonGrants version + errors: + - field: CG-Version + code: version.malformed + message: Version 0.5 is not a full MAJOR.MINOR.PATCH version + requested: "0.5" + supported: + - 0.5.0 + - 0.6.0 + defaultVersion: 0.5.0 + discovery: https://grants.example.org/common-grants/versions +description: A `CG-Version` header that isn't a full `MAJOR.MINOR.PATCH` version diff --git a/website/public/schemas/yaml/VersionRetiredDetail.yaml b/website/public/schemas/yaml/VersionRetiredDetail.yaml new file mode 100644 index 000000000..6684336c9 --- /dev/null +++ b/website/public/schemas/yaml/VersionRetiredDetail.yaml @@ -0,0 +1,27 @@ +$schema: https://json-schema.org/draft/2020-12/schema +$id: VersionRetiredDetail.yaml +type: object +properties: + code: + type: string + const: version.retired + description: Stable error code that clients branch on + requested: + $ref: protocolVersion.yaml + description: The version requested + scope: + $ref: VersionErrorScope.yaml + description: Whether the server or only this route doesn't serve the version + sunset: + type: string + format: date-time + description: When the version stopped being served +required: + - code + - requested + - scope + - sunset +allOf: + - $ref: VersionErrorDetail.yaml +unevaluatedProperties: {} +description: The requested version was retired from this server or this route diff --git a/website/public/schemas/yaml/VersionRetiredError.yaml b/website/public/schemas/yaml/VersionRetiredError.yaml new file mode 100644 index 000000000..ffd5213ab --- /dev/null +++ b/website/public/schemas/yaml/VersionRetiredError.yaml @@ -0,0 +1,38 @@ +$schema: https://json-schema.org/draft/2020-12/schema +$id: VersionRetiredError.yaml +type: object +properties: + status: + type: number + const: 406 + examples: + - 406 + errors: + type: array + items: + $ref: VersionRetiredDetail.yaml + minItems: 1 +required: + - status + - errors +allOf: + - $ref: Error.yaml +unevaluatedProperties: + not: {} +examples: + - status: 406 + message: The requested CommonGrants version has been retired + errors: + - field: CG-Version + code: version.retired + message: "Version 0.3.0 was retired on 2027-06-01. Supported versions: 0.4.0, 0.5.0, 0.6.0" + requested: 0.3.0 + supported: + - 0.4.0 + - 0.5.0 + - 0.6.0 + scope: deployment + defaultVersion: 0.4.0 + discovery: https://grants.example.org/common-grants/versions + sunset: 2027-06-01T00:00:00Z +description: A requested version that was retired from this server or route diff --git a/website/public/schemas/yaml/VersionUnsupportedDetail.yaml b/website/public/schemas/yaml/VersionUnsupportedDetail.yaml new file mode 100644 index 000000000..03c34cc63 --- /dev/null +++ b/website/public/schemas/yaml/VersionUnsupportedDetail.yaml @@ -0,0 +1,22 @@ +$schema: https://json-schema.org/draft/2020-12/schema +$id: VersionUnsupportedDetail.yaml +type: object +properties: + code: + type: string + const: version.unsupported + description: Stable error code that clients branch on + requested: + $ref: protocolVersion.yaml + description: The version requested + scope: + $ref: VersionErrorScope.yaml + description: Whether the server or only this route doesn't serve the version +required: + - code + - requested + - scope +allOf: + - $ref: VersionErrorDetail.yaml +unevaluatedProperties: {} +description: The requested version isn't served by this server or this route diff --git a/website/public/schemas/yaml/VersionUnsupportedError.yaml b/website/public/schemas/yaml/VersionUnsupportedError.yaml new file mode 100644 index 000000000..9b0ac3cd8 --- /dev/null +++ b/website/public/schemas/yaml/VersionUnsupportedError.yaml @@ -0,0 +1,36 @@ +$schema: https://json-schema.org/draft/2020-12/schema +$id: VersionUnsupportedError.yaml +type: object +properties: + status: + type: number + const: 406 + examples: + - 406 + errors: + type: array + items: + $ref: VersionUnsupportedDetail.yaml + minItems: 1 +required: + - status + - errors +allOf: + - $ref: Error.yaml +unevaluatedProperties: + not: {} +examples: + - status: 406 + message: The requested CommonGrants version is not available for this route + errors: + - field: CG-Version + code: version.unsupported + message: "Version 0.4.0 is not served by GET /common-grants/forms. Supported versions: 0.5.0, 0.6.0" + requested: 0.4.0 + supported: + - 0.5.0 + - 0.6.0 + scope: operation + defaultVersion: 0.5.0 + discovery: https://grants.example.org/common-grants/versions +description: A requested version that this server or route doesn't serve From e2f68fa2a1249f3abdfdad47ea192ab2bce72ec6 Mon Sep 17 00:00:00 2001 From: Bryan Thompson <18094023+SnowboardTechie@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:13:33 -0800 Subject: [PATCH 3/5] feat(core): add the versions discovery route (#1399) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### Summary - Fixes #1387 - Time to review: 15 minutes ### Changes proposed A server built on core 0.6.0 can declare `GET /common-grants/versions` and publish which protocol versions it serves: its default version, the versions it serves across routes (the baseline), entries for routes that differ from that baseline, and, while a change is pending, an upcoming default and deprecated versions with their retirement dates. Clients can check support before sending a request, per [ADR 0032](https://github.com/HHS/simpler-grants-protocol/blob/main/website/src/content/docs/governance/adr/0032-api-version-negotiation.md) (API version negotiation). - `Routes.ProtocolVersions.read()` returns the new `Responses.VersionDiscoveryResponse`, wired into the base API at `/common-grants/versions`, tagged `Versions` and `optional`. The route is optional; the ADR requires it of servers that serve more than one version, and the route description carries that and the other server rules. - `Responses.VersionDiscoveryResponse` is the standard success envelope without the version headers. `OkT` spreads `Headers.VersionResponse` since #1401, and the ADR says discovery carries neither `CG-Version-Served` nor `Vary: CG-Version`, because clients call it before they know which version to request. - New models in `CommonGrants.Models`: `VersionDiscovery`, `OperationVersions`, `UpcomingDefault`, `VersionRetirement`, with the two examples from the ADR. These four models accept fields they don't declare (`...Record`, as `FormJsonSchema` and `FormUISchema` already do), so a server can add discovery fields later without a new protocol version, which is what the route's "fields are only ever added" rule promises. Other core models stay closed to undeclared fields, apart from those free-form form-schema models and the typed filter maps. - Regenerated `website/public/openapi/openapi.0.6.0.yaml` and added five JSON Schema files. ### Context for reviewers **Rebased onto #1401 and #1414.** `Versions.v0_6` and `Types.protocolVersion` now come from the version headers PR, so the stubs this PR carried are gone. The field names (`versions`, `defaultVersion`, `operations`, `upcomingDefault`, `deprecated`) match the published ADR. **Why these models are open.** Discovery is the one route a client calls before it knows a version, so its shape can't be versioned per document; that's why these models are open while other core models are closed to undeclared fields (`seal-object-schemas: true` in the website build, which the SDKs' strict validators follow). Whether the additive rule should bind other models is for the ADR, not this PR. **Verified:** - `pnpm --filter @common-grants/core run ci` passes (lint, format, types, example dates, build, compile). - The 0.1.0 through 0.5.0 OpenAPI documents are byte-identical to `CORE-v0.6.0`: `git diff origin/CORE-v0.6.0 -- website/public/openapi/openapi.0.{1,2,3,4,5}.0.yaml` is empty. No existing JSON Schema file changed. - `pnpm --filter website run check:quickstarts`, `build` and `test` pass (1225 tests). - In the 0.6.0 document the route's 200 declares no headers, it takes no `CG-Version` parameter and declares no version errors (the ADR says discovery never returns one), and it is tagged `Versions` and `optional`. - The JSON Schema files reject a `deprecated` key that isn't a protocol version, such as `v0.3`, at the top level and in route entries. This PR targets the `CORE-v0.6.0` hold branch (see [`lib/README.md`](https://github.com/HHS/simpler-grants-protocol/blob/main/lib/README.md) on hold branches), and GitHub doesn't auto-close issues from a hold-branch PR. #1387 is closed by hand when the `feat(core)!: v0.6.0` staging PR merges into `main`, per the hold-branch checklist in that file. **For adopters.** Until the CLI bundles the 0.6.0 base spec, `cg check` reports `/common-grants/versions` as an extra route on a server that implements it early. OpenAPI 3.0 shows one of the two `VersionDiscovery` examples (the lifecycle one); both are in `VersionDiscovery.yaml`. Same emitter behaviour as the existing multi-example scalars. The blank line inside the route's `@doc("""…""")` block carries trailing spaces because `tsp format` writes it that way and `check:format` requires the formatter's output. ### Additional information Discovery response for a server whose baseline is 0.4.0 and whose form list is served only in 0.5.0 (the first example on the model): ```json { "status": 200, "message": "Success", "data": { "versions": ["0.4.0"], "defaultVersion": "0.4.0", "operations": { "GET /common-grants/forms": { "versions": ["0.5.0"], "defaultVersion": "0.5.0" }, "GET /common-grants/forms/{formId}": { "versions": ["0.4.0", "0.5.0"], "defaultVersion": "0.4.0" } } } } ``` --- lib/core/lib/api.tsp | 20 +++ lib/core/lib/core/models/index.tsp | 1 + .../lib/core/models/version-discovery.tsp | 170 ++++++++++++++++++ lib/core/lib/core/responses/success.tsp | 16 ++ lib/core/lib/core/routes/index.tsp | 1 + .../lib/core/routes/version-discovery.tsp | 50 ++++++ website/public/openapi/openapi.0.6.0.yaml | 170 ++++++++++++++++++ .../schemas/yaml/OperationVersions.yaml | 41 +++++ .../public/schemas/yaml/UpcomingDefault.yaml | 16 ++ .../public/schemas/yaml/VersionDiscovery.yaml | 87 +++++++++ .../yaml/VersionDiscoveryResponse.yaml | 14 ++ .../schemas/yaml/VersionRetirement.yaml | 16 ++ 12 files changed, 602 insertions(+) create mode 100644 lib/core/lib/core/models/version-discovery.tsp create mode 100644 lib/core/lib/core/routes/version-discovery.tsp create mode 100644 website/public/schemas/yaml/OperationVersions.yaml create mode 100644 website/public/schemas/yaml/UpcomingDefault.yaml create mode 100644 website/public/schemas/yaml/VersionDiscovery.yaml create mode 100644 website/public/schemas/yaml/VersionDiscoveryResponse.yaml create mode 100644 website/public/schemas/yaml/VersionRetirement.yaml diff --git a/lib/core/lib/api.tsp b/lib/core/lib/api.tsp index 55d868182..d8626375d 100644 --- a/lib/core/lib/api.tsp +++ b/lib/core/lib/api.tsp @@ -30,6 +30,12 @@ using Versioning; description: "Endpoints that MUST be implemented by all CommonGrants APIs", } ) +@tagMetadata( + "Versions", + #{ + description: "Endpoints related to discovering the protocol versions an API serves", + } +) @tagMetadata("Forms", #{ description: "Endpoints related to forms" }) @tagMetadata("Awards", #{ description: "Endpoints related to grant awards" }) @tagMetadata( @@ -246,3 +252,17 @@ namespace Forms { @added(Versions.v0_2) op read is Router.read; } + +// ######################################################### +// Versions +// ######################################################### + +@tag("Versions") +@route("/versions") +namespace ProtocolVersions { + alias Router = Routes.ProtocolVersions; + + @added(Versions.v0_6) + @tag("optional") + op read is Router.read; +} diff --git a/lib/core/lib/core/models/index.tsp b/lib/core/lib/core/models/index.tsp index 028834a10..60e383cbe 100644 --- a/lib/core/lib/core/models/index.tsp +++ b/lib/core/lib/core/models/index.tsp @@ -15,6 +15,7 @@ import "./form.tsp"; import "./form-response.tsp"; import "./mapping.tsp"; import "./applicant-type.tsp"; +import "./version-discovery.tsp"; using TypeSpec.JsonSchema; diff --git a/lib/core/lib/core/models/version-discovery.tsp b/lib/core/lib/core/models/version-discovery.tsp new file mode 100644 index 000000000..ae6b1d834 --- /dev/null +++ b/lib/core/lib/core/models/version-discovery.tsp @@ -0,0 +1,170 @@ +import "../types.tsp"; + +namespace CommonGrants.Models; + +// ######################################################### +// UpcomingDefault +// ######################################################### + +/** A scheduled change to the version a server serves by default */ +@Versioning.added(CommonGrants.Versions.v0_6) +model UpcomingDefault { + /** The version that will become the default */ + version: Types.protocolVersion; + + /** When the new default takes effect */ + date: utcDateTime; + + // Discovery sits outside version selection, so new fields must be tolerated rather than versioned + ...Record; +} + +// ######################################################### +// VersionRetirement +// ######################################################### + +/** The retirement schedule for a deprecated version */ +@Versioning.added(CommonGrants.Versions.v0_6) +model VersionRetirement { + /** When the version was or will be deprecated */ + deprecation: utcDateTime; + + /** When the server will stop serving the version, if scheduled */ + sunset?: utcDateTime; + + ...Record; +} + +// ######################################################### +// OperationVersions +// ######################################################### + +/** The versions a single route serves, when they differ from the API-wide values */ +@Versioning.added(CommonGrants.Versions.v0_6) +model OperationVersions { + /** The versions this route serves */ + @minItems(1) + versions: Types.protocolVersion[]; + + /** The version this route serves when a request doesn't name one, one of `versions` */ + defaultVersion: Types.protocolVersion; + + /** A scheduled change to this route's default version, if any. Its `version` is one of `versions` */ + upcomingDefault?: UpcomingDefault; + + /** Deprecated versions of this route, keyed by version, with their retirement schedule + * + * Each key is a version from `versions`, written exactly as it appears + * there. A server hosting `0.3.1` lists `0.3.1` in `versions` and uses + * `0.3.1` as the key here. + * + * To check whether the version you request is deprecated, compare only + * the major and minor. A client requesting `0.3.0` is served `0.3.1`, so + * its entry is under `0.3.1`. + */ + @TypeSpec.JsonSchema.extension( + "propertyNames", + #{ $ref: "protocolVersion.yaml" } + ) + deprecated?: Record; + + ...Record; +} + +// ######################################################### +// VersionDiscovery +// ######################################################### + +/** The protocol versions an API serves + * + * The top-level fields describe every route that has no entry in + * `operations`. Routes that differ from them have an entry in `operations`. + * New fields are only ever added to this model; clients ignore fields they + * don't recognize. + */ +@example( + Examples.VersionDiscovery.routeEntries, + #{ title: "Baseline with route entries" } +) +@example( + Examples.VersionDiscovery.lifecycle, + #{ title: "Upcoming default and deprecated version" } +) +@Versioning.added(CommonGrants.Versions.v0_6) +model VersionDiscovery { + /** The versions every route without an `operations` entry serves */ + @minItems(1) + versions: Types.protocolVersion[]; + + /** The version every route without an `operations` entry serves when a request doesn't name one, one of `versions` */ + defaultVersion: Types.protocolVersion; + + /** A scheduled change to the API-wide default version, if any. Its `version` is one of `versions` */ + upcomingDefault?: UpcomingDefault; + + /** Deprecated versions, keyed by version, with their retirement schedule + * + * Each key is a version from `versions`, written exactly as it appears + * there. A server hosting `0.3.1` lists `0.3.1` in `versions` and uses + * `0.3.1` as the key here. + * + * To check whether the version you request is deprecated, compare only + * the major and minor. A client requesting `0.3.0` is served `0.3.1`, so + * its entry is under `0.3.1`. + */ + @TypeSpec.JsonSchema.extension( + "propertyNames", + #{ $ref: "protocolVersion.yaml" } + ) + deprecated?: Record; + + /** Routes whose versions differ from the API-wide values + * + * Each key is the HTTP method and the route's published path, separated + * by a space, such as `GET /common-grants/forms/{formId}`. Path parameter + * names are ignored when matching a key to a route. Omitted when every + * route serves the API-wide values. + */ + operations?: Record; + + ...Record; +} + +// ######################################################### +// Examples +// ######################################################### + +/** Examples of version discovery responses */ +namespace Examples.VersionDiscovery { + /** A 0.4.0 baseline with routes that serve other versions */ + const routeEntries = #{ + versions: #["0.4.0"], + defaultVersion: "0.4.0", + operations: #{ + `GET /common-grants/forms`: #{ + versions: #["0.5.0"], + defaultVersion: "0.5.0", + }, + `GET /common-grants/forms/{formId}`: #{ + versions: #["0.4.0", "0.5.0"], + defaultVersion: "0.4.0", + }, + }, + }; + + /** A scheduled default change and a deprecated version */ + const lifecycle = #{ + versions: #["0.3.0", "0.4.0", "0.5.0"], + defaultVersion: "0.4.0", + upcomingDefault: #{ + version: "0.5.0", + date: utcDateTime.fromISO("2027-03-01T00:00:00Z"), + }, + deprecated: #{ + `0.3.0`: #{ + deprecation: utcDateTime.fromISO("2026-12-01T00:00:00Z"), + sunset: utcDateTime.fromISO("2027-06-01T00:00:00Z"), + }, + }, + }; +} diff --git a/lib/core/lib/core/responses/success.tsp b/lib/core/lib/core/responses/success.tsp index e6c13588c..9c8722a8f 100644 --- a/lib/core/lib/core/responses/success.tsp +++ b/lib/core/lib/core/responses/success.tsp @@ -64,6 +64,22 @@ model OkT extends Success { data: T; } +// ############################################################################ +// 200 version discovery response +// ############################################################################ + +/** A 200 response listing the protocol versions an API serves + * + * Discovery sits outside version selection, so unlike `OkT` this response + * carries no version headers: neither `CG-Version-Served` nor `Vary`. + */ +@doc("A 200 response listing the protocol versions an API serves") +@Versioning.added(CommonGrants.Versions.v0_6) +model VersionDiscoveryResponse extends Success { + /** The protocol versions the API serves */ + data: Models.VersionDiscovery; +} + // ############################################################################ // 200 paginated response // ############################################################################ diff --git a/lib/core/lib/core/routes/index.tsp b/lib/core/lib/core/routes/index.tsp index 8f4e4f8f7..bdcba2661 100644 --- a/lib/core/lib/core/routes/index.tsp +++ b/lib/core/lib/core/routes/index.tsp @@ -9,6 +9,7 @@ import "./applications.tsp"; import "./form-responses.tsp"; import "./forms.tsp"; import "./competitions.tsp"; +import "./version-discovery.tsp"; /** A series of routing interfaces for CommonGrants API endpoints * diff --git a/lib/core/lib/core/routes/version-discovery.tsp b/lib/core/lib/core/routes/version-discovery.tsp new file mode 100644 index 000000000..e5bba00f3 --- /dev/null +++ b/lib/core/lib/core/routes/version-discovery.tsp @@ -0,0 +1,50 @@ +import "../models/index.tsp"; +import "../responses/index.tsp"; + +// Define the top-level namespace for CommonGrants routes +namespace CommonGrants.Routes; + +// Expose the contents of the Http and Rest namespaces +// these include the decorators @route, @get, etc. +using TypeSpec.Http; +using TypeSpec.Versioning; + +/** A re-usable interface for the versions discovery router + * + * Unlike the other routers, `read` is deliberately not templated: adopters + * don't type-parameterize the discovery response. Routes that differ from the API-wide + * versions are described in the response's `operations` field instead. + * + * @example Declaring the versions discovery route: + * ```typespec + * using TypeSpec.Http; + * + * @tag("Versions") + * @route("/versions") + * namespace ProtocolVersions { + * alias Router = Routes.ProtocolVersions; + * + * op read is Router.read; + * } + * ``` + */ +@added(CommonGrants.Versions.v0_6) +interface ProtocolVersions { + // ############################### + // List supported versions + // ############################### + + /** `GET /versions` List the protocol versions this API serves */ + @summary("List supported versions") + @doc(""" + List the protocol versions this API serves, its default version, and any routes whose versions differ. + + This route is optional, but a server that serves more than one protocol version MUST implement it. + It ignores the `CG-Version` request header, because clients call it before they know which version to request. + Its responses carry neither `CG-Version-Served` nor `Vary: CG-Version`. + It requires no stronger authentication than the API's required routes, and SHOULD be readable without authentication. + Fields are only ever added to `data`; clients ignore fields they don't recognize. + """) + @get + read(): Responses.VersionDiscoveryResponse; +} diff --git a/website/public/openapi/openapi.0.6.0.yaml b/website/public/openapi/openapi.0.6.0.yaml index 3adb2e665..16c54ae8d 100644 --- a/website/public/openapi/openapi.0.6.0.yaml +++ b/website/public/openapi/openapi.0.6.0.yaml @@ -22,6 +22,8 @@ tags: description: Endpoints related to grant awards - name: Forms description: Endpoints related to forms + - name: Versions + description: Endpoints related to discovering the protocol versions an API serves - name: required description: Endpoints that MUST be implemented by all CommonGrants APIs - name: optional @@ -3585,6 +3587,29 @@ paths: security: - OAuth2Auth: - org.changes:read + /common-grants/versions: + get: + operationId: ProtocolVersions_read + summary: List supported versions + description: |- + List the protocol versions this API serves, its default version, and any routes whose versions differ. + + This route is optional, but a server that serves more than one protocol version MUST implement it. + It ignores the `CG-Version` request header, because clients call it before they know which version to request. + Its responses carry neither `CG-Version-Served` nor `Vary: CG-Version`. + It requires no stronger authentication than the API's required routes, and SHOULD be readable without authentication. + Fields are only ever added to `data`; clients ignore fields they don't recognize. + parameters: [] + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.VersionDiscoveryResponse' + tags: + - Versions + - optional components: parameters: CommonGrants.Headers.VersionRequest: @@ -6279,6 +6304,42 @@ components: active: open inactive: closed default: custom + CommonGrants.Models.OperationVersions: + type: object + required: + - versions + - defaultVersion + properties: + versions: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + minItems: 1 + description: The versions this route serves + defaultVersion: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + description: The version this route serves when a request doesn't name one, one of `versions` + upcomingDefault: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.UpcomingDefault' + description: A scheduled change to this route's default version, if any. Its `version` is one of `versions` + deprecated: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Models.VersionRetirement' + description: |- + Deprecated versions of this route, keyed by version, with their retirement schedule + + Each key is a version from `versions`, written exactly as it appears + there. A server hosting `0.3.1` lists `0.3.1` in `versions` and uses + `0.3.1` as the key here. + + To check whether the version you request is deprecated, compare only + the major and minor. A client requesting `0.3.0` is served `0.3.1`, so + its entry is under `0.3.1`. + additionalProperties: {} + description: The versions a single route serves, when they differ from the API-wide values CommonGrants.Models.OppDefaultFilters: type: object properties: @@ -8102,6 +8163,103 @@ components: A revision moves once from `pending` into a terminal state; a terminal revision is never restated. How a receiver resolves a `pending` change (a human review, a policy engine, a batch job) is out of scope for this contract. + CommonGrants.Models.UpcomingDefault: + type: object + required: + - version + - date + properties: + version: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + description: The version that will become the default + date: + type: string + format: date-time + description: When the new default takes effect + additionalProperties: {} + description: A scheduled change to the version a server serves by default + CommonGrants.Models.VersionDiscovery: + type: object + required: + - versions + - defaultVersion + properties: + versions: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + minItems: 1 + description: The versions every route without an `operations` entry serves + defaultVersion: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + description: The version every route without an `operations` entry serves when a request doesn't name one, one of `versions` + upcomingDefault: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.UpcomingDefault' + description: A scheduled change to the API-wide default version, if any. Its `version` is one of `versions` + deprecated: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Models.VersionRetirement' + description: |- + Deprecated versions, keyed by version, with their retirement schedule + + Each key is a version from `versions`, written exactly as it appears + there. A server hosting `0.3.1` lists `0.3.1` in `versions` and uses + `0.3.1` as the key here. + + To check whether the version you request is deprecated, compare only + the major and minor. A client requesting `0.3.0` is served `0.3.1`, so + its entry is under `0.3.1`. + operations: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Models.OperationVersions' + description: |- + Routes whose versions differ from the API-wide values + + Each key is the HTTP method and the route's published path, separated + by a space, such as `GET /common-grants/forms/{formId}`. Path parameter + names are ignored when matching a key to a route. Omitted when every + route serves the API-wide values. + additionalProperties: {} + description: |- + The protocol versions an API serves + + The top-level fields describe every route that has no entry in + `operations`. Routes that differ from them have an entry in `operations`. + New fields are only ever added to this model; clients ignore fields they + don't recognize. + example: + versions: + - 0.3.0 + - 0.4.0 + - 0.5.0 + defaultVersion: 0.4.0 + upcomingDefault: + version: 0.5.0 + date: '2027-03-01T00:00:00Z' + deprecated: + 0.3.0: + deprecation: '2026-12-01T00:00:00Z' + sunset: '2027-06-01T00:00:00Z' + CommonGrants.Models.VersionRetirement: + type: object + required: + - deprecation + properties: + deprecation: + type: string + format: date-time + description: When the version was or will be deprecated + sunset: + type: string + format: date-time + description: When the server will stop serving the version, if scheduled + additionalProperties: {} + description: The retirement schedule for a deprecated version CommonGrants.Pagination.PaginatedBodyParams: type: object properties: @@ -8899,6 +9057,18 @@ components: - 0.6.0 defaultVersion: 0.5.0 discovery: https://grants.example.org/common-grants/versions + CommonGrants.Responses.VersionDiscoveryResponse: + type: object + required: + - data + properties: + data: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.VersionDiscovery' + description: The protocol versions the API serves + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A 200 response listing the protocol versions an API serves CommonGrants.Responses.VersionErrorDetail: type: object required: diff --git a/website/public/schemas/yaml/OperationVersions.yaml b/website/public/schemas/yaml/OperationVersions.yaml new file mode 100644 index 000000000..a36a7304b --- /dev/null +++ b/website/public/schemas/yaml/OperationVersions.yaml @@ -0,0 +1,41 @@ +$schema: https://json-schema.org/draft/2020-12/schema +$id: OperationVersions.yaml +type: object +properties: + versions: + type: array + items: + $ref: protocolVersion.yaml + minItems: 1 + description: The versions this route serves + defaultVersion: + $ref: protocolVersion.yaml + description: The version this route serves when a request doesn't name one, one of `versions` + upcomingDefault: + $ref: UpcomingDefault.yaml + description: A scheduled change to this route's default version, if any. Its `version` is one of `versions` + deprecated: + $ref: "#/$defs/RecordVersionRetirement" + description: |- + Deprecated versions of this route, keyed by version, with their retirement schedule + + Each key is a version from `versions`, written exactly as it appears + there. A server hosting `0.3.1` lists `0.3.1` in `versions` and uses + `0.3.1` as the key here. + + To check whether the version you request is deprecated, compare only + the major and minor. A client requesting `0.3.0` is served `0.3.1`, so + its entry is under `0.3.1`. + propertyNames: + $ref: protocolVersion.yaml +required: + - versions + - defaultVersion +unevaluatedProperties: {} +description: The versions a single route serves, when they differ from the API-wide values +$defs: + RecordVersionRetirement: + type: object + properties: {} + unevaluatedProperties: + $ref: VersionRetirement.yaml diff --git a/website/public/schemas/yaml/UpcomingDefault.yaml b/website/public/schemas/yaml/UpcomingDefault.yaml new file mode 100644 index 000000000..266e7a54a --- /dev/null +++ b/website/public/schemas/yaml/UpcomingDefault.yaml @@ -0,0 +1,16 @@ +$schema: https://json-schema.org/draft/2020-12/schema +$id: UpcomingDefault.yaml +type: object +properties: + version: + $ref: protocolVersion.yaml + description: The version that will become the default + date: + type: string + format: date-time + description: When the new default takes effect +required: + - version + - date +unevaluatedProperties: {} +description: A scheduled change to the version a server serves by default diff --git a/website/public/schemas/yaml/VersionDiscovery.yaml b/website/public/schemas/yaml/VersionDiscovery.yaml new file mode 100644 index 000000000..872c54906 --- /dev/null +++ b/website/public/schemas/yaml/VersionDiscovery.yaml @@ -0,0 +1,87 @@ +$schema: https://json-schema.org/draft/2020-12/schema +$id: VersionDiscovery.yaml +type: object +properties: + versions: + type: array + items: + $ref: protocolVersion.yaml + minItems: 1 + description: The versions every route without an `operations` entry serves + defaultVersion: + $ref: protocolVersion.yaml + description: The version every route without an `operations` entry serves when a request doesn't name one, one of `versions` + upcomingDefault: + $ref: UpcomingDefault.yaml + description: A scheduled change to the API-wide default version, if any. Its `version` is one of `versions` + deprecated: + $ref: "#/$defs/RecordVersionRetirement" + description: |- + Deprecated versions, keyed by version, with their retirement schedule + + Each key is a version from `versions`, written exactly as it appears + there. A server hosting `0.3.1` lists `0.3.1` in `versions` and uses + `0.3.1` as the key here. + + To check whether the version you request is deprecated, compare only + the major and minor. A client requesting `0.3.0` is served `0.3.1`, so + its entry is under `0.3.1`. + propertyNames: + $ref: protocolVersion.yaml + operations: + $ref: "#/$defs/RecordOperationVersions" + description: |- + Routes whose versions differ from the API-wide values + + Each key is the HTTP method and the route's published path, separated + by a space, such as `GET /common-grants/forms/{formId}`. Path parameter + names are ignored when matching a key to a route. Omitted when every + route serves the API-wide values. +required: + - versions + - defaultVersion +unevaluatedProperties: {} +examples: + - versions: + - 0.3.0 + - 0.4.0 + - 0.5.0 + defaultVersion: 0.4.0 + upcomingDefault: + version: 0.5.0 + date: 2027-03-01T00:00:00Z + deprecated: + 0.3.0: + deprecation: 2026-12-01T00:00:00Z + sunset: 2027-06-01T00:00:00Z + - versions: + - 0.4.0 + defaultVersion: 0.4.0 + operations: + GET /common-grants/forms: + versions: + - 0.5.0 + defaultVersion: 0.5.0 + GET /common-grants/forms/{formId}: + versions: + - 0.4.0 + - 0.5.0 + defaultVersion: 0.4.0 +description: |- + The protocol versions an API serves + + The top-level fields describe every route that has no entry in + `operations`. Routes that differ from them have an entry in `operations`. + New fields are only ever added to this model; clients ignore fields they + don't recognize. +$defs: + RecordVersionRetirement: + type: object + properties: {} + unevaluatedProperties: + $ref: VersionRetirement.yaml + RecordOperationVersions: + type: object + properties: {} + unevaluatedProperties: + $ref: OperationVersions.yaml diff --git a/website/public/schemas/yaml/VersionDiscoveryResponse.yaml b/website/public/schemas/yaml/VersionDiscoveryResponse.yaml new file mode 100644 index 000000000..f2f1792f4 --- /dev/null +++ b/website/public/schemas/yaml/VersionDiscoveryResponse.yaml @@ -0,0 +1,14 @@ +$schema: https://json-schema.org/draft/2020-12/schema +$id: VersionDiscoveryResponse.yaml +type: object +properties: + data: + $ref: VersionDiscovery.yaml + description: The protocol versions the API serves +required: + - data +allOf: + - $ref: Success.yaml +unevaluatedProperties: + not: {} +description: A 200 response listing the protocol versions an API serves diff --git a/website/public/schemas/yaml/VersionRetirement.yaml b/website/public/schemas/yaml/VersionRetirement.yaml new file mode 100644 index 000000000..7aad7db8e --- /dev/null +++ b/website/public/schemas/yaml/VersionRetirement.yaml @@ -0,0 +1,16 @@ +$schema: https://json-schema.org/draft/2020-12/schema +$id: VersionRetirement.yaml +type: object +properties: + deprecation: + type: string + format: date-time + description: When the version was or will be deprecated + sunset: + type: string + format: date-time + description: When the server will stop serving the version, if scheduled +required: + - deprecation +unevaluatedProperties: {} +description: The retirement schedule for a deprecated version From fd599cd5be63527971ff28aeabce383d66df8705 Mon Sep 17 00:00:00 2001 From: Karina Munoz Gonzalez Date: Fri, 20 Nov 2026 11:51:43 -0600 Subject: [PATCH 4/5] feat(website): move the mock API to the CG-Version header (#1415) ### Summary - Fixes #1393 - Time to review: 40 minutes The docs mock API now picks the protocol version from the `CG-Version` header instead of the path, serves `GET /common-grants/versions`, and answers version errors per ADR 0032. Retirement behavior (`Deprecation`, `Sunset`) and SDK support for `CG-Version` are out of scope. ### Changes proposed - Version resolution: - `website/src/lib/mock/http/version.ts`: new resolver for `CG-Version` (default 0.6.0, major.minor matching, `version.malformed` / `version.conflict` / `version.unsupported`), plus `CG-Version-Served` and `Vary` helpers - `website/src/lib/mock/http/envelope.ts`: `versionErrorResponse` builds the error envelope with the `discovery` URL - `website/src/lib/mock/data/fixtures.ts`: `hostedVersionFor` maps a requested version to the served one - Routing by header: - `website/src/lib/mock/router.ts`: one resource route without a path version; resolves the version per route, then dispatches. A path like `/api/v0.5.0/...` is now a plain route miss - `website/src/lib/mock/data/availability.ts`: `versionsFrom` lists the versions a route serves - `website/src/lib/mock/handlers/*.ts`: take the resolved version instead of reading it from the path - `website/src/lib/mock/handlers/versions.ts`: new `GET /common-grants/versions` handler; it ignores `CG-Version` and lists the routes added after 0.1.0 - `website/src/lib/mock/http/cors.ts`: allows `CG-Version` on preflights and exposes `CG-Version-Served`, `Deprecation`, `Sunset` and `Link` - Docs page and Swagger UI: - `website/src/lib/mock/docs-wiring.ts`, `website/src/scripts/inject-mock-server.ts`: every mock spec advertises one server, `/api` - `website/src/lib/api-docs-version.ts`: `withVersionHeader` adds `CG-Version` to mock requests unless the user typed one - `website/src/pages/protocol/api-docs.astro`: wires that helper into Swagger's `requestInterceptor` and lists v0.6.0 as Latest - `website/src/content/docs/governance/adr/0028-mock-api-hosting.md`: note that ADR 0032 supersedes the path version - Tests (`website/__tests__/`): - New: `lib/mock/http/version.spec.ts`, `lib/mock/version-routing.spec.ts`, `lib/mock/versions-discovery.spec.ts`, `lib/api-docs-version.spec.ts` - Migrated to header-based requests through a shared `lib/mock/__fixtures__/mock-request.ts` helper; the golden corpus sends the path version as `CG-Version` - `lib/mock/http/cors.spec.ts`: version headers on preflights and responses ### Context for reviewers The closest look belongs in `router.ts` and `handlers/versions.ts`: version errors come before dispatch, and the discovery route list must stay in step with the 0.6.0 spec (a conformance test walks `openapi.0.6.0.yaml` to check it). To verify: 1. Start the docs site: `pnpm --filter website run dev` 2. Run `curl -si http://localhost:4321/api/common-grants/opportunities -H 'CG-Version: 0.5.1' | grep -i cg-version`. Expect `cg-version-served: 0.5.0`. 3. Run `curl -s http://localhost:4321/api/common-grants/awards -H 'CG-Version: 0.2.0'`. Expect a 406 with `version.unsupported` and `scope: "operation"`. 4. Run `curl -s http://localhost:4321/api/common-grants/versions`. Expect the supported versions and per-route `operations`. 5. Open http://localhost:4321/protocol/api-docs?version=0.1.0, "Try it out" on `GET /common-grants/opportunities`, and Execute. The request carries `CG-Version: 0.1.0` and the response `cg-version-served: 0.1.0`. ### Additional information Preview: https://pr-1415-common-grants.agile6.workers.dev/protocol/api-docs?version=0.1.0. The verification steps above work against it by swapping `http://localhost:4321` for `https://pr-1415-common-grants.agile6.workers.dev`. Mock responses, captured by calling `handleMockRequest` directly: ``` no header 200 served=0.6.0 vary=CG-Version CG-Version: 0.5.1 200 served=0.5.0 vary=CG-Version CG-Version: v0.5 400 served=- vary=CG-Version version.malformed CG-Version: 0.4.0, 0.5.0 400 served=- vary=CG-Version version.conflict CG-Version: 9.0.0 406 served=- vary=CG-Version version.unsupported awards, CG-Version: 0.2.0 406 served=- vary=CG-Version version.unsupported GET /versions, CG-Version: bad 200 served=- vary=- versions=0.1.0,0.2.0,0.3.0,0.4.0,0.5.0,0.6.0 ``` Checks and tests: ``` $ pnpm --filter website run checks CSpell: Files checked: 1494, Issues found: 0 in 0 files. $ pnpm --filter website exec vitest run __tests__/lib/mock __tests__/scripts __tests__/lib/api-docs-version.spec.ts Test Files 25 passed (25) Tests 676 passed (676) ``` Swagger UI "Try it out" on the 0.1.0 spec (`GET /common-grants/opportunities`), run locally. The request goes to `/api` with `CG-Version: 0.1.0`: swagger-0 1 0-request The response is served in 0.1.0, with `Vary` and the CORS allow and expose headers: swagger-0 1 0-headers On the 0.6.0 spec the header field pre-fills from the spec example, which #1401 now sets to 0.6.0. --------- Co-authored-by: Bryan Thompson --- .../__tests__/lib/api-docs-version.spec.ts | 97 +++++++ .../lib/mock/__fixtures__/mock-request.ts | 35 +++ .../lib/mock/__fixtures__/request-matrix.ts | 8 + .../lib/mock/golden-envelopes.spec.ts | 66 +++-- .../lib/mock/handlers/applications.spec.ts | 62 ++--- .../lib/mock/handlers/awards.spec.ts | 9 +- .../lib/mock/handlers/competitions.spec.ts | 2 +- .../__tests__/lib/mock/handlers/forms.spec.ts | 12 +- .../lib/mock/handlers/opportunities.spec.ts | 183 +++++-------- .../lib/mock/handlers/organizations.spec.ts | 15 +- .../lib/mock/handlers/sdk-envelope.spec.ts | 16 +- website/__tests__/lib/mock/http/cors.spec.ts | 132 +++++++-- .../__tests__/lib/mock/http/version.spec.ts | 170 ++++++++++++ website/__tests__/lib/mock/router.spec.ts | 133 ++------- .../lib/mock/version-routing.spec.ts | 259 ++++++++++++++++++ .../lib/mock/versions-discovery.spec.ts | 193 +++++++++++++ .../scripts/inject-mock-server.spec.ts | 25 +- .../governance/adr/0028-mock-api-hosting.md | 4 + website/src/lib/api-docs-version.ts | 44 +++ website/src/lib/mock/data/availability.ts | 11 +- website/src/lib/mock/data/fixtures.ts | 12 + website/src/lib/mock/docs-wiring.ts | 9 +- website/src/lib/mock/handlers/applications.ts | 30 +- website/src/lib/mock/handlers/awards.ts | 6 +- website/src/lib/mock/handlers/competitions.ts | 2 +- website/src/lib/mock/handlers/forms.ts | 4 +- .../src/lib/mock/handlers/opportunities.ts | 6 +- .../src/lib/mock/handlers/organizations.ts | 12 +- website/src/lib/mock/handlers/versions.ts | 86 ++++++ website/src/lib/mock/http/cors.ts | 21 +- website/src/lib/mock/http/envelope.ts | 15 + website/src/lib/mock/http/version.ts | 154 +++++++++++ website/src/lib/mock/router.ts | 189 +++++++------ website/src/pages/protocol/api-docs.astro | 20 +- website/src/scripts/inject-mock-server.ts | 9 +- 35 files changed, 1574 insertions(+), 477 deletions(-) create mode 100644 website/__tests__/lib/api-docs-version.spec.ts create mode 100644 website/__tests__/lib/mock/__fixtures__/mock-request.ts create mode 100644 website/__tests__/lib/mock/http/version.spec.ts create mode 100644 website/__tests__/lib/mock/version-routing.spec.ts create mode 100644 website/__tests__/lib/mock/versions-discovery.spec.ts create mode 100644 website/src/lib/mock/handlers/versions.ts create mode 100644 website/src/lib/mock/http/version.ts diff --git a/website/__tests__/lib/api-docs-version.spec.ts b/website/__tests__/lib/api-docs-version.spec.ts new file mode 100644 index 000000000..907bdd48f --- /dev/null +++ b/website/__tests__/lib/api-docs-version.spec.ts @@ -0,0 +1,97 @@ +/** + * Tests for `withVersionHeader` in `src/lib/api-docs-version.ts` (ADR 0032): + * Swagger UI sends the selected version as the `CG-Version` header on mock + * API requests only. + */ + +import { describe, it, expect } from "vitest"; +import { withVersionHeader } from "@/lib/api-docs-version"; + +/** Swagger UI requests carry string headers keyed by name. */ +const noHeaders = (): Record => ({}); + +const options = { + version: "0.5.0", + basePath: "/api", + header: "CG-Version", + origin: "https://docs.example", +}; + +describe("withVersionHeader", () => { + it("sets the version header on a same-origin mock API request", () => { + const result = withVersionHeader( + { + url: "https://docs.example/api/common-grants/opportunities", + headers: noHeaders(), + }, + options, + ); + + expect(result.headers["CG-Version"]).toBe("0.5.0"); + }); + + it("resolves a relative URL against the origin", () => { + const result = withVersionHeader( + { url: "/api/common-grants/opportunities", headers: noHeaders() }, + options, + ); + + expect(result.headers["CG-Version"]).toBe("0.5.0"); + }); + + it.each(["CG-Version", "cg-version"])( + "keeps a user-entered %s value without adding a second key", + (key) => { + const result = withVersionHeader( + { + url: "https://docs.example/api/common-grants/opportunities", + headers: { [key]: "0.1.0" }, + }, + options, + ); + + expect(result.headers).toEqual({ [key]: "0.1.0" }); + }, + ); + + it("treats an empty existing value as missing", () => { + const result = withVersionHeader( + { + url: "https://docs.example/api/common-grants/opportunities", + headers: { "CG-Version": "" }, + }, + options, + ); + + expect(result.headers["CG-Version"]).toBe("0.5.0"); + }); + + it.each([ + "https://docs.example/openapi-mock/openapi.0.5.0.yaml", + "https://other.example/api/common-grants/opportunities", + "https://docs.example/apiary", + ])("does not add the header to non-mock URL %s", (url) => { + const result = withVersionHeader({ url, headers: noHeaders() }, options); + + expect(result.headers).toEqual({}); + }); + + it("returns the request with every other field unchanged", () => { + const result = withVersionHeader( + { + url: "https://docs.example/api/common-grants/opportunities", + headers: { Accept: "application/json" }, + method: "POST", + body: '{"a":1}', + }, + options, + ); + + expect(result).toEqual({ + url: "https://docs.example/api/common-grants/opportunities", + headers: { Accept: "application/json", "CG-Version": "0.5.0" }, + method: "POST", + body: '{"a":1}', + }); + }); +}); diff --git a/website/__tests__/lib/mock/__fixtures__/mock-request.ts b/website/__tests__/lib/mock/__fixtures__/mock-request.ts new file mode 100644 index 000000000..9c9ef9120 --- /dev/null +++ b/website/__tests__/lib/mock/__fixtures__/mock-request.ts @@ -0,0 +1,35 @@ +/** + * Builds requests for the mock as a client would send them under ADR 0032: + * the path carries no version, and `CG-Version` selects one. + */ + +import { MOCK_API_BASE_PATH } from "@/lib/mock/router"; +import { VERSION_HEADER } from "@/lib/mock/http/version"; + +/** `https://docs.example/api/common-grants{path}`; the host is a placeholder. */ +export function mockUrl(path: string): string { + return `https://docs.example${MOCK_API_BASE_PATH}/common-grants${path}`; +} + +/** + * A request for `path` (below `/common-grants`) that sends `version` as + * `CG-Version`, or no header when `version` is `undefined`. + */ +export function mockRequest( + path: string, + version: string | undefined, + init: RequestInit = {}, +): Request { + const headers = new Headers(init.headers); + if (version !== undefined) headers.set(VERSION_HEADER, version); + return new Request(mockUrl(path), { ...init, headers }); +} + +/** A request for `/opportunities{suffix}` served in `version`. */ +export function opportunitiesRequest( + version: string | undefined, + suffix = "", + init?: RequestInit, +): Request { + return mockRequest(`/opportunities${suffix}`, version, init); +} diff --git a/website/__tests__/lib/mock/__fixtures__/request-matrix.ts b/website/__tests__/lib/mock/__fixtures__/request-matrix.ts index d774d51ff..1e8e1cdd5 100644 --- a/website/__tests__/lib/mock/__fixtures__/request-matrix.ts +++ b/website/__tests__/lib/mock/__fixtures__/request-matrix.ts @@ -25,6 +25,12 @@ export interface MatrixCase { * do). The spec re-inserts the `/api` base into the golden text for those. */ pathEchoing?: boolean; + /** + * Set when this site answers differently on purpose: the Worker's 404 for a + * bad path version became a version error under ADR 0032 (#1393). The golden + * spec checks the status instead of the bytes; the Worker capture ignores it. + */ + siteStatus?: number; } /** `/v{version}/common-grants/opportunities` + optional suffix. */ @@ -187,11 +193,13 @@ const edgeCases: MatrixCase[] = [ name: "version-unsupported", method: "GET", path: opportunities("9.9.9"), + siteStatus: 406, }, { name: "version-malformed", method: "GET", path: "/vabc/common-grants/opportunities", + siteStatus: 400, }, // --- route misses (these quote the request path back; see `pathEchoing`) --- diff --git a/website/__tests__/lib/mock/golden-envelopes.spec.ts b/website/__tests__/lib/mock/golden-envelopes.spec.ts index d108fcf6a..0423c5060 100644 --- a/website/__tests__/lib/mock/golden-envelopes.spec.ts +++ b/website/__tests__/lib/mock/golden-envelopes.spec.ts @@ -1,6 +1,7 @@ import { describe, it, expect } from "vitest"; import { MOCK_API_BASE_PATH, handleMockRequest } from "@/lib/mock/router"; -import { REQUEST_MATRIX } from "./__fixtures__/request-matrix"; +import { VERSION_HEADER } from "@/lib/mock/http/version"; +import { REQUEST_MATRIX, type MatrixCase } from "./__fixtures__/request-matrix"; import goldenEnvelopesJson from "./__fixtures__/golden-envelopes.json"; import type { GoldenEnvelope } from "./__fixtures__/capture-golden"; @@ -19,6 +20,36 @@ import type { GoldenEnvelope } from "./__fixtures__/capture-golden"; const GOLDEN_ENVELOPES: Record = goldenEnvelopesJson; +const PINNED_CASES = REQUEST_MATRIX.filter((c) => c.siteStatus === undefined); +const DIVERGENT_CASES = REQUEST_MATRIX.filter( + (c) => c.siteStatus !== undefined, +); + +/** Matrix paths carry `/v{version}`; this site takes it as `CG-Version`. */ +const PATH_VERSION = /^\/v([^/]+)(\/common-grants.*)$/; + +function siteRequest(testCase: MatrixCase): { + request: Request; + unversionedPath: string; +} { + const match = PATH_VERSION.exec(testCase.path); + if (!match) throw new Error(`Matrix path has no version: ${testCase.path}`); + const [, version, unversionedPath] = match; + + const headers = new Headers({ [VERSION_HEADER]: version }); + if (testCase.body !== undefined) { + headers.set("Content-Type", "application/json"); + } + + return { + unversionedPath, + request: new Request( + `https://docs.example${MOCK_API_BASE_PATH}${unversionedPath}`, + { method: testCase.method, body: testCase.body, headers }, + ), + }; +} + describe("golden envelope byte-identity", () => { it("has a golden entry for every REQUEST_MATRIX case", () => { const missing = REQUEST_MATRIX.map((testCase) => testCase.name).filter( @@ -39,22 +70,11 @@ describe("golden envelope byte-identity", () => { expect(orphans).toEqual([]); }); - it.each(REQUEST_MATRIX)( + it.each(PINNED_CASES)( "matches the 3A Worker's response for $name", async (testCase) => { const golden = GOLDEN_ENVELOPES[testCase.name]; - - const request = new Request( - `https://docs.example${MOCK_API_BASE_PATH}${testCase.path}`, - { - method: testCase.method, - body: testCase.body, - headers: - testCase.body === undefined - ? undefined - : { "Content-Type": "application/json" }, - }, - ); + const { request, unversionedPath } = siteRequest(testCase); const response = await handleMockRequest(request); const text = await response.text(); @@ -63,11 +83,12 @@ describe("golden envelope byte-identity", () => { expect(response.headers.get("Content-Type")).toBe(golden.contentType); if (testCase.pathEchoing) { - // Route-miss 404s quote the request path, which lacks the `/api` base - // here — re-insert it. Every other case compares with no normalization. + // Route-miss 404s quote the request path. The Worker's carried the + // version and lacked the `/api` base; this site's has the base and no + // version, so rewrite the golden text to match. const expected = golden.body.replace( `${testCase.method} ${testCase.path}`, - `${testCase.method} ${MOCK_API_BASE_PATH}${testCase.path}`, + `${testCase.method} ${MOCK_API_BASE_PATH}${unversionedPath}`, ); expect(text).toBe(expected); } else { @@ -75,4 +96,15 @@ describe("golden envelope byte-identity", () => { } }, ); + + it.each(DIVERGENT_CASES)( + "answers $name with a version error where the Worker answered 404", + async (testCase) => { + const { request } = siteRequest(testCase); + + const response = await handleMockRequest(request); + + expect(response.status).toBe(testCase.siteStatus); + }, + ); }); diff --git a/website/__tests__/lib/mock/handlers/applications.spec.ts b/website/__tests__/lib/mock/handlers/applications.spec.ts index d66fbeb32..47682efb0 100644 --- a/website/__tests__/lib/mock/handlers/applications.spec.ts +++ b/website/__tests__/lib/mock/handlers/applications.spec.ts @@ -31,18 +31,19 @@ import { } from "@/lib/mock/handlers/applications"; import { getCompetition } from "@/lib/mock/handlers/competitions"; import { getForm } from "@/lib/mock/handlers/forms"; +import { mockUrl } from "../__fixtures__/mock-request"; const VERSION: Version = "0.4.0"; -/** Builds `https://docs.example/api/v{version}/common-grants/applications{suffix}`. */ -function applicationsUrl(version: string, suffix = ""): string { - return `https://docs.example/api/v${version}/common-grants/applications${suffix}`; +/** Builds `https://docs.example/api/common-grants/applications{suffix}`. */ +function applicationsUrl(suffix = ""): string { + return mockUrl(`/applications${suffix}`); } /** POSTs a JSON body to `/applications/start` and returns the raw `Response`. */ function runStart(version: Version, body: unknown): Promise { return startApplication( - new Request(applicationsUrl(version, "/start"), { + new Request(applicationsUrl("/start"), { method: "POST", body: JSON.stringify(body), headers: { "Content-Type": "application/json" }, @@ -54,7 +55,7 @@ function runStart(version: Version, body: unknown): Promise { /** POSTs a JSON body to `/applications/search` and returns the parsed 200 body. */ async function runSearchBody(version: Version, body: unknown) { const response = await searchApplications( - new Request(applicationsUrl(version, "/search"), { + new Request(applicationsUrl("/search"), { method: "POST", body: JSON.stringify(body), headers: { "Content-Type": "application/json" }, @@ -80,7 +81,7 @@ async function runSearchBody(version: Version, body: unknown) { }; } -describe("POST /v{version}/common-grants/applications/start", () => { +describe("POST /common-grants/applications/start", () => { it("returns 201 with the created application echoing the submitted competitionId, title, and the competition's own opportunityId", async () => { const competition = COMPETITION_FIXTURES.find( (c) => c.id === CANONICAL_COMPETITION_ID, @@ -243,7 +244,7 @@ describe("POST /v{version}/common-grants/applications/start", () => { it("returns 400 'Malformed JSON body' for a malformed JSON body", async () => { const response = await startApplication( - new Request(applicationsUrl(VERSION, "/start"), { + new Request(applicationsUrl("/start"), { method: "POST", body: "{not valid json", headers: { "Content-Type": "application/json" }, @@ -259,7 +260,7 @@ describe("POST /v{version}/common-grants/applications/start", () => { }); }); -describe("GET /v{version}/common-grants/applications/{appId} (detail)", () => { +describe("GET /common-grants/applications/{appId} (detail)", () => { it("returns 200 for the id Swagger UI pre-fills into every path parameter box", async () => { const response = getApplication(CANONICAL_APPLICATION_ID, VERSION); @@ -300,7 +301,7 @@ describe("GET /v{version}/common-grants/applications/{appId} (detail)", () => { }); }); -describe("PUT /v{version}/common-grants/applications/{appId}/submit", () => { +describe("PUT /common-grants/applications/{appId}/submit", () => { it("returns 200 for an application with no validation errors", async () => { const response = await submitApplication(CANONICAL_APPLICATION_ID, VERSION); @@ -387,7 +388,7 @@ describe("PUT /v{version}/common-grants/applications/{appId}/submit", () => { }); }); -describe("POST /v{version}/common-grants/applications/search", () => { +describe("POST /common-grants/applications/search", () => { it("returns 200 with items, paginationInfo, sortInfo, and filterInfo for an empty body", async () => { const body = await runSearchBody(VERSION, {}); @@ -447,7 +448,7 @@ describe("POST /v{version}/common-grants/applications/search", () => { it("returns 400 with a sorting.sortBy field error for an unknown sortBy value", async () => { const response = await searchApplications( - new Request(applicationsUrl(VERSION, "/search"), { + new Request(applicationsUrl("/search"), { method: "POST", body: JSON.stringify({ sorting: { sortBy: "not_a_real_sort_field" }, @@ -475,7 +476,6 @@ describe("POST /v{version}/common-grants/applications/search", () => { const viaQueryResponse = await searchApplications( new Request( applicationsUrl( - VERSION, `/search?filters=${encodeURIComponent(JSON.stringify(filters))}`, ), { method: "POST" }, @@ -503,7 +503,7 @@ describe("POST /v{version}/common-grants/applications/search", () => { /** POSTs to `/search?{query}` with no body and returns the raw response. */ function runSearchQuery(query: string): Promise { return searchApplications( - new Request(applicationsUrl(VERSION, `/search?${query}`), { + new Request(applicationsUrl(`/search?${query}`), { method: "POST", }), VERSION, @@ -543,7 +543,6 @@ describe("POST /v{version}/common-grants/applications/search", () => { const response = await searchApplications( new Request( applicationsUrl( - VERSION, `/search?filters=${encodeURIComponent(JSON.stringify(fromQuery))}`, ), { @@ -582,31 +581,9 @@ describe("POST /v{version}/common-grants/applications/search", () => { expect(body.items.length).toBeLessThan(APPLICATION_FIXTURES.length); }); }); - - it("returns 404 with the protocol Error shape at v0.2, since searchApplications is v0.3+ while its siblings are v0.2+", async () => { - const response = await searchApplications( - new Request(applicationsUrl("0.2.0", "/search"), { - method: "POST", - body: JSON.stringify({}), - headers: { "Content-Type": "application/json" }, - }), - "0.2.0", - ); - - expect(response.status).toBe(404); - - const body = (await response.json()) as { - status: number; - message: string; - errors: unknown[]; - }; - expect(body.status).toBe(404); - expect(typeof body.message).toBe("string"); - expect(Array.isArray(body.errors)).toBe(true); - }); }); -describe("GET /v{version}/common-grants/applications/{appId}/forms/{formId} (read)", () => { +describe("GET /common-grants/applications/{appId}/forms/{formId} (read)", () => { it("resolves the doubly pre-filled (appId, formId) pair Swagger UI arrives with", async () => { expect(canonicalPrefillResolves()).toBe(true); @@ -697,7 +674,7 @@ describe("form answers across the v0.5 form title", () => { }); }); -describe("PUT /v{version}/common-grants/applications/{appId}/forms/{formId} (write)", () => { +describe("PUT /common-grants/applications/{appId}/forms/{formId} (write)", () => { it("echoes the submitted response body under data.response, with formId/applicationId set from the path", async () => { const responseBody = { name: { first: "Taylor", last: "Reyes" }, @@ -709,7 +686,6 @@ describe("PUT /v{version}/common-grants/applications/{appId}/forms/{formId} (wri CANONICAL_FORM_ID, new Request( applicationsUrl( - VERSION, `/${CANONICAL_APPLICATION_ID}/forms/${CANONICAL_FORM_ID}`, ), { @@ -745,7 +721,6 @@ describe("PUT /v{version}/common-grants/applications/{appId}/forms/{formId} (wri CANONICAL_FORM_ID, new Request( applicationsUrl( - VERSION, `/${CANONICAL_APPLICATION_ID}/forms/${CANONICAL_FORM_ID}`, ), { @@ -779,7 +754,6 @@ describe("PUT /v{version}/common-grants/applications/{appId}/forms/{formId} (wri const buildRequest = () => new Request( applicationsUrl( - VERSION, `/${CANONICAL_APPLICATION_ID}/forms/${CANONICAL_FORM_ID}`, ), { @@ -815,7 +789,6 @@ describe("PUT /v{version}/common-grants/applications/{appId}/forms/{formId} (wri CANONICAL_FORM_ID, new Request( applicationsUrl( - VERSION, `/${CANONICAL_APPLICATION_ID}/forms/${CANONICAL_FORM_ID}`, ), { @@ -839,10 +812,7 @@ describe("PUT /v{version}/common-grants/applications/{appId}/forms/{formId} (wri RESERVED_MISSING_ID, CANONICAL_FORM_ID, new Request( - applicationsUrl( - VERSION, - `/${RESERVED_MISSING_ID}/forms/${CANONICAL_FORM_ID}`, - ), + applicationsUrl(`/${RESERVED_MISSING_ID}/forms/${CANONICAL_FORM_ID}`), { method: "PUT", body: JSON.stringify({}), diff --git a/website/__tests__/lib/mock/handlers/awards.spec.ts b/website/__tests__/lib/mock/handlers/awards.spec.ts index d7501088f..b1694d347 100644 --- a/website/__tests__/lib/mock/handlers/awards.spec.ts +++ b/website/__tests__/lib/mock/handlers/awards.spec.ts @@ -13,13 +13,14 @@ import { import { listAwards, getAward, searchAwards } from "@/lib/mock/handlers/awards"; import { CANONICAL_RECORD_ID, RESERVED_MISSING_ID } from "@/lib/mock/data/ids"; import { OPPORTUNITY_FIXTURES } from "@/lib/mock/data/fixtures"; +import { mockUrl } from "../__fixtures__/mock-request"; const VERSION = "0.4.0"; const STATUS_VALUES = ["awarded", "completed", "cancelled", "custom"]; /** Builds a request URL; the host/base path are placeholders. */ function awardsUrl(suffix = ""): string { - return `https://docs.example/api/v${VERSION}/common-grants/awards${suffix}`; + return mockUrl(`/awards${suffix}`); } describe("AWARD_FIXTURES", () => { @@ -85,7 +86,7 @@ describe("getAwardById", () => { }); }); -describe("GET /v{version}/common-grants/awards (list)", () => { +describe("GET /common-grants/awards (list)", () => { it("returns a 200 with the protocol paginated envelope, ordered by lastModifiedAt descending by default", async () => { const response = listAwards(new Request(awardsUrl()), VERSION); @@ -153,7 +154,7 @@ describe("GET /v{version}/common-grants/awards (list)", () => { }); }); -describe("GET /v{version}/common-grants/awards/{awdId} (detail)", () => { +describe("GET /common-grants/awards/{awdId} (detail)", () => { it("returns 200 for the id Swagger UI pre-fills into every path parameter box", async () => { const response = getAward(CANONICAL_AWARD_ID, VERSION); @@ -233,7 +234,7 @@ describe("GET /v{version}/common-grants/awards/{awdId} (detail)", () => { }); }); -describe("POST /v{version}/common-grants/awards/search", () => { +describe("POST /common-grants/awards/search", () => { async function runSearch(body: unknown) { const response = await searchAwards( new Request(awardsUrl("/search"), { diff --git a/website/__tests__/lib/mock/handlers/competitions.spec.ts b/website/__tests__/lib/mock/handlers/competitions.spec.ts index e0b27373f..54d8cff6c 100644 --- a/website/__tests__/lib/mock/handlers/competitions.spec.ts +++ b/website/__tests__/lib/mock/handlers/competitions.spec.ts @@ -50,7 +50,7 @@ describe("COMPETITION_FIXTURES", () => { }); }); -describe("GET /v{version}/common-grants/competitions/{compId} (detail)", () => { +describe("GET /common-grants/competitions/{compId} (detail)", () => { it("returns 200 for the id Swagger UI pre-fills into every path parameter box", async () => { const response = getCompetition(CANONICAL_COMPETITION_ID, VERSION); diff --git a/website/__tests__/lib/mock/handlers/forms.spec.ts b/website/__tests__/lib/mock/handlers/forms.spec.ts index 4be0eaea2..d9dc49d77 100644 --- a/website/__tests__/lib/mock/handlers/forms.spec.ts +++ b/website/__tests__/lib/mock/handlers/forms.spec.ts @@ -12,12 +12,13 @@ import { import { listForms, getForm } from "@/lib/mock/handlers/forms"; import { RESERVED_MISSING_ID } from "@/lib/mock/data/ids"; import type { Version } from "@/lib/mock/data/fixtures"; +import { mockUrl } from "../__fixtures__/mock-request"; const VERSION: Version = "0.4.0"; /** Builds a request URL; the host/base path are placeholders. */ function formsUrl(suffix = ""): string { - return `https://docs.example/api/v${VERSION}/common-grants/forms${suffix}`; + return mockUrl(`/forms${suffix}`); } describe("FORM_FIXTURES", () => { @@ -45,7 +46,7 @@ describe("FORM_FIXTURES", () => { }); }); -describe("GET /v{version}/common-grants/forms (list)", () => { +describe("GET /common-grants/forms (list)", () => { it("returns a 200 with the protocol paginated envelope, ordered by lastModifiedAt descending by default", async () => { const response = listForms(new Request(formsUrl()), VERSION); @@ -148,7 +149,7 @@ describe("GET /v{version}/common-grants/forms (list)", () => { }); }); -describe("GET /v{version}/common-grants/forms/{formId} (detail)", () => { +describe("GET /common-grants/forms/{formId} (detail)", () => { it("returns 200 for the id Swagger UI pre-fills into every path parameter box", async () => { const response = getForm(CANONICAL_FORM_ID, VERSION); @@ -215,10 +216,7 @@ describe("forms per protocol version", () => { const pristine = structuredClone(FORM_FIXTURES); async function listAt(version: Version) { - const response = listForms( - new Request(`https://docs.example/api/v${version}/common-grants/forms`), - version, - ); + const response = listForms(new Request(mockUrl("/forms")), version); expect(response.status).toBe(200); return ((await response.json()) as { items: Record[] }) .items; diff --git a/website/__tests__/lib/mock/handlers/opportunities.spec.ts b/website/__tests__/lib/mock/handlers/opportunities.spec.ts index 65d990fb3..5ef0cdb78 100644 --- a/website/__tests__/lib/mock/handlers/opportunities.spec.ts +++ b/website/__tests__/lib/mock/handlers/opportunities.spec.ts @@ -11,20 +11,14 @@ import { RESERVED_MISSING_OPPORTUNITY_ID, type Version, } from "@/lib/mock/data/fixtures"; +import { opportunitiesRequest } from "../__fixtures__/mock-request"; const VERSIONS: Version[] = ["0.1.0", "0.2.0", "0.3.0", "0.4.0"]; -/** Builds `https://docs.example/api/v{version}/common-grants/opportunities{suffix}`. */ -function opportunitiesUrl(version: string, suffix = ""): string { - return `https://docs.example/api/v${version}/common-grants/opportunities${suffix}`; -} - describe("opportunities routes", () => { - describe("GET /v{version}/common-grants/opportunities (list)", () => { + describe("GET /common-grants/opportunities (list)", () => { it("returns a 200 with all fixtures sorted by lastModifiedAt descending and default pagination", async () => { - const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0")), - ); + const response = await handleMockRequest(opportunitiesRequest("0.3.0")); expect(response.status).toBe(200); @@ -64,7 +58,7 @@ describe("opportunities routes", () => { it("returns an empty items array with valid paginationInfo when page is past the end", async () => { const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0", "?page=999")), + opportunitiesRequest("0.3.0", "?page=999"), ); expect(response.status).toBe(200); @@ -92,7 +86,7 @@ describe("opportunities routes", () => { it("honors a pageSize above the default, since the spec declares no maximum", async () => { const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0", "?pageSize=9999")), + opportunitiesRequest("0.3.0", "?pageSize=9999"), ); expect(response.status).toBe(200); @@ -113,7 +107,7 @@ describe("opportunities routes", () => { "returns 400 with the protocol Error shape when %s=%s falls below the spec minimum", async (param, value) => { const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0", `?${param}=${value}`)), + opportunitiesRequest("0.3.0", `?${param}=${value}`), ); expect(response.status).toBe(400); @@ -134,7 +128,7 @@ describe("opportunities routes", () => { it("returns 400 when a pagination param is present but not an integer", async () => { const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0", "?pageSize=abc")), + opportunitiesRequest("0.3.0", "?pageSize=abc"), ); expect(response.status).toBe(400); @@ -149,9 +143,7 @@ describe("opportunities routes", () => { }); it("applies both spec defaults when the pagination params are omitted entirely", async () => { - const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0")), - ); + const response = await handleMockRequest(opportunitiesRequest("0.3.0")); expect(response.status).toBe(200); @@ -164,7 +156,7 @@ describe("opportunities routes", () => { }); }); - describe("GET /v{version}/common-grants/opportunities/{oppId} (detail)", () => { + describe("GET /common-grants/opportunities/{oppId} (detail)", () => { // A fixture that carries `competitions` (detail-only field), so the // list/detail shape tests can't pass by accident. const STEM_ID = "573525f2-8e15-4405-83fb-e6523511d893"; @@ -175,9 +167,7 @@ describe("opportunities routes", () => { "answers 200 for the id Swagger UI pre-fills, for v%s", async (version) => { const response = await handleMockRequest( - new Request( - opportunitiesUrl(version, `/${CANONICAL_OPPORTUNITY_ID}`), - ), + opportunitiesRequest(version, `/${CANONICAL_OPPORTUNITY_ID}`), ); expect(response.status).toBe(200); @@ -196,11 +186,9 @@ describe("opportunities routes", () => { // regard to case, so the uppercase form must reach the same record. it("answers 200 for the uppercase form of a stored id", async () => { const response = await handleMockRequest( - new Request( - opportunitiesUrl( - "0.3.0", - `/${CANONICAL_OPPORTUNITY_ID.toUpperCase()}`, - ), + opportunitiesRequest( + "0.3.0", + `/${CANONICAL_OPPORTUNITY_ID.toUpperCase()}`, ), ); @@ -213,7 +201,7 @@ describe("opportunities routes", () => { it("echoes the requested oppId and matches the list item's shared fields, while adding the detail-only competitions field", async () => { const listResponse = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0")), + opportunitiesRequest("0.3.0"), ); const listBody = (await listResponse.json()) as { @@ -225,7 +213,7 @@ describe("opportunities routes", () => { expect(listItem).not.toHaveProperty("competitions"); const detailResponse = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0", `/${STEM_ID}`)), + opportunitiesRequest("0.3.0", `/${STEM_ID}`), ); expect(detailResponse.status).toBe(200); @@ -249,9 +237,7 @@ describe("opportunities routes", () => { "returns 404 with the protocol Error shape for a well-formed but unknown UUID, for v%s", async (version) => { const response = await handleMockRequest( - new Request( - opportunitiesUrl(version, `/${RESERVED_MISSING_OPPORTUNITY_ID}`), - ), + opportunitiesRequest(version, `/${RESERVED_MISSING_OPPORTUNITY_ID}`), ); expect(response.status).toBe(404); @@ -274,7 +260,7 @@ describe("opportunities routes", () => { "returns 400 with a field-level validation error for a malformed (non-UUID) oppId, for v%s", async (version) => { const response = await handleMockRequest( - new Request(opportunitiesUrl(version, "/not-a-uuid")), + opportunitiesRequest(version, "/not-a-uuid"), ); expect(response.status).toBe(400); @@ -300,7 +286,7 @@ describe("opportunities routes", () => { it("omits competitions and acceptedApplicantTypes from a v0.1 detail response", async () => { const response = await handleMockRequest( - new Request(opportunitiesUrl("0.1.0", `/${STEM_ID}`)), + opportunitiesRequest("0.1.0", `/${STEM_ID}`), ); expect(response.status).toBe(200); @@ -319,7 +305,7 @@ describe("opportunities routes", () => { // #1220-T4: `OpportunityBase.funders` is `@added(v0_5)`. it("includes funders in the 0.5.0 list and detail responses for a record known to have it, and omits it at 0.4.0", async () => { const listResponse050 = await handleMockRequest( - new Request(opportunitiesUrl("0.5.0")), + opportunitiesRequest("0.5.0"), ); const listBody050 = (await listResponse050.json()) as { items: Array & { id: string }>; @@ -331,7 +317,7 @@ describe("opportunities routes", () => { expect(listItem050).toHaveProperty("funders"); const detailResponse050 = await handleMockRequest( - new Request(opportunitiesUrl("0.5.0", `/${CANONICAL_OPPORTUNITY_ID}`)), + opportunitiesRequest("0.5.0", `/${CANONICAL_OPPORTUNITY_ID}`), ); const detailBody050 = (await detailResponse050.json()) as { data: Record & { id: string }; @@ -339,7 +325,7 @@ describe("opportunities routes", () => { expect(detailBody050.data).toHaveProperty("funders"); const listResponse040 = await handleMockRequest( - new Request(opportunitiesUrl("0.4.0")), + opportunitiesRequest("0.4.0"), ); const listBody040 = (await listResponse040.json()) as { items: Array & { id: string }>; @@ -351,7 +337,7 @@ describe("opportunities routes", () => { expect(listItem040).not.toHaveProperty("funders"); const detailResponse040 = await handleMockRequest( - new Request(opportunitiesUrl("0.4.0", `/${CANONICAL_OPPORTUNITY_ID}`)), + opportunitiesRequest("0.4.0", `/${CANONICAL_OPPORTUNITY_ID}`), ); const detailBody040 = (await detailResponse040.json()) as { data: Record & { id: string }; @@ -363,7 +349,7 @@ describe("opportunities routes", () => { // and `@added(v0_5)` (like `funders`). it("includes awards in the 0.5.0 detail response only, omitting it from the 0.5.0 list and from 0.4.0 entirely", async () => { const detailResponse050 = await handleMockRequest( - new Request(opportunitiesUrl("0.5.0", `/${CANONICAL_OPPORTUNITY_ID}`)), + opportunitiesRequest("0.5.0", `/${CANONICAL_OPPORTUNITY_ID}`), ); const detailBody050 = (await detailResponse050.json()) as { data: Record & { id: string }; @@ -371,7 +357,7 @@ describe("opportunities routes", () => { expect(detailBody050.data).toHaveProperty("awards"); const listResponse050 = await handleMockRequest( - new Request(opportunitiesUrl("0.5.0")), + opportunitiesRequest("0.5.0"), ); const listBody050 = (await listResponse050.json()) as { items: Array & { id: string }>; @@ -386,7 +372,7 @@ describe("opportunities routes", () => { // Search shapes through the same list variant today, so this pins that // a future handler cannot shape it independently and regress. const searchResponse050 = await handleMockRequest( - new Request(opportunitiesUrl("0.5.0", "/search"), { + opportunitiesRequest("0.5.0", "/search", { method: "POST", body: JSON.stringify({}), headers: { "Content-Type": "application/json" }, @@ -402,7 +388,7 @@ describe("opportunities routes", () => { expect(searchItem050).not.toHaveProperty("awards"); const detailResponse040 = await handleMockRequest( - new Request(opportunitiesUrl("0.4.0", `/${CANONICAL_OPPORTUNITY_ID}`)), + opportunitiesRequest("0.4.0", `/${CANONICAL_OPPORTUNITY_ID}`), ); const detailBody040 = (await detailResponse040.json()) as { data: Record & { id: string }; @@ -410,7 +396,7 @@ describe("opportunities routes", () => { expect(detailBody040.data).not.toHaveProperty("awards"); const listResponse040 = await handleMockRequest( - new Request(opportunitiesUrl("0.4.0")), + opportunitiesRequest("0.4.0"), ); const listBody040 = (await listResponse040.json()) as { items: Array & { id: string }>; @@ -428,10 +414,10 @@ describe("opportunities routes", () => { "returns identical bodies across two calls to the list endpoint for v%s", async (version) => { const responseA = await handleMockRequest( - new Request(opportunitiesUrl(version)), + opportunitiesRequest(version), ); const responseB = await handleMockRequest( - new Request(opportunitiesUrl(version)), + opportunitiesRequest(version), ); const bodyA = await responseA.json(); @@ -447,10 +433,10 @@ describe("opportunities routes", () => { const STEM_ID = "573525f2-8e15-4405-83fb-e6523511d893"; const responseA = await handleMockRequest( - new Request(opportunitiesUrl(version, `/${STEM_ID}`)), + opportunitiesRequest(version, `/${STEM_ID}`), ); const responseB = await handleMockRequest( - new Request(opportunitiesUrl(version, `/${STEM_ID}`)), + opportunitiesRequest(version, `/${STEM_ID}`), ); const bodyA = await responseA.json(); @@ -466,7 +452,7 @@ describe("opportunities routes", () => { const STEM_ID = "573525f2-8e15-4405-83fb-e6523511d893"; const listResponse = await handleMockRequest( - new Request(opportunitiesUrl(version)), + opportunitiesRequest(version), ); const listBody = (await listResponse.json()) as { @@ -476,7 +462,7 @@ describe("opportunities routes", () => { expect(listItem).toBeDefined(); const detailResponse = await handleMockRequest( - new Request(opportunitiesUrl(version, `/${STEM_ID}`)), + opportunitiesRequest(version, `/${STEM_ID}`), ); expect(detailResponse.status).toBe(200); @@ -497,10 +483,10 @@ describe("opportunities routes", () => { ); }); - describe("POST /v{version}/common-grants/opportunities/search", () => { + describe("POST /common-grants/opportunities/search", () => { async function runSearch(version: string, body: unknown) { const response = await handleMockRequest( - new Request(opportunitiesUrl(version, "/search"), { + opportunitiesRequest(version, "/search", { method: "POST", body: JSON.stringify(body), headers: { "Content-Type": "application/json" }, @@ -576,7 +562,7 @@ describe("opportunities routes", () => { "returns 400 with the protocol Error shape for an unknown sortBy value, for v%s", async (version) => { const response = await handleMockRequest( - new Request(opportunitiesUrl(version, "/search"), { + opportunitiesRequest(version, "/search", { method: "POST", body: JSON.stringify({ sorting: { sortBy: "not_a_real_sort_field" }, @@ -630,7 +616,7 @@ describe("opportunities routes", () => { it("returns 400 with the protocol Error shape for a malformed JSON body", async () => { const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0", "/search"), { + opportunitiesRequest("0.3.0", "/search", { method: "POST", body: "{not valid json", headers: { "Content-Type": "application/json" }, @@ -658,7 +644,7 @@ describe("opportunities routes", () => { "returns 400 with the protocol Error shape for the valid-JSON-but-not-an-object body %s", async (rawBody) => { const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0", "/search"), { + opportunitiesRequest("0.3.0", "/search", { method: "POST", body: rawBody, headers: { "Content-Type": "application/json" }, @@ -690,7 +676,7 @@ describe("opportunities routes", () => { "returns 400 with the protocol Error shape when search is %s", async (_label, search) => { const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0", "/search"), { + opportunitiesRequest("0.3.0", "/search", { method: "POST", body: JSON.stringify({ search }), headers: { "Content-Type": "application/json" }, @@ -713,7 +699,7 @@ describe("opportunities routes", () => { // "search" as a non-UUID oppId — same as the #1049 spike. it("answers GET on the search path with the detail handler's 400, as the spike's :oppId pattern did", async () => { const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0", "/search")), + opportunitiesRequest("0.3.0", "/search"), ); expect(response.status).toBe(400); @@ -840,7 +826,7 @@ describe("opportunities routes", () => { it("returns 400 with the protocol Error shape for an unknown filter operator", async () => { const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0", "/search"), { + opportunitiesRequest("0.3.0", "/search", { method: "POST", body: JSON.stringify({ filters: { status: { operator: "contains", value: ["open"] } }, @@ -866,7 +852,7 @@ describe("opportunities routes", () => { it("returns 400 with the protocol Error shape for a status filter whose value is not an array", async () => { const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0", "/search"), { + opportunitiesRequest("0.3.0", "/search", { method: "POST", body: JSON.stringify({ filters: { status: { operator: "in", value: 5 } }, @@ -892,7 +878,7 @@ describe("opportunities routes", () => { it("returns 400 with the protocol Error shape for a range filter with no value", async () => { const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0", "/search"), { + opportunitiesRequest("0.3.0", "/search", { method: "POST", body: JSON.stringify({ filters: { closeDateRange: { operator: "between" } }, @@ -975,7 +961,7 @@ describe("opportunities routes", () => { "returns 400 rather than silently dropping a malformed %s bound", async (field, filter, expectedErrorField) => { const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0", "/search"), { + opportunitiesRequest("0.3.0", "/search", { method: "POST", body: JSON.stringify({ filters: { [field]: filter } }), headers: { "Content-Type": "application/json" }, @@ -1028,7 +1014,7 @@ describe("opportunities routes", () => { it("returns 400 for a body pagination value below the spec minimum", async () => { const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0", "/search"), { + opportunitiesRequest("0.3.0", "/search", { method: "POST", body: JSON.stringify({ pagination: { page: 0, pageSize: -1 } }), headers: { "Content-Type": "application/json" }, @@ -1049,22 +1035,22 @@ describe("opportunities routes", () => { }); }); -describe("version path prefix", () => { +describe("CG-Version header", () => { it.each(VERSIONS)( "resolves the list, detail, and search routes for v%s", async (version) => { const listResponse = await handleMockRequest( - new Request(opportunitiesUrl(version)), + opportunitiesRequest(version), ); expect(listResponse.status).toBe(200); const detailResponse = await handleMockRequest( - new Request(opportunitiesUrl(version, `/${CANONICAL_OPPORTUNITY_ID}`)), + opportunitiesRequest(version, `/${CANONICAL_OPPORTUNITY_ID}`), ); expect(detailResponse.status).toBe(200); const searchResponse = await handleMockRequest( - new Request(opportunitiesUrl(version, "/search"), { + opportunitiesRequest(version, "/search", { method: "POST", body: JSON.stringify({}), headers: { "Content-Type": "application/json" }, @@ -1074,59 +1060,32 @@ describe("version path prefix", () => { }, ); - it("returns 404 with the protocol error envelope for an unsupported version prefix", async () => { - const response = await handleMockRequest( - new Request( - "https://docs.example/api/v9.9.9/common-grants/opportunities", - ), - ); - - expect(response.status).toBe(404); + it("serves the default version when no CG-Version header is sent", async () => { + const response = await handleMockRequest(opportunitiesRequest(undefined)); - const body = (await response.json()) as { - status: number; - message: string; - errors: unknown[]; - }; - - expect(body.status).toBe(404); - expect(typeof body.message).toBe("string"); - expect(Array.isArray(body.errors)).toBe(true); + expect(response.status).toBe(200); + expect(response.headers.get("CG-Version-Served")).toBe("0.6.0"); }); - it("returns 404 with the protocol error envelope when the version prefix is missing entirely", async () => { - const response = await handleMockRequest( - new Request("https://docs.example/api/common-grants/opportunities"), - ); - - expect(response.status).toBe(404); + it.each([ + ["9.9.9", 406], + ["abc", 400], + ])( + "returns a protocol error envelope for the CG-Version value %j (status %i)", + async (version, status) => { + const response = await handleMockRequest(opportunitiesRequest(version)); - const body = (await response.json()) as { - status: number; - message: string; - errors: unknown[]; - }; + expect(response.status).toBe(status); - expect(body.status).toBe(404); - expect(typeof body.message).toBe("string"); - expect(Array.isArray(body.errors)).toBe(true); - }); - - it("returns 404 with the protocol error envelope for a malformed version prefix", async () => { - const response = await handleMockRequest( - new Request("https://docs.example/api/vabc/common-grants/opportunities"), - ); - - expect(response.status).toBe(404); - - const body = (await response.json()) as { - status: number; - message: string; - errors: unknown[]; - }; + const body = (await response.json()) as { + status: number; + message: string; + errors: unknown[]; + }; - expect(body.status).toBe(404); - expect(typeof body.message).toBe("string"); - expect(Array.isArray(body.errors)).toBe(true); - }); + expect(body.status).toBe(status); + expect(typeof body.message).toBe("string"); + expect(Array.isArray(body.errors)).toBe(true); + }, + ); }); diff --git a/website/__tests__/lib/mock/handlers/organizations.spec.ts b/website/__tests__/lib/mock/handlers/organizations.spec.ts index d851e62ba..14b10a926 100644 --- a/website/__tests__/lib/mock/handlers/organizations.spec.ts +++ b/website/__tests__/lib/mock/handlers/organizations.spec.ts @@ -24,15 +24,16 @@ import { } from "@/lib/mock/data/organizations"; import { RESERVED_MISSING_ID } from "@/lib/mock/data/ids"; import type { Version } from "@/lib/mock/data/fixtures"; +import { mockUrl } from "../__fixtures__/mock-request"; const VERSION: Version = "0.4.0"; /** Builds a request URL; the host/base path are placeholders. */ function orgsUrl(suffix = ""): string { - return `https://docs.example/api/v${VERSION}/common-grants/orgs${suffix}`; + return mockUrl(`/orgs${suffix}`); } -describe("GET /v{version}/common-grants/orgs (list)", () => { +describe("GET /common-grants/orgs (list)", () => { it("returns a 200 with the protocol paginated envelope, ordered by name ascending", async () => { const response = listOrganizations(new Request(orgsUrl()), VERSION); @@ -172,7 +173,7 @@ describe("GET /v{version}/common-grants/orgs (list)", () => { }); }); -describe("GET /v{version}/common-grants/orgs/{orgId} (read)", () => { +describe("GET /common-grants/orgs/{orgId} (read)", () => { it("returns 200 for the id Swagger UI pre-fills", async () => { const response = getOrganization( CANONICAL_ORGANIZATION_ID, @@ -281,7 +282,7 @@ describe("GET /v{version}/common-grants/orgs/{orgId} (read)", () => { }); }); -describe("PATCH /v{version}/common-grants/orgs/{orgId} (update)", () => { +describe("PATCH /common-grants/orgs/{orgId} (update)", () => { async function runUpdate(orgId: string, body: unknown) { return updateOrganization( orgId, @@ -492,7 +493,7 @@ describe("PATCH /v{version}/common-grants/orgs/{orgId} (update)", () => { }); }); -describe("POST /v{version}/common-grants/orgs/{orgId}/changes (submit)", () => { +describe("POST /common-grants/orgs/{orgId}/changes (submit)", () => { it("returns 202 with a pending revision and a Location header pointing at the new change", async () => { const response = await submitOrgChange( CANONICAL_ORGANIZATION_ID, @@ -585,7 +586,7 @@ describe("POST /v{version}/common-grants/orgs/{orgId}/changes (submit)", () => { }); }); -describe("GET /v{version}/common-grants/orgs/{orgId}/changes (list changes)", () => { +describe("GET /common-grants/orgs/{orgId}/changes (list changes)", () => { it("returns a 200 paginated envelope of the org's revisions, newest createdAt first", async () => { const expected = revisionsForOrg(CANONICAL_ORGANIZATION_ID); @@ -642,7 +643,7 @@ describe("GET /v{version}/common-grants/orgs/{orgId}/changes (list changes)", () }); }); -describe("GET /v{version}/common-grants/orgs/{orgId}/changes/{changeId} (view change)", () => { +describe("GET /common-grants/orgs/{orgId}/changes/{changeId} (view change)", () => { it("returns 200 echoing the id Swagger UI pre-fills into both path parameter boxes", async () => { const response = getOrgChange( CANONICAL_ORGANIZATION_ID, diff --git a/website/__tests__/lib/mock/handlers/sdk-envelope.spec.ts b/website/__tests__/lib/mock/handlers/sdk-envelope.spec.ts index 6ce80045d..e3819f685 100644 --- a/website/__tests__/lib/mock/handlers/sdk-envelope.spec.ts +++ b/website/__tests__/lib/mock/handlers/sdk-envelope.spec.ts @@ -8,16 +8,12 @@ import { describe, it, expect } from "vitest"; import { handleMockRequest } from "@/lib/mock/router"; import { OPPORTUNITY_FIXTURES } from "@/lib/mock/data/fixtures"; - -/** Builds `https://docs.example/api/v{version}/common-grants/opportunities{suffix}`. */ -function opportunitiesUrl(version: string, suffix = ""): string { - return `https://docs.example/api/v${version}/common-grants/opportunities${suffix}`; -} +import { opportunitiesRequest } from "../__fixtures__/mock-request"; /** Runs a search POST and returns the parsed envelope, asserting a 200 first. */ async function runSearch(body: unknown) { const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0", "/search"), { + opportunitiesRequest("0.3.0", "/search", { method: "POST", body: JSON.stringify(body), headers: { "Content-Type": "application/json" }, @@ -141,7 +137,7 @@ describe("search/list envelope shapes the TS SDK's strict zod schemas depend on" "derives totalPages via Math.ceil(totalItems / pageSize) for pageSize=%i", async (pageSize) => { const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0", `?pageSize=${pageSize}`)), + opportunitiesRequest("0.3.0", `?pageSize=${pageSize}`), ); expect(response.status).toBe(200); @@ -171,7 +167,7 @@ describe("search/list envelope shapes the TS SDK's strict zod schemas depend on" describe("top-level envelope key sets", () => { it("search envelope carries exactly status/message/items/paginationInfo/sortInfo/filterInfo", async () => { const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0", "/search"), { + opportunitiesRequest("0.3.0", "/search", { method: "POST", body: JSON.stringify({}), headers: { "Content-Type": "application/json" }, @@ -195,9 +191,7 @@ describe("search/list envelope shapes the TS SDK's strict zod schemas depend on" }); it("list envelope carries exactly status/message/items/paginationInfo", async () => { - const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0")), - ); + const response = await handleMockRequest(opportunitiesRequest("0.3.0")); expect(response.status).toBe(200); diff --git a/website/__tests__/lib/mock/http/cors.spec.ts b/website/__tests__/lib/mock/http/cors.spec.ts index fae256d08..25fe4bc86 100644 --- a/website/__tests__/lib/mock/http/cors.spec.ts +++ b/website/__tests__/lib/mock/http/cors.spec.ts @@ -12,18 +12,37 @@ import { } from "@/lib/mock/data/fixtures"; import { withCors } from "@/lib/mock/http/cors"; import { withErrorBoundary } from "@/lib/mock/http/envelope"; +import { VERSION_HEADER, VERSION_SERVED_HEADER } from "@/lib/mock/http/version"; +import { + mockRequest, + mockUrl, + opportunitiesRequest, +} from "../__fixtures__/mock-request"; + +const EXPOSED_VERSION_HEADERS = [ + VERSION_SERVED_HEADER, + "Deprecation", + "Sunset", + "Link", +]; + +function exposedHeaders(response: Response): string[] { + return (response.headers.get("Access-Control-Expose-Headers") ?? "") + .split(",") + .map((name) => name.trim().toLowerCase()); +} -/** Builds `https://docs.example/api/v{version}/common-grants/opportunities{suffix}`. */ -function opportunitiesUrl(version: string, suffix = ""): string { - return `https://docs.example/api/v${version}/common-grants/opportunities${suffix}`; +function expectExposesVersionHeaders(response: Response) { + const exposed = exposedHeaders(response); + for (const name of EXPOSED_VERSION_HEADERS) { + expect(exposed).toContain(name.toLowerCase()); + } } describe("CORS", () => { describe("success responses carry Access-Control-Allow-Origin: *", () => { it.each(SUPPORTED_VERSIONS)("list route, for v%s", async (version) => { - const response = await handleMockRequest( - new Request(opportunitiesUrl(version)), - ); + const response = await handleMockRequest(opportunitiesRequest(version)); expect(response.status).toBe(200); expect(response.headers.get("Access-Control-Allow-Origin")).toBe("*"); @@ -31,7 +50,7 @@ describe("CORS", () => { it("detail route", async () => { const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0", `/${CANONICAL_OPPORTUNITY_ID}`)), + opportunitiesRequest("0.3.0", `/${CANONICAL_OPPORTUNITY_ID}`), ); expect(response.status).toBe(200); @@ -40,7 +59,7 @@ describe("CORS", () => { it("search route", async () => { const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0", "/search"), { + opportunitiesRequest("0.3.0", "/search", { method: "POST", body: JSON.stringify({}), headers: { "Content-Type": "application/json" }, @@ -55,7 +74,7 @@ describe("CORS", () => { describe("error responses carry Access-Control-Allow-Origin: * too", () => { it("400 for a malformed (non-UUID) detail oppId", async () => { const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0", "/not-a-uuid")), + opportunitiesRequest("0.3.0", "/not-a-uuid"), ); expect(response.status).toBe(400); @@ -64,9 +83,7 @@ describe("CORS", () => { it("404 for a well-formed but unknown detail oppId", async () => { const response = await handleMockRequest( - new Request( - opportunitiesUrl("0.3.0", `/${RESERVED_MISSING_OPPORTUNITY_ID}`), - ), + opportunitiesRequest("0.3.0", `/${RESERVED_MISSING_OPPORTUNITY_ID}`), ); expect(response.status).toBe(404); @@ -75,7 +92,7 @@ describe("CORS", () => { it("400 for a malformed search request body", async () => { const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0", "/search"), { + opportunitiesRequest("0.3.0", "/search", { method: "POST", body: "{not valid json", headers: { "Content-Type": "application/json" }, @@ -118,9 +135,9 @@ describe("CORS", () => { describe("OPTIONS preflight", () => { const preflightTargets: Array<[string, string]> = [ - ["list", opportunitiesUrl("0.3.0")], - ["detail", opportunitiesUrl("0.3.0", `/${CANONICAL_OPPORTUNITY_ID}`)], - ["search", opportunitiesUrl("0.3.0", "/search")], + ["list", mockUrl("/opportunities")], + ["detail", mockUrl(`/opportunities/${CANONICAL_OPPORTUNITY_ID}`)], + ["search", mockUrl("/opportunities/search")], ["health", "https://docs.example/api/"], ["an unmatched path", "https://docs.example/api/nonexistent"], ]; @@ -150,6 +167,7 @@ describe("CORS", () => { expect(allowHeaders).toContain("content-type"); expect(allowHeaders).toContain("x-api-key"); expect(allowHeaders).toContain("authorization"); + expect(allowHeaders).toContain(VERSION_HEADER.toLowerCase()); const text = await response.text(); expect(text).toBe(""); @@ -158,12 +176,12 @@ describe("CORS", () => { it("answers a browser-shaped preflight (Origin + Access-Control-Request-Method/Headers) the same way", async () => { const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0", "/search"), { + opportunitiesRequest("0.3.0", "/search", { method: "OPTIONS", headers: { Origin: "https://commongrants.org", "Access-Control-Request-Method": "POST", - "Access-Control-Request-Headers": "content-type,x-api-key", + "Access-Control-Request-Headers": "content-type,cg-version", }, }), ); @@ -184,16 +202,88 @@ describe("CORS", () => { expect(allowHeaders).toContain("content-type"); expect(allowHeaders).toContain("x-api-key"); expect(allowHeaders).toContain("authorization"); + expect(allowHeaders).toContain(VERSION_HEADER.toLowerCase()); const text = await response.text(); expect(text).toBe(""); }); }); + describe("non-preflight responses expose the version headers", () => { + it("200 opportunities list", async () => { + const response = await handleMockRequest(opportunitiesRequest("0.3.0")); + + expect(response.status).toBe(200); + expectExposesVersionHeaders(response); + }); + + it("404 route miss", async () => { + const response = await handleMockRequest( + new Request("https://docs.example/api/nonexistent"), + ); + + expect(response.status).toBe(404); + expectExposesVersionHeaders(response); + }); + + it("400 for a malformed version", async () => { + const response = await handleMockRequest( + mockRequest("/opportunities", "v1"), + ); + + expect(response.status).toBe(400); + expectExposesVersionHeaders(response); + }); + + it("406 for an unsupported version", async () => { + const response = await handleMockRequest(mockRequest("/awards", "0.2.0")); + + expect(response.status).toBe(406); + expectExposesVersionHeaders(response); + }); + + it("200 versions discovery route", async () => { + const response = await handleMockRequest( + new Request(mockUrl("/versions")), + ); + + expect(response.status).toBe(200); + expectExposesVersionHeaders(response); + }); + + it("200 health route", async () => { + const response = await handleMockRequest( + new Request("https://docs.example/api/"), + ); + + expect(response.status).toBe(200); + expectExposesVersionHeaders(response); + }); + + it("500 from the error boundary", async () => { + const consoleError = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + try { + const response = withCors( + await withErrorBoundary(() => { + throw new Error("boom"); + }), + ); + + expect(response.status).toBe(500); + expectExposesVersionHeaders(response); + } finally { + consoleError.mockRestore(); + } + }); + }); + describe("SDK auth headers on an actual (non-preflight) request", () => { it("a search request carrying X-API-Key and Authorization still returns 200 with the CORS header", async () => { const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0", "/search"), { + opportunitiesRequest("0.3.0", "/search", { method: "POST", body: JSON.stringify({}), headers: { @@ -210,7 +300,7 @@ describe("CORS", () => { it("a search request with no auth headers (Auth.none()) still returns 200 with the CORS header", async () => { const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0", "/search"), { + opportunitiesRequest("0.3.0", "/search", { method: "POST", body: JSON.stringify({}), headers: { "Content-Type": "application/json" }, @@ -227,7 +317,7 @@ describe("CORS", () => { describe("unexpected failures stay on the CORS path", () => { it("answers a JSON body that is valid but not an object without throwing, and with the CORS header", async () => { const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0", "/search"), { + opportunitiesRequest("0.3.0", "/search", { method: "POST", body: "null", headers: { "Content-Type": "application/json" }, diff --git a/website/__tests__/lib/mock/http/version.spec.ts b/website/__tests__/lib/mock/http/version.spec.ts new file mode 100644 index 000000000..07dc2e198 --- /dev/null +++ b/website/__tests__/lib/mock/http/version.spec.ts @@ -0,0 +1,170 @@ +/** + * `CG-Version` resolution (ADR 0032, #1393): which version a route serves for a + * request header, and the 0.6.0 version errors rendered for a bad one. + */ +import { describe, it, expect } from "vitest"; +import { + DEFAULT_VERSION, + VERSION_HEADER, + resolveRequestedVersion, + type RouteVersions, + type VersionError, +} from "@/lib/mock/http/version"; +import { versionErrorResponse } from "@/lib/mock/http/envelope"; +import { SUPPORTED_VERSIONS } from "@/lib/mock/data/fixtures"; +import { getValidator } from "../conformance/schema-validator"; + +const DISCOVERY = "https://docs.example/api/common-grants/versions"; + +const FULL_ROUTE: RouteVersions = { + label: "GET /common-grants/opportunities", + versions: SUPPORTED_VERSIONS, + defaultVersion: "0.6.0", +}; + +const NARROW_ROUTE: RouteVersions = { + label: "GET /common-grants/awards", + versions: ["0.4.0", "0.5.0", "0.6.0"], + defaultVersion: "0.6.0", +}; + +/** Resolves and returns the error, failing the test if resolution succeeded. */ +function errorFor(header: string | null, route = NARROW_ROUTE): VersionError { + const resolution = resolveRequestedVersion(header, route); + if (!("error" in resolution)) { + throw new Error(`Expected an error for ${JSON.stringify(header)}`); + } + return resolution.error; +} + +describe("resolveRequestedVersion", () => { + it("serves the default version when no header is sent", () => { + expect(resolveRequestedVersion(null, FULL_ROUTE)).toEqual({ + version: DEFAULT_VERSION, + }); + expect(DEFAULT_VERSION).toBe("0.6.0"); + }); + + it("serves the route's own default when no header is sent", () => { + const route = { ...NARROW_ROUTE, defaultVersion: "0.5.0" } as const; + + expect(resolveRequestedVersion(null, route)).toEqual({ version: "0.5.0" }); + }); + + it.each([ + ["0.5.1", "0.5.0"], + [" 0.5.0 ", "0.5.0"], + ["0.6.0", "0.6.0"], + ])("serves the hosted version for %j", (header, expected) => { + expect(resolveRequestedVersion(header, NARROW_ROUTE)).toEqual({ + version: expected, + }); + }); + + describe("version.conflict", () => { + it.each(["0.5.0, 0.6.0", "0.5.0, 0.5.0", "banana, 0.5.0", "0.5.0, "])( + "rejects multiple values %j with 400 and names each value", + (header) => { + const error = errorFor(header); + + expect(error.status).toBe(400); + expect(error.detail.code).toBe("version.conflict"); + for (const value of header.split(",").map((v) => v.trim())) { + expect(error.detail.message).toContain(JSON.stringify(value)); + } + expect(error.detail.field).toBe(VERSION_HEADER); + expect(error.detail).not.toHaveProperty("requested"); + expect(error.detail).not.toHaveProperty("scope"); + expect(error.detail.supported).toEqual(NARROW_ROUTE.versions); + expect(error.detail.defaultVersion).toBe(NARROW_ROUTE.defaultVersion); + }, + ); + }); + + describe("version.malformed", () => { + it.each(["banana", "0.5", "v0.5.0", "00.5.0", ""])( + "rejects %j with 400 and echoes it as sent", + (header) => { + const error = errorFor(header); + + expect(error.status).toBe(400); + expect(error.detail).toMatchObject({ + code: "version.malformed", + requested: header, + }); + expect(error.detail.message).toContain(header); + expect(error.detail.field).toBe(VERSION_HEADER); + expect(error.detail).not.toHaveProperty("scope"); + expect(error.detail.supported).toEqual(NARROW_ROUTE.versions); + expect(error.detail.defaultVersion).toBe(NARROW_ROUTE.defaultVersion); + }, + ); + + it("echoes the value untrimmed", () => { + expect(errorFor(" 0.5 ").detail).toMatchObject({ requested: " 0.5 " }); + }); + }); + + describe("version.unsupported", () => { + it.each(["0.9.0", "1.5.0"])( + "rejects %s with 406 at deployment scope", + (header) => { + const error = errorFor(header); + + expect(error.status).toBe(406); + expect(error.detail).toMatchObject({ + code: "version.unsupported", + scope: "deployment", + requested: header, + }); + expect(error.detail.message).toContain(header); + expect(error.detail.field).toBe(VERSION_HEADER); + expect(error.detail.supported).toEqual(NARROW_ROUTE.versions); + expect(error.detail.defaultVersion).toBe(NARROW_ROUTE.defaultVersion); + }, + ); + + it("rejects a version the mock serves but the route does not, at operation scope", () => { + const error = errorFor("0.2.0"); + + expect(error.status).toBe(406); + expect(error.detail).toMatchObject({ + code: "version.unsupported", + scope: "operation", + requested: "0.2.0", + }); + expect(error.detail.message).toContain("0.2.0"); + expect(error.detail.supported).toEqual(NARROW_ROUTE.versions); + expect(error.detail.defaultVersion).toBe(NARROW_ROUTE.defaultVersion); + }); + }); +}); + +describe("versionErrorResponse for version errors", () => { + it.each([ + ["version.malformed", "banana", "VersionMalformedError.yaml"], + ["version.conflict", "0.5.0, 0.6.0", "VersionConflictError.yaml"], + ["version.unsupported", "0.9.0", "VersionUnsupportedError.yaml"], + ])("renders %s as a schema-valid body", async (code, header, schemaName) => { + const error = errorFor(header); + expect(error.detail.code).toBe(code); + + const response = versionErrorResponse(error, DISCOVERY); + const body = await response.json(); + const { validate, errorText } = getValidator("0.6.0", schemaName, { + requireVersioned: true, + }); + + expect(response.status).toBe(error.status); + expect(body.status).toBe(error.status); + expect(body.errors[0].discovery).toBe(DISCOVERY); + expect(validate(body), errorText()).toBe(true); + }); + + it("omits discovery when no discovery URL is given", async () => { + const response = versionErrorResponse(errorFor("banana")); + const body = await response.json(); + + expect(body.errors[0]).not.toHaveProperty("discovery"); + }); +}); diff --git a/website/__tests__/lib/mock/router.spec.ts b/website/__tests__/lib/mock/router.spec.ts index 350f1de04..051f3eb0b 100644 --- a/website/__tests__/lib/mock/router.spec.ts +++ b/website/__tests__/lib/mock/router.spec.ts @@ -8,16 +8,12 @@ import { describe, it, expect } from "vitest"; import type { APIContext } from "astro"; import { handleMockRequest, MOCK_API_BASE_PATH } from "@/lib/mock/router"; import { SUPPORTED_METHODS } from "@/lib/mock/http/methods"; -import { CANONICAL_OPPORTUNITY_ID } from "@/lib/mock/data/fixtures"; +import { VERSION_SERVED_HEADER } from "@/lib/mock/http/version"; import { CANONICAL_APPLICATION_ID } from "@/lib/mock/data/applications"; import { CANONICAL_FORM_ID } from "@/lib/mock/data/forms"; import { CANONICAL_ORGANIZATION_ID } from "@/lib/mock/data/organizations"; import * as apiRoute from "@/pages/api/[...path]"; - -/** Builds `https://docs.example/api/v{version}/common-grants/opportunities{suffix}`. */ -function opportunitiesUrl(version: string, suffix = ""): string { - return `https://docs.example/api/v${version}/common-grants/opportunities${suffix}`; -} +import { mockRequest, opportunitiesRequest } from "./__fixtures__/mock-request"; describe("MOCK_API_BASE_PATH", () => { it("is the fixed base the router strips off the pathname before matching the Worker's route regex", () => { @@ -33,13 +29,11 @@ describe("Astro route wiring (src/pages/api/[...path].ts)", () => { it("delegates ALL to handleMockRequest untouched, for a real opportunities request", async () => { // The ALL handler only needs `request`; the rest of APIContext is cast away. const context = { - request: new Request(opportunitiesUrl("0.3.0")), + request: opportunitiesRequest("0.3.0"), } as unknown as APIContext; const routed = await apiRoute.ALL(context); - const direct = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0")), - ); + const direct = await handleMockRequest(opportunitiesRequest("0.3.0")); expect(routed.status).toBe(direct.status); expect(await routed.json()).toEqual(await direct.json()); @@ -47,8 +41,7 @@ describe("Astro route wiring (src/pages/api/[...path].ts)", () => { }); describe("method allowlist", () => { - const V = "0.4.0"; - const ORG = `/api/v${V}/common-grants/orgs/${CANONICAL_ORGANIZATION_ID}`; + const ORG = `/api/common-grants/orgs/${CANONICAL_ORGANIZATION_ID}`; /** * One route per supported verb, each chosen because it actually serves that @@ -58,8 +51,8 @@ describe("method allowlist", () => { */ const ROUTE_SERVING: Record = { GET: ORG, - POST: `/api/v${V}/common-grants/opportunities/search`, - PUT: `/api/v${V}/common-grants/applications/${CANONICAL_APPLICATION_ID}/forms/${CANONICAL_FORM_ID}`, + POST: "/api/common-grants/opportunities/search", + PUT: `/api/common-grants/applications/${CANONICAL_APPLICATION_ID}/forms/${CANONICAL_FORM_ID}`, PATCH: ORG, }; @@ -119,6 +112,8 @@ describe("method allowlist", () => { const response = await call(method, ROUTE_SERVING[method]); expect(response.status).not.toBe(404); + // Proves dispatch ran rather than a version error answering first. + expect(response.headers.get(VERSION_SERVED_HEADER)).not.toBeNull(); }, ); @@ -162,7 +157,7 @@ describe("base-path handling (new in the website port, no Worker analogue)", () it("treats a path missing the /api base as a route miss, not the opportunities list", async () => { const response = await handleMockRequest( - new Request("https://docs.example/v0.3.0/common-grants/opportunities"), + new Request("https://docs.example/common-grants/opportunities"), ); expect(response.status).toBe(404); @@ -177,7 +172,7 @@ describe("base-path handling (new in the website port, no Worker analogue)", () // alternative — not re-decided here. it("treats a trailing slash on an opportunities path as a route miss, same as the Worker", async () => { const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0", "/")), + opportunitiesRequest("0.3.0", "/"), ); expect(response.status).toBe(404); @@ -189,73 +184,12 @@ describe("base-path handling (new in the website port, no Worker analogue)", () }); }); -describe("the requested version actually reaches the handler, not merely 200", () => { - it("omits acceptedApplicantTypes from the v0.1.0 list record that carries it in v0.3.0", async () => { - const v01Response = await handleMockRequest( - new Request(opportunitiesUrl("0.1.0")), - ); - const v03Response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0")), - ); - - expect(v01Response.status).toBe(200); - expect(v03Response.status).toBe(200); - - const v01Body = (await v01Response.json()) as { - items: Array & { id: string }>; - }; - const v03Body = (await v03Response.json()) as { - items: Array & { id: string }>; - }; - - const v01Item = v01Body.items.find( - (item) => item.id === CANONICAL_OPPORTUNITY_ID, - ); - const v03Item = v03Body.items.find( - (item) => item.id === CANONICAL_OPPORTUNITY_ID, - ); - - expect(v01Item).toBeDefined(); - expect(v03Item).toBeDefined(); - // If the router dropped `version` and always shaped for one of them, - // this pair would collapse. - expect(v01Item).not.toHaveProperty("acceptedApplicantTypes"); - expect(v03Item).toHaveProperty("acceptedApplicantTypes"); - }); -}); - describe("404 discrimination the ported handler/CORS specs leave at status-level only", () => { - it("flags an unsupported version prefix with field: 'version'", async () => { - const response = await handleMockRequest( - new Request(opportunitiesUrl("9.9.9")), - ); - - expect(response.status).toBe(404); - - const body = (await response.json()) as { - errors: Array<{ field: string; message: string }>; - }; - expect(body.errors[0].field).toBe("version"); - }); - - it("flags a malformed version prefix with field: 'version' too", async () => { - const response = await handleMockRequest( - new Request(opportunitiesUrl("abc")), - ); - - expect(response.status).toBe(404); - - const body = (await response.json()) as { - errors: Array<{ field: string; message: string }>; - }; - expect(body.errors[0].field).toBe("version"); - }); - // `field: "path"` lets a caller tell "this is not a route" from "this // record does not exist". it("flags a path outside the served surface with field: 'path'", async () => { const response = await handleMockRequest( - new Request("https://docs.example/api/v0.4.0/common-grants/proposals"), + new Request("https://docs.example/api/common-grants/proposals"), ); expect(response.status).toBe(404); @@ -267,43 +201,30 @@ describe("404 discrimination the ported handler/CORS specs leave at status-level expect(body.errors[0].message).toContain("No route matches"); }); - it("names the adding version for a resource absent from the requested version", async () => { - const response = await handleMockRequest( - new Request("https://docs.example/api/v0.2.0/common-grants/awards"), - ); - - expect(response.status).toBe(404); - - const body = (await response.json()) as { - errors: Array<{ field: string; message: string }>; - }; - expect(body.errors[0].field).toBe("path"); - expect(body.errors[0].message).toContain("added in v0.4.0"); - }); - - // The gate is driven by the RESOURCE_MIN_VERSION table, so every entry - // should behave alike; only awards was covered. + // Driven by the RESOURCE_MIN_VERSION table, so every entry should behave alike. it.each([ + { resource: "awards", version: "0.2.0", addedIn: "0.4.0" }, { resource: "orgs", version: "0.3.0", addedIn: "0.4.0" }, { resource: "competitions", version: "0.1.0", addedIn: "0.2.0" }, { resource: "applications", version: "0.1.0", addedIn: "0.2.0" }, { resource: "forms", version: "0.1.0", addedIn: "0.2.0" }, ])( - "404s $resource at v$version, naming v$addedIn as the version that added it", + "answers $resource at v$version with an operation-scope version.unsupported listing v$addedIn first", async ({ resource, version, addedIn }) => { const response = await handleMockRequest( - new Request( - `https://docs.example/api/v${version}/common-grants/${resource}`, - ), + mockRequest(`/${resource}`, version), ); - expect(response.status).toBe(404); + expect(response.status).toBe(406); const body = (await response.json()) as { - errors: Array<{ field: string; message: string }>; + errors: Array<{ code: string; scope: string; supported: string[] }>; }; - expect(body.errors[0].field).toBe("path"); - expect(body.errors[0].message).toContain(`added in v${addedIn}`); + expect(body.errors[0]).toMatchObject({ + code: "version.unsupported", + scope: "operation", + }); + expect(body.errors[0].supported[0]).toBe(addedIn); }, ); @@ -320,9 +241,7 @@ describe("404 discrimination the ported handler/CORS specs leave at status-level "answers a bare trailing slash on /%s with a route miss, not a 400", async (resource) => { const response = await handleMockRequest( - new Request( - `https://docs.example/api/v0.4.0/common-grants/${resource}/`, - ), + new Request(`https://docs.example/api/common-grants/${resource}/`), ); expect(response.status).toBe(404); @@ -337,7 +256,7 @@ describe("404 discrimination the ported handler/CORS specs leave at status-level it("answers a path nested deeper than any route with a route miss", async () => { const response = await handleMockRequest( new Request( - "https://docs.example/api/v0.4.0/common-grants/opportunities/foo/bar", + "https://docs.example/api/common-grants/opportunities/foo/bar", ), ); @@ -351,7 +270,7 @@ describe("404 discrimination the ported handler/CORS specs leave at status-level it("flags an unsupported method on an otherwise-valid path with field: 'path'", async () => { const response = await handleMockRequest( - new Request(opportunitiesUrl("0.3.0"), { method: "PUT" }), + mockRequest("/opportunities", "0.3.0", { method: "PUT" }), ); expect(response.status).toBe(404); diff --git a/website/__tests__/lib/mock/version-routing.spec.ts b/website/__tests__/lib/mock/version-routing.spec.ts new file mode 100644 index 000000000..4dc9f2541 --- /dev/null +++ b/website/__tests__/lib/mock/version-routing.spec.ts @@ -0,0 +1,259 @@ +/** + * Pins header-based version selection in the router (#1393-T2, ADR 0032): + * `CG-Version` picks the version, the path never does, and each outcome + * carries (or omits) the served/vary headers as the ADR requires. + */ + +import { describe, it, expect } from "vitest"; +import { handleMockRequest } from "@/lib/mock/router"; +import { + SUPPORTED_VERSIONS, + CANONICAL_OPPORTUNITY_ID, + RESERVED_MISSING_OPPORTUNITY_ID, +} from "@/lib/mock/data/fixtures"; +import { + VERSION_HEADER, + VERSION_SERVED_HEADER, + DEFAULT_VERSION, +} from "@/lib/mock/http/version"; +import { mockRequest } from "./__fixtures__/mock-request"; + +interface ErrorBody { + status: number; + message: string; + errors: Array>; +} + +const JSON_HEADERS = { "Content-Type": "application/json" }; + +describe("version selected by the CG-Version header", () => { + it.each(SUPPORTED_VERSIONS)( + "serves GET /opportunities in %s with the served and Vary headers", + async (version) => { + const response = await handleMockRequest( + mockRequest("/opportunities", version), + ); + + expect(response.status).toBe(200); + expect(response.headers.get(VERSION_SERVED_HEADER)).toBe(version); + expect(response.headers.get("Vary")).toContain(VERSION_HEADER); + }, + ); + + it("serves the default version when no header is sent", async () => { + const response = await handleMockRequest( + mockRequest("/opportunities", undefined), + ); + + expect(response.status).toBe(200); + expect(DEFAULT_VERSION).toBe("0.6.0"); + expect(response.headers.get(VERSION_SERVED_HEADER)).toBe("0.6.0"); + expect(response.headers.get("Vary")).toContain(VERSION_HEADER); + }); + + it("serves the hosted version for a patch that isn't hosted", async () => { + const response = await handleMockRequest( + mockRequest("/opportunities", "0.5.9"), + ); + + expect(response.status).toBe(200); + expect(response.headers.get(VERSION_SERVED_HEADER)).toBe("0.5.0"); + }); + + it("ignores a cg-version query parameter", async () => { + const response = await handleMockRequest( + mockRequest("/opportunities?cg-version=0.5.0", undefined), + ); + + expect(response.status).toBe(200); + expect(response.headers.get(VERSION_SERVED_HEADER)).toBe("0.6.0"); + }); + + it("passes the version to the handler, not merely the header", async () => { + const find = async (version: string) => { + const response = await handleMockRequest( + mockRequest("/opportunities", version), + ); + const body = (await response.json()) as { + items: Array & { id: string }>; + }; + return body.items.find((item) => item.id === CANONICAL_OPPORTUNITY_ID); + }; + + const v01Item = await find("0.1.0"); + const v03Item = await find("0.3.0"); + + expect(v01Item).toBeDefined(); + expect(v03Item).toBeDefined(); + expect(v01Item).not.toHaveProperty("acceptedApplicantTypes"); + expect(v03Item).toHaveProperty("acceptedApplicantTypes"); + }); + + it("marks a record 404 with the served version", async () => { + const response = await handleMockRequest( + mockRequest(`/opportunities/${RESERVED_MISSING_OPPORTUNITY_ID}`, "0.3.0"), + ); + + expect(response.status).toBe(404); + expect(response.headers.get(VERSION_SERVED_HEADER)).toBe("0.3.0"); + expect(response.headers.get("Vary")).toContain(VERSION_HEADER); + }); + + it("marks a body validation 400 with the served version", async () => { + const response = await handleMockRequest( + mockRequest("/opportunities/search", "0.3.0", { + method: "POST", + headers: JSON_HEADERS, + body: "{not json", + }), + ); + + expect(response.status).toBe(400); + expect(response.headers.get(VERSION_SERVED_HEADER)).toBe("0.3.0"); + }); +}); + +describe("a version in the path is not a selector", () => { + it("answers /api/v{x}/common-grants/... with the plain route-miss 404", async () => { + const response = await handleMockRequest( + new Request( + "https://docs.example/api/v0.5.0/common-grants/opportunities", + ), + ); + + expect(response.status).toBe(404); + expect(response.headers.get(VERSION_SERVED_HEADER)).toBeNull(); + + const body = (await response.json()) as ErrorBody; + expect(body.status).toBe(404); + expect(body.message).toBe("Not found"); + expect(body.errors[0].field).toBe("path"); + }); +}); + +describe("a route requested in a version that predates it", () => { + it.each([ + { + name: "awards in 0.2.0", + path: "/awards", + init: {}, + supported: ["0.4.0", "0.5.0", "0.6.0"], + }, + { + name: "application search in 0.2.0", + path: "/applications/search", + init: { method: "POST", headers: JSON_HEADERS, body: "{}" }, + supported: ["0.3.0", "0.4.0", "0.5.0", "0.6.0"], + }, + ])("returns 406 version.unsupported (operation) for $name", async (c) => { + const response = await handleMockRequest( + mockRequest(c.path, "0.2.0", c.init), + ); + + expect(response.status).toBe(406); + expect(response.headers.get(VERSION_SERVED_HEADER)).toBeNull(); + + const body = (await response.json()) as ErrorBody; + expect(body.errors[0]).toMatchObject({ + code: "version.unsupported", + scope: "operation", + requested: "0.2.0", + supported: c.supported, + defaultVersion: "0.6.0", + field: "CG-Version", + }); + }); +}); + +describe("route matching comes before version resolution", () => { + it("returns the plain route-miss 404 for an unknown resource even with a malformed header", async () => { + const response = await handleMockRequest( + mockRequest("/proposals", "banana"), + ); + + expect(response.status).toBe(404); + expect(response.headers.get(VERSION_SERVED_HEADER)).toBeNull(); + + const body = (await response.json()) as ErrorBody; + expect(body.message).toBe("Not found"); + expect(body.errors[0].field).toBe("path"); + }); +}); + +describe("a route miss inside a known resource", () => { + it.each([ + ["/awards", { method: "DELETE" }], + ["/opportunities/foo/bar", {}], + ])( + "answers %s with a 404 that carries the served version and Vary", + async (path, init) => { + const response = await handleMockRequest( + mockRequest(path, "0.5.0", init), + ); + + expect(response.status).toBe(404); + expect(response.headers.get(VERSION_SERVED_HEADER)).toBe("0.5.0"); + expect(response.headers.get("Vary")).toContain(VERSION_HEADER); + }, + ); + + // The accepted gap (PLAN-1393 T2): the version is resolved before the + // router knows the sub-route is missing, so a bad header wins over the 404. + it("answers a malformed header with 400 rather than 404", async () => { + const response = await handleMockRequest( + mockRequest("/awards", "banana", { method: "DELETE" }), + ); + + expect(response.status).toBe(400); + }); +}); + +describe("version errors through the router", () => { + it.each([ + { + header: "banana", + status: 400, + code: "version.malformed", + scope: undefined, + }, + { + header: "0.9.0", + status: 406, + code: "version.unsupported", + scope: "deployment", + }, + { + header: "0.5.0, 0.6.0", + status: 400, + code: "version.conflict", + scope: undefined, + }, + ])( + "answers CG-Version: $header with $status $code", + async ({ header, status, code, scope }) => { + const response = await handleMockRequest( + mockRequest("/opportunities", header), + ); + + expect(response.status).toBe(status); + expect(response.headers.get(VERSION_SERVED_HEADER)).toBeNull(); + expect(response.headers.get("Vary")).toContain(VERSION_HEADER); + expect(response.headers.get("Access-Control-Allow-Origin")).toBe("*"); + + const body = (await response.json()) as ErrorBody; + expect(body.errors[0].code).toBe(code); + if (scope) expect(body.errors[0].scope).toBe(scope); + }, + ); +}); + +describe("health route", () => { + it("stays 200 and unversioned", async () => { + const response = await handleMockRequest( + new Request("https://docs.example/api"), + ); + + expect(response.status).toBe(200); + expect(response.headers.get(VERSION_SERVED_HEADER)).toBeNull(); + }); +}); diff --git a/website/__tests__/lib/mock/versions-discovery.spec.ts b/website/__tests__/lib/mock/versions-discovery.spec.ts new file mode 100644 index 000000000..897f7ff64 --- /dev/null +++ b/website/__tests__/lib/mock/versions-discovery.spec.ts @@ -0,0 +1,193 @@ +/** + * The versions discovery route (ADR 0032, #1393-T3): `GET /common-grants/versions` + * lists what the mock serves, ignores `CG-Version`, and is the target of the + * `discovery` URL on every version error. + */ +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { describe, it, expect } from "vitest"; +import yaml from "js-yaml"; +import { handleMockRequest } from "@/lib/mock/router"; +import { VERSION_HEADER, VERSION_SERVED_HEADER } from "@/lib/mock/http/version"; +import { SUPPORTED_VERSIONS } from "@/lib/mock/data/fixtures"; +import { getValidator } from "./conformance/schema-validator"; +import { mockRequest, mockUrl } from "./__fixtures__/mock-request"; + +const DISCOVERY = "https://docs.example/api/common-grants/versions"; + +interface OperationEntry { + versions: string[]; + defaultVersion: string; +} + +interface Discovery { + versions: string[]; + defaultVersion: string; + operations: Record; +} + +async function fetchDiscovery(version?: string) { + const response = await handleMockRequest(mockRequest("/versions", version)); + return { response, body: await response.json() }; +} + +describe("GET /common-grants/versions", () => { + it("returns the success envelope with a VersionDiscovery", async () => { + const { response, body } = await fetchDiscovery(); + + expect(response.status).toBe(200); + expect(body).toMatchObject({ status: 200, message: "Success" }); + const data: Discovery = body.data; + expect(data.versions).toEqual(SUPPORTED_VERSIONS); + expect(data.defaultVersion).toBe("0.6.0"); + expect(typeof data.operations).toBe("object"); + }); + + it("validates against the 0.6.0 VersionDiscovery schema", async () => { + const { body } = await fetchDiscovery(); + const { validate, errorText } = getValidator( + "0.6.0", + "VersionDiscovery.yaml", + { requireVersioned: true }, + ); + + expect(validate(body.data), errorText()).toBe(true); + }); + + it("lists each operation's default inside its own versions", async () => { + const { body } = await fetchDiscovery(); + const entries = Object.values( + body.data.operations as Record, + ); + + expect(entries.length).toBeGreaterThan(0); + for (const entry of entries) { + expect(entry.versions).toContain(entry.defaultVersion); + } + }); + + it("omits upcomingDefault and deprecated", async () => { + const { body } = await fetchDiscovery(); + const levels = [ + body.data, + ...Object.values(body.data.operations ?? {}), + ] as object[]; + + expect(levels.length).toBeGreaterThan(1); + for (const level of levels) { + expect(level).not.toHaveProperty("upcomingDefault"); + expect(level).not.toHaveProperty("deprecated"); + } + }); + + describe("CG-Version", () => { + it.each([undefined, "0.3.0", "v1", "0.5.0, 0.4.0", "9.9.0"])( + "is ignored when the header is %j", + async (header) => { + const baseline = await fetchDiscovery(); + const { response, body } = await fetchDiscovery(header); + + expect(response.status).toBe(200); + expect(body).toEqual(baseline.body); + expect(body.data.versions).toEqual(SUPPORTED_VERSIONS); + expect(response.headers.has(VERSION_SERVED_HEADER)).toBe(false); + expect(response.headers.get("Vary") ?? "").not.toContain( + VERSION_HEADER, + ); + }, + ); + }); + + it("serves only GET", async () => { + const response = await handleMockRequest( + mockRequest("/versions", undefined, { method: "POST" }), + ); + const body = await response.json(); + + expect(response.status).toBe(404); + expect(body.errors[0].field).toBe("path"); + expect(response.headers.has(VERSION_SERVED_HEADER)).toBe(false); + }); +}); + +describe("version errors link to discovery", () => { + it.each([ + ["/awards", "0.2.0", 406, "VersionUnsupportedError.yaml"], + ["/opportunities", "v1", 400, "VersionMalformedError.yaml"], + ["/opportunities", "0.5.0, 0.4.0", 400, "VersionConflictError.yaml"], + ["/opportunities", "9.9.0", 406, "VersionUnsupportedError.yaml"], + ])("%s with %j", async (route, header, status, schemaName) => { + const response = await handleMockRequest(mockRequest(route, header)); + const body = await response.json(); + const { validate, errorText } = getValidator("0.6.0", schemaName, { + requireVersioned: true, + }); + + expect(response.status).toBe(status); + expect(body.errors[0].discovery).toBe(DISCOVERY); + expect(new URL(body.errors[0].discovery).origin).toBe( + new URL(mockUrl("")).origin, + ); + expect(validate(body), errorText()).toBe(true); + }); +}); + +describe("discovery operations vs published OpenAPI", () => { + const HERE = path.dirname(fileURLToPath(import.meta.url)); + const OPENAPI_DIR = path.resolve(HERE, "../../../public/openapi"); + const METHODS = ["get", "post", "put", "patch", "delete"]; + const SELF = "GET /common-grants/versions"; + + /** `" "` keys with exact published paths, per version. */ + function routesFor(version: string): string[] { + const doc = yaml.load( + readFileSync(path.join(OPENAPI_DIR, `openapi.${version}.yaml`), "utf8"), + ) as { paths: Record> }; + return Object.entries(doc.paths).flatMap(([p, item]) => + METHODS.filter((m) => m in item).map((m) => `${m.toUpperCase()} ${p}`), + ); + } + + const normalize = (key: string) => key.replace(/\{[^}]*\}/g, "{}"); + + const byVersion = new Map( + SUPPORTED_VERSIONS.map((v) => [v, routesFor(v).map(normalize)]), + ); + const latest = routesFor("0.6.0").filter((r) => r !== SELF); + + it("has one entry per route that appeared after 0.1.0", async () => { + const { body } = await fetchDiscovery(); + const operations = body.data.operations as Record; + const normalized = new Map( + Object.entries(operations).map(([k, v]) => [normalize(k), v]), + ); + + for (const route of latest) { + const key = normalize(route); + const first = SUPPORTED_VERSIONS.find((v) => + byVersion.get(v)?.includes(key), + ); + if (first === "0.1.0") { + expect(normalized.has(key), `${route} is in 0.1.0`).toBe(false); + continue; + } + const entry = normalized.get(key); + expect(entry, `missing ${route}`).toBeDefined(); + expect(entry?.versions, route).toEqual( + SUPPORTED_VERSIONS.slice(SUPPORTED_VERSIONS.indexOf(first!)), + ); + expect(entry?.defaultVersion, route).toBe("0.6.0"); + } + }); + + it("names only routes published in 0.6.0, with their exact paths", async () => { + const { body } = await fetchDiscovery(); + const keys = Object.keys(body.data.operations); + + expect(keys).toHaveLength(18); + for (const key of keys) { + expect(latest, key).toContain(key); + } + }); +}); diff --git a/website/__tests__/scripts/inject-mock-server.spec.ts b/website/__tests__/scripts/inject-mock-server.spec.ts index b45b218ec..1c820da17 100644 --- a/website/__tests__/scripts/inject-mock-server.spec.ts +++ b/website/__tests__/scripts/inject-mock-server.spec.ts @@ -13,7 +13,7 @@ import { versionFromSpecFilename, MockServerInjector, } from "@/scripts/inject-mock-server"; -import { MOCK_SPEC_DIR_NAME, serverUrlFor } from "@/lib/mock/docs-wiring"; +import { MOCK_SERVER_URL, MOCK_SPEC_DIR_NAME } from "@/lib/mock/docs-wiring"; import { MOCK_API_BASE_PATH } from "@/lib/mock/router"; import { SUPPORTED_VERSIONS } from "@/lib/mock/data/fixtures"; import { Paths } from "@/lib/schema/paths"; @@ -37,9 +37,9 @@ paths: - url: https://not-a-real-top-level-key.example.com `; -describe("serverUrlFor", () => { - it("builds the version-prefixed server URL relative to MOCK_API_BASE_PATH", () => { - expect(serverUrlFor("0.4.0")).toBe(`${MOCK_API_BASE_PATH}/v0.4.0`); +describe("MOCK_SERVER_URL", () => { + it("equals MOCK_API_BASE_PATH, since the version rides in the CG-Version header", () => { + expect(MOCK_SERVER_URL).toBe(MOCK_API_BASE_PATH); }); }); @@ -56,7 +56,7 @@ describe("versionFromSpecFilename", () => { }); describe("injectServers", () => { - const serverUrl = `${MOCK_API_BASE_PATH}/v0.4.0`; + const serverUrl = MOCK_SERVER_URL; it("inserts a top-level servers block immediately before the top-level paths line", () => { const result = injectServers(FIXTURE_YAML, serverUrl); @@ -93,7 +93,7 @@ describe("injectServers", () => { it("is idempotent: replaces an existing top-level servers block rather than duplicating it", () => { const firstPass = injectServers(FIXTURE_YAML, serverUrl); - const newerServerUrl = `${MOCK_API_BASE_PATH}/v0.5.0`; + const newerServerUrl = "/other-api"; const secondPass = injectServers(firstPass, newerServerUrl); const topLevelServersMatches = secondPass.match(/^servers:/gm) ?? []; @@ -121,6 +121,12 @@ describe("assertMockServesVersion", () => { assertMockServesVersion("0.7.0", "openapi.0.7.0.yaml"), ).toThrow(/openapi\.0\.7\.0\.yaml.*does not serve/s); }); + + it("names the unserved version in the error", () => { + expect(() => + assertMockServesVersion("9.9.9", "openapi.9.9.9.yaml"), + ).toThrow(/v9\.9\.9/); + }); }); describe("MockServerInjector", () => { @@ -138,16 +144,17 @@ describe("MockServerInjector", () => { expect(written).toEqual(emittedSpecs.map(({ filename }) => filename)); }); - it("points each copy's servers block at that spec's version of the mock", () => { + it("points each copy's servers block at the unversioned mock base path", () => { MockServerInjector.inject(); - for (const { filename, version } of emittedSpecs) { + for (const { filename } of emittedSpecs) { const copy = readFileSync( join(Paths.PUBLIC_DIR, MOCK_SPEC_DIR_NAME, filename), "utf-8", ); - expect(copy).toContain(`servers:\n - url: ${serverUrlFor(version)}`); + expect(copy).toContain(`servers:\n - url: ${MOCK_SERVER_URL}`); + expect(copy).not.toMatch(/servers:\n\s+- url: \/api\/v/); } }); }); diff --git a/website/src/content/docs/governance/adr/0028-mock-api-hosting.md b/website/src/content/docs/governance/adr/0028-mock-api-hosting.md index cd9e492e4..4748c4cf5 100644 --- a/website/src/content/docs/governance/adr/0028-mock-api-hosting.md +++ b/website/src/content/docs/governance/adr/0028-mock-api-hosting.md @@ -3,6 +3,10 @@ title: Mock API hosting description: Records the decision to serve the fixture-backed mock CommonGrants API from the docs website itself, so the browser, curl, and the SDK all hit the same endpoint and see the same data. --- +:::note +The path version in this record (`/api/v{version}`) is superseded by [ADR 0032](https://commongrants.org/governance/adr/0032-api-version-negotiation/). The mock now serves every route under `/api/common-grants` and selects the protocol version with the `CG-Version` request header. +::: + We want visitors to test the CommonGrants API against a mock for every published spec version (v0.1.0 to v0.4.0). We're turning Swagger UI's "Try it out" back on in the browser, but our core goal is **determinism**. A user should be able to try a request in the browser, copy the `curl` command and run it in their terminal, point the SDK at the same URL, and get the **same data** every time. The mock also gives the quickstart a sandbox: a new SDK user can fetch realistic grant data with no local setup. So the mock has three consumers: diff --git a/website/src/lib/api-docs-version.ts b/website/src/lib/api-docs-version.ts index caf2dd10c..1501e619f 100644 --- a/website/src/lib/api-docs-version.ts +++ b/website/src/lib/api-docs-version.ts @@ -13,3 +13,47 @@ export function resolveVersion(param: string, versions: string[]): string { const normalized = param.replace(/^v/, ""); return versions.includes(normalized) ? normalized : versions[0]; } + +/** + * Swagger UI `requestInterceptor` body: sends the selected spec's version as + * `header` on calls to the mock, so an older spec page isn't served the + * mock's default version. A non-empty value the user typed into the header + * field wins. Other requests, such as the spec fetch, pass through untouched. + * + * @param request - The request Swagger UI is about to send. + * @param options.version - The version selected on the page. + * @param options.basePath - The mock's mount point, e.g. `/api`. + * @param options.header - The version header's name, e.g. `CG-Version`. + * @param options.origin - The page's origin, for resolving relative URLs. + * @returns The same request, with the header set when it applies. + */ +export function withVersionHeader( + request: T, + options: { + version: string; + basePath: string; + header: string; + origin: string; + }, +): T { + const { version, basePath, header, origin } = options; + const url = new URL(request.url, origin); + if (url.origin !== origin || !url.pathname.startsWith(`${basePath}/`)) { + return request; + } + + // Swagger UI's request type leaves `headers` untyped. + const headers = ((request as { headers?: Record }).headers ??= + {}); + const name = header.toLowerCase(); + const existing = Object.keys(headers).find( + (key) => key.toLowerCase() === name, + ); + if (existing !== undefined && headers[existing] !== "") { + return request; + } + + if (existing !== undefined) delete headers[existing]; + headers[header] = version; + return request; +} diff --git a/website/src/lib/mock/data/availability.ts b/website/src/lib/mock/data/availability.ts index f0bc74747..e11ffe942 100644 --- a/website/src/lib/mock/data/availability.ts +++ b/website/src/lib/mock/data/availability.ts @@ -53,9 +53,14 @@ export function isAtLeastVersion( return versionIndex(version) >= versionIndex(minVersion); } +/** Every supported version at or after `minVersion`. */ +export function versionsFrom(minVersion: Version): Version[] { + return SUPPORTED_VERSIONS.filter( + (version) => versionIndex(version) >= versionIndex(minVersion), + ); +} + /** Every supported version in which `resource` is served. */ export function versionsServing(resource: ResourceName): Version[] { - return SUPPORTED_VERSIONS.filter((version) => - isResourceAvailable(resource, version), - ); + return versionsFrom(RESOURCE_MIN_VERSION[resource]); } diff --git a/website/src/lib/mock/data/fixtures.ts b/website/src/lib/mock/data/fixtures.ts index abc5f1001..256cec111 100644 --- a/website/src/lib/mock/data/fixtures.ts +++ b/website/src/lib/mock/data/fixtures.ts @@ -53,6 +53,18 @@ export function isSupportedVersion(value: string): value is Version { return (SUPPORTED_VERSIONS as readonly string[]).includes(value); } +/** + * The hosted version sharing `requested`'s major and minor, if any: a request + * for `0.5.1` is served by `0.5.0`. Expects a well-formed `MAJOR.MINOR.PATCH`. + */ +export function hostedVersionFor(requested: string): Version | undefined { + const [major, minor] = requested.split("."); + return SUPPORTED_VERSIONS.find((version) => { + const [hostedMajor, hostedMinor] = version.split("."); + return hostedMajor === major && hostedMinor === minor; + }); +} + /** Which endpoint shape to project: the list returns `OpportunityBase`, the * single-item read returns `OpportunityDetails` (v0.2+). */ export type ShapeVariant = "list" | "detail"; diff --git a/website/src/lib/mock/docs-wiring.ts b/website/src/lib/mock/docs-wiring.ts index 3f164480a..b77744893 100644 --- a/website/src/lib/mock/docs-wiring.ts +++ b/website/src/lib/mock/docs-wiring.ts @@ -7,12 +7,11 @@ import { MOCK_API_BASE_PATH } from "./router"; /** - * Builds the root-relative server URL for one spec, e.g. `/api/v0.4.0`. The - * version rides in the path, so this doubles as an SDK `baseUrl`. + * The root-relative server URL every spec advertises. The version rides in + * the `CG-Version` header (ADR 0032), so all versions share one URL, which + * doubles as an SDK `baseUrl`. */ -export function serverUrlFor(version: string): string { - return `${MOCK_API_BASE_PATH}/v${version}`; -} +export const MOCK_SERVER_URL = MOCK_API_BASE_PATH; /** * Public directory holding the mock-advertising spec copies, written each build diff --git a/website/src/lib/mock/handlers/applications.ts b/website/src/lib/mock/handlers/applications.ts index b073c7055..540544a3c 100644 --- a/website/src/lib/mock/handlers/applications.ts +++ b/website/src/lib/mock/handlers/applications.ts @@ -21,10 +21,7 @@ import { type Application, type AppFormResponse, } from "../data/applications"; -import { - APPLICATION_SEARCH_MIN_VERSION, - isAtLeastVersion, -} from "../data/availability"; +import { isAtLeastVersion } from "../data/availability"; import { getCompetitionById } from "../data/competitions"; import type { Version } from "../data/fixtures"; import { getFormById } from "../data/forms"; @@ -164,7 +161,7 @@ function titleFieldFor(version: Version): "name" | "title" { } /** - * `POST /v{version}/common-grants/applications/start` — answers 201 with the + * `POST /common-grants/applications/start` — answers 201 with the * application the write would have created. Nothing is retained. */ export async function startApplication( @@ -244,7 +241,7 @@ export async function startApplication( } /** - * `GET /v{version}/common-grants/applications/{appId}` — a single application, + * `GET /common-grants/applications/{appId}` — a single application, * with its form responses and validation errors. */ export function getApplication(appId: string, version: Version): Response { @@ -259,7 +256,7 @@ export function getApplication(appId: string, version: Version): Response { } /** - * `PUT /v{version}/common-grants/applications/{appId}/submit`. Whether it + * `PUT /common-grants/applications/{appId}/submit`. Whether it * answers 200 or 400 is decided by the fixture's own `validationErrors`, so * both branches are reachable. * @@ -382,23 +379,14 @@ async function readSearchRequest( } /** - * `POST /v{version}/common-grants/applications/search`. Added in v0.3, so - * v0.2 answers a protocol-shaped 404 — gated here, not in the router, because - * the rest of `/applications` is served at v0.2. + * `POST /common-grants/applications/search`. Added in v0.3; the router rejects + * earlier versions before this runs, since the rest of `/applications` is + * served at v0.2. */ export async function searchApplications( request: Request, version: Version, ): Promise { - if (!isAtLeastVersion(version, APPLICATION_SEARCH_MIN_VERSION)) { - return errorResponse(404, "Not found", [ - { - field: "path", - message: `Application search was added in v${APPLICATION_SEARCH_MIN_VERSION} and is not served by v${version}`, - }, - ]); - } - const parsed = await readSearchRequest(request); if (!parsed.ok) { return parsed.response; @@ -546,7 +534,7 @@ function lookupForm( } /** - * `GET /v{version}/common-grants/applications/{appId}/forms/{formId}` — read + * `GET /common-grants/applications/{appId}/forms/{formId}` — read * one form response. */ export function readFormResponse( @@ -579,7 +567,7 @@ export function readFormResponse( } /** - * `PUT /v{version}/common-grants/applications/{appId}/forms/{formId}` — echoes + * `PUT /common-grants/applications/{appId}/forms/{formId}` — echoes * the body back in an `AppFormResponse` envelope: `notStarted` for an empty * body, `complete` otherwise. */ diff --git a/website/src/lib/mock/handlers/awards.ts b/website/src/lib/mock/handlers/awards.ts index f0e71df5e..e06bbf1d5 100644 --- a/website/src/lib/mock/handlers/awards.ts +++ b/website/src/lib/mock/handlers/awards.ts @@ -117,7 +117,7 @@ function moneyFilterValue(award: Award): Money | undefined { } /** - * `GET /v{version}/common-grants/awards` — the paginated list, ordered + * `GET /common-grants/awards` — the paginated list, ordered * newest-modified first. */ export function listAwards(request: Request, version: Version): Response { @@ -146,7 +146,7 @@ export function listAwards(request: Request, version: Version): Response { } /** - * `GET /v{version}/common-grants/awards/{awdId}` — a single record. A + * `GET /common-grants/awards/{awdId}` — a single record. A * malformed id answers 400, not a route miss. */ export function getAward(awdId: string, version: Version): Response { @@ -167,7 +167,7 @@ export function getAward(awdId: string, version: Version): Response { } /** - * `POST /v{version}/common-grants/awards/search` — filtered, sorted, paginated + * `POST /common-grants/awards/search` — filtered, sorted, paginated * search over the same fixture set. */ export async function searchAwards( diff --git a/website/src/lib/mock/handlers/competitions.ts b/website/src/lib/mock/handlers/competitions.ts index 9e158c1de..827baf552 100644 --- a/website/src/lib/mock/handlers/competitions.ts +++ b/website/src/lib/mock/handlers/competitions.ts @@ -14,7 +14,7 @@ import { errorResponse, successResponse } from "../http/envelope"; import { isUuid } from "../http/query"; /** - * `GET /v{version}/common-grants/competitions/{compId}` — a single + * `GET /common-grants/competitions/{compId}` — a single * competition. A malformed id answers 400, not a route miss. */ export function getCompetition(compId: string, version: Version): Response { diff --git a/website/src/lib/mock/handlers/forms.ts b/website/src/lib/mock/handlers/forms.ts index 924f80cfe..a7565454e 100644 --- a/website/src/lib/mock/handlers/forms.ts +++ b/website/src/lib/mock/handlers/forms.ts @@ -16,7 +16,7 @@ import { } from "../http/query"; /** - * `GET /v{version}/common-grants/forms` — the paginated list, ordered + * `GET /common-grants/forms` — the paginated list, ordered * newest-modified first per the operation's `@doc`. */ export function listForms(request: Request, version: Version): Response { @@ -45,7 +45,7 @@ export function listForms(request: Request, version: Version): Response { } /** - * `GET /v{version}/common-grants/forms/{formId}` — a single form. A malformed + * `GET /common-grants/forms/{formId}` — a single form. A malformed * id answers 400, not a route miss. */ export function getForm(formId: string, version: Version): Response { diff --git a/website/src/lib/mock/handlers/opportunities.ts b/website/src/lib/mock/handlers/opportunities.ts index 90bb6688a..cdadd4405 100644 --- a/website/src/lib/mock/handlers/opportunities.ts +++ b/website/src/lib/mock/handlers/opportunities.ts @@ -114,7 +114,7 @@ function sortKey(opp: WireOpportunity, sortBy: string): string | number { } /** - * `GET /v{version}/common-grants/opportunities` — the paginated list, ordered + * `GET /common-grants/opportunities` — the paginated list, ordered * newest-modified first. */ export function listOpportunities( @@ -144,7 +144,7 @@ export function listOpportunities( } /** - * `GET /v{version}/common-grants/opportunities/{oppId}` — a single record. The + * `GET /common-grants/opportunities/{oppId}` — a single record. The * id is validated here, not in the router, so a malformed id answers 400 * rather than a route miss. */ @@ -168,7 +168,7 @@ export function getOpportunity(oppId: string, version: Version): Response { } /** - * `POST /v{version}/common-grants/opportunities/search` — filtered, sorted, + * `POST /common-grants/opportunities/search` — filtered, sorted, * paginated search over the same fixture set. */ export async function searchOpportunities( diff --git a/website/src/lib/mock/handlers/organizations.ts b/website/src/lib/mock/handlers/organizations.ts index bdcd3ae28..5108e3374 100644 --- a/website/src/lib/mock/handlers/organizations.ts +++ b/website/src/lib/mock/handlers/organizations.ts @@ -126,7 +126,7 @@ function lookupOrg(orgId: string): OrgLookup { } /** - * `GET /v{version}/common-grants/orgs` — the paginated list, ordered by name + * `GET /common-grants/orgs` — the paginated list, ordered by name * (`OrganizationBase` has no `lastModifiedAt`). `registry` + `id` filter by * external identifier as a pair; one without the other is a 400. */ @@ -182,7 +182,7 @@ export function listOrganizations( } /** - * `GET /v{version}/common-grants/orgs/{orgId}` — a single profile. `?at` is + * `GET /common-grants/orgs/{orgId}` — a single profile. `?at` is * accepted and validated but does not change the response — the fixtures hold * one current profile per org, not a history. */ @@ -252,7 +252,7 @@ function echoedRevision( } /** - * `PATCH /v{version}/common-grants/orgs/{orgId}` — answers 200 with an + * `PATCH /common-grants/orgs/{orgId}` — answers 200 with an * `accepted` revision whose `snapshot` is the fixture with the merge patch * applied. Nothing is retained. */ @@ -281,7 +281,7 @@ export async function updateOrganization( } /** - * `POST /v{version}/common-grants/orgs/{orgId}/changes` — answers 202 with a + * `POST /common-grants/orgs/{orgId}/changes` — answers 202 with a * `pending` revision and a `Location` header. Nothing is stored, so polling * that URL answers 404; the header's shape is still part of the contract. */ @@ -316,7 +316,7 @@ export async function submitOrgChange( } /** - * `GET /v{version}/common-grants/orgs/{orgId}/changes` — the fixture change + * `GET /common-grants/orgs/{orgId}/changes` — the fixture change * history, newest first. Echoed writes never appear here. */ export function listOrgChanges( @@ -350,7 +350,7 @@ export function listOrgChanges( } /** - * `GET /v{version}/common-grants/orgs/{orgId}/changes/{changeId}` — one + * `GET /common-grants/orgs/{orgId}/changes/{changeId}` — one * change, scoped to the org: a change id that belongs to a different * organization answers 404. */ diff --git a/website/src/lib/mock/handlers/versions.ts b/website/src/lib/mock/handlers/versions.ts new file mode 100644 index 000000000..eb7dd4310 --- /dev/null +++ b/website/src/lib/mock/handlers/versions.ts @@ -0,0 +1,86 @@ +/** + * Handler for `GET /common-grants/versions`, the ADR 0032 discovery route. It + * sits outside version selection, so it never reads `CG-Version`. + */ + +import { + APPLICATION_SEARCH_MIN_VERSION, + versionsFrom, + versionsServing, + type ResourceName, +} from "../data/availability"; +import { SUPPORTED_VERSIONS, type Version } from "../data/fixtures"; +import { successResponse } from "../http/envelope"; +import { DEFAULT_VERSION } from "../http/version"; + +/** The discovery route's published path, below the mount point. */ +export const VERSIONS_PATH = "/common-grants/versions"; + +/** The absolute discovery URL that version errors point to. */ +export function discoveryUrl(origin: string, basePath: string): string { + return `${origin}${basePath}${VERSIONS_PATH}`; +} + +/** + * Every route added after 0.1.0, keyed as discovery publishes it, mapped to + * the resource whose availability governs it. The opportunity routes serve + * the whole baseline, so they have no entry. + */ +const ROUTES_BY_RESOURCE: Record< + Exclude, + string[] +> = { + applications: [ + "GET /common-grants/applications/{appId}", + "GET /common-grants/applications/{appId}/forms/{formId}", + "PUT /common-grants/applications/{appId}/forms/{formId}", + "POST /common-grants/applications/start", + "PUT /common-grants/applications/{appId}/submit", + ], + competitions: ["GET /common-grants/competitions/{compId}"], + forms: ["GET /common-grants/forms", "GET /common-grants/forms/{formId}"], + awards: [ + "GET /common-grants/awards", + "GET /common-grants/awards/{awdId}", + "POST /common-grants/awards/search", + ], + orgs: [ + "GET /common-grants/orgs", + "GET /common-grants/orgs/{orgId}", + "PATCH /common-grants/orgs/{orgId}", + "GET /common-grants/orgs/{orgId}/changes", + "POST /common-grants/orgs/{orgId}/changes", + "GET /common-grants/orgs/{orgId}/changes/{changeId}", + ], +}; + +interface OperationVersions { + versions: Version[]; + defaultVersion: Version; +} + +function operations(): Record { + const entries: Record = {}; + for (const [resource, routes] of Object.entries(ROUTES_BY_RESOURCE)) { + const versions = versionsServing(resource as ResourceName); + for (const key of routes) { + entries[key] = { versions, defaultVersion: DEFAULT_VERSION }; + } + } + entries["POST /common-grants/applications/search"] = { + versions: versionsFrom(APPLICATION_SEARCH_MIN_VERSION), + defaultVersion: DEFAULT_VERSION, + }; + return entries; +} + +/** `GET /common-grants/versions`: the baseline plus each route that differs. */ +export function getVersionDiscovery(): Response { + return successResponse({ + data: { + versions: [...SUPPORTED_VERSIONS], + defaultVersion: DEFAULT_VERSION, + operations: operations(), + }, + }); +} diff --git a/website/src/lib/mock/http/cors.ts b/website/src/lib/mock/http/cors.ts index 16c8060c9..e4b20e7cb 100644 --- a/website/src/lib/mock/http/cors.ts +++ b/website/src/lib/mock/http/cors.ts @@ -5,19 +5,33 @@ */ import { SUPPORTED_METHODS } from "./methods"; +import { VERSION_HEADER, VERSION_SERVED_HEADER } from "./version"; /** * `X-API-Key` and `Authorization` are listed because the TS SDK sends them - * when auth is configured; a preflight must name non-simple headers. The - * methods come from `SUPPORTED_METHODS` so they cannot drift from the router. + * when auth is configured, and `CG-Version` because clients select a version + * with it; a preflight must name non-simple headers. The methods come from + * `SUPPORTED_METHODS` so they cannot drift from the router. */ const CORS_HEADERS: Record = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": [...SUPPORTED_METHODS, "OPTIONS"].join(", "), - "Access-Control-Allow-Headers": "Content-Type, X-API-Key, Authorization", + "Access-Control-Allow-Headers": `Content-Type, X-API-Key, Authorization, ${VERSION_HEADER}`, "Access-Control-Max-Age": "86400", }; +/** + * The ADR 0032 response headers a browser client may read. The mock retires + * nothing, so it never sends `Deprecation`, `Sunset` or `Link`; they are listed + * to match the ADR. + */ +const EXPOSED_HEADERS = [ + VERSION_SERVED_HEADER, + "Deprecation", + "Sunset", + "Link", +].join(", "); + /** * Answers 204 to an `OPTIONS` preflight for any path, matched or not — on * purpose: a preflight asks about policy, not whether the resource exists. @@ -32,6 +46,7 @@ export function withCors(response: Response): Response { for (const [name, value] of Object.entries(CORS_HEADERS)) { headers.set(name, value); } + headers.set("Access-Control-Expose-Headers", EXPOSED_HEADERS); return new Response(response.body, { status: response.status, diff --git a/website/src/lib/mock/http/envelope.ts b/website/src/lib/mock/http/envelope.ts index 8dacf9bac..3248c63ad 100644 --- a/website/src/lib/mock/http/envelope.ts +++ b/website/src/lib/mock/http/envelope.ts @@ -4,6 +4,8 @@ * into the body's `status` field, as `Responses.Success` declares. */ +import type { VersionError } from "./version"; + /** A single `{field, message}` validation error carried in the `errors` array. */ export interface FieldError { field: string; @@ -46,6 +48,19 @@ export function acceptedResponse(data: unknown, location?: string): Response { ); } +/** + * Builds a 0.6.0 version error (`version.malformed`, `.unsupported`, + * `.conflict`). `discovery` is the absolute discovery URL, omitted when unset. + */ +export function versionErrorResponse( + error: VersionError, + discovery?: string, +): Response { + const detail = + discovery === undefined ? error.detail : { ...error.detail, discovery }; + return errorResponse(error.status, error.message, [detail]); +} + /** * Runs `handle`, converting an uncaught throw into a protocol-shaped 500. An * uncaught throw would skip `withCors`, so the browser would report an opaque diff --git a/website/src/lib/mock/http/version.ts b/website/src/lib/mock/http/version.ts new file mode 100644 index 000000000..3c694a2c2 --- /dev/null +++ b/website/src/lib/mock/http/version.ts @@ -0,0 +1,154 @@ +/** + * Resolves the `CG-Version` request header to the protocol version a route is + * served in, per ADR 0032. Pure: the router supplies the header value and the + * route's versions, and turns a returned error into a response with + * `versionErrorResponse` (`./envelope.ts`). + */ + +import { hostedVersionFor, type Version } from "../data/fixtures"; + +export const VERSION_HEADER = "CG-Version" as const; +export const VERSION_SERVED_HEADER = "CG-Version-Served"; + +/** Every route's default today; the router passes it as `RouteVersions.defaultVersion`. */ +export const DEFAULT_VERSION: Version = "0.6.0"; + +/** The versions one route serves, as version errors report them. */ +export interface RouteVersions { + /** Request method and path, e.g. `GET /common-grants/awards`. */ + label: string; + versions: readonly Version[]; + defaultVersion: Version; +} + +/** Fields every version error carries, describing the route called. */ +interface VersionErrorBase { + field: typeof VERSION_HEADER; + message: string; + supported: Version[]; + defaultVersion: Version; +} + +/** One `errors[]` entry of a 0.6.0 version error, minus `discovery`. */ +export type VersionErrorDetail = VersionErrorBase & + ( + | { code: "version.conflict" } + | { code: "version.malformed"; requested: string } + | { + code: "version.unsupported"; + requested: string; + scope: "deployment" | "operation"; + } + ); + +/** A version error ready to render: status, envelope message, and detail. */ +export interface VersionError { + status: 400 | 406; + message: string; + detail: VersionErrorDetail; +} + +export type VersionResolution = { version: Version } | { error: VersionError }; + +/** `protocolVersion`'s pattern from the 0.6.0 schemas: no `v`, no leading zeros. */ +const PROTOCOL_VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/; + +/** + * Resolves a raw `CG-Version` value (`null` when absent) for one route. + * Checks, in order: more than one value, format, whether the server serves the + * major.minor, whether this route does. + */ +export function resolveRequestedVersion( + headerValue: string | null, + route: RouteVersions, +): VersionResolution { + if (headerValue === null) return { version: route.defaultVersion }; + + const routeFields = { + field: VERSION_HEADER, + supported: [...route.versions], + defaultVersion: route.defaultVersion, + }; + const supportedText = route.versions.join(", "); + + // Fetch `Headers` joins a repeated header with ", ", so a comma means two values. + if (headerValue.includes(",")) { + // Quoted so an empty value (`"0.5.0, "`) still reads in the message. + const values = headerValue + .split(",") + .map((value) => JSON.stringify(value.trim())); + return { + error: { + status: 400, + message: "The request sent more than one CG-Version value", + detail: { + ...routeFields, + code: "version.conflict", + message: `Received CG-Version values ${values.join(" and ")}`, + }, + }, + }; + } + + const trimmed = headerValue.trim(); + if (!PROTOCOL_VERSION.test(trimmed)) { + return { + error: { + status: 400, + message: "The CG-Version header is not a valid CommonGrants version", + detail: { + ...routeFields, + code: "version.malformed", + message: `Version ${headerValue} is not a full MAJOR.MINOR.PATCH version`, + requested: headerValue, + }, + }, + }; + } + + const hosted = hostedVersionFor(trimmed); + if (hosted !== undefined && route.versions.includes(hosted)) { + return { version: hosted }; + } + + const scope = hosted === undefined ? "deployment" : "operation"; + const servedBy = scope === "deployment" ? "this server" : route.label; + return { + error: { + status: 406, + message: + scope === "deployment" + ? "The requested CommonGrants version is not available on this server" + : "The requested CommonGrants version is not available for this route", + detail: { + ...routeFields, + code: "version.unsupported", + message: `Version ${trimmed} is not served by ${servedBy}. Supported versions: ${supportedText}`, + requested: trimmed, + scope, + }, + }, + }; +} + +/** Adds `Vary: CG-Version`, since the response depends on the request header. */ +export function withVaryVersion(response: Response): Response { + const headers = new Headers(response.headers); + headers.append("Vary", VERSION_HEADER); + + return new Response(response.body, { + status: response.status, + statusText: response.statusText, + headers, + }); +} + +/** Adds `CG-Version-Served` and `Vary: CG-Version` to a response served in `version`. */ +export function withVersionHeaders( + response: Response, + version: Version, +): Response { + const varied = withVaryVersion(response); + varied.headers.set(VERSION_SERVED_HEADER, version); + return varied; +} diff --git a/website/src/lib/mock/router.ts b/website/src/lib/mock/router.ts index 56417228f..4c112a3bc 100644 --- a/website/src/lib/mock/router.ts +++ b/website/src/lib/mock/router.ts @@ -2,21 +2,23 @@ * Routes mock API requests to the fixture-backed resource handlers. Mounted * under `/api` by the Astro endpoint (`src/pages/api/[...path].ts`). * - * Opportunities keep the 3A Worker's regex verbatim and are matched first, so - * the golden byte-identity corpus (`golden-envelopes.spec.ts`) stays pinned. - * Version gating lives in `data/availability.ts`. + * The protocol version comes from the `CG-Version` header, never the path + * (ADR 0032). A request is matched to a route first, then its version is + * resolved against the versions that route serves (`data/availability.ts`), + * then it is dispatched. The discovery route (`/common-grants/versions`) + * skips version resolution. + * + * The opportunity routes keep the behavior the golden byte-identity corpus + * (`golden-envelopes.spec.ts`) pins. */ import { - isResourceAvailable, - RESOURCE_MIN_VERSION, + APPLICATION_SEARCH_MIN_VERSION, + versionsFrom, + versionsServing, type ResourceName, } from "./data/availability"; -import { - SUPPORTED_VERSIONS, - isSupportedVersion, - type Version, -} from "./data/fixtures"; +import { SUPPORTED_VERSIONS, type Version } from "./data/fixtures"; import { getApplication, readFormResponse, @@ -41,8 +43,24 @@ import { submitOrgChange, updateOrganization, } from "./handlers/organizations"; +import { + discoveryUrl, + getVersionDiscovery, + VERSIONS_PATH, +} from "./handlers/versions"; import { preflightResponse, withCors } from "./http/cors"; -import { errorResponse, withErrorBoundary } from "./http/envelope"; +import { + errorResponse, + versionErrorResponse, + withErrorBoundary, +} from "./http/envelope"; +import { + DEFAULT_VERSION, + VERSION_HEADER, + resolveRequestedVersion, + withVaryVersion, + withVersionHeaders, +} from "./http/version"; const SERVICE_NAME = "CommonGrants mock API"; @@ -53,20 +71,12 @@ const SERVICE_NAME = "CommonGrants mock API"; export const MOCK_API_BASE_PATH = "/api"; /** - * `/v{version}/common-grants/opportunities` with an optional trailing segment. - * Verbatim from the Worker so the corpus-pinned surface matches identically; - * `version` is captured loosely and narrowed by `isSupportedVersion`. + * Resource segment for every route; the remainder is matched per resource + * below. Segments use `[^/]+`, never `[^/]*`, so a trailing slash + * is a route-miss 404 rather than a 400 from an empty id — matching what + * `/opportunities/` has always answered. */ -const OPPORTUNITIES_ROUTE = - /^\/v([^/]+)\/common-grants\/opportunities(?:\/([^/]+))?$/; - -/** - * Version prefix + resource segment for every non-opportunity route; the - * remainder is matched per resource below. Segments use `[^/]+`, never - * `[^/]*`, so a trailing slash is a route-miss 404 rather than a 400 from an - * empty id — matching what `/opportunities/` has always answered. - */ -const RESOURCE_ROUTE = /^\/v([^/]+)\/common-grants\/([^/]+)((?:\/[^/]+)*)$/; +const RESOURCE_ROUTE = /^\/common-grants\/([^/]+)((?:\/[^/]+)*)$/; /** `/{id}`, `/{id}/changes`, and `/{id}/changes/{changeId}` for the org routes. */ const ORG_CHANGES_ROUTE = /^\/([^/]+)\/changes(?:\/([^/]+))?$/; @@ -105,32 +115,6 @@ function routeMissResponse(method: string, pathname: string): Response { ]); } -/** - * 404 for a resource added after the requested version. Deliberately distinct - * from a plain route miss — it tells the caller what to change. - */ -function resourceNotInVersionResponse( - resource: ResourceName, - version: string, -): Response { - return errorResponse(404, "Not found", [ - { - field: "path", - message: `The ${resource} endpoints were added in v${RESOURCE_MIN_VERSION[resource]} and are not served by v${version}`, - }, - ]); -} - -/** Protocol-shaped 404 for a version this mock does not serve at all. */ -function unsupportedVersionResponse(version: string): Response { - return errorResponse(404, "Unsupported protocol version", [ - { - field: "version", - message: `Version ${version} is not served by this mock; supported versions are ${SUPPORTED_VERSIONS.join(", ")}`, - }, - ]); -} - /** * Reduces a docs-origin pathname to the path the Worker would have seen, or * `undefined` when the request isn't the mock's. `/api` and `/api/` are both @@ -144,15 +128,15 @@ function stripBasePath(pathname: string): string | undefined { return undefined; } -/** - * Dispatches the opportunity endpoints — matched before anything else so the - * corpus-pinned surface is unaffected by the routing added around it. - */ +/** Dispatches the opportunity endpoints, whose behavior the golden corpus pins. */ async function routeOpportunities( request: Request, version: Version, - segment: string | undefined, + remainder: string, ): Promise { + const segment = remainder === "" ? undefined : remainder.slice(1); + if (segment !== undefined && segment.includes("/")) return undefined; + // `GET .../search` falls through to the detail handler and answers 400 // "Must be a valid UUID", as the Worker does — only POST serves `/search`. if (request.method === "GET") { @@ -286,8 +270,61 @@ async function routeCompetitions( return compId.includes("/") ? undefined : getCompetition(compId, version); } +/** + * Resolves the version for a matched route, then dispatches. A version error + * carries `Vary` but no `CG-Version-Served`; every response after selection + * carries both, including a route miss inside a known resource. + */ +async function serveVersioned( + request: Request, + { origin, pathname }: URL, + path: string, + versions: readonly Version[], + dispatchRoute: (version: Version) => Promise, +): Promise { + const resolution = resolveRequestedVersion( + request.headers.get(VERSION_HEADER), + { + label: `${request.method} ${path}`, + versions, + defaultVersion: DEFAULT_VERSION, + }, + ); + if ("error" in resolution) { + return withVaryVersion( + versionErrorResponse( + resolution.error, + discoveryUrl(origin, MOCK_API_BASE_PATH), + ), + ); + } + + const response = await dispatchRoute(resolution.version); + return withVersionHeaders( + response ?? routeMissResponse(request.method, pathname), + resolution.version, + ); +} + +/** `POST /applications/search` is served from `APPLICATION_SEARCH_MIN_VERSION`. */ +function versionsForRoute( + resource: ResourceName, + method: string, + remainder: string, +): readonly Version[] { + if ( + resource === "applications" && + method === "POST" && + remainder === "/search" + ) { + return versionsFrom(APPLICATION_SEARCH_MIN_VERSION); + } + return versionsServing(resource); +} + async function route(request: Request): Promise { - const { pathname } = new URL(request.url); + const url = new URL(request.url); + const { pathname } = url; const path = stripBasePath(pathname); if (path === undefined) { @@ -299,15 +336,11 @@ async function route(request: Request): Promise { return healthResponse(); } - // Opportunities get their own regex and the first look (see module doc). - const opportunityMatch = OPPORTUNITIES_ROUTE.exec(path); - if (opportunityMatch) { - const [, version, segment] = opportunityMatch; - if (!isSupportedVersion(version)) { - return unsupportedVersionResponse(version); - } - const response = await routeOpportunities(request, version, segment); - return response ?? routeMissResponse(request.method, pathname); + // Discovery sits outside version selection, so it never resolves a version. + if (path === VERSIONS_PATH) { + return request.method === "GET" + ? getVersionDiscovery() + : routeMissResponse(request.method, pathname); } const match = RESOURCE_ROUTE.exec(path); @@ -315,21 +348,19 @@ async function route(request: Request): Promise { return routeMissResponse(request.method, pathname); } - const [, version, segment, remainder] = match; - if (!isSupportedVersion(version)) { - return unsupportedVersionResponse(version); - } - + const [, segment, remainder] = match; const resource = RESOURCE_BY_SEGMENT[segment]; if (resource === undefined) { return routeMissResponse(request.method, pathname); } - if (!isResourceAvailable(resource, version)) { - return resourceNotInVersionResponse(resource, version); - } - const response = await dispatch(request, version, resource, remainder); - return response ?? routeMissResponse(request.method, pathname); + return serveVersioned( + request, + url, + path, + versionsForRoute(resource, request.method, remainder), + (version) => dispatch(request, version, resource, remainder), + ); } /** Hands a matched resource to its own router. */ @@ -340,6 +371,8 @@ function dispatch( remainder: string, ): Promise { switch (resource) { + case "opportunities": + return routeOpportunities(request, version, remainder); case "awards": return routeAwards(request, version, remainder); case "orgs": @@ -350,10 +383,6 @@ function dispatch( return routeForms(request, version, remainder); case "competitions": return routeCompetitions(request, version, remainder); - case "opportunities": - // Reachable when a path like `/opportunities/foo/bar` fails the stricter - // OPPORTUNITIES_ROUTE; `undefined` makes it the route miss it should be. - return Promise.resolve(undefined); } } @@ -364,6 +393,6 @@ export async function handleMockRequest(request: Request): Promise { } // Every non-preflight response passes through CORS and the error boundary; - // `preflightResponse()` sets the same headers itself. + // `preflightResponse()` sets the same `Allow-*` headers itself. return withCors(await withErrorBoundary(() => route(request))); } diff --git a/website/src/pages/protocol/api-docs.astro b/website/src/pages/protocol/api-docs.astro index 9c7deae6a..d7dabc9d1 100644 --- a/website/src/pages/protocol/api-docs.astro +++ b/website/src/pages/protocol/api-docs.astro @@ -1,12 +1,14 @@ --- import StarlightPage from "@astrojs/starlight/components/StarlightPage.astro"; import "swagger-ui-dist/swagger-ui.css"; -import { SPEC_DIR_URL } from "@/lib/mock/docs-wiring"; +import { MOCK_SERVER_URL, SPEC_DIR_URL } from "@/lib/mock/docs-wiring"; import { SUPPORTED_METHODS } from "@/lib/mock/http/methods"; +import { VERSION_HEADER } from "@/lib/mock/http/version"; // Available OpenAPI versions (mirror of the emitted specs in public/openapi/) const availableVersions = [ - { version: "0.5.0", label: "v0.5.0 (Latest)" }, + { version: "0.6.0", label: "v0.6.0 (Latest)" }, + { version: "0.5.0", label: "v0.5.0" }, { version: "0.4.0", label: "v0.4.0" }, { version: "0.3.0", label: "v0.3.0" }, { version: "0.2.0", label: "v0.2.0" }, @@ -31,6 +33,8 @@ const availableVersions = [
@@ -87,7 +91,7 @@ const availableVersions = [