UNPKG

@softr/sdk

Version:

The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.

140 lines (138 loc) • 7.14 kB
import { assert, requireDefined } from "../assertions.js"; import { softrConfig } from "../softr-config.js"; import { INTERNAL_KIND, buildFilterCriteria } from "./filter.js"; import { makeChain } from "./fields.js"; //#region src/datasource/enforced-filter.ts /** The group levels Studio can show and edit. The root group is level 1. */ const MAX_LEVELS = 4; const USER_TOKEN = /^(?:\{USER:::(EMAIL|EMAIL_DOMAIN)\}|USER:::(.+))$/; const DATE_TOKEN = /^(?:PREDEFINED:(?:TODAY|YESTERDAY|TOMORROW)|FIXED_DATE:(?:DAYS_AGO|DAYS_FROM_NOW):\d+)$/; /** Anything in the token namespaces. A value here that is no known token is a typo, not data. */ const TOKEN_LIKE = /^\{?(?:USER|PREDEFINED|FIXED_DATE):/; /** * Builds the filter that a query declares into the shape a read sends. Subjects stay aliases and * tokens stay unresolved: the datasource resolves them on each read. */ function buildEnforcedFilter(declared, aliases) { const root = requireDefined(buildFilterCriteria(toConstructable(declared)).filterConditionGroup); const levels = levelsOf(root); assert(levels <= MAX_LEVELS, () => `the filter has ${levels} group levels, and Studio shows at most ${MAX_LEVELS}`); return { filterConditionGroup: root }; function toConstructable(node) { assert(isObject(node) && Object.keys(node).length > 0, "a filter must be an object with at least one key"); const members = []; for (const [key, value] of Object.entries(node)) if (key === "$and") members.push(...junction(key, value).flatMap((member) => membersOf(member, "AND"))); else if (key === "$or") members.push(group("OR", junction(key, value).flatMap((member) => membersOf(member, "OR")))); else members.push(...conditions(key, value)); return members.length === 1 ? members[0] : group("AND", members); } function junction(key, value) { assert(Array.isArray(value) && value.length > 0, () => `${key} must be a list of at least one filter`); return value.map(toConstructable); } function conditions(alias, value) { assert(aliases.includes(alias), () => `the filter names "${alias}", which is not one of filterFields`); assert(isObject(value) && Object.keys(value).length > 0, () => `"${alias}" in the filter needs at least one operator`); const chain = makeChain(alias); return Object.entries(value).map(([operator, argument]) => { assert(Object.hasOwn(chain, operator), () => `"${operator}" on "${alias}" is not a filter operator`); const build = chain[operator]; let values$1 = [argument]; if (build.length === 0) { assert(argument === true, () => `"${operator}" on "${alias}" takes true`); values$1 = []; } else if (build.length === 2) { assert(Array.isArray(argument) && argument.length === 2, () => `"${operator}" on "${alias}" takes a pair`); values$1 = argument; } for (const token of values$1.flat()) { const unbraced = typeof token === "string" ? /^\{(USER:::.+)\}$/.exec(token)?.[1] : void 0; assert(typeof token !== "string" || !TOKEN_LIKE.test(token) || USER_TOKEN.test(token) || DATE_TOKEN.test(token), () => `"${token}" on "${alias}" is not a known token` + (unbraced === void 0 ? "" : `. Write a field of the visitor without braces: "${unbraced}"`)); const key = typeof token === "string" ? USER_TOKEN.exec(token)?.[2] : void 0; assert(key === void 0 || Object.values(softrConfig().user?.properties ?? {}).includes(key), () => `"${token}" on "${alias}" names a field that softr.json does not declare under user.properties`); } return build(...values$1); }); } } /** Whether the filter reads a value of the visitor, so a read has to know who the visitor is. */ function readsVisitor(group$1) { return values(group$1).some((value) => typeof value === "string" && USER_TOKEN.test(value)); } /** Each alias that the filter compares with a user token, with the first such token. */ function aliasesComparedWithUser(group$1) { const compared = /* @__PURE__ */ new Map(); visit(group$1); return compared; function visit({ filters, filterGroups }) { for (const filter of filters) { const token = (Array.isArray(filter.value) ? filter.value : [filter.value]).find((value) => typeof value === "string" && USER_TOKEN.test(value)); if (token !== void 0 && !compared.has(filter.subject)) compared.set(filter.subject, token); } filterGroups.forEach(visit); } } /** * The part of the filter that can match rows for this visitor, or `null` when no part can. * * The datasource resolves each user token from the session. For a visitor with no value, it * compares with an empty value, and that matches the wrong rows. So a condition whose user token * has no value never goes out. The visitor is signed out, or their row holds nothing there. * * In an AND group, such a condition makes the group match nothing. In an OR group, only that * branch drops out. Either way the visitor reads fewer rows, never more. */ function filterForVisitor(group$1, visitor) { const filters = group$1.filters.filter(filterCanMatch); const filterGroups = group$1.filterGroups.flatMap((nested) => filterForVisitor(nested, visitor) ?? []); const kept = filters.length + filterGroups.length; return (group$1.logicalOperator === "AND" ? kept === group$1.filters.length + group$1.filterGroups.length : kept > 0) ? { ...group$1, filters, filterGroups } : null; function filterCanMatch(filter) { if (Array.isArray(filter.value)) return filter.value.every((value) => valueCount(value) > 0); return valueCount(filter.value) === 1; } function valueCount(value) { const user = typeof value === "string" ? USER_TOKEN.exec(value) : null; if (user === null) return 1; return visitor === null ? 0 : userValues(visitor, user[1], user[2]).length; } } /** `property` is EMAIL or EMAIL_DOMAIN for the braced tokens, and `key` is set for the others. */ function userValues(visitor, property, key) { if (property === "EMAIL") return [visitor.email]; if (property === "EMAIL_DOMAIN") { const domain = visitor.email.slice(visitor.email.indexOf("@") + 1); return visitor.email.includes("@") && domain !== "" ? [domain] : []; } const raw = visitor.field(requireDefined(key)); return (Array.isArray(raw) ? raw : [raw]).filter((item) => item !== null && item !== void 0 && item !== ""); } function levelsOf(group$1) { return 1 + Math.max(0, ...group$1.filterGroups.map(levelsOf)); } function values(group$1) { return [...group$1.filters.flatMap((filter) => Array.isArray(filter.value) ? filter.value : [filter.value]), ...group$1.filterGroups.flatMap(values)]; } /** * A member that is itself a group of `logicalOperator` gives its members. So the filter stays as * shallow as written. */ function membersOf(member, logicalOperator) { return member[INTERNAL_KIND] === "LOGICAL_GROUP" && member.logicalOperator === logicalOperator ? member.filters : [member]; } function group(logicalOperator, filters) { return { logicalOperator, filters, [INTERNAL_KIND]: "LOGICAL_GROUP" }; } function isObject(value) { return typeof value === "object" && value !== null && !Array.isArray(value); } //#endregion export { aliasesComparedWithUser, buildEnforcedFilter, filterForVisitor, readsVisitor };