diff --git a/.changeset/34990-nested-relation-filter-node.md b/.changeset/34990-nested-relation-filter-node.md index f693881999d..f00e25c4586 100644 --- a/.changeset/34990-nested-relation-filter-node.md +++ b/.changeset/34990-nested-relation-filter-node.md @@ -11,13 +11,13 @@ Metadata-protocol: none **BREAKING** for a host that filters a `ValueDataSource` (the in-memory `provider: 'value'` source) with a comparison whose comparand is a plain object (prototype `Object.prototype` or `null`) with no `$` key, such as `['account', '!=', { owner: 'u1' }]`, under `!=`, `not_contains` or an ordering operator (`>`, `>=`, `<`, `<=`). -- FROM: `!=` and `not_contains` served every row, and an ordering operator compared each value with the text `[object Object]` and served the string values that happened to sort past it. -- TO: the condition is refused by name. It excludes every row and logs the sentence the object form `{ account: { owner: 'u1' } }` already logs. `=` matched no row before and matches none now; it only gains the log line. +- FROM: `!=` served every other row (every row but one holding the caller's own object) and `not_contains` every row, and an ordering operator compared each value with the text `[object Object]` and served the string values that happened to sort past it. That holds for an object whose prototype is `Object.prototype`. A `null`-prototype object has no `toString` or `valueOf`, so an ordering operator threw `TypeError: Cannot convert object to primitive value` and `find` rejected; `not_contains` threw as soon as it reached a row holding a string, and served every row when none did. +- TO: the condition is refused by name. It excludes every row and logs the sentence the object form `{ account: { owner: 'u1' } }` already logs. `=` compared by reference, so it matched no row unless a row held the caller's own object (stored through `create` or `update`, which copy shallowly), and that row matched; it matches none now and gains the log line. - The spec's comparand door already refuses an object comparand under these operators, so the rows served before were a wrong answer. Spell a relation condition only against a server-backed source, whose server joins it; a value source holds flat rows, so filter there on the row's own fields. `convertFiltersToAST` now lowers the nested-relation form the spec declares on `FilterCondition` (`{ account: { owner: 'u1' } }`, a plain object with no `$` key beneath a field) to one equality node, `['account', '=', { owner: 'u1' }]`, which the spec's `parseFilterAST` reads back as the same nested condition. It used to refuse that shape as an unknown operator. The condition travels as written, deeper relations included; whether the field is a relationship is judged by the server, which answers `INVALID_FILTER` / 400 for such a condition under a field that stores a scalar or a structured-JSON value, and, under a relationship, for a condition key the related object does not declare, a dotted key, or a relation nested past the hop limit. A map that mixes `$` operators with plain keys is still refused. -`ValueDataSource` (the in-memory `provider: 'value'` source) does not descend into relations, and it now says so for the lowered node too: a comparison whose comparand is a plain object with no `$` key, such as `['account', '=', { owner: 'u1' }]`, excludes every row and logs the same sentence the object form `{ account: { owner: 'u1' } }` already logged, for `=`, `!=` and every other operator that reads the comparand. Before this, `=` compared the object by reference and matched no row without a word, and `!=` matched every row. A class instance is not refused, even one with keys of its own such as a moment, luxon or decimal object: it is a value, and an ordering operator still compares it through its `valueOf`. +`ValueDataSource` (the in-memory `provider: 'value'` source) does not descend into relations, and it now says so for the lowered node too: a comparison whose comparand is a plain object with no `$` key, such as `['account', '=', { owner: 'u1' }]`, excludes every row and logs the same sentence the object form `{ account: { owner: 'u1' } }` already logged, for `=`, `!=` and every other operator that reads the comparand. Before this, `=` compared the object by reference and matched no row without a word, unless a row held the caller's own object, and `!=` matched every other row. A class instance is not refused as a relation, even one with keys of its own such as a moment, luxon or decimal object: it is a value. An ordering operator compares it through its `valueOf` when that returns a primitive, otherwise as its text; under an equality, membership or text operator it is refused, in a sentence of its own. `resolveDatasetDrillFilter` uses it: a dataset dimension whose field is a relationship path (`account.owner`, up to three hops) drills as `{ account: { owner: VALUE } }`, nested one level per hop, instead of reading up to 200 related ids per hop and filtering on `$in` them. No related record is read, nothing is capped, and the `too-many` answer is no longer produced; `DATASET_DRILL_RELATED_ID_CAP` and the `too-many` member of `DatasetDrillResolution` stay exported, marked deprecated. The schema reads that check each hop is a single-valued relationship, the hop limit and the empty-bucket refusal are unchanged. diff --git a/.changeset/35735-filter-flag-and-comparand-edges.md b/.changeset/35735-filter-flag-and-comparand-edges.md new file mode 100644 index 00000000000..dd726764754 --- /dev/null +++ b/.changeset/35735-filter-flag-and-comparand-edges.md @@ -0,0 +1,32 @@ +--- +'@object-ui/core': patch +--- + +fix(core)!: a non-boolean `$null` / `$exists` flag is refused in the filter converter and the value data source, and so are the object comparands the value data source cannot compare + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +**BREAKING** for `convertFiltersToAST` and `ValueDataSource` (the in-memory `provider: 'value'` data source), for four filter shapes. + +1. **A `$null` / `$exists` flag that is not a boolean**, such as `{ owner: { $null: 'no' } }`, `{ owner: { $exists: 1 } }` or `{ owner: { $null: { id: 'u1' } } }`. + - FROM: the flag was read for its truthiness. `convertFiltersToAST` lowered `{ owner: { $null: 'no' } }` to `['owner', 'is_null', true]` and `{ owner: { $exists: 'no' } }` to `['owner', 'is_not_null', true]`, so a server-backed source answered the null-ness rows and its own door never saw the flag; the value data source answered the same rows (`'no'`, `1` and an object read as `true`; `0` and `null` as `false`). + - TO: both refuse it, as they already refused a non-boolean `$empty` flag. The converter throws `FilterOperatorError` (`INVALID_FILTER` / 400) with `The '$null' filter operator on field 'owner' takes a boolean flag (true or false); received "no"`, and the value data source excludes every row and logs `filter operator '$null' on field 'owner' takes a boolean flag (true or false); received "no"`. `true` and `false` lower and match exactly as before. The spec's `FilterConditionSchema` and every query face already refused these flags. + - The AST null-ness operators (`is_null`, `is_not_null` and their spellings) carry no flag and are not moved: direction comes from the operator name and the value slot is not read, as the spec's `parseFilterAST` reads it. +2. **A plain object of another realm** (an iframe, a `vm` context), whose prototype is that realm's `Object.prototype`. + - FROM: `convertFiltersToAST` read it as an operator map, so `{ age: foreignObject }` with `$gte: 18` lowered to `['age', '>=', 18]`, and the value data source answered it with the right rows, the ones with `age >= 18`: that is the answer this change takes away. One with no `$` key lowered to the nested-relation node `['owner', '=', foreignObject]`. In comparand position the value data source compared it as a value: by reference under `$eq` / `=` and as an `$in` member, so no row matched unless a row held the caller's own object (stored through `create` or `update`, which copy shallowly), and that row did; `$ne` / `!=` and `$nin` served every other row; and under an ordering operator it compared as the text `[object Object]`, serving the string values that sort past that text. + - TO: it is a comparand, as the spec's filter walk and the engine's `isNoOperatorObject` read it: the converter refuses it as the field's whole condition in a sentence of its own (`The filter on field 'age' is a plain object from another realm (an iframe, a vm context). Only a plain object of this realm (prototype Object.prototype or null) is read as an operator map or a nested condition here…`), and the value data source refuses it in comparand position under every operator (`filter comparand on field 'owner' is a plain object from another realm, which is neither a comparison value nor filter structure here`). The server refused it already when the object reached it in process; sent as JSON, it arrives as a plain object of the server's realm. + - Also moved, by the same prototype test (the operator-map test no longer takes a second prototype hop): an object whose prototype is a `null`-prototype object, such as `Object.create(Object.create(null))`. FROM: `convertFiltersToAST` read it as an operator map (with no own key it was refused as an empty operator map; with `$` keys it lowered). In comparand position the value data source compared it by reference under `$eq` and as an `$in` member, so no row matched unless a row held the caller's own object, and `$ne` / `!=` and `$nin` served every other row: these are the rows this change takes away. It has no text of its own, so under an ordering operator, `$between`, and a text operator on a row holding a string, the comparison threw `TypeError: Cannot convert object to primitive value` and `find` rejected, unless its prototype defines a `valueOf` or `toString` that returns a primitive, which it then compared through; with no row holding a string, `$contains`, `$startsWith` and `$endsWith` served no row and `$notContains` every row. TO: both faces refuse it as `an object of an unrecognised type`: the converter as the field's whole condition, and the value data source in comparand position under every operator. +3. **A plain object with a `$` key that is not a `{ $field }` reference**, in comparand position on the value data source, the spec's `{ $now, addDays }` date anchor among them, such as `{ due: { $lt: { $now: true, addDays: 7 } } }`. + - FROM: compared as a value: by reference under `$eq` and as an `$in` member, so no row matched unless a row held the caller's own object (stored through `create` or `update`), and that row did; `$ne` and `$nin` served every other row, and `$notContains` every row; under an ordering operator it compared as the text `[object Object]`, so `$lt` answered the rows sorting before that text. A `null`-prototype one has no text: under an ordering operator, `$between`, and a text operator on a row holding a string, the comparison threw `TypeError: Cannot convert object to primitive value` and `find` rejected. + - TO: refused under every operator that reads a comparand, whole or as a list member, in both dialects. The anchor (by the spec's test: `$now` is `true` or a string) gets `filter comparand on field 'due' is a { $now, addDays } date anchor, which the in-memory matcher does not resolve…`, ending in the remedy `compare with a concrete Date or ISO string here`: the platform resolves it in the compared column's temporal form, and this source has no field types to read a form from, the reason it already refuses a `{ $field, addDays }` offset. Any other one gets `filter comparand on field 'owner' is an object carrying the key '$foo', which is neither a comparison value nor a { $field } reference`, the comparand the spec's door refuses. `convertFiltersToAST` still lowers the anchor verbatim for a server-backed source, which resolves it. +4. **A class instance** (a moment or luxon date, a decimal object, a `RegExp`, a `Map`) as the comparand of an equality, membership or text operator on the value data source: `$eq`, `$ne`, an `$in` / `$nin` member, `$contains`, `$notContains`, `$startsWith`, `$endsWith`, and their AST spellings. + - FROM: compared by reference or as its text. `$eq` / `=` and `$in` answered no row unless a row held the caller's own instance (stored through `create` or `update`), and that row matched; `$ne` and `$nin` served every other row. `$contains`, `$startsWith` and `$endsWith` matched on the instance's `String()` text and served rows (a `new String('ab')`, a class with a `toString`), and `$notContains` served their complement. + - TO: refused, in both dialects, with `filter comparand on field 'age' is a Amount instance, which the in-memory matcher compares only by order…`. The spec's comparand door refuses it at these operators. + - Not moved: under `$gt` / `$gte` / `$lt` / `$lte` / `$between` it is still compared through its `valueOf` when that returns a primitive; otherwise as its text. `$icontains` keeps its own text-comparand refusal. + +**Not moved.** A scalar, a `Date` and a `{ $field }` reference are compared as before; `$empty` keeps its boolean-flag refusal, with the converter's sentence now built by the same helper as `$null` / `$exists`; a `null`-prototype object of this realm is still an operator map. + +The fix for a caller: write the flag as the boolean itself (`{ owner: { $null: true } }`, `{ owner: { $exists: false } }`); compare with a scalar, a `Date` or a `{ $field }` reference; rebuild a filter object from another realm in this one (`{ ...condition }` per operator map, or `structuredClone(filter)`); filter a relative date on a server-backed source, or compare a value source with a concrete `Date` or ISO string; and convert a class-instance comparand to its primitive (`moment.toDate()`, `decimal.toNumber()`) before filtering. diff --git a/ui/packages/core/src/adapters/ValueDataSource.ts b/ui/packages/core/src/adapters/ValueDataSource.ts index f2ad67e8bfc..e7b62f0c57d 100644 --- a/ui/packages/core/src/adapters/ValueDataSource.ts +++ b/ui/packages/core/src/adapters/ValueDataSource.ts @@ -19,6 +19,7 @@ import type { AggregateResult, } from '@object-ui/types'; import { + ACCEPTED_FILTER_COMPARAND_TYPES_SENTENCE, asciiCaseInsensitiveContains, canonicalAstOperator, FILTER_OPERATORS, @@ -33,6 +34,7 @@ import { textComparandRefusalReason, } from '../utils/text-comparand.js'; import { toFilterNodeSafely, type FilterOperatorError } from '../utils/filter-converter.js'; +import { isForeignRealmPlainObject } from '../utils/foreign-realm-object.js'; // --------------------------------------------------------------------------- // Configuration @@ -135,6 +137,21 @@ const DOLLAR_FLAG_OPERATORS = new Set(['$null', '$exists', '$empty']); */ const DOLLAR_COMPARAND_OPERATORS: ReadonlySet = new Set(FILTER_OPERATORS); +/** + * The operators that compare their comparand by EQUALITY, MEMBERSHIP or TEXT + * rather than by order, in each dialect. Under these a class instance is + * refused (see {@link classInstanceComparandRefusalReason}); under the + * orderings and `$between` it is compared through its `valueOf` when that + * returns a primitive, and otherwise as its text. `$icontains` + * is not here: its own text door already refuses every non-string comparand. + */ +const DOLLAR_BY_VALUE_OPERATORS: ReadonlySet = new Set([ + '$eq', '$ne', '$in', '$nin', '$contains', '$notContains', '$startsWith', '$endsWith', +]); +const AST_BY_VALUE_OPERATORS: ReadonlySet = new Set([ + '=', '!=', 'in', 'nin', 'contains', 'not_contains', 'starts_with', 'ends_with', +]); + /** * Is this stored value EMPTY, in the sense the spec's `$empty` operator gives * the word (objectui#11094)? @@ -503,12 +520,16 @@ function nestedRelationRefusalReason(field: string, key: string): string { * The first key of an AST comparand that is a nested relation condition, or * `undefined` when it is not one. The shape is the one `convertFiltersToAST` * lowers to `[rel, '=', condition]`: a non-empty PLAIN object with no `$` key. + * The two name one population: the converter's operator-map test is the same + * prototype test, so a plain object of another realm is a comparand to both, + * refused by the converter and by {@link objectComparandRefusal} here. * * Plain means prototype `Object.prototype` or `null`, the test the spec's * filter walk uses to tell filter structure from data. A class instance is * data even when it carries its own non-`$` keys: a moment or luxon date, or a - * decimal object, under `>` / `<` compares through its `valueOf` in the switch - * below and is not refused as a relation. + * decimal object, under `>` / `<` compares through its `valueOf` (when that + * returns a primitive; otherwise as its text) in the switch below and is not + * refused as a relation. * A `Date` has no own keys, so it is never one either. */ function nestedRelationComparandKey(target: unknown): string | undefined { @@ -530,6 +551,16 @@ function isPlainObject(value: unknown): value is Record { return proto === Object.prototype || proto === null; } +/** + * The refusal for a flag operator (`$null`, `$exists`, `$empty`) whose flag is + * not a boolean. `SpecialOperatorSchema` declares all three `z.boolean()`, and + * the spec's save door and every query face refuse anything else. + */ +function nonBooleanFlagRefusalReason(field: string, operator: string, flag: unknown): string { + return `filter operator '${operator}' on field '${field}' takes a boolean flag (true or false); ` + + `received ${describeComparand(flag)}`; +} + /** * The refusal for an EMPTY plain object, `{}`, in comparand position. There is * no key to name, and it is neither a comparison value nor a relation @@ -542,19 +573,143 @@ function emptyObjectComparandRefusalReason(field: string): string { + `neither a comparison value nor a nested relation constraint`; } -/** {@link plainObjectComparandRefusal} for one value: a whole comparand or one list member. */ -function plainObjectValueRefusal(field: string, value: unknown): string | undefined { +/** + * The refusal for a `{ $now, addDays }` date anchor in comparand position. + * `NowAnchorSchema` declares it and the platform resolves it, but the shift is + * made in the compared column's temporal form (a calendar day for a `date` + * column, an instant for a `datetime` one), and this matcher has no field types + * to read a form from: the same reason {@link resolveFieldReference} refuses a + * `{ $field, addDays }` offset. Compared as an object, it read as the text + * `[object Object]`. The remedy is the comparand this matcher can compare. + */ +function nowAnchorComparandRefusalReason(field: string): string { + return `filter comparand on field '${field}' is a { $now, addDays } date anchor, which the ` + + 'in-memory matcher does not resolve: the platform shifts the current instant in the ' + + "compared column's temporal form, and this matcher has no field types to read one from; " + + 'compare with a concrete Date or ISO string here'; +} + +/** + * Is `value` a `{ $now }` anchor, by the spec's own test: an object whose + * `$now` is `true` or a string (`isNowAnchor` in the spec's comparand walk, + * `nowAnchorOf` in `driver-sql`). `{ $now: 0 }` and `{ $now: false }` are not + * one: the platform refuses them as malformed, so they take the `$`-key + * sentence instead of being told the platform resolves them. + */ +function isNowAnchorComparand(value: Record): boolean { + return value.$now === true || typeof value.$now === 'string'; +} + +/** + * The refusal for a plain object with a `$` key that is neither a `{ $field }` + * reference nor a `{ $now }` anchor, such as `{ $foo: 1 }`, in comparand + * position. The spec's comparand door refuses it as a plain object no driver + * can compare. + */ +function operatorKeyedComparandRefusalReason(field: string, key: string): string { + return `filter comparand on field '${field}' is an object carrying the key '${key}', which is ` + + 'neither a comparison value nor a { $field } reference'; +} + +/** + * A plain object of ANOTHER realm ({@link isForeignRealmPlainObject}, the one + * test the filter converter uses too). The spec's filter walk does not read it + * as filter structure, and it has no `valueOf` worth comparing, so in + * comparand position it is refused under every operator, the way the spec's + * comparand door refuses it. + */ +function foreignRealmComparandRefusalReason(field: string): string { + return `filter comparand on field '${field}' is a plain object from another realm, which is ` + + 'neither a comparison value nor filter structure here'; +} + +/** + * Is `value` an object whose prototype is a `null`-prototype object, such as + * `Object.create(Object.create(null))`? Its chain never reaches + * `Object.prototype`, so it inherits no `toString` or `valueOf` from it (an + * ordering threw on it, unless its prototype defines one), and it is refused + * under every operator, in a sentence that names it as the converter does. + * + * The test alone also matches a plain object of ANOTHER realm: it relies on + * {@link objectValueRefusal} running {@link isForeignRealmPlainObject} first. + */ +function isNullRootedObject(value: unknown): boolean { + if (!value || typeof value !== 'object' || Array.isArray(value) || isPlainObject(value)) return false; + try { + const proto = Object.getPrototypeOf(value) as object | null; + return proto !== null && Object.getPrototypeOf(proto) === null; + } catch { + return false; + } +} + +function nullRootedComparandRefusalReason(field: string, value: object): string { + return `filter comparand on field '${field}' is ${instanceName(value)}, which is ` + + 'neither a comparison value nor filter structure here'; +} + +/** `a Moment instance`, or a fallback when the constructor cannot be read. */ +function instanceName(value: object): string { + try { + const name = (Object.getPrototypeOf(value) as { constructor?: { name?: unknown } } | null) + ?.constructor?.name; + if (typeof name === 'string' && name !== '') return `a ${name} instance`; + } catch { + // fall through: a refusal sentence must never throw + } + return 'an object of an unrecognised type'; +} + +/** + * The refusal for a class instance (a moment or luxon date, a decimal object, + * a `RegExp`, a `Map`) as the comparand of an equality, membership or text + * operator. It is data, and the ordering operators compare it through its + * `valueOf` when that returns a primitive, and otherwise as its text; these + * operators would compare it by reference (`$eq` no row, + * `$ne` / `$nin` every row) or as its text, and the spec's comparand door + * refuses it at every one of them. One sentence for both dialects: it names no + * operator. + */ +function classInstanceComparandRefusalReason(field: string, value: object): string { + return `filter comparand on field '${field}' is ${instanceName(value)}, which the in-memory ` + + 'matcher compares only by order (under $gt / $gte / $lt / $lte / $between, through its ' + + 'valueOf when that returns a primitive, otherwise as its text); an equality, membership or ' + + 'text comparison would read it by reference or as ' + + `text, so a comparison value there must be ${ACCEPTED_FILTER_COMPARAND_TYPES_SENTENCE}`; +} + +/** + * {@link objectComparandRefusal} for one value: a whole comparand or one list + * member. `byValue` is whether the operator compares by equality, membership or + * text rather than by order. + */ +function objectValueRefusal(field: string, value: unknown, byValue: boolean): string | undefined { const key = nestedRelationComparandKey(value); if (key !== undefined) return nestedRelationRefusalReason(field, key); - if (isPlainObject(value) && Object.keys(value).length === 0) { - return emptyObjectComparandRefusalReason(field); + if (isPlainObject(value)) { + const keys = Object.keys(value); + if (keys.length === 0) return emptyObjectComparandRefusalReason(field); + // A `{ $field }` reference is resolved, or refused by name, further on. + if (isFieldReferenceComparand(value)) return undefined; + if (isNowAnchorComparand(value)) return nowAnchorComparandRefusalReason(field); + // nestedRelationComparandKey returned every non-empty plain object with no + // `$` key above, so a `$` key is present here. + return operatorKeyedComparandRefusalReason(field, keys.find((k) => k.startsWith('$')) as string); + } + if (isForeignRealmPlainObject(value)) return foreignRealmComparandRefusalReason(field); + if (isNullRootedObject(value)) return nullRootedComparandRefusalReason(field, value as object); + if ( + byValue && value !== null && typeof value === 'object' && !Array.isArray(value) + && !isAcceptedFilterComparand(value) + ) { + return classInstanceComparandRefusalReason(field, value); } return undefined; } /** - * The refusal for a comparand that is a PLAIN object with no `$` key, empty or - * not, or `undefined` when the comparand is not one. ONE builder for both arms: + * The refusal for an OBJECT comparand this matcher cannot compare, or + * `undefined` when the comparand is not one. ONE builder for both arms: * {@link matchesComparisonNode} calls it for every AST operator that reads the * value slot, and {@link matchesDollarOperator} for every `$` operator of the * spec's `FILTER_OPERATORS` that reads a comparand. @@ -568,22 +723,34 @@ function plainObjectValueRefusal(field: string, value: unknown): string | undefi * (`normalizeFilterComparandTypes`) refuses the same comparand in both * positions, so a `provider: 'value'` list refuses where the platform does. * - * A NON-EMPTY one is a nested relation condition and gets - * {@link nestedRelationRefusalReason}, which names its first key. An EMPTY one, - * `{}`, has no key to name and gets {@link emptyObjectComparandRefusalReason}. - * A `Date`, a class instance and a `{ $field }` reference are not plain objects - * with no `$` key, so they are still compared. + * What is refused, under every operator that reads a comparand: + * + * - a plain object with no `$` key: a NON-EMPTY one is a nested relation + * condition and gets {@link nestedRelationRefusalReason}, which names its + * first key; an EMPTY one, `{}`, gets {@link emptyObjectComparandRefusalReason}; + * - a plain object with a `$` key that is not a `{ $field }` reference: the + * `{ $now, addDays }` date anchor gets {@link nowAnchorComparandRefusalReason}, + * any other one {@link operatorKeyedComparandRefusalReason}; + * - a plain object of another realm ({@link isForeignRealmPlainObject}), and an + * object whose prototype is a `null`-prototype object of no realm's `Object` + * ({@link isNullRootedObject}). + * + * And, only under an operator that compares by equality, membership or text + * (`byValue`), a class instance ({@link classInstanceComparandRefusalReason}). + * Under an ordering this builder does not refuse it. It refuses neither a + * `Date` nor a `{ $field }` reference. */ -function plainObjectComparandRefusal( +function objectComparandRefusal( field: string, rawTarget: unknown, listOperator: boolean, + byValue: boolean, ): string | undefined { - const whole = plainObjectValueRefusal(field, rawTarget); + const whole = objectValueRefusal(field, rawTarget, byValue); if (whole !== undefined) return whole; if (listOperator && Array.isArray(rawTarget)) { for (const member of rawTarget) { - const refusal = plainObjectValueRefusal(field, member); + const refusal = objectValueRefusal(field, member, byValue); if (refusal !== undefined) return refusal; } } @@ -647,10 +814,14 @@ function matchesComparisonNode( // the object form of the same filter is refused by name. Checked for every // operator that reads the slot, so `!=` cannot answer it as every row, and // for each member of a list comparand, so `nin` cannot either. An EMPTY plain - // object, `{}`, is refused by the same builder in a sentence of its own. + // object, `{}`, a `$`-keyed object that is no `{ $field }` reference (the + // `{ $now, addDays }` anchor among them), a plain object of another realm and, + // under an equality, membership or text operator, a class instance are + // refused by the same builder, each in a sentence of its own. if (!AST_NO_COMPARAND_OPERATORS.has(operator)) { - const plainRefusal = plainObjectComparandRefusal( + const plainRefusal = objectComparandRefusal( field, rawTarget, AST_LIST_COMPARAND_OPERATORS.has(operator), + AST_BY_VALUE_OPERATORS.has(operator), ); if (plainRefusal !== undefined) return refuseFilterNode(refusals, plainRefusal); } @@ -931,20 +1102,20 @@ function matchesDollarOperator( return refuseListMemberFieldReference(refusals, field, operator); } - // A plain object with no `$` key as the comparand, NON-EMPTY or EMPTY (`{}`), - // whole or as a list member: the AST arm's refusals, from the same builder, - // so `$ne` / `$notContains` / `$nin` cannot answer it as every row. A - // non-empty one gets the nested-relation sentence, `{}` its own. Judged for - // every declared operator that reads a comparand. The three flag operators - // are not: `$empty` refuses a non-boolean flag on its own arm, and `$null` / - // `$exists` read their flag's truthiness, as their lowering does. Keys - // outside `FILTER_OPERATORS` keep the refusal the `default` arm gives them. + // An object comparand this matcher cannot compare, whole or as a list member: + // the AST arm's refusals, from the same builder, so `$ne` / `$notContains` / + // `$nin` cannot answer it as every row. See objectComparandRefusal for the + // population. Judged for every declared operator that reads a comparand. The + // three flag operators are not: each refuses a non-boolean flag on its own + // arm below. Keys outside `FILTER_OPERATORS` keep the refusal the `default` + // arm gives them. if ( DOLLAR_COMPARAND_OPERATORS.has(operator) && !DOLLAR_FLAG_OPERATORS.has(operator) ) { - const plainRefusal = plainObjectComparandRefusal( + const plainRefusal = objectComparandRefusal( field, rawTarget, DOLLAR_LIST_COMPARAND_OPERATORS.has(operator), + DOLLAR_BY_VALUE_OPERATORS.has(operator), ); if (plainRefusal !== undefined) return refuseFilterNode(refusals, plainRefusal); } @@ -1009,15 +1180,20 @@ function matchesDollarOperator( // -- Null-ness. Unlike the AST spelling, direction comes from the VALUE: // `$null: true` is IS NULL and `$null: false` is IS NOT NULL, which is the // lowering `convertFiltersToAST` already performs. + // + // The flag is a BOOLEAN by declaration (`SpecialOperatorSchema`), so + // anything else is refused here rather than read for its truthiness, as + // `$empty` below is and as the converter refuses it before lowering: a + // truthy `'no'` would have answered the IS NULL rows. case '$null': - return target - ? value === null || value === undefined - : value !== null && value !== undefined; + if (target === true) return value === null || value === undefined; + if (target === false) return value !== null && value !== undefined; + return refuseFilterNode(refusals, nonBooleanFlagRefusalReason(field, operator, target)); // `$exists` is the exact INVERSE of `$null`, and that is the platform's own // reading rather than one invented here: `convertFiltersToAST` // (`../utils/filter-converter.ts`) lowers `$exists: true` to `is_not_null` - // and `$exists: false` to `is_null`, three lines below where it lowers + // and `$exists: false` to `is_null`, in the same arm where it lowers // `$null` the other way round. Both operators are absent from that file's // `convertOperatorToAST` map and both are special-cased BEFORE it, so that // map's silence is not a decision about either of them. Two producers in @@ -1027,9 +1203,9 @@ function matchesDollarOperator( // would have turned "every row" into "no rows" on a filter that looks like // it works, which is the one outcome worse than the bug. case '$exists': - return target - ? value !== null && value !== undefined - : value === null || value === undefined; + if (target === true) return value !== null && value !== undefined; + if (target === false) return value === null || value === undefined; + return refuseFilterNode(refusals, nonBooleanFlagRefusalReason(field, operator, target)); // objectui#11094 — `$empty`, which `@objectstack/spec` 17.6.0 admitted to // `FILTER_OPERATORS` (objectstack#20446) and to which it lowers `is_empty` / @@ -1044,11 +1220,7 @@ function matchesDollarOperator( case '$empty': if (target === true) return isEmptyStoredValue(value); if (target === false) return !isEmptyStoredValue(value); - return refuseFilterNode( - refusals, - `filter operator '$empty' on field '${field}' takes a boolean flag (true or false); ` - + `received ${describeComparand(target)}`, - ); + return refuseFilterNode(refusals, nonBooleanFlagRefusalReason(field, operator, target)); // objectui#8515 — the hand-authored IMPLICIT form `{ amount: { $field: 'x' } }`. // It is not a reference comparand: an object whose only key starts with `$` diff --git a/ui/packages/core/src/adapters/__tests__/ValueDataSource.astFilterVocabulary.test.ts b/ui/packages/core/src/adapters/__tests__/ValueDataSource.astFilterVocabulary.test.ts index d9b4501de5b..66c6dfe00be 100644 --- a/ui/packages/core/src/adapters/__tests__/ValueDataSource.astFilterVocabulary.test.ts +++ b/ui/packages/core/src/adapters/__tests__/ValueDataSource.astFilterVocabulary.test.ts @@ -48,6 +48,7 @@ */ import { describe, it, expect, vi, afterEach } from 'vitest'; +import { runInNewContext } from 'node:vm'; import { VIEW_FILTER_OPERATORS } from '@objectstack/spec/ui'; import { canonicalAstOperator, @@ -619,3 +620,88 @@ describe('the nested-relation node is refused by name in both dialects', () => { expect(warn).not.toHaveBeenCalled(); }); }); + +/** + * The AST arm's null-ness operators carry no flag: direction comes from the + * operator NAME, and the value slot is never read. That is the spec's own + * reading, so this face needs no flag door of its own: `parseFilterAST` + * hands `['f', 'is_null', ]` back as `{ f: { $null: true } }`. The + * flag door sits where a flag exists, on the `$` arm and in the converter, + * which refuses a non-boolean before it can lower one. + */ +describe('the AST null-ness operators read no flag, as the spec reads them', () => { + const ROWS = [ + { id: 'has', ts: 't' }, + { id: 'null', ts: null }, + { id: 'missing' }, + ]; + + it.each([['no'], [{ owner: 'u1' }], [false], [0]])( + '`is_null` with %j in the value slot is the spec’s `$null: true`, with nothing logged', + async (slot) => { + expect(parseFilterAST(['ts', 'is_null', slot] as never)).toEqual({ ts: { $null: true } }); + expect(parseFilterAST(['ts', 'is_not_null', slot] as never)).toEqual({ ts: { $null: false } }); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + expect(await selectedIds(['ts', 'is_null', slot], ROWS)).toEqual(['null', 'missing']); + expect(await selectedIds(['ts', 'is_not_null', slot], ROWS)).toEqual(['has']); + expect(warn).not.toHaveBeenCalled(); + }, + ); +}); + +/** + * The shared comparand builder on the AST arm: a `{ $now, addDays }` anchor, a + * `$`-keyed object that is no `{ $field }` reference and a plain object of + * another realm are refused under every operator that reads the slot, and a + * class instance under an equality, membership or text operator. + */ +describe('object comparands the AST arm cannot compare are refused by name', () => { + class Amount { + readonly units: number; + constructor(units: number) { + this.units = units; + } + valueOf(): number { + return this.units; + } + } + + it.each([ + ['<', { $now: true, addDays: 7 }, 'is a { $now, addDays } date anchor'], + ['=', { $now: true, addDays: 0 }, 'is a { $now, addDays } date anchor'], + ['!=', { $foo: 1 }, "is an object carrying the key '$foo'"], + ['>', runInNewContext('({ id: "u1" })'), 'is a plain object from another realm'], + ['!=', runInNewContext('({ id: "u1" })'), 'is a plain object from another realm'], + ['=', new Amount(25), 'is a Amount instance'], + ['!=', new Amount(25), 'is a Amount instance'], + ['not_contains', new Amount(25), 'is a Amount instance'], + ['starts_with', new Amount(25), 'is a Amount instance'], + // Neither is a plain object from another realm: one structural test with + // the converter (foreign-realm-object.ts). + ['>', Object.create(Object.create(null) as object) as object, 'is an object of an unrecognised type, which'], + ['=', Object.create({ id: 'u1' }) as object, 'is a Object instance, which'], + ] as const)('`%s` refuses %j', async (operator, comparand, words) => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + expect(await selectedIds(['age', operator, comparand])).toEqual([]); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0]?.[0])).toContain(`filter comparand on field 'age' ${words}`); + }); + + it.each([ + ['in', [new Amount(25), 30]], + ['nin', [new Amount(25)]], + ['in', [{ $now: true, addDays: 1 }]], + ['between', [runInNewContext('({})'), 30]], + ] as const)('`%s` refuses such an object as a list member', async (operator, list) => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + expect(await selectedIds(['age', operator, list])).toEqual([]); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0]?.[0])).toContain("filter comparand on field 'age' is "); + }); + + it('CONTROL: a class instance under `between` compares through valueOf, with nothing logged', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + expect(await selectedIds(['age', 'between', [new Amount(22), new Amount(28)]])).toEqual(['b']); + expect(warn).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/packages/core/src/adapters/__tests__/ValueDataSource.dollarFilterVocabulary.test.ts b/ui/packages/core/src/adapters/__tests__/ValueDataSource.dollarFilterVocabulary.test.ts index 5eac8e4c358..41f3d0dc76d 100644 --- a/ui/packages/core/src/adapters/__tests__/ValueDataSource.dollarFilterVocabulary.test.ts +++ b/ui/packages/core/src/adapters/__tests__/ValueDataSource.dollarFilterVocabulary.test.ts @@ -73,6 +73,7 @@ */ import { describe, it, expect, vi, afterEach } from 'vitest'; +import { runInNewContext } from 'node:vm'; import { FILTER_OPERATORS } from '@objectstack/spec/data'; import { ValueDataSource } from '../ValueDataSource'; import { toFilterNodeSafely } from '../../utils/filter-converter'; @@ -776,3 +777,281 @@ describe('a plain-object comparand under a `$` operator is refused as the AST ar expect(lines[0]).toContain("carries the non-operator key 'profile'"); }); }); + +/** + * `$null` / `$exists` take a BOOLEAN flag on this face too, as `$empty` does, + * and the converter refuses the same flags before lowering, so the object form + * and its lowered form cannot answer apart: neither one serves rows. + * `nickname` is present on `a`, null on `b`, absent on `c`. + */ +describe('a `$null` / `$exists` flag that is not a boolean is refused on the `$` arm', () => { + const NON_BOOLEAN_FLAGS: unknown[] = ['no', 'false', 1, 0, null, { owner: 'u1' }, {}]; + + async function refusalOf(filter: unknown): Promise<{ ids: string[]; lines: string[] }> { + const warn = spyWarn(); + const ids = await selectedIds(filter); + const lines = warn.mock.calls.map((call) => String(call[0])); + warn.mockRestore(); + return { ids, lines }; + } + + describe.each(['$null', '$exists'] as const)('%s', (operator) => { + it.each(NON_BOOLEAN_FLAGS.map((flag) => [JSON.stringify(flag), flag]))( + 'the flag %s excludes every row and logs the boolean-flag sentence once', + async (_label, flag) => { + const { ids, lines } = await refusalOf({ nickname: { [operator]: flag } }); + expect(ids).toEqual([]); + expect(lines).toHaveLength(1); + expect(lines[0]).toContain( + `filter operator '${operator}' on field 'nickname' takes a boolean flag (true or false)`, + ); + }, + ); + + it('the converter refuses the same filter, so there is no lowered form to split from', () => { + const lowered = toFilterNodeSafely({ nickname: { [operator]: 'no' } }); + expect(lowered.ok).toBe(false); + if (!lowered.ok) { + expect(lowered.refusal).toMatchObject({ code: 'INVALID_FILTER', operator, field: 'nickname' }); + } + }); + }); + + it.each([ + [{ nickname: { $null: true } }, ['b', 'c']], + [{ nickname: { $null: false } }, ['a']], + [{ nickname: { $exists: true } }, ['a']], + [{ nickname: { $exists: false } }, ['b', 'c']], + ] as const)( + 'CONTROL: %j answers as before, in the object form and in its lowered form, with nothing logged', + async (filter, expected) => { + const lowered = toFilterNodeSafely(filter); + if (!lowered.ok) throw new Error(`the lowering refused ${JSON.stringify(filter)}`); + const warn = spyWarn(); + expect(await selectedIds(filter)).toEqual(expected); + expect(await selectedIds(lowered.node)).toEqual(expected); + expect(warn).not.toHaveBeenCalled(); + }, + ); +}); + +/** + * Three more object comparands this matcher cannot compare, refused on both + * arms by the shared builder: a `$`-keyed plain object that is no `{ $field }` + * reference (the `{ $now, addDays }` date anchor among them), a plain object + * of another realm, and a class instance under an equality, membership or text + * operator. The spec's comparand door refuses the last two at every operator; + * it steps around a well-formed anchor, which the platform resolves in the + * compared column's temporal form, and this face, which has no field types, + * refuses it in words instead of comparing it as `[object Object]`. + */ +describe('a `$`-keyed object, a foreign-realm object and a class instance in comparand position', () => { + const ROWS_2 = [ + { id: 'a', owner: 'zeta', age: 30, due: '2099-01-01', floor: 25 }, + { id: 'b', owner: 'Alpha', age: 25, due: '2000-01-01', floor: 25 }, + { id: 'c', owner: null, age: 20, due: null, floor: 10 }, + ]; + const FLAG_OPERATORS = new Set(['$null', '$exists', '$empty']); + const LIST_OPERATORS = new Set(['$in', '$nin', '$between']); + const COMPARAND_OPERATORS = FILTER_OPERATORS.filter((op) => !FLAG_OPERATORS.has(op)); + + /** + * How each comparand operator compares: by ORDER (a class instance is + * compared through its `valueOf`), by VALUE (equality, membership, text: a + * class instance is refused), or by its own text door (`$icontains`, which + * refuses every non-string comparand already). + */ + const COMPARISON_KIND: Record = { + $eq: 'value', $ne: 'value', $in: 'value', $nin: 'value', + $contains: 'value', $notContains: 'value', $startsWith: 'value', $endsWith: 'value', + $gt: 'order', $gte: 'order', $lt: 'order', $lte: 'order', $between: 'order', + $icontains: 'text-door', + }; + + async function refusalOf(filter: unknown): Promise<{ ids: string[]; lines: string[] }> { + const warn = spyWarn(); + const ids = await selectedIds(filter, ROWS_2); + const lines = warn.mock.calls.map((call) => String(call[0])); + warn.mockRestore(); + return { ids, lines }; + } + + /** The whole comparand, or a list member for a list operator. */ + const placed = (operator: string, comparand: unknown): unknown => + LIST_OPERATORS.has(operator) ? [comparand, 'zzz'] : comparand; + + it('the comparison-kind table covers the comparand operators exactly', () => { + expect(Object.keys(COMPARISON_KIND).sort()).toEqual([...COMPARAND_OPERATORS].sort()); + }); + + const ANCHOR = { $now: true, addDays: 7 }; + const ANCHOR_REFUSAL = + "filter comparand on field 'due' is a { $now, addDays } date anchor, which the in-memory " + + 'matcher does not resolve'; + + it.each(COMPARAND_OPERATORS)( + '`%s` refuses a `{ $now, addDays }` anchor by name, whole or as a list member', + async (operator) => { + const { ids, lines } = await refusalOf({ due: { [operator]: placed(operator, ANCHOR) } }); + expect(ids).toEqual([]); + expect(lines).toHaveLength(1); + expect(lines[0]).toContain(ANCHOR_REFUSAL); + }, + ); + + it('the anchor sentence names the remedy this face can compare', async () => { + const { lines } = await refusalOf({ due: { $lt: ANCHOR } }); + expect(lines[0]).toContain('; compare with a concrete Date or ISO string here'); + }); + + it.each([ + ['{ $now: 0 }', { $now: 0 }], + ['{ $now: false, addDays: 7 }', { $now: false, addDays: 7 }], + ])('%s is no anchor by the spec’s test, so it takes the `$`-key sentence', async (_label, comparand) => { + const { ids, lines } = await refusalOf({ due: { $lt: comparand } }); + expect(ids).toEqual([]); + expect(lines).toHaveLength(1); + expect(lines[0]).not.toContain('date anchor'); + expect(lines[0]).toContain("filter comparand on field 'due' is an object carrying the key '$now'"); + }); + + it('the resolved anchor form (`$now` holding an instant) is refused in the same words', async () => { + const { ids, lines } = await refusalOf({ due: { $lt: { $now: '2026-01-01T00:00:00Z', addDays: 7 } } }); + expect(ids).toEqual([]); + expect(lines[0]).toContain(ANCHOR_REFUSAL); + }); + + it.each(COMPARAND_OPERATORS)( + '`%s` refuses another `$`-keyed object that is no `{ $field }` reference', + async (operator) => { + const { ids, lines } = await refusalOf({ owner: { [operator]: placed(operator, { $foo: 1 }) } }); + expect(ids).toEqual([]); + expect(lines).toHaveLength(1); + expect(lines[0]).toContain( + "filter comparand on field 'owner' is an object carrying the key '$foo', which is neither " + + 'a comparison value nor a { $field } reference', + ); + }, + ); + + it.each(COMPARAND_OPERATORS)( + '`%s` refuses a plain object of another realm, whole or as a list member', + async (operator) => { + const foreign = runInNewContext('({ id: "u1" })'); + const { ids, lines } = await refusalOf({ owner: { [operator]: placed(operator, foreign) } }); + expect(ids).toEqual([]); + expect(lines).toHaveLength(1); + expect(lines[0]).toContain("filter comparand on field 'owner' is a plain object from another realm"); + }, + ); + + it('a plain object of another realm as the WHOLE condition is refused in the converter’s words', async () => { + const { ids, lines } = await refusalOf({ owner: runInNewContext('({ id: "u1" })') }); + expect(ids).toEqual([]); + expect(lines).toHaveLength(1); + expect(lines[0]).toContain("The filter on field 'owner' is a plain object from another realm"); + expect(lines[0]).toContain('{ ...condition } for each operator map, or structuredClone(filter)'); + }); + + it.each([ + // THIS realm, constructor `Object`, but its prototype's prototype is + // `Object.prototype`: a class-instance-like object, refused by value only. + ['Object.create(somePlainObject)', () => Object.create({ id: 'u1' }) as object, 'is a Object instance, which'], + // A prototype whose prototype is `null`, but with no `constructor`: no + // text, so refused under every operator, named as the converter names it. + [ + 'Object.create(Object.create(null))', + () => Object.create(Object.create(null) as object) as object, + 'is an object of an unrecognised type, which is neither a comparison value nor filter structure here', + ], + ])('%s is not called a plain object from another realm', async (_label, make, named) => { + const { ids, lines } = await refusalOf({ owner: { $eq: make() } }); + expect(ids).toEqual([]); + expect(lines).toHaveLength(1); + expect(lines[0]).toContain(`filter comparand on field 'owner' ${named}`); + expect(lines[0]).not.toMatch(/another realm/); + }); + + it.each(COMPARAND_OPERATORS)( + '`%s` refuses `Object.create(Object.create(null))` instead of throwing on it', + async (operator) => { + const { ids, lines } = await refusalOf({ + owner: { [operator]: placed(operator, Object.create(Object.create(null) as object)) }, + }); + expect(ids).toEqual([]); + expect(lines).toHaveLength(1); + expect(lines[0]).toContain("filter comparand on field 'owner' is an object of an unrecognised type"); + }, + ); + + /** A class instance: data, compared through its `valueOf` under an ordering. */ + class Amount { + readonly units: number; + constructor(units: number) { + this.units = units; + } + valueOf(): number { + return this.units; + } + toString(): string { + return `Amount(${this.units})`; + } + } + const CLASS_REFUSAL = "filter comparand on field 'age' is a Amount instance, which the in-memory matcher compares only by order"; + + it.each(COMPARAND_OPERATORS.filter((op) => COMPARISON_KIND[op] === 'value'))( + '`%s` refuses a class instance, whole or as a list member, by name', + async (operator) => { + const { ids, lines } = await refusalOf({ age: { [operator]: placed(operator, new Amount(25)) } }); + expect(ids).toEqual([]); + expect(lines).toHaveLength(1); + expect(lines[0]).toContain(CLASS_REFUSAL); + }, + ); + + it('`$icontains` keeps its own text door for a class instance', async () => { + const { ids, lines } = await refusalOf({ age: { $icontains: new Amount(25) } }); + expect(ids).toEqual([]); + expect(lines).toHaveLength(1); + expect(lines[0]).not.toContain(CLASS_REFUSAL); + expect(lines[0]).toContain('$icontains'); + }); + + it('CONTROL: under `$between` a class instance endpoint compares through valueOf, with nothing logged', async () => { + const warn = spyWarn(); + expect(await selectedIds({ age: { $between: [new Amount(22), new Amount(28)] } }, ROWS_2)).toEqual(['b']); + expect(warn).not.toHaveBeenCalled(); + }); + + it('CONTROL: a scalar, a `Date` and a `{ $field }` reference are compared, with nothing logged', async () => { + const warn = spyWarn(); + expect(await selectedIds({ owner: { $ne: 'zeta' } }, ROWS_2)).toEqual(['b', 'c']); + expect(await selectedIds({ due: { $lt: '2050-01-01' } }, ROWS_2)).toEqual(['b']); + expect(await selectedIds({ age: { $eq: { $field: 'floor' } } }, ROWS_2)).toEqual(['b']); + const dated = [{ id: 'x', at: new Date('2026-03-01T00:00:00Z') }, { id: 'y', at: new Date('2026-01-01T00:00:00Z') }]; + expect(await selectedIds({ at: { $eq: new Date('2026-03-01T00:00:00Z') } }, dated)).toEqual(['x']); + expect(await selectedIds({ at: { $nin: [new Date('2026-03-01T00:00:00Z')] } }, dated)).toEqual(['y']); + expect(warn).not.toHaveBeenCalled(); + }); + + it.each([ + ['$lt anchor', { due: { $lt: ANCHOR } }], + ['$in anchor member', { due: { $in: [ANCHOR] } }], + ['$ne $-keyed', { owner: { $ne: { $foo: 1 } } }], + ['$eq class instance', { age: { $eq: new Amount(25) } }], + ['$nin class member', { age: { $nin: [new Amount(25)] } }], + ['$notContains class instance', { age: { $notContains: new Amount(25) } }], + ] as const)( + '%s: the object form and its lowered AST form log one and the same sentence', + async (_label, filter) => { + const lowered = toFilterNodeSafely(filter); + if (!lowered.ok) throw new Error(`the lowering refused ${JSON.stringify(filter)}`); + const objectForm = await refusalOf(filter); + const astForm = await refusalOf(lowered.node); + expect(objectForm.ids).toEqual([]); + expect(astForm.ids).toEqual([]); + expect(objectForm.lines).toHaveLength(1); + expect(astForm.lines).toEqual(objectForm.lines); + }, + ); +}); diff --git a/ui/packages/core/src/utils/__tests__/filter-converter.test.ts b/ui/packages/core/src/utils/__tests__/filter-converter.test.ts index c082718680f..d9d1e0a8b96 100644 --- a/ui/packages/core/src/utils/__tests__/filter-converter.test.ts +++ b/ui/packages/core/src/utils/__tests__/filter-converter.test.ts @@ -201,3 +201,82 @@ describe('the nested-relation node (objectstack#34990)', () => { .toEqual({ code: 'INVALID_FILTER', status: 400, field: 'account' }); }); }); + +/** + * `$null` and `$exists` take a BOOLEAN flag, as `$empty` does. + * `SpecialOperatorSchema` declares all three `z.boolean()`, and the spec's save + * door and every query face refuse a non-boolean rather than read it for its + * truthiness. The converter used to lower `{ f: { $null: 'no' } }` to + * `['f', 'is_null', true]` (a truthy string read as IS NULL), so a server-backed + * source answered rows its own door would have refused. + */ +describe('a `$null` / `$exists` flag that is not a boolean is refused, not read for truthiness', () => { + const NON_BOOLEAN_FLAGS: unknown[] = ['no', 'true', 'false', 1, 0, null, { owner: 'u1' }, {}, []]; + + const thrownBy = (run: () => unknown): unknown => { + try { + run(); + } catch (error) { + return error; + } + return undefined; + }; + + describe.each(['$null', '$exists'] as const)('%s', (operator) => { + it.each(NON_BOOLEAN_FLAGS.map((flag) => [JSON.stringify(flag), flag]))( + 'refuses the flag %s in the INVALID_FILTER envelope, naming the operator and the field', + (_label, flag) => { + const thrown = thrownBy(() => convertFiltersToAST({ f: { [operator]: flag } })); + expect(thrown).toBeInstanceOf(FilterOperatorError); + expect(thrown).toMatchObject({ code: 'INVALID_FILTER', httpStatus: 400, operator, field: 'f' }); + expect((thrown as Error).message.split('; ')[0]) + .toBe(`[ObjectUI] The '${operator}' filter operator on field 'f' takes a boolean flag (true or false)`); + }, + ); + + it('refuses it beside a key that lowers, so it cannot vanish from the filter', () => { + const thrown = thrownBy(() => convertFiltersToAST({ status: 'a', f: { [operator]: 'no' } })); + expect(thrown).toMatchObject({ code: 'INVALID_FILTER', operator, field: 'f' }); + }); + }); + + it('CONTROL: `true` and `false` lower exactly as before, and round-trip through the spec', () => { + const cases = [ + [{ f: { $null: true } }, ['f', 'is_null', true], { f: { $null: true } }], + [{ f: { $null: false } }, ['f', 'is_not_null', true], { f: { $null: false } }], + [{ f: { $exists: true } }, ['f', 'is_not_null', true], { f: { $null: false } }], + [{ f: { $exists: false } }, ['f', 'is_null', true], { f: { $null: true } }], + ] as const; + for (const [filter, node, readBack] of cases) { + expect(convertFiltersToAST(filter)).toEqual(node); + expect(parseFilterAST(node as unknown as FilterNode)).toEqual(readBack); + } + }); + + it('`$empty` refuses in the same sentence shape', () => { + const thrown = thrownBy(() => convertFiltersToAST({ f: { $empty: 'yes' } })); + expect(thrown).toMatchObject({ code: 'INVALID_FILTER', httpStatus: 400, operator: '$empty', field: 'f' }); + expect((thrown as Error).message.split('; ')[0]) + .toBe("[ObjectUI] The '$empty' filter operator on field 'f' takes a boolean flag (true or false)"); + }); + + it.each([ + ['$null', 'a missing value', 'a present one'], + ['$exists', 'a present value', 'a missing one'], + ['$empty', 'an empty value', 'a non-empty one'], + ] as const)('`%s` refuses in one full sentence: the received value and both directions', (operator, whenTrue, whenFalse) => { + const thrown = thrownBy(() => convertFiltersToAST({ f: { [operator]: 'no' } })); + expect((thrown as Error).message).toBe( + `[ObjectUI] The '${operator}' filter operator on field 'f' takes a boolean flag (true or false); ` + + `received "no". Write { f: { ${operator}: true } } for ${whenTrue}, or ` + + `{ f: { ${operator}: false } } for ${whenFalse}.`, + ); + }); + + it('a flag that cannot be serialised is still refused in words, not by a second throw', () => { + const cyclic: Record = {}; + cyclic.self = cyclic; + const thrown = thrownBy(() => convertFiltersToAST({ f: { $null: cyclic } })); + expect(thrown).toMatchObject({ code: 'INVALID_FILTER', operator: '$null', field: 'f' }); + }); +}); diff --git a/ui/packages/core/src/utils/__tests__/filter-exotic-comparand-8567.test.ts b/ui/packages/core/src/utils/__tests__/filter-exotic-comparand-8567.test.ts index fb53e2e5b0f..42a2bb295c8 100644 --- a/ui/packages/core/src/utils/__tests__/filter-exotic-comparand-8567.test.ts +++ b/ui/packages/core/src/utils/__tests__/filter-exotic-comparand-8567.test.ts @@ -317,13 +317,61 @@ describe('objectui#8567 — the identity and the operator path are untouched', ( expect(convertFiltersToAST({ age: bag })).toEqual(['age', '>=', 18]); }); - it('a CROSS-REALM plain object is still an operator map', () => { - // Its prototype is another realm's `Object.prototype`, so an identity test - // against this realm's would refuse a perfectly plain object. The gate takes - // the second hop instead: a plain object's prototype has a null prototype. - const foreign = runInNewContext('({ $gte: 18 })') as Record; - expect(Object.getPrototypeOf(foreign)).not.toBe(Object.prototype); - expect(convertFiltersToAST({ age: foreign })).toEqual(['age', '>=', 18]); + it('a CROSS-REALM plain object is a comparand, refused as the spec refuses it', () => { + // Its prototype is another realm's `Object.prototype`. The spec's filter + // walk (`isFilterNode`) and the engine's `isNoOperatorObject` read only + // this realm's `Object.prototype` or `null` as filter structure, so the + // spec judges it as a literal comparand and refuses it; the converter's + // operator-map test is the same prototype test, and refuses it too. + for (const source of ['({ $gte: 18 })', '({ owner: "u1" })']) { + const foreign = runInNewContext(source) as Record; + expect(Object.getPrototypeOf(foreign)).not.toBe(Object.prototype); + expect(() => normalizeFilterComparandTypes({ age: foreign })).toThrow(/which no driver can compare/); + const { thrown } = refusalOf(() => convertFiltersToAST({ age: foreign })); + expect(thrown).toBeInstanceOf(FilterOperatorError); + expect(thrown).toMatchObject({ ...INVALID_FILTER, field: 'age' }); + // Its own sentence, not the exotic one: the author wrote a valid + // operator map in the wrong realm, and the fix is a copy. + expect((thrown as Error).message).toBe( + "[ObjectUI] The filter on field 'age' is a plain object from another realm (an iframe, a vm " + + 'context). Only a plain object of this realm (prototype Object.prototype or null) is read as an ' + + "operator map or a nested condition here, as the spec's filter walk reads it; '@objectstack/spec' " + + 'reads this one as a comparand and answers 400 INVALID_FILTER. Rebuild the filter in this realm ' + + 'before filtering it: { ...condition } for each operator map, or structuredClone(filter).', + ); + expect((thrown as Error).message).not.toMatch(/comparand position/); + // The copy it names lowers. + expect(convertFiltersToAST({ age: { ...foreign } })).toEqual( + convertFiltersToAST({ age: structuredClone(foreign) }), + ); + } + expect(convertFiltersToAST({ age: { ...(runInNewContext('({ $gte: 18 })') as object) } })) + .toEqual(['age', '>=', 18]); + }); + + it.each([ + // THIS realm, constructor `Object`, but its prototype's prototype is + // `Object.prototype`: not a foreign plain object. + ['Object.create(somePlainObject)', () => Object.create({ $gte: 18 }) as object, 'a Object instance'], + // A prototype whose prototype is `null`, but with no `constructor`. + [ + 'Object.create(Object.create(null))', + () => Object.create(Object.create(null) as object) as object, + 'an object of an unrecognised type', + ], + ])('%s is an exotic comparand, not a plain object from another realm', (_label, make, named) => { + const value = make(); + expect(() => normalizeFilterComparandTypes({ age: value })).toThrow(/which no driver can compare/); + const { thrown } = refusalOf(() => convertFiltersToAST({ age: value })); + expect(thrown).toBeInstanceOf(FilterOperatorError); + expect(thrown).toMatchObject({ ...INVALID_FILTER, field: 'age' }); + expect((thrown as Error).message).toContain(`The filter on field 'age' carries ${named} in comparand position`); + expect((thrown as Error).message).not.toMatch(/another realm/); + }); + + it('CONTROL: a `null`-prototype object of THIS realm is still an operator map', () => { + const bare = Object.assign(Object.create(null) as Record, { $gte: 18 }); + expect(convertFiltersToAST({ age: bare })).toEqual(['age', '>=', 18]); }); it('a Date comparand still LOWERS — the other half of this arm (objectui#8555)', () => { diff --git a/ui/packages/core/src/utils/__tests__/filter-refusal-subject-9050.test.ts b/ui/packages/core/src/utils/__tests__/filter-refusal-subject-9050.test.ts index 4375a402561..a1511c881d1 100644 --- a/ui/packages/core/src/utils/__tests__/filter-refusal-subject-9050.test.ts +++ b/ui/packages/core/src/utils/__tests__/filter-refusal-subject-9050.test.ts @@ -34,6 +34,9 @@ * the two comparand arms it names no operator, so `field` is its subject. * objectui#11094 added the `$empty` flag refusal (a flag that is not a * boolean) the same way; it names its operator, so `$empty` is its subject. + * objectstack#35533 added the foreign-realm refusal (a field's whole condition + * is a plain object of another realm); it names no operator, so `field` is its + * subject. * * ⚠️ Each input is driven through `toFilterNodeSafely` — the RENDER-time entry, * not `convertFiltersToAST` directly — because the question is what a renderer @@ -43,6 +46,7 @@ import { describe, it, expect } from 'vitest'; import { readFileSync } from 'node:fs'; +import { runInNewContext } from 'node:vm'; import { fileURLToPath } from 'node:url'; import { dirname, join } from 'node:path'; import { @@ -70,6 +74,7 @@ const REFUSALS: Array<{ { site: 'combinator value is not an array', input: { $and: 'nope' }, operator: '$and', field: undefined, subject: '$and' }, { site: 'combinator member is not an object', input: { $and: ['nope'] }, operator: '$and', field: undefined, subject: '$and' }, { site: '$icontains comparand', input: { name: { $icontains: '' } }, operator: '$icontains', field: 'name', subject: '$icontains' }, + { site: 'plain object from another realm', input: { age: runInNewContext('({ $gte: 18 })') }, operator: undefined, field: 'age', subject: 'age' }, { site: 'empty operator map with no other condition', input: { a: {} }, operator: undefined, field: 'a', subject: 'a' }, { site: '$not combinator', input: { $not: { a: 1 } }, operator: '$not', field: undefined, subject: '$not' }, { site: 'bare array equality comparand', input: { tags: ['a', 'b'] }, operator: undefined, field: 'tags', subject: 'tags' }, diff --git a/ui/packages/core/src/utils/filter-converter.ts b/ui/packages/core/src/utils/filter-converter.ts index 53704b04742..7bfc7ad311e 100644 --- a/ui/packages/core/src/utils/filter-converter.ts +++ b/ui/packages/core/src/utils/filter-converter.ts @@ -22,6 +22,7 @@ import { } from '@objectstack/spec/ui'; import { isAcceptedFilterComparand, ACCEPTED_FILTER_COMPARAND_TYPES_SENTENCE } from '@objectstack/spec/data'; import { isRefusedTextComparand, textComparandRefusalReason } from './text-comparand.js'; +import { isForeignRealmPlainObject } from './foreign-realm-object.js'; /** * FilterNode AST type definition @@ -334,10 +335,16 @@ function falseIdentityLeaf(field: string, value: unknown[]): FilterNode { * pinned in filter-date-comparand-8555.test.ts section 4; that row now pins * the refusal.) * - * The second hop admits a CROSS-REALM plain object (an iframe, a `vm` context), - * whose prototype is that realm's `Object.prototype` rather than this one's: a - * plain object's prototype has a null prototype, while a `RegExp`'s chain is one - * link longer. So the test is about SHAPE, not about object identity. + * Plain means prototype `Object.prototype` or `null`, of THIS realm: the test + * the spec's filter walk (`isFilterNode` in `normalizeFilterComparandTypes`) + * and the engine's `isNoOperatorObject` make, so the client and the server name + * one population. A plain object from ANOTHER realm (an iframe, a `vm` + * context), whose prototype is that realm's `Object.prototype`, is therefore + * not an operator map here either: the spec reads it as a literal comparand and + * answers `INVALID_FILTER` / 400, so the converter refuses it with a sentence + * of its own (see {@link refuseForeignRealmCondition}), and the value data + * source, which routes a non-plain condition to this converter, refuses it in + * the same words. * * A plain object with no entries stays an operator map with no operators, * whatever else it happens to be. That boundary is deliberate: @@ -349,7 +356,7 @@ function falseIdentityLeaf(field: string, value: unknown[]): FilterNode { */ function isOperatorMap(value: object): boolean { const proto = Object.getPrototypeOf(value) as object | null; - return proto === null || proto === Object.prototype || Object.getPrototypeOf(proto) === null; + return proto === null || proto === Object.prototype; } /** @@ -464,6 +471,67 @@ function refuseTextComparand(field: string, operator: string, target: unknown): ); } +/** + * A field whose whole condition is a plain object of ANOTHER realm (an iframe, + * a `vm` context): `{ age: foreignObject }` with `foreignObject` built as + * `{ $gte: 18 }` there ({@link isForeignRealmPlainObject}). + * + * The author wrote a valid operator map in the wrong realm, so the exotic + * comparand sentence is the wrong one for them: it tells them a comparison + * value must be a string or a number, and that the condition used to be + * dropped, when until objectstack#35533 it lowered. This sentence says what is + * read as filter structure here and names the copy that rebuilds the filter in + * this realm. Same envelope as the exotic refusal: `INVALID_FILTER` / 400, + * naming the field. + */ +function refuseForeignRealmCondition(field: string): never { + throw new FilterOperatorError( + `[ObjectUI] The filter on field '${field}' is a plain object from another realm (an iframe, a vm ` + + `context). Only a plain object of this realm (prototype Object.prototype or null) is read as an ` + + `operator map or a nested condition here, as the spec's filter walk reads it; '@objectstack/spec' ` + + `reads this one as a comparand and answers 400 INVALID_FILTER. Rebuild the filter in this realm ` + + `before filtering it: { ...condition } for each operator map, or structuredClone(filter).`, + { field }, + ); +} + +/** What `true` and `false` select, for each of the three flag operators. */ +const FLAG_OPERATOR_DIRECTIONS: Record<'$null' | '$exists' | '$empty', readonly [string, string]> = { + $null: ['a missing value', 'a present one'], + $exists: ['a present value', 'a missing one'], + $empty: ['an empty value', 'a non-empty one'], +}; + +/** + * A flag operator — `$null`, `$exists`, `$empty` — whose flag is not a + * boolean: `{ a: { $null: 'no' } }`, `{ a: { $exists: { owner: 'u1' } } }`. + * + * `SpecialOperatorSchema` declares all three flags `z.boolean()`, the spec's + * save door refuses anything else, and the query faces refuse it rather than + * coerce it because the backends read a non-boolean in opposite directions + * (`"false"` the string is truthy). One sentence for the three, so the + * prescription names the two spellings that work. + * + * The received value is rendered defensively: a refusal message must never + * itself throw (a cyclic object has no JSON form). + */ +function refuseNonBooleanFlag(field: string, operator: '$null' | '$exists' | '$empty', flag: unknown): never { + let received: string; + try { + received = JSON.stringify(flag) ?? String(flag); + } catch { + received = typeof flag; + } + const [whenTrue, whenFalse] = FLAG_OPERATOR_DIRECTIONS[operator]; + throw new FilterOperatorError( + `[ObjectUI] The '${operator}' filter operator on field '${field}' takes a boolean flag ` + + `(true or false); received ${received}. ` + + `Write { ${field}: { ${operator}: true } } for ${whenTrue}, or ` + + `{ ${field}: { ${operator}: false } } for ${whenFalse}.`, + { operator, field }, + ); +} + /** * A field that names NO operator — `{ a: {} }` — wherever it appears in a * filter: alone (objectui#9164) or beside a key that lowers (objectui#10788). @@ -548,8 +616,11 @@ function refuseEmptyOperatorMap(field: string): never { * the condition travels verbatim in the object dialect, nested relations * included. Nothing here judges it. Whether `field` is a relationship and the * condition's keys are fields of the related object is decided where the - * declarations are: the engine refuses anything else with `INVALID_FILTER` / - * 400, and on a read it matches the relationship with one in-database + * declarations are: the engine answers `INVALID_FILTER` / 400 for such a + * condition under a field that stores a scalar or a structured-JSON value, + * and, under a relationship, for a condition key the related object does not + * declare, a dotted key, or a relation nested past the hop limit. On a read it + * matches the relationship with one in-database * subquery under the related object's own read scope, never an id list this * app reads first. * @@ -608,7 +679,9 @@ function isNestedRelationCondition(entries: ReadonlyArray<[string, unknown]>): b * operator map (`{ a: {} }`) — alone (objectui#9164) or * beside a key that lowers (objectui#10788): see {@link refuseEmptyOperatorMap}, * or if a `$empty` flag is not a boolean (`{ a: { $empty: 'yes' } }`, - * objectui#11094). + * objectui#11094), or if a `$null` / `$exists` flag is not one + * (`{ a: { $null: 'no' } }`, `{ a: { $exists: { owner: 'u1' } } }`): see + * {@link refuseNonBooleanFlag}. * * @example * // A field with NO operator (objectui#9164) @@ -822,6 +895,11 @@ export function convertFiltersToAST( // The accepted-type list is the spec's own sentence, not a second list // spelled out here, for the same reason the gate above is the spec's // predicate rather than a local `instanceof Date`. + // + // A plain object of ANOTHER realm is refused first, in its own sentence: + // it is a valid operator map written in the wrong realm, and the caller's + // fix is a copy, not a different comparand (refuseForeignRealmCondition). + if (isForeignRealmPlainObject(value)) refuseForeignRealmCondition(field); if (!isOperatorMap(value)) { throw new FilterOperatorError( `[ObjectUI] The filter on field '${field}' carries ${describeExoticComparand(value)} ` + @@ -829,7 +907,7 @@ export function convertFiltersToAST( `be ${ACCEPTED_FILTER_COMPARAND_TYPES_SENTENCE} (ACCEPTED_FILTER_COMPARAND_TYPES), so ` + `isAcceptedFilterComparand is false for it and normalizeFilterComparandTypes answers 400 ` + `INVALID_FILTER — "which no driver can compare". It is not an operator map either: only ` + - `a plain object can be one, so until objectui#8567 this value was read as ZERO operators ` + + `a plain object of this realm (prototype Object.prototype or null) can be one, so until objectui#8567 this value was read as ZERO operators ` + `and the '${field}' condition was dropped from the filter entirely, silently WIDENING the ` + `result set. Spell a text match as { ${field}: { $contains: '...' } } ($startsWith / ` + `$endsWith; a pattern itself has no operator here, see the $regex refusal), a membership ` + @@ -877,15 +955,22 @@ export function convertFiltersToAST( ); } - // $null / $exists translate based on their boolean value (per spec semantics). + // $null / $exists take their direction from a boolean flag (per spec semantics). // $null: true → IS NULL | $null: false → IS NOT NULL // $exists: true → IS NOT NULL | $exists: false → IS NULL - if (operator === '$null') { - conditions.push([field, operatorValue ? 'is_null' : 'is_not_null', true]); - continue; - } - if (operator === '$exists') { - conditions.push([field, operatorValue ? 'is_not_null' : 'is_null', true]); + // + // The flag is a BOOLEAN by declaration (`SpecialOperatorSchema`), so a + // non-boolean (`'no'`, `1`, `null`, an object) is refused rather than + // read for its truthiness, as `$empty` below is: the spec's save door + // and every query face refuse it with `INVALID_FILTER` / 400, and + // `ValueDataSource`'s `$null` / `$exists` arms refuse the same values, + // so the object form and its lowered node cannot answer apart. + if (operator === '$null' || operator === '$exists') { + if (operatorValue !== true && operatorValue !== false) { + refuseNonBooleanFlag(field, operator, operatorValue); + } + const isNull = operator === '$null' ? operatorValue : !operatorValue; + conditions.push([field, isNull ? 'is_null' : 'is_not_null', true]); continue; } // objectui#11094 — `$empty`, admitted to the spec's `FILTER_OPERATORS` @@ -903,13 +988,7 @@ export function convertFiltersToAST( // Until this arm the operator reached the unknown-operator throw below. if (operator === '$empty') { if (operatorValue !== true && operatorValue !== false) { - throw new FilterOperatorError( - `[ObjectUI] The '$empty' filter operator on field '${field}' takes a boolean flag ` + - `(true or false); received ${JSON.stringify(operatorValue) ?? String(operatorValue)}. ` + - `Write { ${field}: { $empty: true } } for an empty value, or ` + - `{ ${field}: { $empty: false } } for a non-empty one.`, - { operator: '$empty', field }, - ); + refuseNonBooleanFlag(field, operator, operatorValue); } conditions.push([field, operatorValue ? 'is_empty' : 'is_not_empty', true]); continue; diff --git a/ui/packages/core/src/utils/foreign-realm-object.ts b/ui/packages/core/src/utils/foreign-realm-object.ts new file mode 100644 index 00000000000..65f4bd18cda --- /dev/null +++ b/ui/packages/core/src/utils/foreign-realm-object.ts @@ -0,0 +1,44 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * Is `value` a plain object of ANOTHER realm (an iframe, a `vm` context)? + * + * Its prototype is that realm's `Object.prototype`: not this realm's + * `Object.prototype` and not `null`, a prototype whose own prototype is + * `null`, and whose `constructor` is named `Object`. All three are needed: + * + * - `Object.create(somePlainObject)` is of THIS realm and its constructor is + * `Object`, but its prototype's prototype is `Object.prototype`, not `null`; + * - `Object.create(Object.create(null))` has a prototype whose prototype is + * `null`, but that prototype has no `constructor`. + * + * Neither is a foreign plain object, and neither is filter structure here. + * + * The spec's filter walk (`isFilterNode`) and the engine's + * `isNoOperatorObject` read only this realm's `Object.prototype` or `null` as + * filter structure, so a foreign plain object is a comparand to both. ONE test + * for both faces: the filter converter refuses it as a field's whole condition, + * and `ValueDataSource` refuses it in comparand position, each naming it with + * this answer. + * + * Every read is guarded: the answer feeds a refusal sentence, and a refusal + * must never itself throw (a revoked `Proxy` throws on `getPrototypeOf`). + */ +export function isForeignRealmPlainObject(value: unknown): boolean { + if (!value || typeof value !== 'object') return false; + try { + if (Array.isArray(value)) return false; + const proto = Object.getPrototypeOf(value) as { constructor?: { name?: unknown } } | null; + if (proto === null || proto === Object.prototype) return false; + if (Object.getPrototypeOf(proto) !== null) return false; + return proto.constructor?.name === 'Object'; + } catch { + return false; + } +} diff --git a/ui/packages/plugin-dashboard/src/DatasetWidget.tsx b/ui/packages/plugin-dashboard/src/DatasetWidget.tsx index 271f5b466e6..ba79652dfff 100644 --- a/ui/packages/plugin-dashboard/src/DatasetWidget.tsx +++ b/ui/packages/plugin-dashboard/src/DatasetWidget.tsx @@ -891,8 +891,9 @@ export function DatasetWidget({ widget, dataSource, heading, onForbidden, packag const [state, setState] = useState<{ status: 'idle' | 'loading' | 'ok' | 'error'; rows: Row[]; fields?: DatasetResultField[]; object?: string; dimensionFields?: Record; drillRawRows?: Array>; drillRanges?: Array>; totals?: DatasetResultTotals[]; drillScopes?: unknown; error?: string; forbidden?: boolean; signature?: string; refreshing?: boolean }>({ status: 'idle', rows: [] }); // Drill-through (ADR-0021 D2): the clicked bucket's record-list filter + title. // A bucket on a relationship-path dimension opens the drawer on a `notice` - // while its related ids are read, and keeps one when they cannot be - // (`resolveDatasetDrillFilter`); `filter` is set once there is a list to read. + // while each hop's schema is read, and keeps one when the path cannot be + // drilled (`resolveDatasetDrillFilter`); `filter` is set once there is a list + // to read. const [drill, setDrill] = useState<{ filter?: Record; title: string; notice?: DrillDownNotice } | null>(null); // The click a pending relationship resolution answers: a later click, or the // drawer closing, makes an earlier answer stale. @@ -1331,11 +1332,13 @@ export function DatasetWidget({ widget, dataSource, heading, onForbidden, packag const drillTitle = title || String(widget?.title ?? ''); const request = ++drillRequest.current; const scopedFilter = scopeDrillFilter(runtimeFilter, scope); - // A dimension whose field is a `relationship.field` path is filtered on the - // relationship field `$in` the related ids matching the clicked value, read - // through this widget's data source first: the data API refuses the dotted - // path itself. The drawer opens at once on a notice and lists once the - // ids are in; a path it cannot resolve, or too many ids, keeps a notice. + // A dimension whose field is a `relationship.field` path drills as one + // nested-relation condition (`{ account: { owner: VALUE } }`), which the + // server matches in the database; no related id is read here. Each hop's + // schema is read through this widget's data source first, to confirm it is + // a single-valued relationship, so the drawer opens at once on a notice and + // lists once the filter is built; a path it cannot drill keeps a notice. + // `too-many` is no longer produced and stays mapped for compatibility. if (datasetDrillHasRelationshipPath(drillDims, dimensionFields)) { setDrill({ title: drillTitle, notice: 'resolving' }); resolveDatasetDrillFilter({ diff --git a/ui/packages/plugin-dashboard/src/DrillDownDrawer.tsx b/ui/packages/plugin-dashboard/src/DrillDownDrawer.tsx index 27f4b8f2edc..baa9251a489 100644 --- a/ui/packages/plugin-dashboard/src/DrillDownDrawer.tsx +++ b/ui/packages/plugin-dashboard/src/DrillDownDrawer.tsx @@ -74,8 +74,10 @@ export interface DrillDownDrawerProps { * none can be read (a dataset drill across a relationship, * `resolveDatasetDrillFilter` in `@object-ui/core`): * - * - `'resolving'` — the related ids are still being read; - * - `'too-many'` — more related records match than the drill may list; + * - `'resolving'` — the relationship path is still being checked (one + * schema read per hop; no related id is read); + * - `'too-many'` — kept for compatibility: a relationship drill no longer + * produces it, because it reads no related ids to count; * - `'unavailable'` — the relationship cannot be resolved from here; * - `'failed'` — a read on the way failed. * diff --git a/ui/packages/plugin-report/src/DatasetReportRenderer.tsx b/ui/packages/plugin-report/src/DatasetReportRenderer.tsx index 2fc0bb8888f..522371f80e0 100644 --- a/ui/packages/plugin-report/src/DatasetReportRenderer.tsx +++ b/ui/packages/plugin-report/src/DatasetReportRenderer.tsx @@ -869,14 +869,15 @@ function drillFilterOrRefusal( /** * The drill filter of a bucket whose dimensions cross a relationship - * (`relationship.field` paths in `dimensionFields`), handed to `emit` once the - * related ids are read — `resolveDatasetDrillFilter` in `@object-ui/core`. - * The data API refuses the dotted path itself, so the filter names the - * relationship field `$in` the related ids matching the clicked value. + * (`relationship.field` paths in `dimensionFields`), handed to `emit` once each + * hop's schema is read — `resolveDatasetDrillFilter` in `@object-ui/core`. + * The data API refuses the dotted path itself, so the filter is one + * nested-relation condition (`{ account: { owner: VALUE } }`), which the server + * matches in the database; no related id is read here. * * A bucket it cannot resolve (a path past ADR-0071's hop limit, an unknown - * relationship, the empty bucket, more related records than the drill may - * list) or a read that fails emits no drill and logs why: the host builds its + * relationship, the empty bucket) or a read that fails emits no drill and logs + * why (the `too-many` branch below is no longer produced): the host builds its * own fallback from an absent `objectFilter`, which would drop the scope, so * there is no drill rather than a wider one — the posture * {@link drillFilterOrRefusal} takes for a refused filter.