import type { AxisId, ColumnUniversalId, PObjectId, PTableColumnId, PTableColumnIdColumn, } from "@milaboratories/pl-model-common"; import { extractPObjectId, getAxisId, matchAxisId } from "@milaboratories/pl-model-common"; import type { ColumnRecipe } from "../../columns"; /** * Resolves a user-supplied PTableColumnId against the discovered set of * columns and axes. For column refs, accepts either the full recipe id (rich * {@link ColumnUniversalId}) or the bare {@link PObjectId} and returns a ref * carrying the recipe's full id — the same id that appears as the leaf in the * emitted SpecQuery, so engine-side dedup is consistent with the resolver's * view. Axis refs are checked against the union of axes spanned by the * columns and pass through unchanged on hit. * Returns `undefined` when the reference cannot be matched. */ export type ColumnResolver = (ref: PTableColumnId) => PTableColumnId | undefined; export function createColumnResolver(columns: ColumnRecipe[]): ColumnResolver { const axisIds: AxisId[] = []; for (const c of columns) { for (const ax of c.getSpec().axesSpec) { axisIds.push(getAxisId(ax)); } } const byFullId = new Map(); const byPObjectId = new Map(); for (const c of columns) { byFullId.set(c.id, c); const pid = extractPObjectId(c.id); if (!byPObjectId.has(pid)) byPObjectId.set(pid, c); } return (ref: PTableColumnId): PTableColumnId | undefined => { if (ref.type === "axis") { return axisIds.some((a) => matchAxisId(ref.id, a)) ? ref : undefined; } const pid = tryExtractPObjectId(ref.id); const hit = byFullId.get(ref.id) ?? (pid === undefined ? undefined : byPObjectId.get(pid)); if (hit === undefined) return undefined; return { type: "column", id: hit.id } satisfies PTableColumnIdColumn; }; } /** {@link extractPObjectId} for a stored reference: an id it cannot parse resolves to * nothing, so the one entry is dropped instead of failing the whole table. */ function tryExtractPObjectId(id: ColumnUniversalId): PObjectId | undefined { try { return extractPObjectId(id); } catch { return undefined; } }