Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/Assemble.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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"}}');
});
Expand Down Expand Up @@ -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);
Expand Down
4 changes: 2 additions & 2 deletions src/Handlers.test.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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"],
Expand Down
4 changes: 2 additions & 2 deletions src/Handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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<string> =>
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),
Expand Down
6 changes: 3 additions & 3 deletions src/Middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ import {
Layer,
Option,
Predicate,
Record,
Record as Rec,
Schema,
SchemaAST,
SchemaIssue,
Expand Down Expand Up @@ -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-" +
Expand Down Expand Up @@ -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,
);
Expand Down
26 changes: 26 additions & 0 deletions src/Query.filter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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")),
Expand Down
12 changes: 4 additions & 8 deletions src/Query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -1678,7 +1678,7 @@ export const schema = <R extends Any, const O extends Options<R>>(
// 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,
Expand All @@ -1691,12 +1691,8 @@ export const schema = <R extends Any, const O extends Options<R>>(
// bracket reshaper, so `page[*]` / `fields[*]` are untouched.
SchemaTransformation.transformEffect<Values, Values>({
decode: (flatValues, parseOptions) => {
const others: Record<string, unknown> = {};
const filterKeys: Record<string, unknown> = {};
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(
Expand Down
4 changes: 2 additions & 2 deletions src/internal/codecs.test.ts
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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 = <V>(key: string, value: V) => Record.fromEntries([[key, value]]);
const record = <V>(key: string, value: V) => Rec.fromEntries([[key, value]]);

describe("nest", () => {
it("reshapes one bracket level into groups", () => {
Expand Down
16 changes: 9 additions & 7 deletions src/internal/codecs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -163,24 +163,26 @@ 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<string, unknown> => {
const nested: Record<string, unknown> = {};
export const nest = <V>(flat: {
readonly [key: string]: V;
}): Record<string, V | Record<string, V>> => {
const nested: Record<string, V | Record<string, V>> = {};
// 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)) {
define(nested, key, value);
} else {
// No bare key holds the name, so an own entry under it is a group this
// loop made.
const group = Option.getOrElse(Record.get(nested, name), () => {
const group = Option.getOrElse(Rec.get(nested, name), () => {
const made = {};
define(nested, name, made);
return made;
}) as Record<string, unknown>;
}) as Record<string, V>;
define(group, member, value);
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/internal/filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -42,7 +42,7 @@ class InvalidFilter extends Schema.TaggedError<InvalidFilter>()("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 = <V>(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
Expand Down
6 changes: 6 additions & 0 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<K, V>` 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",
Expand Down
Loading