From e4867f4796565e77061f797d3c017405b2b3621b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 9 Oct 2026 07:37:40 +0000 Subject: [PATCH 1/2] fix: read include / sort support off the family's own vocabulary (#294 follow-up) Follow-up to #294 (refs #282) and the shared declared-name walk (closes #297). - The include and sort codecs publish a dedicated internal vocabulary annotation (src/internal/vocabulary.ts), which the error-meta renderer also reads, in place of the generic error-meta annotation. Its shape also covers the page, filter and per-type fields vocabularies. - The support check reads only the decoded property named include / sort, follows unions and Schema.suspend with a visited set, and counts a family unsupported only when every value it can decode draws on an empty vocabulary. A codec with no vocabulary, or a non-empty vocabulary in any union member, keeps it supported. - Middleware.ts imports declaredNames from src/internal/declaredQuery.ts instead of carrying its own copy. - Tests: the hand-built queries the review reproduced, Suspend, the mixed-vocabulary unions, and 406/415 precedence on an empty vocabulary. - Docs and pending changesets: allow-listed empty vocabularies are decoded rather than ignored; empty-vocabulary endpoints now answer 400 where they used to answer 406/415. Claude-Session: https://claude.ai/code/session_0187g2QpzaHqEzX8GJxiJBVc Co-Authored-By: Claude --- .changeset/empty-vocabulary-unsupported.md | 4 +- .changeset/reject-unsupported-include-sort.md | 2 +- README.md | 2 +- src/Middleware.query.test.ts | 218 ++++++++++++++++++ src/Middleware.ts | 108 ++------- src/Query.ts | 17 +- src/internal/codecs.ts | 31 +-- src/internal/errorMeta.ts | 52 +++-- src/internal/vocabulary.ts | 168 ++++++++++++++ test/entry-points.test.ts | 1 + 10 files changed, 472 insertions(+), 131 deletions(-) create mode 100644 src/internal/vocabulary.ts diff --git a/.changeset/empty-vocabulary-unsupported.md b/.changeset/empty-vocabulary-unsupported.md index c5d75d61..e318d791 100644 --- a/.changeset/empty-vocabulary-unsupported.md +++ b/.changeset/empty-vocabulary-unsupported.md @@ -2,6 +2,8 @@ "@thomasfosterau/effect-jsonapi": patch --- -**Behaviour change: an `include` or `sort` family declared with an empty vocabulary now counts as unsupported, so a request that used to succeed can now answer 400.** This covers `include: { paths: [] }`, `include: true` on a resource with no relationships, and `sort: true` on a resource with no attributes. The `SchemaErrors` middleware now answers any `?include=` or `?sort=` on such an endpoint exactly as it answers one on an endpoint that never declared the family: a 400 naming the parameter in `source.parameter`, with the detail saying the endpoint does not support it. That includes an empty value (`?include=`, `?sort=`), which used to answer 200, and a bracketed member such as `include[x]`, which used to be ignored. A non-empty value used to answer 400 with the detail `Expected never` and `meta.includablePaths: []` / `meta.sortableFields: []`. It now gets that same unsupported-parameter 400, without the `meta` (#282). +**Behaviour change: an `include` or `sort` family declared with an empty vocabulary now counts as unsupported, so a request that used to succeed can now answer 400.** This covers `include: { paths: [] }`, `include: true` on a resource with no relationships, and `sort: true` on a resource with no attributes. The `SchemaErrors` middleware now answers any `?include=` or `?sort=` on such an endpoint exactly as it answers one on an endpoint that never declared the family: a 400 naming the parameter in `source.parameter`, with the detail saying the endpoint does not support it. That includes an empty value (`?include=`, `?sort=`), which used to answer 200, and a bracketed member such as `include[x]`, which used to be ignored. A non-empty value used to answer 400 with the detail `Expected never` and `meta.includablePaths: []` / `meta.sortableFields: []`. It now gets that same unsupported-parameter 400, without the `meta` (#282). Because the middleware answers it before content negotiation, such a request that also carries an unacceptable `Accept` or an unsupported `Content-Type` now answers this 400 where it used to answer 406 or 415, as on an endpoint that never declared the family. + +Only the endpoint's own decoded `include` / `sort` property counts, read through a union and through `Schema.suspend`. A hand-built query whose `include` is `Query.IncludeList`, or whose `sort` is a custom codec, publishes no vocabulary and keeps the family supported, and so does a union in which any member's vocabulary is non-empty. A vocabulary under another property name, such as a second `Query.Include` the query declares as `other`, never decides it. Where such a value still reaches the codec, its rejection now says why: an `allowedQueryParameters` entry that admits the family, or a direct decode with `Query.Include`, `Query.Sort` or `Query.schema`. The detail is `This endpoint supports no include paths.` or `This endpoint supports no sortable fields.` in place of `Expected never`. diff --git a/.changeset/reject-unsupported-include-sort.md b/.changeset/reject-unsupported-include-sort.md index 24c4e3b3..0788a295 100644 --- a/.changeset/reject-unsupported-include-sort.md +++ b/.changeset/reject-unsupported-include-sort.md @@ -4,4 +4,4 @@ **Behaviour change — a request that used to succeed can now answer 400:** an `include` or `sort` query parameter on an endpoint whose `query` schema does not declare it is now rejected with **400 Bad Request** instead of being ignored, as JSON:API 1.1 requires. For `include`, §Inclusion of Related Resources: "If an endpoint does not support the `include` parameter, it **MUST** respond with `400 Bad Request` to any requests that include it." For `sort` on an endpoint that responds with a resource collection, §Sorting: "If the server does not support sorting as specified in the query parameter `sort`, it **MUST** return `400 Bad Request`" (that section "applies to any endpoint that responds with a resource collection as primary data"). For `sort` on any other endpoint, such as a single-resource `GET`, the general rule of §Implementation-Specific Query Parameters: "If a server encounters a query parameter that does not follow the naming conventions above, or the server does not know how to process it as a query parameter from this specification, it **MUST** return `400 Bad Request`." For example `GET /articles/1?include=author` on `Endpoint.get(Article)` declared without `include`, `GET /articles/1?sort=title` on any `Endpoint.get`, `GET /articles?sort=title` on an `Endpoint.list` without `sort`, or either parameter on a `DELETE`. Any value is rejected, an empty `?include=` included, as is a bracketed member such as `include[x]`. A client that sends one of these and relied on it being ignored must stop sending it. -The 400 carries one error object per offending parameter, naming it in `source.parameter` (`code: "bad_request"`), with a detail saying the endpoint does not support the parameter. The `SchemaErrors` middleware every `Endpoint` constructor attaches answers it before the endpoint decodes anything, under `Middleware.layer`, `Middleware.layerWith`, `Middleware.layerHostNegotiated` and `Middleware.SchemaErrorsLive` alike, and `Middleware.checkQueryParameters` applies the same rule: it rejects `include` and `sort` unless `declared` lists them. An endpoint that declares the family with at least one legal value keeps answering as before; one whose vocabulary is empty is covered by a separate entry (#282). Listing `include` or `sort` in `allowedQueryParameters` admits it on every endpoint, which then ignores it. An undeclared `fields[TYPE]`, `page[…]` or `filter[…]` is still ignored. +The 400 carries one error object per offending parameter, naming it in `source.parameter` (`code: "bad_request"`), with a detail saying the endpoint does not support the parameter. The `SchemaErrors` middleware every `Endpoint` constructor attaches answers it before the endpoint decodes anything, under `Middleware.layer`, `Middleware.layerWith`, `Middleware.layerHostNegotiated` and `Middleware.SchemaErrorsLive` alike, and `Middleware.checkQueryParameters` applies the same rule: it rejects `include` and `sort` unless `declared` lists them. An endpoint that declares the family with at least one legal value keeps answering as before; one whose vocabulary is empty is covered by a separate entry (#282). Listing `include` or `sort` in `allowedQueryParameters` admits it on every endpoint: one that does not declare it then ignores it, and one that declares it with an empty vocabulary decodes it, so its codec rejects any value that names a path or field. An undeclared `fields[TYPE]`, `page[…]` or `filter[…]` is still ignored. diff --git a/README.md b/README.md index c921d28e..ab2bc45b 100644 --- a/README.md +++ b/README.md @@ -1286,7 +1286,7 @@ Layer.provide( Each entry must be such a base name: `lang[region]`, `Lang`, ` lang` or `""` throws `Middleware.InvalidAllowedQueryParameter` when the layer is built, rather than silently admitting nothing (list a bracketed member by its base name; a name with any other character is never rejected, so it needs no entry). -An allowed name never reaches the endpoint's decoded `query`, which keeps only what its `query` schema declares — also when that schema declares nothing ([#260](https://github.com/thomasfosterau/effect-jsonapi/issues/260)); it is only no longer rejected. Listing `include` or `sort` switches off the specification's 400 for that family on every endpoint that doesn't declare it, which then ignores the parameter instead ([Query parameters](#query-parameters)); an endpoint that declares it still decodes it. `Middleware.checkQueryParameters(names, { declared, allowedQueryParameters })` is the same check standalone, for a hook that decodes requests itself: it returns the 400 document, or `undefined`. +An allowed name never reaches the endpoint's decoded `query`, which keeps only what its `query` schema declares — also when that schema declares nothing ([#260](https://github.com/thomasfosterau/effect-jsonapi/issues/260)); it is only no longer rejected. Listing `include` or `sort` switches off the specification's 400 for that family on every endpoint that doesn't declare it, which then ignores the parameter instead ([Query parameters](#query-parameters)); an endpoint that declares it still decodes it, so one that declares it with an empty vocabulary answers any path or field with its codec's 400 (`This endpoint supports no include paths.`). `Middleware.checkQueryParameters(names, { declared, allowedQueryParameters })` is the same check standalone, for a hook that decodes requests itself: it returns the 400 document, or `undefined`. And to call it — the same definitions drive a fully typed client: diff --git a/src/Middleware.query.test.ts b/src/Middleware.query.test.ts index 2fe5eaf9..ac44c510 100644 --- a/src/Middleware.query.test.ts +++ b/src/Middleware.query.test.ts @@ -717,6 +717,25 @@ describe("spec families an endpoint does not support (#261)", () => { // without the unsupported parameter, the same request is the 415 expect((await serve("/people/1", middleware, contentType)).status).toBe(415); }); + + // A family declared with an empty vocabulary is unsupported (#282), so + // its 400 takes the same precedence; before #282 the request reached the + // negotiation, which answered 406 / 415 first. + it.each(layers)( + "for a family declared with an empty vocabulary, over a 406 and a 415, under %s", + async (_, middleware) => { + const accept = { headers: { accept: parameterised } }; + const path = await serve("/tags/1?include=author", middleware, accept); + expect(path.status).toBe(400); + expect(path.body).toEqual({ errors: [unsupported("include", "include")] }); + expect((await serve("/tags/1", middleware, accept)).status).toBe(406); + const contentType = { headers: { "content-type": parameterised } }; + const field = await serve("/tags?sort=", middleware, contentType); + expect(field.status).toBe(400); + expect(field.body).toEqual({ errors: [unsupported("sort", "sort")] }); + expect((await serve("/tags", middleware, contentType)).status).toBe(415); + }, + ); }); it("applies under the host-negotiated layer too", async () => { @@ -745,3 +764,202 @@ describe("spec families an endpoint does not support (#261)", () => { expect(field.body.errors[0].source).toEqual({ parameter: "sort" }); }); }); + +describe("which declared `include` / `sort` an endpoint supports (#282)", () => { + // The support check reads the vocabulary the `include` / `sort` codecs + // publish, on the decoded property of that name only. A family counts as + // unsupported when every value its property could decode is drawn from an + // empty vocabulary; one that publishes no vocabulary (`Query.IncludeList`, + // a custom codec) or a non-empty one somewhere is supported. + const Person = Resource.make("people", { attributes: { name: Schema.NonEmptyString } }); + const Post = Resource.make("posts", { + attributes: { title: Schema.NonEmptyString }, + relationships: { author: Relationship.one(() => Person) }, + }); + const Tag = Resource.make("tags", { attributes: {} }); + + // A recursive codec with no vocabulary, so the walk must not loop on it. + // Its recursive member comes first, so a walk that reads union members in + // order reaches the recursion before the string that settles the answer. + type Nested = { readonly next?: Nested } | string; + const Nested: Schema.Codec = Schema.Union([ + Schema.Struct({ + next: Schema.optionalKey(Schema.suspend((): Schema.Codec => Nested)), + }), + Schema.String, + ]); + + const endpoints = { + "include-list": Schema.Struct({ include: Schema.optionalKey(Query.IncludeList) }), + "custom-sort": Schema.Struct({ sort: Schema.optionalKey(Schema.String) }), + "recursive-include": Schema.Struct({ include: Schema.optionalKey(Nested) }), + "union-of-queries": Schema.Union([ + Query.schema(Tag, { include: { paths: [] } }), + Query.schema(Post, { include: true }), + ]), + "union-of-sorts": Schema.Struct({ + sort: Schema.optionalKey(Schema.Union([Query.Sort([]), Query.Sort(["title"])])), + }), + "union-with-open-include": Schema.Struct({ + include: Schema.optionalKey(Schema.Union([Query.Include(Tag), Query.IncludeList])), + }), + "open-include-beside-empty": Schema.Struct({ + include: Schema.optionalKey(Query.IncludeList), + Other: Schema.optionalKey(Query.Include(Tag)), + }), + "empty-include-beside-other": Schema.Struct({ + include: Schema.optionalKey(Query.Include(Tag)), + other: Schema.optionalKey(Query.Include(Post)), + }), + "empty-sort-beside-other": Schema.Struct({ + sort: Schema.optionalKey(Query.Sort([])), + order: Schema.optionalKey(Query.Sort(["title"])), + }), + "suspended-query": Schema.suspend(() => Query.schema(Tag, { include: { paths: [] } })), + "suspended-include": Schema.Struct({ + include: Schema.optionalKey(Schema.suspend(() => Query.Include(Tag))), + }), + // `Schema.optional` decodes `undefined` too, which carries no value. + "optional-include": Schema.Struct({ include: Schema.optional(Query.Include(Tag)) }), + // Only the family's own vocabulary counts. + "sort-codec-as-include": Schema.Struct({ include: Schema.optionalKey(Query.Sort([])) }), + } as const; + type Name = keyof typeof endpoints; + const endpoint = (name: N) => + HttpApiEndpoint.get(name, `/${name}`, { + query: endpoints[name], + success: Schema.Unknown, + }).middleware(Middleware.SchemaErrors); + const VocabulariesApi = HttpApi.make("vocabularies").add( + HttpApiGroup.make("vocabularies").add( + endpoint("include-list"), + endpoint("custom-sort"), + endpoint("recursive-include"), + endpoint("union-of-queries"), + endpoint("union-of-sorts"), + endpoint("union-with-open-include"), + endpoint("open-include-beside-empty"), + endpoint("empty-include-beside-other"), + endpoint("empty-sort-beside-other"), + endpoint("suspended-query"), + endpoint("suspended-include"), + endpoint("optional-include"), + endpoint("sort-codec-as-include"), + ), + ); + // Each handler answers the decoded `query` it received. + const echo = ({ query }: { readonly query: unknown }) => Effect.succeed(query); + const VocabulariesLive = HttpApiBuilder.group(VocabulariesApi, "vocabularies", (handlers) => + handlers.handleAll({ + "include-list": echo, + "custom-sort": echo, + "recursive-include": echo, + "union-of-queries": echo, + "union-of-sorts": echo, + "union-with-open-include": echo, + "open-include-beside-empty": echo, + "empty-include-beside-other": echo, + "empty-sort-beside-other": echo, + "suspended-query": echo, + "suspended-include": echo, + "optional-include": echo, + "sort-codec-as-include": echo, + }), + ); + + const serve = async (url: string) => { + const appLayer = HttpApiBuilder.layer(VocabulariesApi).pipe( + Layer.provide(VocabulariesLive), + Layer.provide(Middleware.SchemaErrorsLive), + Layer.provide(platformLayer), + ); + const { dispose, handler } = HttpRouter.toWebHandler(appLayer); + const response = await handler(new Request(`http://localhost${url}`)).finally(dispose); + return { status: response.status, body: decodeJson(await response.text()) }; + }; + + const unsupported = (family: "include" | "sort") => ({ + errors: [ + { + status: "400", + code: "bad_request", + title: "Bad Request", + detail: expect.stringContaining(`does not support the "${family}" parameter`), + source: { parameter: family }, + }, + ], + }); + + it.each([ + [ + "`Query.IncludeList`, which publishes no vocabulary", + "/include-list?include=author", + { + include: ["author"], + }, + ], + ["`Query.IncludeList`, an empty value", "/include-list?include=", { include: [] }], + ["a custom `sort` codec", "/custom-sort?sort=-anything", { sort: "-anything" }], + [ + "a recursive `include` codec with no vocabulary", + "/recursive-include?include=a", + { + include: "a", + }, + ], + [ + "a union of an empty and a non-empty query", + "/union-of-queries?include=author", + { + include: ["author"], + }, + ], + [ + "a union of an empty and a non-empty `sort`", + "/union-of-sorts?sort=title", + { + sort: [{ field: "title", direction: "asc" }], + }, + ], + [ + "a union of an empty `include` and `Query.IncludeList`", + "/union-with-open-include?include=author", + { + include: ["author"], + }, + ], + [ + "`Query.IncludeList` beside an empty vocabulary under another name", + "/open-include-beside-empty?include=author", + { + include: ["author"], + }, + ], + ["another family's empty vocabulary", "/sort-codec-as-include?include=", { include: [] }], + ] as const)("supports %s", async (_, url, query) => { + const response = await serve(url); + expect(response.status).toBe(200); + expect(response.body).toEqual(query); + }); + + it.each([ + [ + "an empty `include` beside a non-empty one under another name", + "/empty-include-beside-other?include=author", + "include", + ], + [ + "an empty `sort` beside a non-empty one under another name", + "/empty-sort-beside-other?sort=title", + "sort", + ], + ["a suspended query", "/suspended-query?include=author", "include"], + ["a suspended query, an empty value", "/suspended-query?include=", "include"], + ["a suspended `include` codec", "/suspended-include?include=author", "include"], + ["an optional `include`", "/optional-include?include=", "include"], + ] as const)("rejects an empty vocabulary as unsupported: %s", async (_, url, family) => { + const response = await serve(url); + expect(response.status).toBe(400); + expect(response.body).toEqual(unsupported(family)); + }); +}); diff --git a/src/Middleware.ts b/src/Middleware.ts index 95d18ee6..ec1dae28 100644 --- a/src/Middleware.ts +++ b/src/Middleware.ts @@ -75,7 +75,6 @@ import { ErrorReporter, Layer, Option, - Predicate, Record as Rec, Schema, SchemaAST, @@ -95,10 +94,11 @@ import { } from "./ApiError.js"; import { pointer } from "./Document.js"; import type { ErrorSource } from "./Document.js"; -import type { ErrorMeta } from "./internal/errorMeta.js"; -import { errorMetaOf, indexErrorMeta } from "./internal/errorMeta.js"; +import { declaredNames } from "./internal/declaredQuery.js"; +import { indexErrorMeta } from "./internal/errorMeta.js"; import { MEDIA_TYPE, parseMediaType } from "./internal/media.js"; import { withCreatedLocation } from "./internal/responseBody.js"; +import { admitsNoValue } from "./internal/vocabulary.js"; import { errorResponse, SERVER_ERROR } from "./ServerErrors.js"; // --------------------------------------------------------------------------- @@ -486,7 +486,7 @@ const SPEC_FAMILIES: ReadonlyArray = ["fields", "page", "filter"]; // that responds with a resource collection, and under the general // §Implementation-Specific Query Parameters rule on any other. An endpoint // supports one by declaring it with at least one legal value (#282). -const SUPPORT_FAMILIES: Readonly> = { +const SUPPORT_FAMILIES: Readonly> = { include: 'This endpoint does not support the "include" parameter. JSON:API requires an ' + "endpoint that does not support inclusion of related resources to reject any " + @@ -496,6 +496,8 @@ const SUPPORT_FAMILIES: Readonly> = { "that does not support the requested sorting to reject it.", }; +const SUPPORT_FAMILY_NAMES = Rec.keys(SUPPORT_FAMILIES); + // A family base name made only of a-z is reserved for the specification. const RESERVED_BASE_NAME = /^[a-z]+$/; @@ -526,9 +528,11 @@ export interface QueryParameterOptions { * JSON:API 1.1 reserves these names for the specification, so accepting one * is a deliberate deviation: prefer renaming the parameter (`langCode`, * `x-lang`) when the host controls it. Listing `include` or `sort` admits - * it on an endpoint that does not support it, which then ignores it - * instead of answering the 400 the specification requires. Defaults to - * none. + * it on an endpoint that does not support it instead of answering the 400 + * the specification requires: an endpoint that does not declare it then + * ignores it, and one that declares it with an empty vocabulary decodes it, + * so its codec rejects any value that names a path or field ("This + * endpoint supports no include paths."). Defaults to none. * * An entry that is not such a base name — a bracketed member (`lang[x]`), * a name with any other character (`Lang`, ` lang`), or `""` — is refused @@ -614,7 +618,7 @@ const rejectQueryParameters = ( code: BadRequest.code, ...(BadRequest.title !== undefined ? { title: BadRequest.title } : {}), detail: Option.getOrElse( - Rec.get(SUPPORT_FAMILIES, baseName(parameter)), + Rec.get(SUPPORT_FAMILIES, baseName(parameter)), () => `Query parameter "${parameter}" is not supported. JSON:API reserves parameter ` + "names made only of the letters a-z for the specification; an implementation-" + @@ -703,88 +707,19 @@ export const checkQueryParameters = ( rejectQueryParameters(names, options?.declared ?? [], allowedBaseNames(options)), ); -// What an endpoint's query schema declares, for `checkQueryParameters`: -// the wire names of its encoded (flat) side, or none when that side could -// accept a name this walk cannot enumerate — a record keyed by any string, -// say — in which case the check stands aside rather than reject a parameter -// the endpoint might process. `filter: true`'s `filter[…]` rest is the -// spec's own family and enumerable as such. -const declaredNames = (ast: SchemaAST.AST): Option.Option> => { - const encoded = SchemaAST.toEncoded(ast); - if (SchemaAST.isObjects(encoded)) { - return Option.map( - Option.all(encoded.indexSignatures.map(({ parameter }) => familyPrefix(parameter))), - (prefixes) => [ - ...encoded.propertySignatures.map((signature) => String(signature.name)), - ...prefixes, - ], - ); - } - if (SchemaAST.isUnion(encoded)) { - return Option.map(Option.all(encoded.types.map(declaredNames)), Arr.flatten); - } - if (SchemaAST.isSuspend(encoded)) return declaredNames(encoded.thunk()); - return Option.none(); -}; - -// The family an index signature's key admits, when it names one: a template -// literal whose literal head closes the base name (`filter[`). Any other key -// could match a base name of any spelling. -const familyPrefix = (parameter: SchemaAST.AST): Option.Option => { - if (!SchemaAST.isTemplateLiteral(parameter)) return Option.none(); - const [head] = parameter.parts; - return head !== undefined && - SchemaAST.isLiteral(head) && - Predicate.isString(head.literal) && - head.literal.includes("[") - ? Option.some(head.literal) - : Option.none(); -}; - -// The `meta` member under which each support family's codec publishes its -// vocabulary: `Query.Include`'s include paths, `Query.Sort`'s sortable fields. -const VOCABULARY_META = { include: "includablePaths", sort: "sortableFields" } as const; - -const isEmptyVocabulary = Schema.is(Schema.Tuple([])); - -// The schemas directly under a node that can carry error `meta`. A `Suspend` -// is not followed, so a recursive schema cannot loop the walk. -const childrenOf = (ast: SchemaAST.AST): ReadonlyArray => { - if (SchemaAST.isObjects(ast)) { - return [ - ...ast.propertySignatures.map((signature) => signature.type), - ...ast.indexSignatures.map((signature) => signature.type), - ]; - } - if (SchemaAST.isArrays(ast)) return [...ast.elements, ...ast.rest]; - return SchemaAST.isUnion(ast) ? ast.types : []; -}; - -// Every error `meta` a schema publishes, from its own node and every node -// under it (struct members, array elements, union members). -const errorMetaWithin = (ast: SchemaAST.AST): ReadonlyArray => { - const own = errorMetaOf(ast.annotations); - return [...(own === undefined ? [] : [own]), ...childrenOf(ast).flatMap(errorMetaWithin)]; -}; - // The support families an endpoint's query schema declares with an empty // vocabulary: `include: { paths: [] }`, `include: true` over no // relationships, `sort: true` over no attributes. Such a family supports no // value, so it counts as undeclared (owner decision on #282): every request // that carries it gets the same 400 as on an endpoint that never declared it. -// A family counts as empty only when every vocabulary the schema publishes -// for it is empty. -const emptyVocabularies = (ast: SchemaAST.AST): ReadonlyArray => { - const published = errorMetaWithin(SchemaAST.toType(ast)); - return Arr.filter(Rec.keys(VOCABULARY_META), (family) => { - const key = VOCABULARY_META[family]; - const vocabularies = Arr.flatMap(published, (meta) => (Rec.has(meta, key) ? [meta[key]] : [])); - return Arr.isReadonlyArrayNonEmpty(vocabularies) && Arr.every(vocabularies, isEmptyVocabulary); - }); -}; +// Each family is read off its own decoded property only (`admitsNoValue`). +const emptyVocabularies = (ast: SchemaAST.AST): ReadonlyArray => + Arr.filter(SUPPORT_FAMILY_NAMES, (family) => admitsNoValue(ast, family)); -// What an endpoint supports, for `checkQueryParameters`: the names its query -// schema declares, less a support family it declares with no legal value. +// What an endpoint supports, for `checkQueryParameters`: the wire names its +// query schema declares (`declaredNames`; none when it could accept a name +// the walk cannot enumerate, and the check then stands aside), less a support +// family it declares with no legal value. const supportedNames = (ast: SchemaAST.AST): Option.Option> => Option.map(declaredNames(ast), (names) => { const empty = emptyVocabularies(ast); @@ -1038,7 +973,10 @@ export const schemaErrorsLayer = (options?: QueryParameterOptions): Layer.Layer< * `?include=` too). So is one the schema declares with an empty vocabulary, * which supports no value: `include: { paths: [] }`, `include: true` on a * resource with no relationships, `sort: true` on one with no attributes. - * JSON:API 1.1 requires it: §Inclusion of Related Resources for `include`; + * Only the schema's own decoded `include` / `sort` property counts, read + * through a union or `Schema.suspend`; one whose codec publishes no + * vocabulary (`Query.IncludeList`, a custom codec), or a non-empty one in + * any member of a union, supports the family. JSON:API 1.1 requires it: §Inclusion of Related Resources for `include`; * for `sort`, §Sorting on an endpoint that responds with a resource * collection, and on a single-resource endpoint (`GET /articles/1?sort=title`) * the general §Implementation-Specific Query Parameters rule, since that diff --git a/src/Query.ts b/src/Query.ts index 96048698..7306b5a1 100644 --- a/src/Query.ts +++ b/src/Query.ts @@ -745,13 +745,18 @@ export const Include = < ) as ReadonlyArray>; return repeatable( CommaSeparated( - // The whitelist rides on the literal schema as error `meta`, so the 400 - // `Middleware.schemaErrorDocument` renders for a rejected path carries - // `meta.includablePaths` — the same set `ApiError.UnsupportedIncludePath` - // publishes — and a caller learns the legal paths without a second call. - // An empty set says so rather than "Expected never" (#282). + // The whitelist rides on the literal schema as the `include` + // vocabulary, so the 400 `Middleware.schemaErrorDocument` renders for a + // rejected path carries `meta.includablePaths` — the same set + // `ApiError.UnsupportedIncludePath` publishes — and a caller learns the + // legal paths without a second call. An empty set makes `include` + // unsupported (#282), and its rejection says so rather than "Expected + // never". Schema.Literals(paths).annotate( - vocabularyAnnotations("includablePaths", paths, "This endpoint supports no include paths."), + vocabularyAnnotations( + { family: "include", values: paths }, + "This endpoint supports no include paths.", + ), ), ), ) as Include>; diff --git a/src/internal/codecs.ts b/src/internal/codecs.ts index 9a9f0dda..9aeeca23 100644 --- a/src/internal/codecs.ts +++ b/src/internal/codecs.ts @@ -6,7 +6,8 @@ import { Array as Arr, Option, Record as Rec, Schema, SchemaTransformation } from "effect"; import type { Term } from "../Sort.js"; import { define } from "./define.js"; -import { errorMeta } from "./errorMeta.js"; +import type { Vocabulary } from "./vocabulary.js"; +import { vocabularyAnnotation } from "./vocabulary.js"; /** * A comma-separated list codec: `"a,b,c"` ↔ `["a", "b", "c"]`. @@ -92,18 +93,18 @@ export const repeatable = ( /** * The annotations of a closed vocabulary's literal schema: its whole set as - * error `meta` under `key`, and, when the set is empty, a `message` saying so — - * `Schema.Literals([])` is `never`, whose rejection would otherwise read - * "Expected never" (#282). + * the family's vocabulary (`internal/vocabulary.ts`), which the 400 for a + * rejected value renders as error `meta` and the support check reads, and, + * when the set is empty, a `message` saying so — `Schema.Literals([])` is + * `never`, whose rejection would otherwise read "Expected never" (#282). */ export const vocabularyAnnotations = ( - key: string, - vocabulary: ReadonlyArray, + vocabulary: Vocabulary, emptyMessage: string, ): Schema.Annotations.Annotations => - Arr.match(vocabulary, { - onEmpty: () => ({ ...errorMeta({ [key]: vocabulary }), message: emptyMessage }), - onNonEmpty: () => errorMeta({ [key]: vocabulary }), + Arr.match(vocabulary.values, { + onEmpty: () => ({ ...vocabularyAnnotation(vocabulary), message: emptyMessage }), + onNonEmpty: () => vocabularyAnnotation(vocabulary), }); /** @@ -135,11 +136,15 @@ export interface Sort extends Schema.decodeTo< */ export const Sort = (fields: ReadonlyArray): Sort => { const item = Schema.Struct({ - // The sortable set rides on the literal schema as error `meta`, so the 400 - // for an unknown field carries `meta.sortableFields` (see `errorMeta`). - // An empty set says so rather than "Expected never" (#282). + // The sortable set rides on the literal schema as the `sort` vocabulary, + // so the 400 for an unknown field carries `meta.sortableFields` (see + // `errorMeta`), and an empty set makes `sort` unsupported (#282). An + // empty set's rejection says so rather than "Expected never". field: Schema.Literals(fields as ReadonlyArray).annotate( - vocabularyAnnotations("sortableFields", fields, "This endpoint supports no sortable fields."), + vocabularyAnnotations( + { family: "sort", values: fields }, + "This endpoint supports no sortable fields.", + ), ), direction: Schema.Literals(["asc", "desc"] as ["asc", "desc"]), }); diff --git a/src/internal/errorMeta.ts b/src/internal/errorMeta.ts index b80a430a..617f8835 100644 --- a/src/internal/errorMeta.ts +++ b/src/internal/errorMeta.ts @@ -1,19 +1,18 @@ /** * Error `meta` carried by a schema, for the 400 a decode failure renders. * - * A closed vocabulary — the include paths an endpoint supports, the fields a - * resource sorts on — is derived once, at schema-build time, and the schema - * that enforces it is the only place that knows the whole set. When a request - * names a member outside it, the spec-compliant answer is a 400 whose `detail` - * says which value failed; what the caller actually needs next is the set it - * should have picked from. This annotation lets the codec that owns the set - * publish it, and lets the schema-error renderer (`Middleware.schemaErrorDocument`) - * copy it onto the error object's `meta` — `meta.includablePaths`, - * `meta.sortableFields` — without the renderer knowing anything about - * includes or sorts. + * When a request names a member outside a closed vocabulary — the include + * paths an endpoint supports, the fields a resource sorts on — the + * spec-compliant answer is a 400 whose `detail` says which value failed; + * what the caller actually needs next is the set it should have picked from. + * The codec that owns the set publishes it as its vocabulary + * (`internal/vocabulary.ts`), and this module lets the schema-error renderer + * (`Middleware.schemaErrorDocument`) copy it onto the error object's `meta` — + * `meta.includablePaths`, `meta.sortableFields` — without the renderer + * knowing anything about includes or sorts. * * The lookup walks the issue tree once, recording the `meta` of every node - * whose AST carries the annotation together with the path at which it was + * whose AST publishes a vocabulary together with the path at which it was * found; a formatted leaf then takes the meta of the nearest annotated node * above it (the node's path is a prefix of the leaf's), so a failure inside a * repeated-key list (`include[1]`) still reaches the annotation on the list's @@ -21,24 +20,29 @@ */ import type { Schema } from "effect"; import type { SchemaIssue } from "effect"; +import * as Option from "effect/Option"; +import type { Family } from "./vocabulary.js"; +import { vocabularyOf } from "./vocabulary.js"; -/** The annotation key. Namespaced so it can never collide with a consumer's. */ -const ERROR_META_ANNOTATION = "~@thomasfosterau/effect-jsonapi/errorMeta"; +/** The `meta` a vocabulary renders as: members merged into the error object's `meta`. */ +type ErrorMeta = Readonly>; -/** The shape the annotation carries: members merged into the error object's `meta`. */ -export type ErrorMeta = Readonly>; - -/** The annotation object `schema.annotate(...)` takes to publish `meta`. */ -export const errorMeta = (meta: ErrorMeta): { readonly [ERROR_META_ANNOTATION]: ErrorMeta } => ({ - [ERROR_META_ANNOTATION]: meta, -}); +// The `meta` member each family's vocabulary renders under. A family not +// listed here publishes its vocabulary to the support check only. +const META_KEYS: Partial>> = { + include: "includablePaths", + sort: "sortableFields", +}; -/** The `meta` a schema node publishes through its annotations, if any. */ -export const errorMetaOf = ( +/** The `meta` a schema node publishes through its vocabulary, if any. */ +const errorMetaOf = ( annotations: Schema.Annotations.Annotations | undefined, ): ErrorMeta | undefined => { - const meta = annotations?.[ERROR_META_ANNOTATION]; - return typeof meta === "object" && meta !== null ? (meta as ErrorMeta) : undefined; + if (annotations === undefined) return undefined; + const vocabulary = vocabularyOf(annotations); + if (Option.isNone(vocabulary)) return undefined; + const key = META_KEYS[vocabulary.value.family]; + return key === undefined ? undefined : { [key]: vocabulary.value.values }; }; /** One annotated node: where in the decoded value it sits, and what it publishes. */ diff --git a/src/internal/vocabulary.ts b/src/internal/vocabulary.ts new file mode 100644 index 00000000..5e6f878d --- /dev/null +++ b/src/internal/vocabulary.ts @@ -0,0 +1,168 @@ +/** + * The closed vocabulary a query family's codec admits, published on the + * codec's schema. + * + * A closed vocabulary — the include paths an endpoint supports, the fields a + * resource sorts on — is derived once, at schema-build time, and the schema + * that enforces it is the only place that knows the whole set. This + * annotation lets that schema publish it, so two readers can use it without + * knowing how any family's codec is built: + * + * - the schema-error renderer (`internal/errorMeta.ts`) copies it onto a + * rejected value's error object as `meta` (`meta.includablePaths`, + * `meta.sortableFields`), so a caller learns the legal set; + * - `Middleware`'s support check ({@link admitsNoValue}) treats a family + * whose vocabulary is empty as one the endpoint does not support (#282). + * + * @internal + */ +import * as Arr from "effect/Array"; +import * as Option from "effect/Option"; +import * as Predicate from "effect/Predicate"; +import type * as Schema from "effect/Schema"; +import * as SchemaAST from "effect/SchemaAST"; + +/** The annotation key. Namespaced so it can never collide with a consumer's. */ +const VOCABULARY_ANNOTATION = "~@thomasfosterau/effect-jsonapi/vocabulary"; + +/** + * A closed vocabulary: every value one JSON:API query parameter family's + * codec admits. Only `include` and `sort` publish one today; `page`, + * `filter` and the per-type `fields[TYPE]` are spelled here so their codecs + * can publish theirs under the same annotation. + * + * @internal + */ +export type Vocabulary = + | { + /** The family whose values these are: one parameter, unbracketed or bracketed. */ + readonly family: "include" | "sort" | "page" | "filter"; + /** Every value the codec admits: include paths, sortable fields, member names. */ + readonly values: ReadonlyArray; + } + | { + /** A sparse fieldset, whose parameter is bracketed per resource type. */ + readonly family: "fields"; + /** The resource type of the `fields[TYPE]` parameter it governs. */ + readonly type: string; + /** Every field name the fieldset admits. */ + readonly values: ReadonlyArray; + }; + +/** + * The JSON:API query parameter families a vocabulary can belong to. + * + * @internal + */ +export type Family = Vocabulary["family"]; + +/** + * The annotation object `schema.annotate(...)` takes to publish a vocabulary. + * + * @internal + */ +export const vocabularyAnnotation = (vocabulary: Vocabulary) => + ({ [VOCABULARY_ANNOTATION]: vocabulary }) satisfies Schema.Annotations.Annotations; + +const isVocabulary = (value: unknown): value is Vocabulary => + Predicate.hasProperty(value, "family") && Predicate.hasProperty(value, "values"); + +/** + * The vocabulary a schema node publishes through its annotations, if any. + * + * @internal + */ +export const vocabularyOf = ( + annotations: Schema.Annotations.Annotations, +): Option.Option => + Option.liftPredicate(annotations[VOCABULARY_ANNOTATION], isVocabulary); + +// The suspended schemas on the way down to a node, so a recursive schema +// cannot loop a walk: a `Suspend` already on the path is not followed again. +type Visiting = ReadonlyArray; + +const enter = (visiting: Visiting, ast: SchemaAST.Suspend): Option.Option => + visiting.includes(ast) ? Option.none() : Option.some([...visiting, ast]); + +// The family's own vocabulary a node publishes, if it publishes one. +const ownVocabulary = (ast: SchemaAST.AST, family: Family): Option.Option => + Option.filter( + Option.flatMap(Option.fromNullishOr(ast.annotations), vocabularyOf), + (vocabulary) => vocabulary.family === family, + ); + +// Whether every value `ast` decodes draws its `family` values from an empty +// vocabulary. A node publishing the family's vocabulary decides it; a union +// does when all its members do (an `undefined` member carries no value); a +// struct or an array does when any member does, a value of it carrying that +// member's values; anything else publishes no vocabulary, so it admits +// values this walk cannot see. A `Suspend` already on the path admits them +// too: it adds nothing the path has not already been asked. +const drawsOnlyFromEmpty = (ast: SchemaAST.AST, family: Family, visiting: Visiting): boolean => + Option.match(ownVocabulary(ast, family), { + onSome: (vocabulary) => Arr.isReadonlyArrayEmpty(vocabulary.values), + onNone: () => { + const within = (child: SchemaAST.AST) => drawsOnlyFromEmpty(child, family, visiting); + if (SchemaAST.isUnion(ast)) { + const members = Arr.filter(ast.types, (member) => !SchemaAST.isUndefined(member)); + return Arr.isReadonlyArrayNonEmpty(members) && Arr.every(members, within); + } + if (SchemaAST.isObjects(ast)) { + return Arr.some([...ast.propertySignatures, ...ast.indexSignatures], ({ type }) => + within(type), + ); + } + if (SchemaAST.isArrays(ast)) return Arr.some([...ast.elements, ...ast.rest], within); + if (SchemaAST.isSuspend(ast)) { + return Option.exists(enter(visiting, ast), (next) => + drawsOnlyFromEmpty(ast.thunk(), family, next), + ); + } + return false; + }, + }); + +// The schemas a query decodes its property `name` with: the property of that +// name on a struct, on every member of a union, through a suspended schema. +const propertiesNamed = ( + ast: SchemaAST.AST, + name: string, + visiting: Visiting, +): ReadonlyArray => { + if (SchemaAST.isObjects(ast)) { + return Arr.flatMap(ast.propertySignatures, (signature) => + signature.name === name ? [signature.type] : [], + ); + } + if (SchemaAST.isUnion(ast)) { + return Arr.flatMap(ast.types, (member) => propertiesNamed(member, name, visiting)); + } + if (SchemaAST.isSuspend(ast)) { + return Option.match(enter(visiting, ast), { + onNone: () => [], + onSome: (next) => propertiesNamed(ast.thunk(), name, next), + }); + } + return []; +}; + +/** + * Whether a query schema declares `family` only with an empty vocabulary, so + * that no value of it can decode: `include: { paths: [] }`, `include: true` + * over no relationships, `sort: true` over no attributes. Reads the decoded + * property named after the family and nothing else, so a vocabulary under + * another name never counts. True only when every such property, in every + * member of a union query, draws its values from empty vocabularies alone; a + * property that publishes no vocabulary (`Query.IncludeList`, a custom codec) + * or a non-empty one anywhere admits a value, and so does an endpoint that + * declares no such property. + * + * @internal + */ +export const admitsNoValue = (query: SchemaAST.AST, family: Family): boolean => { + const properties = propertiesNamed(SchemaAST.toType(query), family, []); + return ( + Arr.isReadonlyArrayNonEmpty(properties) && + Arr.every(properties, (property) => drawsOnlyFromEmpty(property, family, [])) + ); +}; diff --git a/test/entry-points.test.ts b/test/entry-points.test.ts index 34f9983e..c02f8180 100644 --- a/test/entry-points.test.ts +++ b/test/entry-points.test.ts @@ -92,6 +92,7 @@ const HTTP_TIER = [ "internal/httpMedia.ts", "internal/linkage.ts", "internal/responseBody.ts", + "internal/vocabulary.ts", ]; /** From 4c582111253eb43a89c4bc5b020e1bb667375848 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 9 Oct 2026 07:43:18 +0000 Subject: [PATCH 2/2] docs(Middleware): say which property decides an empty vocabulary after the spec citation The sentence sat between the empty-vocabulary list and "JSON:API 1.1 requires it", so "it" no longer read as the 400. Claude-Session: https://claude.ai/code/session_0187g2QpzaHqEzX8GJxiJBVc Co-Authored-By: Claude --- src/Middleware.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/Middleware.ts b/src/Middleware.ts index ec1dae28..8649ce92 100644 --- a/src/Middleware.ts +++ b/src/Middleware.ts @@ -973,16 +973,17 @@ export const schemaErrorsLayer = (options?: QueryParameterOptions): Layer.Layer< * `?include=` too). So is one the schema declares with an empty vocabulary, * which supports no value: `include: { paths: [] }`, `include: true` on a * resource with no relationships, `sort: true` on one with no attributes. - * Only the schema's own decoded `include` / `sort` property counts, read - * through a union or `Schema.suspend`; one whose codec publishes no - * vocabulary (`Query.IncludeList`, a custom codec), or a non-empty one in - * any member of a union, supports the family. JSON:API 1.1 requires it: §Inclusion of Related Resources for `include`; + * JSON:API 1.1 requires it: §Inclusion of Related Resources for `include`; * for `sort`, §Sorting on an endpoint that responds with a resource * collection, and on a single-resource endpoint (`GET /articles/1?sort=title`) * the general §Implementation-Specific Query Parameters rule, since that * endpoint does not know how to process `sort` as a query parameter from the - * specification. An undeclared `fields[TYPE]`, `page[…]` or `filter[…]` is - * still ignored. + * specification. Only the schema's own decoded `include` / `sort` property + * decides whether its vocabulary is empty, read through a union or + * `Schema.suspend`: one whose codec publishes no vocabulary + * (`Query.IncludeList`, a custom codec), or a non-empty one in any member of + * a union, supports the family. An undeclared `fields[TYPE]`, `page[…]` or + * `filter[…]` is still ignored. * * A handler whose response fails to encode against its endpoint's own schema * (`HttpApiSchemaError` kind `"Body"` or `"ResponseHeaders"`) is a server