From 96ed1217847c7600a111f8696e9e697ff2f04715 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 8 Oct 2026 06:14:26 +0000 Subject: [PATCH 1/2] fix: answer every request carrying `include` with an `included` key (#232) Follow-up to #257's review. - `ResourceHandlers.related`: a to-one with empty linkage validated no include paths and answered `{ data: null }` without `included`. It now validates the request's paths (400 for one outside the whitelist or too deep) and answers `{ data: null, included: [] }` when the request carried `include`. - Presence of `include` is the signal everywhere: `Assemble`'s walk and `Handlers.resolveIncluded` treated the `[]` a bare `?include=` decodes to as "not requested"; both now answer it with `[]`, so the document keeps its `included` key. - `Handlers.DocumentValue` always declares `included?`, so `Handlers.data(r, { included: [] }).included` type-checks. - Tests: the related to-one cases, `?include=` with no paths through `Assemble` / `resolveIncluded` and end to end in the github example, validate-only `collection` / `unpaginatedCollection`, "no include, no key" regressions in the github and northwind examples, and a type test. Claude-Session: https://claude.ai/code/session_0187g2QpzaHqEzX8GJxiJBVc Co-Authored-By: Claude --- .changeset/included-key-on-bare-include.md | 5 +++ README.md | 4 +- examples/github/test/github.test.ts | 35 +++++++++++++++ examples/northwind/test/northwind.test.ts | 13 ++++++ src/Assemble.test.ts | 44 ++++++++++++++++++- src/Assemble.ts | 18 +++++--- src/Handlers.include.test.ts | 10 ++++- src/Handlers.ts | 51 ++++++++++++---------- src/ResourceHandlers.test.ts | 38 ++++++++++++++++ src/ResourceHandlers.ts | 34 +++++++++++---- test/empty-included.types.ts | 45 +++++++++++++++++++ 11 files changed, 254 insertions(+), 43 deletions(-) create mode 100644 .changeset/included-key-on-bare-include.md create mode 100644 test/empty-included.types.ts diff --git a/.changeset/included-key-on-bare-include.md b/.changeset/included-key-on-bare-include.md new file mode 100644 index 00000000..0d95a87c --- /dev/null +++ b/.changeset/included-key-on-bare-include.md @@ -0,0 +1,5 @@ +--- +"@thomasfosterau/effect-jsonapi": patch +--- + +Presence of `include` now decides the `included` key everywhere. A bare `?include=` decodes to `[]`; `Assemble.resource` / `Assemble.collection` / `Assemble.unpaginatedCollection` used to treat that as no `include` and omit the key, and now answer it with `included: []`, as does `Handlers.resolveIncluded`, which returns `[]` for an empty path list instead of `undefined`. `ResourceHandlers.related` answers a to-one with empty linkage `{ data: null, included: [] }` when the request carried `include`, and validates those paths first, so an unsupported path is a `400` there as it is for a resolved to-one (it used to answer `200` with no `included`). `Handlers.DocumentValue` now always declares an optional `included`, so `Handlers.data(r, { included: [] }).included` type-checks. diff --git a/README.md b/README.md index c0375547..8ec15dcd 100644 --- a/README.md +++ b/README.md @@ -1175,7 +1175,7 @@ What it guarantees, and why each one matters: | **Cycles terminate** | A graph that loops (`articles → comments → articles`) revisits resources the document already holds, which are never re-loaded | | **Depth-capped** | `depth` (default `3`, the deepest path `Query.Include` legalises) bounds the number of hops. §7.1 leaves the bound implementation-defined and each hop is another round of loader calls, so this is a denial-of-service boundary, not just an ergonomic one | | **Unresolvable refs dropped** | A type with no target, an id the batch didn't return, a row this viewer may not see: all normal outcomes, simply absent from `included`. A loader's own failure propagates and fails the document | -| **`undefined` when unasked** | So the builders omit the member. `[]` is the different statement "your walk resolved to nothing", which they emit as `included: []` | +| **`undefined` when unasked** | So the builders omit the member. `[]` is the different statement "your walk resolved to nothing" (a bare `?include=`, an empty path list, answers it too), which they emit as `included: []` | Because every resource is reached _through_ a document resource's linkage, full linkage holds by construction **for the array the resolver returns**: handed unchanged to `Handlers.data` / `Handlers.collection` with the same primary data, the builders' check is a guard over the resolver's own output rather than a live constraint. It is live again when anything between the walk and the document changes linkage, because the check runs on the resources the document actually emits: @@ -1536,7 +1536,7 @@ The refusal applies only when no range of any media type carries `q > 0`; anothe ### The assembler, the handlers and the registry -`Assemble.resource` / `Assemble.collection` are the seam a handler's document returns go through: capability `meta` (`canEdit` / `canDelete`, computed per resource by a hook — `roleCapabilities`, `ownedCapabilities`, or your own), links stringified, fieldsets projected, the `include` walk validated and resolved batched through a `Handlers.IncludeTargets` registry, the `jsonapi` member set. A request carrying `include` always gets the `included` key — `[]` when nothing resolved or every candidate was already primary data; without `include` the key is absent unless members the caller resolved itself survive the dedupe. +`Assemble.resource` / `Assemble.collection` are the seam a handler's document returns go through: capability `meta` (`canEdit` / `canDelete`, computed per resource by a hook — `roleCapabilities`, `ownedCapabilities`, or your own), links stringified, fieldsets projected, the `include` walk validated and resolved batched through a `Handlers.IncludeTargets` registry, the `jsonapi` member set. A request carrying `include` always gets the `included` key — `[]` when nothing resolved or every candidate was already primary data. Presence is the signal: a bare `?include=` decodes to `[]` and is a request carrying `include` too. Without `include` the key is absent unless members the caller resolved itself survive the dedupe. `ResourceHandlers.related` answers an empty to-one the same way: `{ data: null, included: [] }` when the request carried `include`, its paths validated (`400` for one outside the whitelist) though there is nothing to walk from. `Assemble.collection(resources, pagination, options?)` surfaces the page math — `meta.totalCount` and the five offset pagination links, carrying the request's other query pairs. A collection served whole (a small fixed list, or a to-many related collection that is never paged) uses `Assemble.unpaginatedCollection(resources, options?)` instead: the same stamping, projection, `include` walk, `included` handling and `jsonapi` member, with no pagination `links` (and no `links` member at all unless `self` is given) and no `meta` (unless `meta` is given) — and its `UnpaginatedCollectionDocument` type has no page math and no pagination links, so no `meta.totalCount` and no `next` / `last` link the endpoint doesn't honour is advertised: diff --git a/examples/github/test/github.test.ts b/examples/github/test/github.test.ts index d527f217..73b76cc3 100644 --- a/examples/github/test/github.test.ts +++ b/examples/github/test/github.test.ts @@ -78,6 +78,41 @@ describe("github example: fetching", () => { expect(document.included?.map((resource) => resource.type)).toEqual(["users"]); }); + it("omits `included` when the request carries no `include` (#232)", async () => { + const { list, one } = await run( + Effect.gen(function* () { + const client = yield* buildClient; + const one = yield* client.repositories.get({ + params: { id: Repository.Id.make("1") }, + query: {}, + }); + const list = yield* client.repositories.list({ query: {} }); + return { list, one }; + }), + ); + expect(one).not.toHaveProperty("included"); + expect(list).not.toHaveProperty("included"); + }); + + it("answers `?include=` with no paths with an empty `included` (#232)", async () => { + // `include: []` goes on the wire as a bare `?include=`, which decodes to + // `[]`: the request carried `include`, so the compound document keeps its + // key (§Fetching Includes), empty because no path names anything to load. + const { list, one } = await run( + Effect.gen(function* () { + const client = yield* buildClient; + const one = yield* client.repositories.get({ + params: { id: Repository.Id.make("1") }, + query: { include: [] }, + }); + const list = yield* client.repositories.list({ query: { include: [] } }); + return { list, one }; + }), + ); + expect(one.included).toEqual([]); + expect(list.included).toEqual([]); + }); + it("resolves 2-hop include paths: issue → repository → owner", async () => { const document = await run( Effect.gen(function* () { diff --git a/examples/northwind/test/northwind.test.ts b/examples/northwind/test/northwind.test.ts index afb074a6..1ab12175 100644 --- a/examples/northwind/test/northwind.test.ts +++ b/examples/northwind/test/northwind.test.ts @@ -106,6 +106,19 @@ describe("northwind example: fetching", () => { ]); }); + it("omits `included` when the request carries no `include` (#232)", async () => { + const { list, one } = await run( + Effect.gen(function* () { + const client = yield* buildClient; + const one = yield* client.products.get({ params: { id: Product.Id.make("1") }, query: {} }); + const list = yield* client.products.list({ query: {} }); + return { list, one }; + }), + ); + expect(one).not.toHaveProperty("included"); + expect(list).not.toHaveProperty("included"); + }); + it("narrows `included` to the requested include paths on the client", async () => { const include = ["category"] as const; const document = await run( diff --git a/src/Assemble.test.ts b/src/Assemble.test.ts index 5d55cc4d..99580e5a 100644 --- a/src/Assemble.test.ts +++ b/src/Assemble.test.ts @@ -242,9 +242,15 @@ describe("Assemble.resource", () => { expect( await run(Assemble.resource(person("p1"), { includable: ["birthPlace"] })), ).not.toHaveProperty("included"); + }); + + it("emits `included: []` for `?include=` with no paths: the request carried `include` (#232)", async () => { + // Presence is the signal: `?include=` decodes to `[]`, and a client that + // supplied `include`, even empty, gets the compound document's key. expect( - await run(Assemble.resource(person("p1"), { include: [], includable: ["birthPlace"] })), - ).not.toHaveProperty("included"); + (await run(Assemble.resource(person("p1"), { include: [], includable: ["birthPlace"] }))) + .included, + ).toEqual([]); }); it("emits `included: []` when include was requested and nothing resolved (#232)", async () => { @@ -469,6 +475,24 @@ describe("Assemble.collection", () => { ).toEqual([]); }); + it("emits `included: []` in validate-only mode: include, no registry (#232)", async () => { + const pagination = { totalCount: 3, offset: 0, limit: 10, baseUrl }; + expect( + ( + await run( + Assemble.collection(page, pagination, { + include: ["birthPlace"], + includable: ["birthPlace"], + }), + ) + ).included, + ).toEqual([]); + // `?include=` with no paths is still a request that carried `include`. + expect( + (await run(Assemble.collection(page, pagination, { include: [], includable: [] }))).included, + ).toEqual([]); + }); + it("resolves the page's include walk in one batch per target type, deduplicated", async () => { const { calls, targets } = registry([place]); const document = await run( @@ -619,6 +643,22 @@ describe("Assemble.unpaginatedCollection", () => { expect(deduped.included).toEqual([]); }); + it("emits `included: []` in validate-only mode: include, no registry (#232)", async () => { + expect( + ( + await run( + Assemble.unpaginatedCollection(whole, { + include: ["birthPlace"], + includable: ["birthPlace"], + }), + ) + ).included, + ).toEqual([]); + expect( + (await run(Assemble.unpaginatedCollection(whole, { include: [], includable: [] }))).included, + ).toEqual([]); + }); + it("assembles what `collection` does, less its links and meta", async () => { const options = { viewer: NON_ADMIN, diff --git a/src/Assemble.ts b/src/Assemble.ts index efdcc2c2..0ab3ab26 100644 --- a/src/Assemble.ts +++ b/src/Assemble.ts @@ -358,7 +358,12 @@ export interface Options | undefined; /** * The legal include paths — anything else fails @@ -685,9 +690,10 @@ const asValue = (resource: ResourceLike): Handlers.ResourceValue => /** * Validates the requested paths, then walks them. `undefined` means the - * request carried no `include`, and only that: a request that did gets an - * array, `[]` when there is no registry to walk through, so the document - * keeps its `included` key (§Fetching Includes, #232). + * request carried no `include`, and only that: a request that did — even a + * bare `?include=`, which decodes to `[]` — gets an array, `[]` when there is + * no registry to walk through or no path to walk, so the document keeps its + * `included` key (§Fetching Includes, #232). */ const walk = ( primary: ReadonlyArray, @@ -699,8 +705,8 @@ const walk = ( | Handlers.IncludeTargetError, Handlers.IncludeTargetServices > => { - const include = options.include ?? []; - if (include.length === 0) return Effect.succeed(undefined); + const include = options.include; + if (include === undefined) return Effect.succeed(undefined); const depth = options.depth ?? MAX_INCLUDE_DEPTH; return Query.validateIncludePaths(include, { includable: options.includable ?? [], diff --git a/src/Handlers.include.test.ts b/src/Handlers.include.test.ts index 1541ef94..0e301688 100644 --- a/src/Handlers.include.test.ts +++ b/src/Handlers.include.test.ts @@ -97,16 +97,22 @@ const graph: ReadonlyArray = [ const run = (effect: Effect.Effect) => Effect.runPromise(effect); describe("Handlers.resolveIncluded — nothing requested", () => { - it("resolves to undefined when no paths were requested, so the member is omitted", async () => { + it("resolves to undefined when no `include` was requested, so the member is omitted", async () => { const db = store(graph); expect( await run(Handlers.resolveIncluded(article1, undefined, db.targets("people"))), ).toBeUndefined(); - expect(await run(Handlers.resolveIncluded(article1, [], db.targets("people")))).toBeUndefined(); // and nothing was loaded to find that out expect(db.calls).toEqual([]); }); + it("resolves to [] for `?include=` with no paths: the request carried `include` (#232)", async () => { + const db = store(graph); + expect(await run(Handlers.resolveIncluded(article1, [], db.targets("people")))).toEqual([]); + // nothing to walk, so nothing loaded + expect(db.calls).toEqual([]); + }); + it("resolves to [] — not undefined — when the walk ran and came back empty", async () => { const db = store(graph); const empty: Handlers.ResourceValue = { type: "articles", id: "7" }; diff --git a/src/Handlers.ts b/src/Handlers.ts index 3118b7d8..43549c02 100644 --- a/src/Handlers.ts +++ b/src/Handlers.ts @@ -995,11 +995,12 @@ const resolve = ( * target, an id the batch didn't return, a row the viewer may not see: all * are normal outcomes, and simply absent from `included`. A loader's own * failure propagates and fails the document. - * - **`undefined` when nothing was requested**, so the builders omit the - * member. An empty array is the different statement "your walk resolved to - * nothing", and {@link data} / {@link collection} emit it as `included: []` - * — §Fetching Includes requires the key in every response to a request - * carrying `include`. + * - **`undefined` when nothing was requested** (`paths` is `undefined`), so + * the builders omit the member. An empty array is the different statement + * "your walk resolved to nothing" — including for an empty `paths`, which is + * a bare `?include=`: the request carried `include` — and {@link data} / + * {@link collection} emit it as `included: []`, because §Fetching Includes + * requires the key in every response to a request carrying `include`. * * **Full linkage holds by construction — for the array this returns.** Every * member is reached *through* the linkage of the primary data the walk started @@ -1106,15 +1107,17 @@ export const resolveIncluded = ( IncludeTargetError, IncludeTargetServices > => - (paths === undefined || paths.length === 0 + (paths === undefined ? Effect.succeed(undefined) - : resolve( - primary === null ? [] : Array.isArray(primary) ? primary : [primary as ResourceValue], - paths, - targets, - options?.concurrency ?? "unbounded", - options?.depth ?? 3, - )) as Effect.Effect< + : paths.length === 0 + ? Effect.succeed([]) + : resolve( + primary === null ? [] : Array.isArray(primary) ? primary : [primary as ResourceValue], + paths, + targets, + options?.concurrency ?? "unbounded", + options?.depth ?? 3, + )) as Effect.Effect< ReadonlyArray> | undefined, IncludeTargetError, IncludeTargetServices @@ -1125,17 +1128,18 @@ export const resolveIncluded = ( * {@link collection} return, named so consumers can annotate their own * document-assembling functions instead of hand-rolling the envelope type. * - * The `jsonapi` member is *conditional* on `J`, the same way `included` is - * conditional on `Included` and `meta` on `M`: it is present (and required, - * not optional — a builder that infers `J` from an argument has one to put - * there) only when a caller actually passed the `jsonapi` option, so the + * The `jsonapi` member is *conditional* on `J`, the same way `meta` is + * conditional on `M`: it is present (and required, not optional — a builder + * that infers `J` from an argument has one to put there) only when a caller actually passed the `jsonapi` option, so the * return type of `Handlers.data(article, { jsonapi: Document.v1_1 })` carries * `jsonapi: Document.JsonApiObjectValue` and the return type of * `Handlers.data(article)` has no `jsonapi` member at all — no cast needed - * either way. + * either way. `included` is always declared, optional: a builder emits any + * array it is given, so `Handlers.data(article, { included: [] })` — whose + * literal `[]` infers `Included = never` — still reads back `included: []`. * * The type stays *conditional* on its generics so TypeScript only infers - * `Included` / `M` / `J` from arguments — never from the expected (contextual) + * `M` / `J` from arguments — never from the expected (contextual) * return type of a handler, which breaks down inside `pipe(Effect.map(...))` * chains. * @@ -1148,10 +1152,11 @@ export type DocumentValue< M extends MetaValue = never, J extends JsonApiObjectValue = never, > = Simplify< - { readonly data: Data; readonly links?: LinksValue } & ([Included] extends [never] - ? {} - : { readonly included?: ReadonlyArray }) & - ([M] extends [never] ? {} : { readonly meta?: M }) & + { + readonly data: Data; + readonly included?: ReadonlyArray; + readonly links?: LinksValue; + } & ([M] extends [never] ? {} : { readonly meta?: M }) & ([J] extends [never] ? {} : { readonly jsonapi: J }) >; diff --git a/src/ResourceHandlers.test.ts b/src/ResourceHandlers.test.ts index 17f8509e..8a49d7a0 100644 --- a/src/ResourceHandlers.test.ts +++ b/src/ResourceHandlers.test.ts @@ -516,4 +516,42 @@ describe("related", () => { jsonapi: { version: "1.1" }, }); }); + + it("answers an empty to-one with `included: []` when the request carried `include` (#232)", async () => { + // §Fetching Includes: a request carrying `include` gets the `included` key, + // even when there is no related resource to walk from. + const empty = ResourceHandlers.related({ + ...config, + key: "polity", + cardinality: "one", + includable: ["country"], + }); + const [withPath, bareInclude, withoutInclude] = await Effect.runPromise( + Effect.all([ + empty({ params: { id: "c1" }, query: { include: ["country"] } }), + // `?include=` (no paths) is still a request that carried `include`. + empty({ params: { id: "c1" }, query: { include: [] } }), + empty({ params: { id: "c1" }, query: {} }), + ]), + ); + expect(withPath).toEqual({ data: null, included: [], jsonapi: { version: "1.1" } }); + expect(bareInclude).toEqual({ data: null, included: [], jsonapi: { version: "1.1" } }); + // Without `include` the key stays absent. + expect(withoutInclude).not.toHaveProperty("included"); + }); + + it("validates an empty to-one's include paths, as it does a resolved one's", async () => { + const empty = ResourceHandlers.related({ + ...config, + key: "polity", + cardinality: "one", + includable: ["country"], + }); + expect( + await failure(empty({ params: { id: "c1" }, query: { include: ["nope"] } })), + ).toBeInstanceOf(ApiError.UnsupportedIncludePath); + expect( + await failure(empty({ params: { id: "c1" }, query: { include: ["a.b.c.d"] } })), + ).toBeInstanceOf(ApiError.UnsupportedIncludeDepth); + }); }); diff --git a/src/ResourceHandlers.ts b/src/ResourceHandlers.ts index 1fb56926..efc9f973 100644 --- a/src/ResourceHandlers.ts +++ b/src/ResourceHandlers.ts @@ -768,7 +768,9 @@ const loadRefs = ( * paginated collection (offset / limit over the linkage; only the page's * refs are loaded, one call per distinct target type), a **to-one** the * single related resource honouring `?include=`, or `{ data: null }` for - * empty linkage. A ref that doesn't resolve is dropped, never a failure. + * empty linkage — with `included: []` when the request carried `include`, + * whose paths are validated either way. A ref that doesn't resolve is + * dropped, never a failure. * * @since 0.16.0 * @category constructors @@ -784,12 +786,14 @@ export const related = < Targets extends Handlers.IncludeTargets = never, >( config: RelatedConfig, -): (( - request: RelatedRequest, -) => Effect.Effect< +): ((request: RelatedRequest) => Effect.Effect< | Assemble.CollectionDocument | Assemble.ResourceDocument - | { readonly data: null; readonly jsonapi: typeof Assemble.JSONAPI_MEMBER }, + | { + readonly data: null; + readonly included?: readonly []; + readonly jsonapi: typeof Assemble.JSONAPI_MEMBER; + }, E | Assemble.IncludeError | Handlers.IncludeTargetError, R | RV | RL | Handlers.IncludeTargetServices >) => { @@ -828,8 +832,18 @@ export const related = < const refs = Assemble.relationshipRefs(yield* config.loadParent(params.id), config.key); const [resource] = yield* loadRefs(refs.slice(0, 1), config.targets, concurrency); // An empty linkage and a ref that doesn't resolve are the same answer on - // the wire: `data: null`. - if (resource === undefined) return { data: null, jsonapi: Assemble.JSONAPI_MEMBER } as const; + // the wire: `data: null`. There is nothing to walk from, but the request's + // paths are still validated as a resolved resource's are, and a request + // carrying `include` still gets the key, empty (§Fetching Includes, #232). + if (resource === undefined) { + const include = query?.include; + if (include === undefined) return { data: null, jsonapi: Assemble.JSONAPI_MEMBER } as const; + yield* Query.validateIncludePaths(include, { + includable: config.includable ?? [], + maxDepth: Assemble.MAX_INCLUDE_DEPTH, + }); + return { data: null, included: [], jsonapi: Assemble.JSONAPI_MEMBER } as const; + } return yield* Assemble.resource(resource, { ...capabilities, viewer: yield* viewer, @@ -844,7 +858,11 @@ export const related = < ) => Effect.Effect< | Assemble.CollectionDocument | Assemble.ResourceDocument - | { readonly data: null; readonly jsonapi: typeof Assemble.JSONAPI_MEMBER }, + | { + readonly data: null; + readonly included?: readonly []; + readonly jsonapi: typeof Assemble.JSONAPI_MEMBER; + }, E | Assemble.IncludeError | Handlers.IncludeTargetError, R | RV | RL | Handlers.IncludeTargetServices >; diff --git a/test/empty-included.types.ts b/test/empty-included.types.ts new file mode 100644 index 00000000..7f7dacca --- /dev/null +++ b/test/empty-included.types.ts @@ -0,0 +1,45 @@ +/** + * Type-level tests for the `included` member of the `Handlers` document + * builders' return type (#232). + * + * `Handlers.data(r, { included: [] })` emits `included: []` on the wire, so the + * return type must let a caller read `.included` back, even though a literal + * `[]` infers the member type `never`. The member is optional in every + * `DocumentValue`: `undefined` (or no option at all) omits it. + * + * This file is type-checked by the `typecheck` task and never executed. + */ +import { Schema } from "effect"; +import { Handlers, Relationship, Resource } from "@thomasfosterau/effect-jsonapi"; + +const Person = Resource.make("people", { attributes: { name: Schema.String } }); +const person = Person.make({ id: Person.Id.make("9"), attributes: { name: "Dan" } }); +const Article = Resource.make("articles", { + attributes: { title: Schema.String }, + relationships: { author: Relationship.one(() => Person) }, +}); +const article = Article.make({ + id: Article.Id.make("1"), + attributes: { title: "Hi" }, + relationships: { author: { data: { type: "people", id: person.id } } }, +}); + +// A literal `[]` infers `Included = never`; the member still reads back. +export const dataEmpty = Handlers.data(article, { included: [] }); +export const dataEmptyIncluded: ReadonlyArray | undefined = dataEmpty.included; + +export const collectionEmpty = Handlers.collection([article], { included: [] }); +export const collectionEmptyIncluded: ReadonlyArray | undefined = collectionEmpty.included; + +// No option at all: the member is optional and holds nothing. +export const dataBare = Handlers.data(article); +export const dataBareIncluded: ReadonlyArray | undefined = dataBare.included; + +// Negative control: the member is optional, never required. +// @ts-expect-error -- `included` may be absent, so it is not a plain array +export const dataEmptyRequired: ReadonlyArray = dataEmpty.included; + +// A non-empty `included` keeps its element type. +export const dataWithAuthor = Handlers.data(article, { included: [person] }); +export const dataWithAuthorIncluded: ReadonlyArray | undefined = + dataWithAuthor.included; From 9f03440ac8fdc4cfab10a115f7a41416776392e0 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 8 Oct 2026 06:43:47 +0000 Subject: [PATCH 2/2] fix: address review of the empty `included` follow-up (#232) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `.changeset/dedupe-included-against-primary.md`: a document whose `included` candidates are all primary data now carries `included: []` (the presence rule from #232), not an omitted member; say so, and that the `Assemble` builders omit it only without `include`. - `src/ResourceHandlers.test.ts`: give the empty to-one test's `Effect.all` an explicit `{ concurrency: 1 }` (`require-effect-concurrency`), accept a 3-hop path at the default depth limit, and reject a path when no `includable` is configured. - `test/empty-included.types.ts`: pin the `included` member exactly with `Equals, …>`, which fails when the key is absent, required or `any`; import `Schema` from `effect/Schema`. - `src/Handlers.ts`: reflow an overlong `DocumentValue` doc line. Part of #232. Claude-Session: https://claude.ai/code/session_0187g2QpzaHqEzX8GJxiJBVc Co-Authored-By: Claude --- .changeset/dedupe-included-against-primary.md | 2 +- src/Handlers.ts | 5 +- src/ResourceHandlers.test.ts | 27 +++++++--- test/empty-included.types.ts | 51 +++++++++++++------ 4 files changed, 59 insertions(+), 26 deletions(-) diff --git a/.changeset/dedupe-included-against-primary.md b/.changeset/dedupe-included-against-primary.md index 68a24376..4022c686 100644 --- a/.changeset/dedupe-included-against-primary.md +++ b/.changeset/dedupe-included-against-primary.md @@ -2,4 +2,4 @@ "@thomasfosterau/effect-jsonapi": patch --- -`Handlers.data`, `Handlers.collection`, `Handlers.buildIncluded` and the `Assemble` builders that route through them no longer emit a resource in `included` when it is already present as primary data. A compound document now carries one resource object per `(type, id)` pair, as JSON:API requires — previously a heterogeneous collection whose include target was also one of the hits (e.g. `/search?include=author`) repeated that resource in `included`. When every `included` candidate is already primary data, the `included` member is omitted, as it is when none is passed — so a call that passes a primary resource in `included` with nothing referencing it (e.g. `Handlers.data(article, { included: [article] })`), which used to fail the full-linkage check, now succeeds with `included` omitted. +`Handlers.data`, `Handlers.collection`, `Handlers.buildIncluded` and the `Assemble` builders that route through them no longer emit a resource in `included` when it is already present as primary data. A compound document now carries one resource object per `(type, id)` pair, as JSON:API requires — previously a heterogeneous collection whose include target was also one of the hits (e.g. `/search?include=author`) repeated that resource in `included`. When every `included` candidate is already primary data, `Handlers.data` and `Handlers.collection` emit `included: []`, as they do any `included` array they are given, and the `Assemble` builders do the same when the request carried `include` (without `include` they omit the key) — so a call that passes a primary resource in `included` with nothing referencing it (e.g. `Handlers.data(article, { included: [article] })`), which used to fail the full-linkage check, now succeeds with `included: []`. diff --git a/src/Handlers.ts b/src/Handlers.ts index 43549c02..06867ab7 100644 --- a/src/Handlers.ts +++ b/src/Handlers.ts @@ -1130,8 +1130,9 @@ export const resolveIncluded = ( * * The `jsonapi` member is *conditional* on `J`, the same way `meta` is * conditional on `M`: it is present (and required, not optional — a builder - * that infers `J` from an argument has one to put there) only when a caller actually passed the `jsonapi` option, so the - * return type of `Handlers.data(article, { jsonapi: Document.v1_1 })` carries + * that infers `J` from an argument has one to put there) only when a caller + * actually passed the `jsonapi` option, so the return type of + * `Handlers.data(article, { jsonapi: Document.v1_1 })` carries * `jsonapi: Document.JsonApiObjectValue` and the return type of * `Handlers.data(article)` has no `jsonapi` member at all — no cast needed * either way. `included` is always declared, optional: a builder emits any diff --git a/src/ResourceHandlers.test.ts b/src/ResourceHandlers.test.ts index 8a49d7a0..47f5e352 100644 --- a/src/ResourceHandlers.test.ts +++ b/src/ResourceHandlers.test.ts @@ -524,17 +524,23 @@ describe("related", () => { ...config, key: "polity", cardinality: "one", - includable: ["country"], + includable: ["country", "country.capital.mayor"], }); - const [withPath, bareInclude, withoutInclude] = await Effect.runPromise( - Effect.all([ - empty({ params: { id: "c1" }, query: { include: ["country"] } }), - // `?include=` (no paths) is still a request that carried `include`. - empty({ params: { id: "c1" }, query: { include: [] } }), - empty({ params: { id: "c1" }, query: {} }), - ]), + const [withPath, threeHops, bareInclude, withoutInclude] = await Effect.runPromise( + Effect.all( + [ + empty({ params: { id: "c1" }, query: { include: ["country"] } }), + // A path at the default depth limit (3 hops) is accepted. + empty({ params: { id: "c1" }, query: { include: ["country.capital.mayor"] } }), + // `?include=` (no paths) is still a request that carried `include`. + empty({ params: { id: "c1" }, query: { include: [] } }), + empty({ params: { id: "c1" }, query: {} }), + ], + { concurrency: 1 }, + ), ); expect(withPath).toEqual({ data: null, included: [], jsonapi: { version: "1.1" } }); + expect(threeHops).toEqual({ data: null, included: [], jsonapi: { version: "1.1" } }); expect(bareInclude).toEqual({ data: null, included: [], jsonapi: { version: "1.1" } }); // Without `include` the key stays absent. expect(withoutInclude).not.toHaveProperty("included"); @@ -553,5 +559,10 @@ describe("related", () => { expect( await failure(empty({ params: { id: "c1" }, query: { include: ["a.b.c.d"] } })), ).toBeInstanceOf(ApiError.UnsupportedIncludeDepth); + // With no `includable` configured, no path is includable. + const closed = ResourceHandlers.related({ ...config, key: "polity", cardinality: "one" }); + expect( + await failure(closed({ params: { id: "c1" }, query: { include: ["country"] } })), + ).toBeInstanceOf(ApiError.UnsupportedIncludePath); }); }); diff --git a/test/empty-included.types.ts b/test/empty-included.types.ts index 7f7dacca..c927dc9c 100644 --- a/test/empty-included.types.ts +++ b/test/empty-included.types.ts @@ -9,9 +9,16 @@ * * This file is type-checked by the `typecheck` task and never executed. */ -import { Schema } from "effect"; +import * as Schema from "effect/Schema"; import { Handlers, Relationship, Resource } from "@thomasfosterau/effect-jsonapi"; +/** Pins a value to an expected type without using it (`noUnusedLocals`). */ +const assertType = (_value: Expected): void => {}; + +// Whether two types are identical, not merely mutually assignable. +type Equals = + (() => T extends A ? 1 : 2) extends () => T extends B ? 1 : 2 ? true : false; + const Person = Resource.make("people", { attributes: { name: Schema.String } }); const person = Person.make({ id: Person.Id.make("9"), attributes: { name: "Dan" } }); const Article = Resource.make("articles", { @@ -24,22 +31,36 @@ const article = Article.make({ relationships: { author: { data: { type: "people", id: person.id } } }, }); -// A literal `[]` infers `Included = never`; the member still reads back. -export const dataEmpty = Handlers.data(article, { included: [] }); -export const dataEmptyIncluded: ReadonlyArray | undefined = dataEmpty.included; +// Each assertion pins the `included` member exactly: `Pick` fails to compile +// when the key is absent, and `Equals` tells an optional member from a required +// one and rejects `any`. + +// A literal `[]` infers `Included = never`; the member is still declared. +const dataEmpty = Handlers.data(article, { included: [] }); +assertType< + Equals, { readonly included?: ReadonlyArray }> +>(true); +// Negative control: the member is optional, never required. +assertType, { readonly included: ReadonlyArray }>>( + false, +); -export const collectionEmpty = Handlers.collection([article], { included: [] }); -export const collectionEmptyIncluded: ReadonlyArray | undefined = collectionEmpty.included; +const collectionEmpty = Handlers.collection([article], { included: [] }); +assertType< + Equals, { readonly included?: ReadonlyArray }> +>(true); // No option at all: the member is optional and holds nothing. -export const dataBare = Handlers.data(article); -export const dataBareIncluded: ReadonlyArray | undefined = dataBare.included; - -// Negative control: the member is optional, never required. -// @ts-expect-error -- `included` may be absent, so it is not a plain array -export const dataEmptyRequired: ReadonlyArray = dataEmpty.included; +const dataBare = Handlers.data(article); +assertType, { readonly included?: ReadonlyArray }>>( + true, +); // A non-empty `included` keeps its element type. -export const dataWithAuthor = Handlers.data(article, { included: [person] }); -export const dataWithAuthorIncluded: ReadonlyArray | undefined = - dataWithAuthor.included; +const dataWithAuthor = Handlers.data(article, { included: [person] }); +assertType< + Equals< + Pick, + { readonly included?: ReadonlyArray } + > +>(true);