Files
webstudio/packages/content-engine/src/query-source.ts
T
Oleg Isonen 2ec78c183d feat: Add single-result modes to Assets queries (#6040)
## Summary

- Add `many`, `one`, `first`, and `last` result modes to Assets queries
while keeping `many` as the backward-compatible default.
- Return direct items for single-result modes, validate deterministic
ordering, and report duplicate `one` matches as a structured
`MULTIPLE_RESULTS` error.
- Update Builder controls, preview/published runtime handling, SDK
resource encoding, MCP/CLI guidance, generated contracts, and fixtures.

## Implementation TODOs

- [x] Add result-mode schemas and core execution behavior.
- [x] Select single results before content hydration and preserve
deterministic ID tie-breaking.
- [x] Add structured duplicate-match transport errors.
- [x] Update Builder controls and hide/reset pagination for
single-result modes.
- [x] Keep existing settings first, then Output and Result, without a
duplicate Return label.
- [x] Preserve legacy saved resources with an implicit `many` default.
- [x] Update preview, published runtime, SDK, protocol, MCP, and CLI
behavior.
- [x] Regenerate runtime contracts, server metadata, CLI docs, and
fixtures.
- [x] Review documentation impact and update the authoritative MCP/CLI
guidance.
- [x] Add regression coverage and verify the new tests fail without the
implementation.
- [ ] Run the agent evaluation suite (not run; requires explicit user
approval).

## Compatibility and behavior

- Existing queries without `result` continue to behave as `many` and
retain the ID-keyed collection shape.
- `one` returns an item or `null`, but fails when more than one asset
matches.
- `first` and `last` require explicit sorting; the existing asset-ID
tie-breaker makes equal sort values deterministic.
- Single-result modes ignore and do not persist pagination controls.
Materialized collection queries remain collection-only; single-result
queries execute dynamically.

## Verification

- Content engine typecheck and full test suite (291 tests).
- Query builder, query-builder React, SDK, protocol, asset uploader,
project build, Builder, and CLI targeted typechecks/tests.
- Root lint.
- MCP documentation tests, typecheck, sync check, and generated-doc
checks.
- Generated API contract checks.
- Fixture generation pipeline.
- Final focused content-engine regression run (53 tests).
- Final DRY review: affected typechecks, focused tests, lint, package
boundaries, generated checks, and fixtures.

Closes #6039
2026-08-07 19:13:19 +02:00

177 lines
4.7 KiB
TypeScript

import { type QuerySourceDefinition } from "@webstudio-is/query-builder";
import { z } from "zod";
import { contentEngineLimits } from "./limits";
import {
assetObservedFieldType,
assetQueryFieldPath,
assetQueryOperators,
assetQueryStandardFields,
assetQueryStandardFieldTypes,
assetResourceContentOptions,
assetResourceOutputSelection,
defaultAssetResourceOutputSelection,
getAssetQueryOperatorsForFieldTypes,
type AssetObservedFieldType,
type AssetQueryFilter,
type AssetQueryResultMode,
} from "./schema";
export const assetQueryResultOptions = [
{ value: "many", label: "Many" },
{ value: "one", label: "Exactly one" },
{ value: "first", label: "First" },
{ value: "last", label: "Last" },
] as const satisfies readonly {
value: AssetQueryResultMode;
label: string;
}[];
const getDefaultFilterValue = (operator: AssetQueryFilter["operator"]) =>
operator === "in"
? "[]"
: operator === "exists" || operator === "isEmpty"
? "true"
: '""';
const fieldLabels: Record<(typeof assetQueryStandardFields)[number], string> = {
id: "id",
url: "url",
width: "width",
height: "height",
name: "name",
description: "description",
path: "path",
key: "key",
folderId: "folder id",
extension: "extension",
mimeType: "mime type",
size: "size",
createdAt: "created at",
revision: "revision",
excerpt: "excerpt",
};
const operatorLabels: Record<AssetQueryFilter["operator"], string> = {
eq: "equals",
ne: "does not equal",
in: "is one of",
contains: "contains",
startsWith: "starts with",
endsWith: "ends with",
gt: "greater than",
gte: "greater than or equal",
lt: "less than",
lte: "less than or equal",
exists: "exists",
isEmpty: "is empty",
};
/** Asset-specific source contract consumed by generic query codecs. */
export const assetQuerySourceDefinition = {
fields: assetQueryStandardFields.map((field) => ({
path: [field],
label: fieldLabels[field],
types: assetQueryStandardFieldTypes[field],
})),
operators: assetQueryOperators.map((operator) => ({
value: operator,
label: operatorLabels[operator],
types: assetObservedFieldType.options.filter((type) =>
getAssetQueryOperatorsForFieldTypes([type]).includes(operator)
),
input: {
control:
operator === "exists" || operator === "isEmpty"
? ("none" as const)
: ("expression" as const),
defaultValue: getDefaultFilterValue(operator),
},
})),
source: {
fieldPathSchema: z.toJSONSchema(assetQueryFieldPath, {
target: "draft-2020-12",
io: "input",
}),
controls: [
{
type: "variant" as const,
key: "output",
label: "output",
defaultValue: defaultAssetResourceOutputSelection,
schema: z.toJSONSchema(assetResourceOutputSelection, {
target: "draft-2020-12",
io: "input",
}),
},
{
type: "variant" as const,
key: "content",
label: "content",
defaultValue: { mode: "none" },
schema: z.toJSONSchema(assetResourceContentOptions, {
target: "draft-2020-12",
io: "input",
}),
},
{
type: "select" as const,
key: "result",
label: "Result",
sectionLabel: "Result",
defaultValue: "many",
options: assetQueryResultOptions,
},
{
type: "filter" as const,
key: "where",
label: "filters",
defaultValue: { all: [] },
combinators: ["all", "any"] as const,
limits: {
conditions: contentEngineLimits.filterCount,
depth: contentEngineLimits.filterDepth,
},
defaultCondition: {
field: ["path"],
operator: "startsWith" as const,
},
},
{
type: "sort" as const,
key: "sort",
label: "sort",
defaultValue: [],
defaultItem: { field: ["name"], direction: "asc" as const },
directions: [
{ value: "asc", label: "Ascending" },
{ value: "desc", label: "Descending" },
],
max: contentEngineLimits.sortCount,
},
{
type: "expression" as const,
key: "limit",
label: "limit",
defaultValue: String(contentEngineLimits.defaultResultCount),
input: "number" as const,
min: 0,
max: contentEngineLimits.resultCount,
integer: true,
},
{
type: "expression" as const,
key: "offset",
label: "offset",
defaultValue: "0",
input: "number" as const,
min: 0,
max: contentEngineLimits.candidateDocuments,
integer: true,
},
],
},
} satisfies QuerySourceDefinition<
AssetObservedFieldType,
AssetQueryFilter["operator"]
>;