diff --git a/src/Assemble.test.ts b/src/Assemble.test.ts index f48c1455..c85b3270 100644 --- a/src/Assemble.test.ts +++ b/src/Assemble.test.ts @@ -6,7 +6,7 @@ * relationship document. */ import { describe, expect, it } from "vite-plus/test"; -import { Effect, Exit, Record as R, Schema } from "effect"; +import { Effect, Exit, Record as Rec, Schema } from "effect"; import * as ApiError from "./ApiError.js"; import * as Assemble from "./Assemble.js"; import type * as Handlers from "./Handlers.js"; @@ -928,7 +928,7 @@ describe("helpers", () => { const linked = Assemble.toWireSafeResource({ type: "things", id: "2", - attributes: R.fromEntries([["__proto__", { at: new URL("https://example.test/a") }]]), + attributes: Rec.fromEntries([["__proto__", { at: new URL("https://example.test/a") }]]), }); expect(toJson(linked.attributes)).toBe('{"__proto__":{"at":"https://example.test/a"}}'); }); @@ -965,11 +965,11 @@ describe("helpers", () => { const coerced = Assemble.toWireSafeResource({ type: "things", id: "1", - attributes: R.fromEntries([ + attributes: Rec.fromEntries([ [key, { at: new URL("https://example.test/a") }], ["title", "T"], ]), - meta: R.fromEntries([[key, 1]]), + meta: Rec.fromEntries([[key, 1]]), }); const { attributes, meta } = coerced; expect(Object.getPrototypeOf(attributes)).toBe(Object.prototype); diff --git a/src/Handlers.test.ts b/src/Handlers.test.ts index 7e92c0ba..b0d694ec 100644 --- a/src/Handlers.test.ts +++ b/src/Handlers.test.ts @@ -1,6 +1,6 @@ import { describe, expect, expectTypeOf, it } from "vite-plus/test"; import * as Arr from "effect/Array"; -import * as R from "effect/Record"; +import * as Rec from "effect/Record"; import { Schema } from "effect"; import * as Document from "./Document.js"; import * as Handlers from "./Handlers.js"; @@ -356,7 +356,7 @@ describe("Handlers.project", () => { const resource = { type: "articles", id: "3", - attributes: R.fromEntries([ + attributes: Rec.fromEntries([ [key, { inner: 2 }], ["title", "T"], ["body", "B"], diff --git a/src/Handlers.ts b/src/Handlers.ts index 0b928a1b..fa2ed03b 100644 --- a/src/Handlers.ts +++ b/src/Handlers.ts @@ -45,7 +45,7 @@ * * @since 0.1.0 */ -import { Array as Arr, Effect, HashMap, HashSet, Option, Record } from "effect"; +import { Array as Arr, Effect, HashMap, HashSet, Option, Record as Rec } from "effect"; import type { JsonApiObject } from "./Document.js"; import { serialise, withPagePairs } from "./internal/canonical.js"; import { assign } from "./internal/define.js"; @@ -568,7 +568,7 @@ const key = (identifier: ResourceIdentifierValue): string => `${identifier.type} // The keys of every resource identifier in a resource's inline relationship // linkage — the edges the full-linkage walk follows out of it. const linkageKeys = (resource: ResourceValue): Array => - Arr.flatMap(Record.values(resource.relationships ?? {}), ({ data: linkage }) => + Arr.flatMap(Rec.values(resource.relationships ?? {}), ({ data: linkage }) => linkage === null || linkage === undefined ? [] : Arr.map(Array.isArray(linkage) ? linkage : [linkage], key), diff --git a/src/Middleware.ts b/src/Middleware.ts index 815151bd..b3501a00 100644 --- a/src/Middleware.ts +++ b/src/Middleware.ts @@ -72,7 +72,7 @@ import { Layer, Option, Predicate, - Record, + Record as Rec, Schema, SchemaAST, SchemaIssue, @@ -608,7 +608,7 @@ const rejectQueryParameters = ( code: BadRequest.code, ...(BadRequest.title !== undefined ? { title: BadRequest.title } : {}), detail: Option.getOrElse( - Record.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-" + @@ -936,7 +936,7 @@ export const schemaErrorsLayer = (options?: QueryParameterOptions): Layer.Layer< if (Option.isSome(declared)) { const params = yield* ParsedSearchParams; const rejected = rejectQueryParameters( - Record.keys(params), + Rec.keys(params), declared.value, allowedQueryParameters, ); diff --git a/src/Query.filter.test.ts b/src/Query.filter.test.ts index 442a6611..23c7a0d0 100644 --- a/src/Query.filter.test.ts +++ b/src/Query.filter.test.ts @@ -1275,6 +1275,32 @@ describe("Query.schema with filter: true", () => { expect(decodeQuery({ "page[limit]": "5" })).toEqual({ page: { limit: 5 } }); }); + // The decode splits the flat record into the filter keys and the rest + // before either is read (#275); a key named after an `Object.prototype` + // member must land on its own side as an ordinary name (#260, #264). + it.each(inherited)( + "routes filter[%s] to the grammar and a bare key of that name nowhere", + (name) => { + const result = Schema.decodeUnknownResult(query)({ + [`filter[${name}]`]: "x", + "page[limit]": "5", + }); + if (result._tag === "Success") throw new Error("expected the decode to fail"); + expect( + SchemaIssue.makeFormatterStandardSchemaV1()(result.failure.issue).issues.map((issue) => ({ + key: String(issue.path?.[0]), + message: issue.message, + })), + ).toEqual([{ key: `filter[${name}]`, message: `Unknown filter field "${name}"` }]); + // An own `__proto__` key, as `UrlParams.toRecord` writes one. + const wire = JSON.parse( + `{"${name}": "x", "${name}[polluted]": "yes", "filter[status]": "open", "page[limit]": "5"}`, + ); + expect(decodeQuery(wire)).toEqual({ filter: eq("status", "open"), page: { limit: 5 } }); + expect(Object.hasOwn(Object.prototype, "polluted")).toBe(false); + }, + ); + it("encodes the nested shape back to canonical flat keys", () => { const encoded = Schema.encodeSync(query)({ filter: Filter.or(eq("status", "open"), Filter.isNull("deletedAt")), diff --git a/src/Query.ts b/src/Query.ts index e7c2bbf9..6381b3d6 100644 --- a/src/Query.ts +++ b/src/Query.ts @@ -48,7 +48,7 @@ * @since 0.1.0 */ import type { SchemaAST, Types } from "effect"; -import { Effect, Record, Schema, SchemaIssue, SchemaTransformation } from "effect"; +import { Effect, Record as Rec, Schema, SchemaIssue, SchemaTransformation } from "effect"; import * as ApiError from "./ApiError.js"; import type { Ast, Node } from "./Filter.js"; import { Ast as AstSchema, PROFILE_URI } from "./Filter.js"; @@ -1678,7 +1678,7 @@ export const schema = >( // only the declared keys makes the empty case drop them too (#260); with // fields it is a no-op, the struct having dropped the rest already. const declaredOnly = (values: Values): Values => - Record.filter(values, (_, key) => Record.has(flatFields, key)); + Rec.filter(values, (_, key) => Rec.has(flatFields, key)); return flat.pipe( Schema.decodeTo( nested, @@ -1691,12 +1691,8 @@ export const schema = >( // bracket reshaper, so `page[*]` / `fields[*]` are untouched. SchemaTransformation.transformEffect({ decode: (flatValues, parseOptions) => { - const others: Record = {}; - const filterKeys: Record = {}; - for (const [key, value] of Object.entries(flatValues)) { - if (isFilterKey(key)) filterKeys[key] = value; - else others[key] = value; - } + const filterKeys = Rec.filter(flatValues, (_, key) => isFilterKey(key)); + const others = Rec.filter(flatValues, (_, key) => !isFilterKey(key)); const nestedValues = nest(others); if (Object.keys(filterKeys).length === 0) return Effect.succeed(nestedValues); return Effect.map( diff --git a/src/internal/codecs.test.ts b/src/internal/codecs.test.ts index 8d187e67..a334f896 100644 --- a/src/internal/codecs.test.ts +++ b/src/internal/codecs.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test"; -import * as Record from "effect/Record"; +import * as Rec from "effect/Record"; import { flatten, nest } from "./codecs.js"; // A reshaper that wrote through `__proto__` would pollute every object in the @@ -11,7 +11,7 @@ afterEach(() => { // `Record.fromEntries` makes `__proto__` an own key, as `UrlParams.toRecord` // does; an object literal would set the prototype instead. -const record = (key: string, value: V) => Record.fromEntries([[key, value]]); +const record = (key: string, value: V) => Rec.fromEntries([[key, value]]); describe("nest", () => { it("reshapes one bracket level into groups", () => { diff --git a/src/internal/codecs.ts b/src/internal/codecs.ts index e1592fd1..75bb05c3 100644 --- a/src/internal/codecs.ts +++ b/src/internal/codecs.ts @@ -3,7 +3,7 @@ * * @internal */ -import { Option, Record, Schema, SchemaTransformation } from "effect"; +import { Option, Record as Rec, Schema, SchemaTransformation } from "effect"; import type { Term } from "../Sort.js"; import { define } from "./define.js"; import { errorMeta } from "./errorMeta.js"; @@ -163,12 +163,14 @@ const bracketKey = /^([^[\]]+)\[([^[\]]+)\]$/; * struct then drops whichever spelling it doesn't declare. Every key is * written as an own property, so `__proto__` is an ordinary name here. */ -export const nest = (flat: { readonly [key: string]: unknown }): Record => { - const nested: Record = {}; +export const nest = (flat: { + readonly [key: string]: V; +}): Record> => { + const nested: Record> = {}; // Whether a bare key holds `name`, wherever it sits in `flat`. const holdsBare = (name: string): boolean => - Option.getOrUndefined(Record.get(flat, name)) !== undefined; - for (const [key, value] of Record.toEntries(flat)) { + Option.getOrUndefined(Rec.get(flat, name)) !== undefined; + for (const [key, value] of Rec.toEntries(flat)) { if (value === undefined) continue; const [, name, member] = bracketKey.exec(key) ?? []; if (name === undefined || member === undefined || holdsBare(name)) { @@ -176,11 +178,11 @@ export const nest = (flat: { readonly [key: string]: unknown }): Record { + const group = Option.getOrElse(Rec.get(nested, name), () => { const made = {}; define(nested, name, made); return made; - }) as Record; + }) as Record; define(group, member, value); } } diff --git a/src/internal/filter.ts b/src/internal/filter.ts index 26f49e77..a7129045 100644 --- a/src/internal/filter.ts +++ b/src/internal/filter.ts @@ -5,7 +5,7 @@ * * @internal */ -import { Option, Record, Schema, SchemaIssue } from "effect"; +import { Option, Record as Rec, Schema, SchemaIssue } from "effect"; import type { Node } from "../Filter.js"; import { conjunctions, listOperators, nullOperator, operators } from "./operators.js"; @@ -42,7 +42,7 @@ class InvalidFilter extends Schema.TaggedError()("InvalidFilter", // and the field name comes from the request, so `constructor`, `__proto__`, // `toString`, … must read as undeclared, not as an `Object.prototype` member. const declaration = (fields: { readonly [field: string]: V }, field: string) => - Option.getOrUndefined(Record.get(fields, field)); + Option.getOrUndefined(Rec.get(fields, field)); /** * Encodes one literal of a field to its wire string, before escaping. Throws diff --git a/vite.config.ts b/vite.config.ts index 5dd16885..a8597943 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -85,6 +85,12 @@ export default defineConfig({ // 269 `avoid-native-object-helpers`, 245 `avoid-non-null-assertion`. "effect/require-safety-comment-for-type-assertion": "warn", "effect/no-chained-type-assertions": "warn", + // This rule and `no-known-value-widening` only check the built-in + // `Record` while no local binding is named `Record`, so importing + // effect's `Record` module under that name hides every such site in + // the file (#275). Never bind it as `Record`: spell the alias `Rec` + // everywhere (`import { Record as Rec } from "effect"`), never `R`, + // which is the resource type parameter in many files. "effect/no-unsafe-dictionary-type": "warn", "effect/no-runtime-typeof": "warn", "effect/use-clock-service": "warn",