@mgamadeus/ddd-web 0.0.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/query/errors.ts","../../src/query/literals.ts","../../src/query/structure.ts","../../src/query/filters.ts","../../src/query/order-by.ts","../../src/query/select.ts","../../src/query/paging.ts","../../src/query/expand.ts","../../src/query/query-options.ts","../../src/query/keys.ts","../../src/query/values.ts","../../src/query/definition.ts"],"sourcesContent":["/** Thrown by the builders for input the backend would answer with 400 (or parse differently than intended). */\nexport class QueryOptionsError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'QueryOptionsError';\n }\n}\n","import { formatDddDateTime } from '../contract/datetime';\nimport { QueryOptionsError } from './errors';\n\n/** A scalar filter value. A `Date` is written as a DDD date-time (`Y-m-d H:i:s`, UTC). */\nexport type FilterScalar = string | number | boolean | Date | null;\n\n/** A filter value: a scalar, or a list for `in` / `ni` / `bw`. */\nexport type FilterValue = FilterScalar | readonly FilterScalar[];\n\n/**\n * Escapes text for use inside a single-quoted filter literal.\n *\n * Mirrors `FiltersOptionsParser::parseLiteral()`: inside `'…'` exactly two escapes exist, `\\'` (a quote) and `\\\\`\n * (one backslash); the literal ends at the first unescaped quote. Same rule as `FiltersOptions::toCanonicalLiteral()`.\n * (Doubling quotes, `''`, is NOT understood by the backend: it ends the literal.)\n */\nexport function escapeFilterString(value: string): string {\n return value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\");\n}\n\n/** Alias of {@link escapeFilterString}, kept for code ported from OData-style helpers. */\nexport const escapeOData = escapeFilterString;\n\n/**\n * The string form of a scalar as the backend validates it (`FiltersOptions::getFilterValueAsString()`):\n * a bool is `1` / `0`, a `Date` a UTC DDD date-time, a number its decimal form. Throws for a non-finite number or one\n * that only has an exponent form (the column-kind check accepts `-?\\d+(\\.\\d+)?` only).\n */\nexport function filterScalarToString(value: Exclude<FilterScalar, null>): string {\n if (typeof value === 'boolean') {\n return value ? '1' : '0';\n }\n if (value instanceof Date) {\n return formatDddDateTime(value);\n }\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n throw new QueryOptionsError(`Filter value ${String(value)} is not a finite number`);\n }\n const text = String(value);\n if (/e/i.test(text)) {\n throw new QueryOptionsError(`Filter value ${text} has no plain decimal form; pass it as a string`);\n }\n return text;\n }\n return value;\n}\n\n/**\n * Writes one scalar literal: `null` for null, every other scalar single-quoted and escaped.\n *\n * The backend rule is \"every scalar MUST be wrapped in single quotes\" (`FiltersOptions::getSyntaxDocumentation()`):\n * the parser only reads unsigned unquoted numbers (`-5` fails), so numbers are quoted too; the column-kind check\n * judges a quoted literal by content (`id eq '12'` is an int).\n */\nexport function formatFilterScalar(value: FilterScalar): string {\n if (value === null) {\n return 'null';\n }\n return `'${escapeFilterString(filterScalarToString(value))}'`;\n}\n\n/**\n * Writes one list item as a JSON value: a double-quoted JSON string (every scalar is written as its string form, as\n * in {@link formatFilterScalar}) or `null`. `FiltersOptionsParser::parseArrayLiteral()` keeps the escapes of a\n * double-quoted item and JSON-decodes the list, so every character — also newlines and other control characters,\n * which a single-quoted item cannot carry — arrives unchanged.\n */\nexport function formatFilterListItem(value: FilterScalar): string {\n return value === null ? 'null' : JSON.stringify(filterScalarToString(value));\n}\n\n/**\n * Writes a filter literal: a scalar via {@link formatFilterScalar}, a list as `[\"a\",\"b\"]` (bracket list of JSON\n * items, see {@link formatFilterListItem}).\n */\nexport function formatFilterLiteral(value: FilterValue): string {\n if (Array.isArray(value)) {\n return `[${(value as readonly FilterScalar[]).map(formatFilterListItem).join(',')}]`;\n }\n return formatFilterScalar(value as FilterScalar);\n}\n\nconst PROPERTY_PATH = /^[A-Za-z0-9_]+(\\.[A-Za-z0-9_]+)*$/;\n\n/**\n * Throws unless `property` is a valid filter / orderBy / select property path. Mirrors\n * `FiltersOptionsParser::parseIdentifier()`: letters, digits, `_` and `.` (dot-notation through expands).\n */\nexport function assertPropertyPath(property: string, context = 'property'): void {\n if (!PROPERTY_PATH.test(property)) {\n throw new QueryOptionsError(`Invalid ${context} '${property}': use letters, digits, '_' and '.' only`);\n }\n}\n","import type { FilterJoinOperator } from '../contract/operators';\n\n/**\n * Returns the join operators (`and` / `or`) that occur at the top level of a filter expression — outside quoted\n * literals, bracket lists and parentheses. Tokenisation mirrors `FiltersOptionsParser`: single-quoted literals with\n * `\\'` / `\\\\` escapes, double-quoted items inside lists, case-insensitive keywords that follow a term (whitespace\n * optional) and are followed by whitespace, a parenthesis or the end of input.\n */\nexport function topLevelJoinOperators(expression: string): Set<FilterJoinOperator> {\n const found = new Set<FilterJoinOperator>();\n let depth = 0;\n let quote: string | null = null;\n for (let index = 0; index < expression.length; index++) {\n const char = expression[index] as string;\n if (quote !== null) {\n if (char === '\\\\') {\n index++;\n continue;\n }\n if (char === quote) {\n quote = null;\n }\n continue;\n }\n if (char === \"'\" || char === '\"') {\n quote = char;\n continue;\n }\n if (char === '(' || char === '[') {\n depth++;\n continue;\n }\n if (char === ')' || char === ']') {\n depth = Math.max(0, depth - 1);\n continue;\n }\n if (depth > 0) {\n continue;\n }\n // The backend tries `and` / `or` right after a term, with or without whitespace: after a closing quote,\n // bracket or parenthesis, a number literal or `null` (`a eq '1'or b eq '2'` is valid). A false positive (e.g. an\n // identifier ending in a digit) only adds parentheses; a missed keyword would change the meaning.\n const previous = index === 0 ? ' ' : (expression[index - 1] as string);\n if (!/[\\s)\\]'\"0-9]/.test(previous) && !/null$/i.test(expression.slice(Math.max(0, index - 4), index))) {\n continue;\n }\n for (const keyword of ['and', 'or'] as const) {\n const candidate = expression.slice(index, index + keyword.length).toLowerCase();\n const next = expression[index + keyword.length];\n if (candidate === keyword && (next === undefined || /\\s|\\(|\\)/.test(next))) {\n found.add(keyword);\n }\n }\n }\n return found;\n}\n\n/** Wraps a clause in parentheses. */\nexport function groupFilter(clause: string): string {\n return `(${clause})`;\n}\n\n/**\n * Joins clauses with `joinOperator`, parenthesising every clause that contains a top-level join operator other than\n * `joinOperator`. Needed because `FiltersOptionsParser::parseExpression()` has NO precedence: it reads strictly\n * left to right, so `x and a or b` means `(x and a) or b`.\n */\nexport function joinFilters(joinOperator: FilterJoinOperator, clauses: readonly string[]): string | undefined {\n const nonEmpty = clauses.map(clause => clause.trim()).filter(clause => clause.length > 0);\n if (nonEmpty.length === 0) {\n return undefined;\n }\n if (nonEmpty.length === 1) {\n return nonEmpty[0];\n }\n return nonEmpty\n .map(clause => {\n const operators = topLevelJoinOperators(clause);\n const mixesOtherOperator = [...operators].some(operator => operator !== joinOperator);\n return mixesOtherOperator ? groupFilter(clause) : clause;\n })\n .join(` ${joinOperator} `);\n}\n","import { isValidDddDate } from '../contract/datetime';\nimport {\n isFilterOperator,\n isFulltextOperator,\n isListOperator,\n NULL_OPERATORS,\n type FilterOperator,\n type FulltextOperator,\n type ListOperator,\n} from '../contract/operators';\nimport { QueryOptionsError } from './errors';\nimport {\n assertPropertyPath,\n formatFilterLiteral,\n type FilterScalar,\n type FilterValue,\n} from './literals';\nimport { joinFilters } from './structure';\n\nfunction isNullLike(value: FilterValue): boolean {\n return value === null || (typeof value === 'string' && value.toLowerCase() === 'null');\n}\n\n/**\n * Throws when the value shape does not fit the operator. Mirrors `FilterOptionsConstraintValidator::validate()`:\n * null only with `eq` / `ne`; a list only with `in` / `ni` / `bw`; `in` / `ni` / `bw` need a list; `bw` exactly two\n * items; `ft` / `fb` a non-empty string. Additionally refuses an empty `in` / `ni` list (an empty SQL IN list).\n */\nexport function assertValueFitsOperator(operator: FilterOperator, value: FilterValue): void {\n if (!isFilterOperator(operator)) {\n throw new QueryOptionsError(`Unknown filter operator '${String(operator)}'`);\n }\n const isList = Array.isArray(value);\n if (!isList && isNullLike(value) && !(NULL_OPERATORS as readonly string[]).includes(operator)) {\n throw new QueryOptionsError(`A null value is only allowed with ${NULL_OPERATORS.join(', ')} (got '${operator}')`);\n }\n if (isList && !isListOperator(operator)) {\n throw new QueryOptionsError(`A list value is only allowed with in, ni, bw (got '${operator}')`);\n }\n if (!isList && isListOperator(operator)) {\n throw new QueryOptionsError(`Operator '${operator}' needs a list value`);\n }\n if (isList) {\n const items = value as readonly FilterScalar[];\n if (operator === 'bw' && items.length !== 2) {\n throw new QueryOptionsError(`Operator 'bw' needs exactly 2 values (got ${items.length})`);\n }\n if (items.length === 0) {\n throw new QueryOptionsError(`Operator '${operator}' needs at least one value`);\n }\n if (items.some(item => Array.isArray(item))) {\n throw new QueryOptionsError(`List items of '${operator}' must be scalars`);\n }\n }\n if (isFulltextOperator(operator) && (typeof value !== 'string' || value.trim() === '')) {\n throw new QueryOptionsError(`Fulltext operator '${operator}' needs a non-empty string value`);\n }\n}\n\n/**\n * Builds one comparison `<property> <operator> <literal>`, e.g. `title eq 'O\\'Brien'`, `id in [\"1\",\"2\"]`,\n * `published bw [\"2026-01-01\",\"2026-12-31\"]`. The value is written by `formatFilterLiteral()` (quoted, escaped,\n * bracket list for list operators), so callers never concatenate values themselves — the client-side counterpart of\n * `FiltersOptions::createExpression()`. Throws {@link QueryOptionsError} for an invalid property path or a value\n * shape the backend rejects.\n */\nexport function buildFieldFilter(property: string, value: FilterValue, operator: FilterOperator = 'eq'): string {\n assertPropertyPath(property, 'filter property');\n assertValueFitsOperator(operator, value);\n return `${property} ${operator} ${formatFilterLiteral(value)}`;\n}\n\n/** `<property> in|ni|bw [<values>]`; see {@link buildFieldFilter}. */\nexport function buildListFilter(property: string, operator: ListOperator, values: readonly FilterScalar[]): string {\n return buildFieldFilter(property, values, operator);\n}\n\n/** `<property> in [<values>]` — the value is one of the list. */\nexport function buildInFilter(property: string, values: readonly FilterScalar[]): string {\n return buildFieldFilter(property, values, 'in');\n}\n\n/** `<property> ni [<values>]` — the value is none of the list. */\nexport function buildNotInFilter(property: string, values: readonly FilterScalar[]): string {\n return buildFieldFilter(property, values, 'ni');\n}\n\n/** `<property> bw [<from>,<to>]` — inclusive range (SQL BETWEEN). */\nexport function buildBetweenFilter(property: string, from: FilterScalar, to: FilterScalar): string {\n return buildFieldFilter(property, [from, to], 'bw');\n}\n\n/** `<property> eq null` (IS NULL) or, with `negate`, `<property> ne null` (IS NOT NULL). */\nexport function buildNullFilter(property: string, negate = false): string {\n return buildFieldFilter(property, null, negate ? 'ne' : 'eq');\n}\n\n/**\n * `<property> eq '*<term>*'` — a LIKE \"contains\" match. `*` is the only wildcard on the backend (LIKE's own `%`, `_`\n * are literal, `FiltersOptions::getFiltersExpressionForDoctrineQueryBuilder()`); a `*` in the term cannot be matched\n * literally and acts as a wildcard too. Returns `undefined` for a blank term.\n */\nexport function buildContainsFilter(property: string, term: string, negate = false): string | undefined {\n const trimmed = term.trim();\n if (!trimmed) {\n return undefined;\n }\n return buildFieldFilter(property, `*${trimmed}*`, negate ? 'ne' : 'eq');\n}\n\n/** Appends `*` to each word for boolean-mode fulltext prefix matching: `dune mess` → `dune* mess*`. */\nexport function toBooleanPrefix(value: string): string {\n return value\n .split(/\\s+/)\n .filter(Boolean)\n .map(word => (word.endsWith('*') ? word : `${word}*`))\n .join(' ');\n}\n\n/** Options of {@link buildFulltextFilter}. */\nexport interface FulltextFilterOptions {\n /** `ft` natural language mode (default) or `fb` boolean mode. */\n mode?: FulltextOperator;\n /** In boolean mode, append `*` to every word (prefix match). Default `true` for `fb`. */\n prefix?: boolean;\n}\n\n/**\n * `<property> ft|fb '<term>'` — fulltext search (MATCH AGAINST). Requires a FULLTEXT index on the backend\n * (`FiltersDefinition::$supportsFulltext`). Returns `undefined` for a blank term.\n */\nexport function buildFulltextFilter(\n property: string,\n term: string,\n options: FulltextFilterOptions = {},\n): string | undefined {\n const mode = options.mode ?? 'ft';\n const trimmed = term.trim();\n if (!trimmed) {\n return undefined;\n }\n const usePrefix = options.prefix ?? mode === 'fb';\n return buildFieldFilter(property, mode === 'fb' && usePrefix ? toBooleanPrefix(trimmed) : trimmed, mode);\n}\n\n/** Options of {@link buildIntEqFilter}. */\nexport interface IntEqFilterOptions {\n /** A literal prefix to strip before the check, e.g. `#` in `#12`. */\n stripLeadingChar?: string;\n}\n\n/**\n * `<property> eq '<n>'` for a search term over an int column. Returns `undefined` unless the (optionally prefix-\n * stripped) term is purely numeric: the backend answers 400 for a non-numeric value on an int column\n * (`FiltersOptions::isFilterValueValidForColumnKind()`), so the clause is omitted instead.\n */\nexport function buildIntEqFilter(\n rawValue: string,\n property: string,\n options: IntEqFilterOptions = {},\n): string | undefined {\n const prefix = options.stripLeadingChar;\n const term = prefix && rawValue.startsWith(prefix) ? rawValue.slice(prefix.length) : rawValue;\n if (!/^\\d+$/.test(term)) {\n return undefined;\n }\n return buildFieldFilter(property, term, 'eq');\n}\n\n/**\n * `<property> bw [\"<day> 00:00:00\",\"<day> 23:59:59\"]` — a full UTC calendar day on a date-time column. Returns\n * `undefined` unless `rawValue` is a real `YYYY-MM-DD` date: a partial date (`2026-10`) or one the calendar lacks\n * (`2026-13-45`, `2026-02-30`) would answer 400 (`FiltersOptions::isFilterDateTimeLiteral()`).\n */\nexport function buildFullDayFilter(rawValue: string, property: string): string | undefined {\n const day = rawValue.trim();\n if (!isValidDddDate(day)) {\n return undefined;\n }\n return buildBetweenFilter(property, `${day} 00:00:00`, `${day} 23:59:59`);\n}\n\n/**\n * AND-joins filter clauses, skipping empty ones; `undefined` when none remain. A clause that contains a top-level\n * `or` is parenthesised first: the backend parser has no precedence (`FiltersOptionsParser::parseExpression()` reads\n * left to right), so `x and a or b` would mean `(x and a) or b`.\n */\nexport function combineFilters(...parts: ReadonlyArray<string | null | undefined | false>): string | undefined {\n return joinFilters('and', parts.filter((part): part is string => typeof part === 'string'));\n}\n\n/**\n * OR-joins filter clauses, skipping empty ones; `undefined` when none remain. A clause with a top-level `and` is\n * parenthesised (no precedence on the backend). The result is not wrapped; {@link combineFilters} groups it when it\n * is AND-joined with other clauses.\n */\nexport function anyOfFilters(...parts: ReadonlyArray<string | null | undefined | false>): string | undefined {\n return joinFilters('or', parts.filter((part): part is string => typeof part === 'string'));\n}\n","import type { OrderDirection } from '../contract/query-options';\nimport { QueryOptionsError } from './errors';\nimport { assertPropertyPath } from './literals';\n\n/** One sort item: `'title'`, `'title desc'` or `{ property: 'title', direction: 'desc' }`. */\nexport type OrderByItem = string | { property: string; direction?: OrderDirection };\n\n/** Sort input: one item or a list (applied in order). */\nexport type OrderByInput = OrderByItem | readonly OrderByItem[];\n\n/** A parsed sort item. */\nexport interface OrderByEntry {\n property: string;\n direction?: OrderDirection;\n}\n\n/** Normalises one sort item; throws for an invalid property or direction. */\nexport function toOrderByEntry(item: OrderByItem): OrderByEntry {\n if (typeof item !== 'string') {\n assertPropertyPath(item.property, 'orderBy property');\n if (item.direction !== undefined && item.direction !== 'asc' && item.direction !== 'desc') {\n throw new QueryOptionsError(`Invalid orderBy direction '${String(item.direction)}'`);\n }\n return item.direction ? { property: item.property, direction: item.direction } : { property: item.property };\n }\n const parts = item.trim().split(/\\s+/);\n if (parts.length > 2 || !parts[0]) {\n throw new QueryOptionsError(`Invalid orderBy item '${item}'`);\n }\n const property = parts[0];\n assertPropertyPath(property, 'orderBy property');\n if (parts[1] === undefined) {\n return { property };\n }\n const direction = parts[1].toLowerCase();\n if (direction !== 'asc' && direction !== 'desc') {\n throw new QueryOptionsError(`Invalid orderBy direction '${parts[1]}'`);\n }\n return { property, direction };\n}\n\n/** Normalises sort input to a list of entries. */\nexport function toOrderByEntries(input: OrderByInput | null | undefined): OrderByEntry[] {\n if (input === null || input === undefined) {\n return [];\n }\n const items: readonly OrderByItem[] = Array.isArray(input) ? input : [input as OrderByItem];\n return items.map(toOrderByEntry);\n}\n\n/**\n * Builds the `orderBy` value, e.g. `title asc,id desc`; `undefined` for no items. Mirrors\n * `OrderByOptions::fromString()`: items split on `,`, property and direction split on ONE space, direction `asc` /\n * `desc` (case-insensitive, default asc). Dot-notation (`author.name`) and the fulltext `<property>Score` suffix are\n * plain property paths here.\n */\nexport function buildOrderBy(input: OrderByInput | null | undefined): string | undefined {\n const entries = toOrderByEntries(input);\n if (entries.length === 0) {\n return undefined;\n }\n return entries.map(entry => (entry.direction ? `${entry.property} ${entry.direction}` : entry.property)).join(',');\n}\n","import { assertPropertyPath } from './literals';\n\n/** Select input: a list of property paths or one comma-separated string. */\nexport type SelectInput = string | readonly string[];\n\n/**\n * Builds the `select` value, e.g. `id,title,author.name`; `undefined` for no fields. Mirrors\n * `SelectOptions::fromString()`: properties unquoted, separated by `,`, dot-notation allowed; duplicates are dropped.\n */\nexport function buildSelect(input: SelectInput | null | undefined): string | undefined {\n if (input === null || input === undefined) {\n return undefined;\n }\n const fields = (typeof input === 'string' ? input.split(',') : [...input])\n .map(field => field.trim())\n .filter(field => field.length > 0);\n if (fields.length === 0) {\n return undefined;\n }\n for (const field of fields) {\n assertPropertyPath(field, 'select property');\n }\n return [...new Set(fields)].join(',');\n}\n","import { QueryOptionsError } from './errors';\n\n/** What to do with a `top` above `maxTop`: `throw` (default) or `clamp` to `maxTop`. */\nexport type TopOverflow = 'throw' | 'clamp';\n\n/** Options of {@link normalizeTop}. */\nexport interface TopOptions {\n /** Upper bound (`#[QueryOptions(maxTop: …)]`, `x-ddd-query.maxTop`); null/undefined = none. */\n maxTop?: number | null;\n overflow?: TopOverflow;\n}\n\nfunction assertInteger(name: string, value: number): void {\n if (!Number.isInteger(value)) {\n throw new QueryOptionsError(`${name} must be an integer (got ${String(value)})`);\n }\n}\n\n/**\n * Validates `top`. Mirrors `AppliedQueryOptions::setTop()`: above `maxTop` the backend answers 400, so this throws\n * (or clamps with `overflow: 'clamp'`); below 1 the backend raises to 1, so this throws for a non-positive value\n * instead of silently changing it. `undefined` stays `undefined` (backend default 50).\n */\nexport function normalizeTop(top: number | null | undefined, options: TopOptions = {}): number | undefined {\n if (top === null || top === undefined) {\n return undefined;\n }\n assertInteger('top', top);\n if (top < 1) {\n throw new QueryOptionsError(`top must be at least 1 (got ${top})`);\n }\n const maxTop = options.maxTop;\n if (maxTop !== null && maxTop !== undefined && top > maxTop) {\n if (options.overflow === 'clamp') {\n return maxTop;\n }\n throw new QueryOptionsError(`top may be at most ${maxTop} here (got ${top})`);\n }\n return top;\n}\n\n/**\n * Validates `skip`: a non-negative integer (`AppliedQueryOptions::setSkip()` clamps below 0). `undefined` and `0` stay\n * as given.\n */\nexport function normalizeSkip(skip: number | null | undefined): number | undefined {\n if (skip === null || skip === undefined) {\n return undefined;\n }\n assertInteger('skip', skip);\n if (skip < 0) {\n throw new QueryOptionsError(`skip must not be negative (got ${skip})`);\n }\n return skip;\n}\n\n/** `skip` for a zero-based page index and page size: `pageIndex * pageSize`. */\nexport function pageToSkip(pageIndex: number, pageSize: number): number {\n assertInteger('pageIndex', pageIndex);\n assertInteger('pageSize', pageSize);\n return Math.max(0, pageIndex) * Math.max(1, pageSize);\n}\n","import { QueryOptionsError } from './errors';\nimport { combineFilters } from './filters';\nimport { buildOrderBy, type OrderByInput } from './order-by';\nimport { normalizeSkip, normalizeTop } from './paging';\nimport { buildSelect, type SelectInput } from './select';\n\n/** Clauses of one expand, written as `property(filters=…;orderBy=…;select=…;top=…;skip=…;expand=…)`. */\nexport interface ExpandClauses {\n /** Filter(s) on the expanded collection; a list is AND-combined. Cuts the expanded collection, not the roots. */\n filters?: string | ReadonlyArray<string | null | undefined | false>;\n orderBy?: OrderByInput;\n select?: SelectInput;\n top?: number;\n skip?: number;\n /** Nested expands. */\n expand?: ExpandInput;\n}\n\n/**\n * One expand item: a property name, a dotted path (`author.books` = `author(expand=books)`), or an object with\n * `property` and clauses.\n */\nexport type ExpandItem = string | ({ property: string } & ExpandClauses);\n\n/** A map form: `{ author: true, reviews: { top: 5 } }`. */\nexport type ExpandMap = { readonly [property: string]: true | ExpandClauses };\n\n/** Expand input: one item, a list of items, or a map. */\nexport type ExpandInput = ExpandItem | readonly ExpandItem[] | ExpandMap;\n\ninterface ExpandNode {\n filters: string[];\n orderBy?: OrderByInput;\n select?: SelectInput;\n top?: number;\n skip?: number;\n children: Map<string, ExpandNode>;\n}\n\nconst EXPAND_PROPERTY = /^\\w+$/;\n\nfunction newNode(): ExpandNode {\n return { filters: [], children: new Map() };\n}\n\nfunction isItemObject(value: unknown): value is { property: string } & ExpandClauses {\n return typeof value === 'object' && value !== null && typeof (value as { property?: unknown }).property === 'string';\n}\n\nfunction childNode(parent: Map<string, ExpandNode>, property: string): ExpandNode {\n if (!EXPAND_PROPERTY.test(property)) {\n throw new QueryOptionsError(`Invalid expand property '${property}': use letters, digits and '_' only`);\n }\n let node = parent.get(property);\n if (!node) {\n node = newNode();\n parent.set(property, node);\n }\n return node;\n}\n\n/** Resolves a (possibly dotted) path to its deepest node, creating intermediate nodes. */\nfunction nodeForPath(root: Map<string, ExpandNode>, path: string): ExpandNode {\n const segments = path.trim().split('.');\n let level = root;\n let node: ExpandNode | undefined;\n for (const segment of segments) {\n node = childNode(level, segment);\n level = node.children;\n }\n return node as ExpandNode;\n}\n\nfunction applyClauses(node: ExpandNode, clauses: ExpandClauses): void {\n if (clauses.filters !== undefined) {\n const list = typeof clauses.filters === 'string' ? [clauses.filters] : clauses.filters;\n for (const filter of list) {\n if (typeof filter === 'string' && filter.trim()) {\n node.filters.push(filter);\n }\n }\n }\n if (clauses.orderBy !== undefined) node.orderBy = clauses.orderBy;\n if (clauses.select !== undefined) node.select = clauses.select;\n if (clauses.top !== undefined) node.top = clauses.top;\n if (clauses.skip !== undefined) node.skip = clauses.skip;\n if (clauses.expand !== undefined) addInput(node.children, clauses.expand);\n}\n\nfunction addInput(level: Map<string, ExpandNode>, input: ExpandInput): void {\n if (typeof input === 'string') {\n for (const part of input.split(',')) {\n if (part.trim()) {\n nodeForPath(level, part);\n }\n }\n return;\n }\n if (Array.isArray(input)) {\n for (const item of input as readonly ExpandItem[]) {\n addInput(level, item);\n }\n return;\n }\n if (isItemObject(input)) {\n applyClauses(nodeForPath(level, input.property), input);\n return;\n }\n for (const [path, clauses] of Object.entries(input as ExpandMap)) {\n const node = nodeForPath(level, path);\n if (clauses !== true) {\n applyClauses(node, clauses);\n }\n }\n}\n\n/**\n * Throws for a clause value the backend's expand regexes cannot carry: `ExpandOption::parseExpandParameters()` cuts\n * every clause at the first `;` (quotes are not honoured), finds `expand=` anywhere in the clause text, and\n * `ExpandOptions::fromString()` needs balanced parentheses (also inside quoted literals).\n */\nfunction assertClauseValue(name: string, value: string): void {\n if (value.includes(';')) {\n throw new QueryOptionsError(`Expand ${name} must not contain ';' (got \"${value}\")`);\n }\n if (/expand\\s*=/i.test(value)) {\n throw new QueryOptionsError(`Expand ${name} must not contain 'expand=' (got \"${value}\")`);\n }\n let depth = 0;\n for (const char of value) {\n if (char === '(') depth++;\n if (char === ')') depth--;\n if (depth < 0) break;\n }\n if (depth !== 0) {\n throw new QueryOptionsError(`Expand ${name} must have balanced parentheses (got \"${value}\")`);\n }\n}\n\nfunction serializeLevel(level: Map<string, ExpandNode>): string {\n return [...level.entries()].map(([property, node]) => serializeNode(property, node)).join(',');\n}\n\nfunction serializeNode(property: string, node: ExpandNode): string {\n const clauses: string[] = [];\n const filters = combineFilters(...node.filters);\n if (filters) {\n assertClauseValue('filters', filters);\n clauses.push(`filters=${filters}`);\n }\n const orderBy = buildOrderBy(node.orderBy);\n if (orderBy) clauses.push(`orderBy=${orderBy}`);\n const select = buildSelect(node.select);\n if (select) clauses.push(`select=${select}`);\n const top = normalizeTop(node.top);\n if (top !== undefined) clauses.push(`top=${top}`);\n const skip = normalizeSkip(node.skip);\n if (skip !== undefined) clauses.push(`skip=${skip}`);\n if (node.children.size > 0) clauses.push(`expand=${serializeLevel(node.children)}`);\n return clauses.length > 0 ? `${property}(${clauses.join(';')})` : property;\n}\n\n/**\n * Builds the `expand` value, e.g. `author(select=id,name),reviews(filters=rating ge '4';orderBy=created desc;top=5)`;\n * `undefined` for no items. Grammar of `ExpandOptions::fromString()` / `ExpandOption::parseExpandParameters()`:\n * comma-separated property names (`\\w+`), each with optional `;`-separated clauses in parentheses — `filters`,\n * `orderBy`, `select`, `top`, `skip` and a recursive `expand`. Dotted paths (`author.books`) become nested expands;\n * repeated properties are merged (filters AND-combined, later clause values win).\n */\nexport function buildExpand(input: ExpandInput | null | undefined): string | undefined {\n if (input === null || input === undefined) {\n return undefined;\n }\n const root = new Map<string, ExpandNode>();\n addInput(root, input);\n return root.size > 0 ? serializeLevel(root) : undefined;\n}\n\n/** A normalised expand: one property with its merged clauses and nested expands. */\nexport interface ExpandTreeNode {\n property: string;\n filters?: string;\n orderBy?: OrderByInput;\n select?: SelectInput;\n top?: number;\n skip?: number;\n children: ExpandTreeNode[];\n}\n\nfunction toTreeNodes(level: Map<string, ExpandNode>): ExpandTreeNode[] {\n return [...level.entries()].map(([property, node]) => {\n const treeNode: ExpandTreeNode = { property, children: toTreeNodes(node.children) };\n const filters = combineFilters(...node.filters);\n if (filters) treeNode.filters = filters;\n if (node.orderBy !== undefined) treeNode.orderBy = node.orderBy;\n if (node.select !== undefined) treeNode.select = node.select;\n if (node.top !== undefined) treeNode.top = node.top;\n if (node.skip !== undefined) treeNode.skip = node.skip;\n return treeNode;\n });\n}\n\n/** Normalises expand input into a tree (dotted paths nested, repeated properties merged). */\nexport function toExpandTree(input: ExpandInput | null | undefined): ExpandTreeNode[] {\n if (input === null || input === undefined) {\n return [];\n }\n const root = new Map<string, ExpandNode>();\n addInput(root, input);\n return toTreeNodes(root);\n}\n\n/** Top-level property names of an expand input (e.g. to check a filter's `requiresExpand`). */\nexport function expandedProperties(input: ExpandInput | null | undefined): string[] {\n return toExpandTree(input).map(node => node.property);\n}\n","import type { QueryOptionsParams } from '../contract/query-options';\nimport { buildExpand, type ExpandInput } from './expand';\nimport { combineFilters } from './filters';\nimport { buildOrderBy, type OrderByInput } from './order-by';\nimport { normalizeSkip, normalizeTop, type TopOverflow } from './paging';\nimport { buildSelect, type SelectInput } from './select';\n\n/** Input of {@link buildQueryOptions}. */\nexport interface QueryOptionsInput {\n /** One filter expression or a list of clauses (AND-combined, `or` clauses parenthesised). */\n filters?: string | ReadonlyArray<string | null | undefined | false> | null;\n orderBy?: OrderByInput | null;\n expand?: ExpandInput | null;\n select?: SelectInput | null;\n top?: number | null;\n skip?: number | null;\n}\n\n/** Options of {@link buildQueryOptions}. */\nexport interface BuildQueryOptionsOptions {\n /** Upper bound for `top` (`x-ddd-query.maxTop`). */\n maxTop?: number | null;\n /** Above `maxTop`: `throw` (default, the backend would answer 400) or `clamp`. */\n topOverflow?: TopOverflow;\n}\n\n/**\n * Builds the QueryOptions request parameters with the wire names the backend reads (`filters`, `orderBy`,\n * `expand`, `select`, `top`, `skip` — no `$` prefix, `DtoQueryOptionsTrait`). Empty parts are left out, so the result\n * can be spread into a query-argument object directly.\n */\nexport function buildQueryOptions(\n input: QueryOptionsInput,\n options: BuildQueryOptionsOptions = {},\n): QueryOptionsParams {\n const params: QueryOptionsParams = {};\n const filterList = typeof input.filters === 'string' ? [input.filters] : (input.filters ?? []);\n const filters = combineFilters(...filterList);\n if (filters) params.filters = filters;\n const orderBy = buildOrderBy(input.orderBy);\n if (orderBy) params.orderBy = orderBy;\n const expand = buildExpand(input.expand);\n if (expand) params.expand = expand;\n const select = buildSelect(input.select);\n if (select) params.select = select;\n const top = normalizeTop(input.top, { maxTop: options.maxTop, overflow: options.topOverflow });\n if (top !== undefined) params.top = top;\n const skip = normalizeSkip(input.skip);\n if (skip !== undefined) params.skip = skip;\n return params;\n}\n","/** Removes leading whitespace from a search input (trailing whitespace is kept while the user is typing). */\nexport function sanitizeSearchInput(value: string): string {\n return value.replace(/^\\s+/, '');\n}\n\n/** Sanitises every per-column search value and drops the empty ones. */\nexport function sanitizeColumnSearches(columnSearches: Record<string, string>): Record<string, string> {\n return Object.fromEntries(\n Object.entries(columnSearches)\n .map(([key, value]) => [key, sanitizeSearchInput(value)] as const)\n .filter(([, value]) => value.length > 0),\n );\n}\n\n/** JSON form of a key value; values JSON cannot represent (BigInt, cycles) fall back to their string form. */\nfunction keyValue(value: unknown): unknown {\n if (value === undefined) {\n return null;\n }\n try {\n JSON.stringify(value);\n return value;\n } catch {\n return String(value);\n }\n}\n\nconst byKey = ([a]: [string, unknown], [b]: [string, unknown]): number => (a < b ? -1 : a > b ? 1 : 0);\n\n/**\n * Builds a stable key from static query arguments, e.g. to reset paging when they change: the arguments sorted by\n * name, serialised as a JSON list of `[name, value]` pairs (collision-free: `{ a: '1&b=2' }` and `{ a: '1', b: '2' }`\n * differ). `undefined` counts as `null`. Empty for no arguments.\n */\nexport function buildStaticArgsKey(staticArgs: Record<string, unknown> | null | undefined): string {\n if (!staticArgs) {\n return '';\n }\n const entries = Object.entries(staticArgs).sort(byKey);\n return entries.length === 0 ? '' : JSON.stringify(entries.map(([key, value]) => [key, keyValue(value)]));\n}\n\n/** Builds a stable key from per-column search state (non-empty values, sorted by column key, JSON pairs). */\nexport function buildColumnSearchesKey(searches: Record<string, string>): string {\n const entries = Object.entries(searches)\n .filter(([, value]) => value.length > 0)\n .sort(byKey);\n return entries.length === 0 ? '' : JSON.stringify(entries);\n}\n","import type { DddColumnKind } from '../contract/extensions';\n\n/** Days in a month of a year (proleptic Gregorian). */\nfunction daysInMonth(year: number, month: number): number {\n return new Date(Date.UTC(year, month, 0)).getUTCDate();\n}\n\nconst FILTER_DATE_TIME =\n /^(\\d{4})-(\\d{1,2})-(\\d{1,2})(?:(?: (\\d{1,2}):(\\d{2})(?::(\\d{2})(Z|[+-]\\d{2}:?\\d{2})?)?)|(?:T(\\d{1,2}):(\\d{2}):(\\d{2})(Z|[+-]\\d{2}:?\\d{2})?))?$/;\n\n/**\n * Whether a string is a date-time filter literal the backend accepts. Mirrors `FiltersOptions::isFilterDateTimeLiteral()`\n * over `DateTime::MODEL_INPUT_FORMATS` plus `Y-m-d`: `Y-m-d H:i:sP`, `Y-m-d\\TH:i:sP`, `Y-m-d H:i:s`, `Y-m-d H:i`,\n * `Y-m-d\\TH:i:s`, `Y-m-d` (offset or `Z`); a date the calendar lacks (`2026-13-45`) fails.\n */\nexport function isFilterDateTimeLiteral(value: string): boolean {\n const match = FILTER_DATE_TIME.exec(value);\n if (!match) {\n return false;\n }\n const year = Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n if (month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month)) {\n return false;\n }\n const hours = match[4] ?? match[8];\n const minutes = match[5] ?? match[9];\n const seconds = match[6] ?? match[10];\n if (hours !== undefined && Number(hours) > 23) return false;\n if (minutes !== undefined && Number(minutes) > 59) return false;\n if (seconds !== undefined && Number(seconds) > 59) return false;\n return true;\n}\n\n/**\n * Whether one value (its string form) fits a scalar column kind. Mirrors\n * `FiltersOptions::isFilterValueValidForColumnKind()`: int / float `-?\\d+(\\.\\d+)?` (a decimal is accepted on an int\n * column), bool `1|0|true|false` (case-insensitive), datetime {@link isFilterDateTimeLiteral}; every other kind and\n * null pass.\n */\nexport function isFilterValueValidForColumnKind(value: string | null, columnKind: DddColumnKind): boolean {\n if (value === null) {\n return true;\n }\n switch (columnKind) {\n case 'int':\n case 'float':\n return /^-?\\d+(\\.\\d+)?$/.test(value);\n case 'bool':\n return /^(1|0|true|false)$/i.test(value);\n case 'datetime':\n return isFilterDateTimeLiteral(value);\n default:\n return true;\n }\n}\n","import { formatDddDate } from '../contract/datetime';\nimport type { DddExpandDefinition, DddFilterDefinition, DddQueryDefinition } from '../contract/extensions';\nimport { isFulltextOperator, NULL_OPERATORS, type FilterOperator } from '../contract/operators';\nimport type { QueryOptionsParams } from '../contract/query-options';\nimport { QueryOptionsError } from './errors';\nimport { toExpandTree, type ExpandInput, type ExpandTreeNode } from './expand';\nimport { assertValueFitsOperator, buildFieldFilter } from './filters';\nimport { filterScalarToString, type FilterScalar, type FilterValue } from './literals';\nimport { toOrderByEntries, type OrderByInput } from './order-by';\nimport { buildQueryOptions, type QueryOptionsInput } from './query-options';\nimport type { TopOverflow } from './paging';\nimport { isFilterValueValidForColumnKind } from './values';\n\n/** Machine-readable reason of a {@link QueryIssue}. */\nexport type QueryIssueCode =\n | 'unknown-property'\n | 'operator-not-allowed'\n | 'fulltext-not-supported'\n | 'invalid-value-shape'\n | 'column-kind'\n | 'value-rule'\n | 'option-not-allowed'\n | 'expand-required'\n | 'unknown-expand'\n | 'computed-expand-clauses'\n | 'unknown-order-by'\n | 'select-not-supported'\n | 'unknown-select'\n | 'top-exceeds-max';\n\n/** One problem found by the definition-driven validators; the backend would answer 400 for it. */\nexport interface QueryIssue {\n code: QueryIssueCode;\n message: string;\n}\n\n/** One filter condition before it is written as a string. */\nexport interface FilterCondition {\n property: string;\n operator: FilterOperator;\n value: FilterValue;\n}\n\n/** Context of a filter validation: the expands that will be sent with the filter. */\nexport interface FilterValidationContext {\n expand?: ExpandInput | null;\n}\n\n/** Thrown by the `buildDefined*` helpers; carries every issue found. */\nexport class QueryValidationError extends QueryOptionsError {\n readonly issues: QueryIssue[];\n\n constructor(issues: QueryIssue[]) {\n super(issues.map(issue => issue.message).join(' '));\n this.name = 'QueryValidationError';\n this.issues = issues;\n }\n}\n\n/** A resolved filter definition plus the expand chain it was reached through (`author.name` → `['author']`). */\nexport interface ResolvedFilterDefinition {\n definition: DddFilterDefinition;\n expandPath: string[];\n}\n\n/**\n * Finds the definition of a filter property. Mirrors `FiltersOptions::validateAgainstDefinitions()`: an exact name\n * match first; otherwise a dotted property (`author.name`) resolves through the expand definition of its first\n * segment and that expand's own filters, recursively.\n */\nexport function resolveFilterDefinition(\n query: Pick<DddQueryDefinition, 'filters' | 'expand'>,\n property: string,\n): ResolvedFilterDefinition | undefined {\n const direct = query.filters?.find(filter => filter.name === property);\n if (direct) {\n return { definition: direct, expandPath: [] };\n }\n const dot = property.indexOf('.');\n if (dot < 0) {\n return undefined;\n }\n const first = property.slice(0, dot);\n const expandDefinition = query.expand?.find(expand => expand.name === first);\n if (!expandDefinition) {\n return undefined;\n }\n const nested = resolveFilterDefinition(expandDefinition, property.slice(dot + 1));\n return nested ? { definition: nested.definition, expandPath: [first, ...nested.expandPath] } : undefined;\n}\n\n/** Shorthand of {@link resolveFilterDefinition} returning only the definition. */\nexport function findFilterDefinition(\n query: Pick<DddQueryDefinition, 'filters' | 'expand'>,\n property: string,\n): DddFilterDefinition | undefined {\n return resolveFilterDefinition(query, property)?.definition;\n}\n\nfunction scalarString(value: FilterScalar): string | null {\n return value === null ? null : filterScalarToString(value);\n}\n\nfunction isNullComparison(operator: FilterOperator, value: FilterValue): boolean {\n return (\n (NULL_OPERATORS as readonly string[]).includes(operator) &&\n (value === null || (typeof value === 'string' && value.toUpperCase() === 'NULL'))\n );\n}\n\n/**\n * Column-kind rules of `FiltersOptions::validateValueAgainstColumnKind()`: skipped without a kind, for fulltext\n * operators and for null comparisons; a JSON column takes no comparison; a plain Translatable only `eq` / `ne` with a\n * `*` wildcard; a wildcard value on another kind is not type-checked; every other value must fit the kind.\n */\nfunction columnKindIssues(definition: DddFilterDefinition, condition: FilterCondition): QueryIssue[] {\n const { property, operator, value } = condition;\n let kind = definition.columnKind ?? null;\n if (kind === null || isFulltextOperator(operator) || isNullComparison(operator, value)) {\n return [];\n }\n const usesWildcard = typeof value === 'string' && value.includes('*');\n if (kind === 'json') {\n return [{ code: 'column-kind', message: `'${property}' is a JSON column: no comparison matches it.` }];\n }\n if (kind === 'translatable') {\n if (usesWildcard && (operator === 'eq' || operator === 'ne')) {\n return [];\n }\n return [\n {\n code: 'column-kind',\n message: `'${property}' holds the translations of all languages: use eq / ne with a '*' wildcard.`,\n },\n ];\n }\n if (usesWildcard) {\n return [];\n }\n if (kind === 'translatable-searchable') {\n kind = 'string';\n }\n const elements: readonly FilterScalar[] = Array.isArray(value) ? value : [value as FilterScalar];\n for (const element of elements) {\n if (!isFilterValueValidForColumnKind(scalarString(element), kind)) {\n return [\n {\n code: 'column-kind',\n message: `Filter value '${String(scalarString(element))}' for '${property}' is not a valid ${kind}.`,\n },\n ];\n }\n }\n return [];\n}\n\nfunction valueRuleIssues(definition: DddFilterDefinition, condition: FilterCondition): QueryIssue[] {\n const rule = definition.valueRules?.[condition.operator];\n if (!rule || isNullComparison(condition.operator, condition.value)) {\n return [];\n }\n if (rule === 'wildcard-required' && !(typeof condition.value === 'string' && condition.value.includes('*'))) {\n return [\n { code: 'value-rule', message: `'${condition.property} ${condition.operator}' needs a value with a '*' wildcard.` },\n ];\n }\n if (rule === 'null-only') {\n return [{ code: 'value-rule', message: `'${condition.property} ${condition.operator}' only compares with null.` }];\n }\n return [];\n}\n\n/** `FiltersOptions::validateAgainstDefinitions()`: with `options`, every value (each list item) must be one of them. */\nfunction optionIssues(definition: DddFilterDefinition, condition: FilterCondition): QueryIssue[] {\n const options = definition.options;\n if (!options || options.length === 0) {\n return [];\n }\n const allowed = new Set(options.map(String));\n const elements: readonly FilterScalar[] = Array.isArray(condition.value)\n ? condition.value\n : [condition.value as FilterScalar];\n const rejected = elements.filter(element => {\n const text = scalarString(element);\n return text === null || !allowed.has(text);\n });\n if (rejected.length === 0) {\n return [];\n }\n return [\n {\n code: 'option-not-allowed',\n message: `Value(s) [${rejected.map(element => String(scalarString(element))).join(', ')}] for '${condition.property}' are not allowed. Allowed values are: [${options.join(', ')}].`,\n },\n ];\n}\n\n/**\n * Validates a filter condition against an `x-ddd-query` definition and returns every issue (empty = the backend\n * accepts it). Rules mirrored: unknown property (`validateAgainstDefinitions`), declared operators, fulltext only\n * with `supportsFulltext` (strict fulltext default), the value shape (`FilterOptionsConstraintValidator`), column\n * kinds (`validateValueAgainstColumnKind`), contract `valueRules`, `options`, and required expands.\n */\nexport function validateFilter(\n query: Pick<DddQueryDefinition, 'filters' | 'expand'>,\n condition: FilterCondition,\n context: FilterValidationContext = {},\n): QueryIssue[] {\n const resolved = resolveFilterDefinition(query, condition.property);\n if (!resolved) {\n const allowed = (query.filters ?? []).map(filter => filter.name).join(', ');\n return [\n {\n code: 'unknown-property',\n message: `Property name used to filter '${condition.property}' is not allowed. Allowed property names are: [${allowed}].`,\n },\n ];\n }\n const { definition, expandPath } = resolved;\n const issues: QueryIssue[] = [];\n if (definition.operators && !definition.operators.includes(condition.operator)) {\n issues.push({\n code: 'operator-not-allowed',\n message: `Operator '${condition.operator}' is not available for '${condition.property}' (allowed: ${definition.operators.join(', ')}).`,\n });\n }\n if (isFulltextOperator(condition.operator) && definition.supportsFulltext !== true) {\n issues.push({\n code: 'fulltext-not-supported',\n message: `The fulltext operator '${condition.operator}' is not available for '${condition.property}': no FULLTEXT index.`,\n });\n }\n try {\n assertValueFitsOperator(condition.operator, condition.value);\n } catch (error) {\n issues.push({ code: 'invalid-value-shape', message: (error as Error).message });\n return issues;\n }\n issues.push(...columnKindIssues(definition, condition));\n issues.push(...valueRuleIssues(definition, condition));\n issues.push(...optionIssues(definition, condition));\n\n const tree = toExpandTree(context.expand);\n let level: ExpandTreeNode[] = tree;\n for (const segment of expandPath) {\n const node = level.find(candidate => candidate.property === segment);\n if (!node) {\n issues.push({\n code: 'expand-required',\n message: `Filter '${condition.property}' needs the expand '${expandPath.join('.')}'.`,\n });\n break;\n }\n level = node.children;\n }\n if (definition.requiresExpand && !level.some(node => node.property === definition.requiresExpand)) {\n issues.push({\n code: 'expand-required',\n message: `Filter '${condition.property}' needs the expand '${definition.requiresExpand}'.`,\n });\n }\n return issues;\n}\n\n/**\n * Validates and builds a filter clause from a definition; throws {@link QueryValidationError} with every issue. A\n * `Date` value on a `DAY` filter is written as `Y-m-d`; on other filters as a UTC DDD date-time.\n */\nexport function buildDefinedFilter(\n query: Pick<DddQueryDefinition, 'filters' | 'expand'>,\n property: string,\n operator: FilterOperator,\n value: FilterValue,\n context: FilterValidationContext = {},\n): string {\n const definition = findFilterDefinition(query, property);\n const toDay = (scalar: FilterScalar): FilterScalar => (scalar instanceof Date ? formatDddDate(scalar) : scalar);\n const typedValue: FilterValue =\n definition?.temporalKind === 'DAY'\n ? Array.isArray(value)\n ? (value as readonly FilterScalar[]).map(toDay)\n : toDay(value as FilterScalar)\n : value;\n const issues = validateFilter(query, { property, operator, value: typedValue }, context);\n if (issues.length > 0) {\n throw new QueryValidationError(issues);\n }\n return buildFieldFilter(property, typedValue, operator);\n}\n\nfunction orderByAllowed(\n definition: Pick<DddQueryDefinition, 'filters' | 'orderBy' | 'expand'>,\n property: string,\n): boolean {\n if (definition.orderBy?.includes(property)) {\n return true;\n }\n const score = /^(.+)Score$/.exec(property);\n if (score && definition.filters?.some(filter => filter.name === score[1] && filter.supportsFulltext === true)) {\n return true;\n }\n const dot = property.indexOf('.');\n if (dot < 0) {\n return false;\n }\n const expandDefinition = definition.expand?.find(expand => expand.name === property.slice(0, dot));\n return expandDefinition ? orderByAllowed(expandDefinition, property.slice(dot + 1)) : false;\n}\n\n/**\n * Validates sort input against `x-ddd-query.orderBy` (`OrderByOptions::validateAgainstDefinitions()`): declared\n * properties, `<filter>Score` for a fulltext filter, dotted paths through expands. Without an `orderBy` list nothing\n * is checked.\n */\nexport function validateOrderBy(\n query: Pick<DddQueryDefinition, 'filters' | 'orderBy' | 'expand'>,\n input: OrderByInput | null | undefined,\n): QueryIssue[] {\n if (!query.orderBy) {\n return [];\n }\n return toOrderByEntries(input)\n .filter(entry => !orderByAllowed(query, entry.property))\n .map(entry => ({\n code: 'unknown-order-by' as const,\n message: `Sorting by '${entry.property}' is not allowed. Allowed: [${(query.orderBy ?? []).join(', ')}].`,\n }));\n}\n\nfunction expandIssues(definitions: DddExpandDefinition[] | undefined, nodes: ExpandTreeNode[], prefix: string): QueryIssue[] {\n const issues: QueryIssue[] = [];\n for (const node of nodes) {\n const path = prefix ? `${prefix}.${node.property}` : node.property;\n const definition = definitions?.find(candidate => candidate.name === node.property);\n if (!definition) {\n issues.push({ code: 'unknown-expand', message: `'${path}' cannot be expanded.` });\n continue;\n }\n const hasClauses =\n node.filters !== undefined ||\n node.orderBy !== undefined ||\n node.select !== undefined ||\n node.top !== undefined ||\n node.skip !== undefined ||\n node.children.length > 0;\n if (definition.computed && hasClauses) {\n issues.push({ code: 'computed-expand-clauses', message: `'${path}' is a computed field and takes no clauses.` });\n continue;\n }\n if (node.top !== undefined && definition.maxTop !== undefined && definition.maxTop !== null && node.top > definition.maxTop) {\n issues.push({ code: 'top-exceeds-max', message: `top in '${path}' may be at most ${definition.maxTop}.` });\n }\n if (node.orderBy !== undefined) {\n issues.push(...validateOrderBy(definition, node.orderBy));\n }\n issues.push(...expandIssues(definition.expand, node.children, path));\n }\n return issues;\n}\n\n/**\n * Validates expand input against `x-ddd-query.expand` (`ExpandOptions::validateAgainstDefinitionsFromReferenceClass()`):\n * declared names at every nesting level, no clauses on computed fields, `top` within an expand's `maxTop`, sort\n * properties of the expand. Without an `expand` list every expand is reported unknown.\n */\nexport function validateExpand(query: Pick<DddQueryDefinition, 'expand'>, input: ExpandInput | null | undefined): QueryIssue[] {\n return expandIssues(query.expand, toExpandTree(input), '');\n}\n\n/** Validates `select` fields against `x-ddd-query.select` (`true` = any field, a list = those fields). */\nexport function validateSelect(query: Pick<DddQueryDefinition, 'select'>, fields: readonly string[] | string | null | undefined): QueryIssue[] {\n const list = (typeof fields === 'string' ? fields.split(',') : [...(fields ?? [])]).map(field => field.trim()).filter(Boolean);\n if (list.length === 0) {\n return [];\n }\n if (!query.select) {\n return [{ code: 'select-not-supported', message: 'This operation does not accept select.' }];\n }\n if (query.select === true) {\n return [];\n }\n const allowed = query.select;\n return list\n .filter(field => !allowed.includes(field))\n .map(field => ({ code: 'unknown-select' as const, message: `'${field}' cannot be selected.` }));\n}\n\n/** Options of {@link buildDefinedQueryOptions}. */\nexport interface DefinedQueryOptionsOptions {\n /** Above `maxTop`: `throw` (default) or `clamp`. */\n topOverflow?: TopOverflow;\n}\n\n/**\n * {@link buildQueryOptions} checked against an `x-ddd-query` definition: validates `orderBy`, `expand` and `select`\n * and honours `maxTop`; throws {@link QueryValidationError} with every issue. `filters` are taken as given — build\n * the clauses with {@link buildDefinedFilter} to validate them.\n */\nexport function buildDefinedQueryOptions(\n query: DddQueryDefinition,\n input: QueryOptionsInput,\n options: DefinedQueryOptionsOptions = {},\n): QueryOptionsParams {\n const issues = [\n ...validateOrderBy(query, input.orderBy),\n ...validateExpand(query, input.expand),\n ...validateSelect(query, typeof input.select === 'string' || Array.isArray(input.select) ? input.select : null),\n ];\n if (issues.length > 0) {\n throw new QueryValidationError(issues);\n }\n return buildQueryOptions(input, { maxTop: query.maxTop, topOverflow: options.topOverflow });\n}\n"],"mappings":";;;;;;;;;;;;AACO,IAAM,oBAAN,cAAgC,MAAM;AAAA,EAC3C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;;;ACUO,SAAS,mBAAmB,OAAuB;AACxD,SAAO,MAAM,QAAQ,OAAO,MAAM,EAAE,QAAQ,MAAM,KAAK;AACzD;AAGO,IAAM,cAAc;AAOpB,SAAS,qBAAqB,OAA4C;AAC/E,MAAI,OAAO,UAAU,WAAW;AAC9B,WAAO,QAAQ,MAAM;AAAA,EACvB;AACA,MAAI,iBAAiB,MAAM;AACzB,WAAO,kBAAkB,KAAK;AAAA,EAChC;AACA,MAAI,OAAO,UAAU,UAAU;AAC7B,QAAI,CAAC,OAAO,SAAS,KAAK,GAAG;AAC3B,YAAM,IAAI,kBAAkB,gBAAgB,OAAO,KAAK,CAAC,yBAAyB;AAAA,IACpF;AACA,UAAM,OAAO,OAAO,KAAK;AACzB,QAAI,KAAK,KAAK,IAAI,GAAG;AACnB,YAAM,IAAI,kBAAkB,gBAAgB,IAAI,iDAAiD;AAAA,IACnG;AACA,WAAO;AAAA,EACT;AACA,SAAO;AACT;AASO,SAAS,mBAAmB,OAA6B;AAC9D,MAAI,UAAU,MAAM;AAClB,WAAO;AAAA,EACT;AACA,SAAO,IAAI,mBAAmB,qBAAqB,KAAK,CAAC,CAAC;AAC5D;AAQO,SAAS,qBAAqB,OAA6B;AAChE,SAAO,UAAU,OAAO,SAAS,KAAK,UAAU,qBAAqB,KAAK,CAAC;AAC7E;AAMO,SAAS,oBAAoB,OAA4B;AAC9D,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,WAAO,IAAK,MAAkC,IAAI,oBAAoB,EAAE,KAAK,GAAG,CAAC;AAAA,EACnF;AACA,SAAO,mBAAmB,KAAqB;AACjD;AAEA,IAAM,gBAAgB;AAMf,SAAS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,EACxC,IAAI,YAAU,EAAE,MAAM,kBAA2B,SAAS,IAAI,KAAK,wBAAwB,EAAE;AAClG;AAaO,SAAS,yBACd,OACA,OACA,UAAsC,CAAC,GACnB;AACpB,QAAM,SAAS;AAAA,IACb,GAAG,gBAAgB,OAAO,MAAM,OAAO;AAAA,IACvC,GAAG,eAAe,OAAO,MAAM,MAAM;AAAA,IACrC,GAAG,eAAe,OAAO,OAAO,MAAM,WAAW,YAAY,MAAM,QAAQ,MAAM,MAAM,IAAI,MAAM,SAAS,IAAI;AAAA,EAChH;AACA,MAAI,OAAO,SAAS,GAAG;AACrB,UAAM,IAAI,qBAAqB,MAAM;AAAA,EACvC;AACA,SAAO,kBAAkB,OAAO,EAAE,QAAQ,MAAM,QAAQ,aAAa,QAAQ,YAAY,CAAC;AAC5F;","names":[]}
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The token pair a DDD backend issues on login and refresh (`accessToken` + `refreshToken`).
3
+ *
4
+ * The refresh token is a stateless JWT that the backend re-issues with a renewed lifetime on every refresh
5
+ * (no rotation list): storing the newest one is enough.
6
+ */
7
+ interface DddTokens {
8
+ /** Short-lived bearer token sent as `Authorization: Bearer …`. */
9
+ accessToken: string | null;
10
+ /** Long-lived token exchanged for a fresh pair at the refresh endpoint. */
11
+ refreshToken: string | null;
12
+ }
13
+ /**
14
+ * A partial token update. `undefined` leaves a stored value untouched, `null` removes it.
15
+ */
16
+ interface DddTokensUpdate {
17
+ accessToken?: string | null;
18
+ refreshToken?: string | null;
19
+ }
20
+ /** Body of the DDD `POST …/common/auth/login` request. */
21
+ interface DddLoginRequest {
22
+ email: string;
23
+ password: string;
24
+ }
25
+ /** Body of the DDD `POST …/common/auth/refresh` request. */
26
+ interface DddRefreshRequest {
27
+ refreshToken: string;
28
+ }
29
+ /** Response of the DDD login and refresh endpoints (`AuthPostResponseDto`). */
30
+ interface DddAuthResponse {
31
+ accessToken?: string | null;
32
+ refreshToken?: string | null;
33
+ }
34
+
35
+ export type { DddTokens as D, DddLoginRequest as a, DddAuthResponse as b, DddRefreshRequest as c, DddTokensUpdate as d };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mgamadeus/ddd-web",
3
- "version": "0.0.1",
3
+ "version": "0.2.2",
4
4
  "description": "TypeScript web client for backends built with mgamadeus/ddd, the DDD entity framework for Symfony and Doctrine (Composer/Packagist). Generates a typed RTK Query SDK from the backend's OpenAPI document, builds DDD QueryOptions (filters, orderBy, expand, select, paging) and handles JWT auth with token refresh.",
5
5
  "keywords": [
6
6
  "ddd",
@@ -27,15 +27,70 @@
27
27
  "license": "MIT",
28
28
  "author": "Marius-Eugen Gerdan <marius@gerdan.net>",
29
29
  "type": "module",
30
+ "sideEffects": false,
31
+ "exports": {
32
+ "./contract": {
33
+ "types": "./dist/contract/index.d.ts",
34
+ "import": "./dist/contract/index.js"
35
+ },
36
+ "./query": {
37
+ "types": "./dist/query/index.d.ts",
38
+ "import": "./dist/query/index.js"
39
+ },
40
+ "./api": {
41
+ "types": "./dist/api/index.d.ts",
42
+ "import": "./dist/api/index.js"
43
+ },
44
+ "./auth": {
45
+ "types": "./dist/auth/index.d.ts",
46
+ "import": "./dist/auth/index.js"
47
+ },
48
+ "./codegen": {
49
+ "types": "./dist/codegen/index.d.ts",
50
+ "import": "./dist/codegen/index.js"
51
+ },
52
+ "./package.json": "./package.json"
53
+ },
54
+ "bin": {
55
+ "ddd-web-sdk": "./dist/codegen/cli.js",
56
+ "ddd-web": "./dist/codegen/cli.js"
57
+ },
30
58
  "files": [
59
+ "dist",
60
+ ".claude/skills",
31
61
  "README.md",
62
+ "CHANGELOG.md",
32
63
  "LICENSE"
33
64
  ],
34
65
  "engines": {
35
66
  "node": ">=20"
36
67
  },
37
- "packageManager": "pnpm@11.15.1",
38
68
  "publishConfig": {
39
69
  "access": "public"
70
+ },
71
+ "dependencies": {
72
+ "@rtk-query/codegen-openapi": "^2.2.0",
73
+ "jiti": "^2.7.0",
74
+ "prettier": "^3.9.10"
75
+ },
76
+ "peerDependencies": {
77
+ "@reduxjs/toolkit": "^2.0.0"
78
+ },
79
+ "peerDependenciesMeta": {
80
+ "@reduxjs/toolkit": {
81
+ "optional": true
82
+ }
83
+ },
84
+ "devDependencies": {
85
+ "@reduxjs/toolkit": "^2.13.0",
86
+ "@types/node": "^26.6.6",
87
+ "tsup": "^9.0.0",
88
+ "typescript": "^6.0.3",
89
+ "vitest": "^5.0.5"
90
+ },
91
+ "scripts": {
92
+ "build": "node scripts/clean.mjs && tsup",
93
+ "typecheck": "tsc -p .",
94
+ "test": "vitest run"
40
95
  }
41
- }
96
+ }