diff --git a/.changeset/20003-record-id-filter-token.md b/.changeset/20003-record-id-filter-token.md new file mode 100644 index 00000000000..c5e789222cf --- /dev/null +++ b/.changeset/20003-record-id-filter-token.md @@ -0,0 +1,26 @@ +--- +"@objectstack/spec": minor +"@objectstack/core": minor +"@objectstack/lint": minor +--- + +A record-scoped filter token, `{record_id}`: the id of the record a `type: 'record'` page is showing. It resolves where a record is in context, and is refused by name everywhere else (#20003). + +On a record page, `record:related_list` was the only component that could scope itself to the record in view. Every other data-bearing component takes a `FilterCondition`, and the only dynamic values a filter could hold named the signed-in viewer. So "open tasks" on a person's record page counted the whole organisation's tasks, under that person's name. `{ assignee: '{record_id}' }` now says "this record's". + +**Where it is accepted, and where it is refused:** + +- **Accepted:** a filter on a component of a `type: 'record'` page (`regions[].components[]`, `slots`, and any filter key inside them). `os lint` / `os validate` pass it there. A page with no `type` is a record page by `PageSchema`'s default. +- **Refused by `os lint` / `os validate`** (rule `filter-token-unknown`, `error`), with the reason "no record in context on this surface" rather than the unknown-token message: list views (top-level `views` and an object's list views and field filters), dashboard widgets and dashboard filters, reports, datasets, app navigation filters, and every page whose `type` is not `'record'` (`home`, `app`, `utility`, `list`, including a list page's `interfaceConfig.filterBy`). +- **Refused on every server path.** `resolveFilterTokens()` in `@objectstack/core` throws `UnresolvedFilterTokenError` (`FILTER_TOKEN_UNRESOLVED` / 400, `token: 'record_id'`) on the ObjectQL read path (`find`, `findOne`, `count`, `aggregate`), the write path (`update` / `delete`, by id or `multi`), the analytics query door and the dataset executor. That is the same envelope a session token gets when the request has no value for it. It happens whatever the request carries, because no server path knows which record a page is showing. The token never becomes `null` (a count "about nobody"), is never dropped (a count "about everybody"), and never reaches the driver. + +**What is in `@objectstack/spec/data`:** + +- `RECORD_CONTEXT_TOKENS` (`['record_id']`), `RecordContextToken` and `isRecordContextToken()`: a sibling of `CONTEXT_TOKENS`, not a member. `CONTEXT_TOKENS` resolves against the caller's session, and `{record_id}` resolves against the surface. So `isContextToken('record_id')`, `ContextTokenSchema` and `ContextTokenPlaceholderSchema` are unchanged and still reject it, and a client resolver that fills `CONTEXT_TOKENS` from the session does not pick it up. +- `classifyFilterToken('{record_id}')` returns the new kind `{ kind: 'record-context', token: 'record_id' }` instead of `unknown`. A consumer that switches exhaustively on `kind` gets a compile error until it handles the new kind. +- `isKnownFilterToken('record_id')` stays `false`. That predicate answers "can the server resolve it?", and its one consumer, the flow engine's filter hand-off, is a server position. A flow addresses its own record as `{record.id}`. +- Near misses are still refused, now with `{record_id}` suggested: `{recordId}` (the URL / flow-template placeholder), `{record.id}`, `{record-id}`, `{current_record_id}`. `CONTEXT_TOKEN_SUGGESTIONS`' value type widens to `ContextToken | RecordContextToken`. + +**Presentation scope, not access.** Like `{current_user_id}`, `{record_id}` narrows what a component shows. It decides nothing about which rows the caller may read; that is still RLS. + +**What you do:** on a record page, filter a component on the record in view with `{ : '{record_id}' }`. If `os validate` refuses it with "no record in context on this surface", the filter is on a surface with no record: move it onto a component of a `type: 'record'` page, or filter on a concrete id. Until the renderer you run resolves `{record_id}`, a record-page query that carries it is refused by the server with `FILTER_TOKEN_UNRESOLVED` rather than answered with a wrong number. diff --git a/content/docs/references/data/context-tokens.mdx b/content/docs/references/data/context-tokens.mdx index c6976670c26..ee82a378b0c 100644 --- a/content/docs/references/data/context-tokens.mdx +++ b/content/docs/references/data/context-tokens.mdx @@ -6,7 +6,18 @@ description: Context Tokens protocol schemas {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} Context Tokens — the declarative placeholders that resolve against the -**caller's session** (who am I, which org am I in) rather than the clock. +**caller's session** (who am I, which org am I in) rather than the clock, +plus one sibling that resolves against the **surface**: `{record_id}`, the +record a `type: 'record'` page is showing. + +The two resolve against different things, so they are two lists, never one: + +| | `CONTEXT_TOKENS` | `RECORD_CONTEXT_TOKENS` | +|---|---|---| +| Tokens | `{current_user_id}`, `{current_org_id}` | `{record_id}` | +| Resolves against | the caller's session | the record the page is bound to | +| Known on the server | yes — `ExecutionContext` | never — only the page renderer knows which record is in view | +| Valid on | every filter surface | a component on a `type: 'record'` page, and nowhere else | ## Why this lives in `spec` @@ -38,11 +49,24 @@ neither is an ERROR, not a null comparand: resolving to `null` degrades to `IS NULL` on most drivers and would hand back the rows the filter was written to exclude. +`{record_id}` is resolved on ONE side of the wire only: by the page +renderer, which substitutes the id of the record a `type: 'record'` page +is showing before the filter leaves the browser. The server never knows +which record a page is showing, so a filter that reaches +`resolveFilterTokens()` still carrying `{record_id}` is refused by name +(`FILTER_TOKEN_UNRESOLVED` / 400) — which is also what an author sees +from a renderer that does not resolve the token yet. It never becomes +`null`, `undefined` or the literal string: a number written as "about +this record" must neither silently become "about everybody" (the +condition dropped) nor "about nobody" (the token compared as text). + ## Presentation scope, NOT a security boundary This is the single most important thing to understand about these tokens. `{current_user_id}` scopes what a surface *shows*; it does not -decide what a caller is *allowed* to read. Enforcement is RLS, which +decide what a caller is *allowed* to read. `{record_id}` is the same: it +narrows a record-page component to the record in view, and which of those +rows the caller may read is still not its decision. Enforcement is RLS, which uses a different and genuinely server-side vocabulary rooted at `current_user` (`owner_id = current_user.id`, compiled by `@objectstack/plugin-security`'s RLS compiler). @@ -62,12 +86,38 @@ a `{current_user_id}` filter widens a *view*; it must never widen ## Where the tokens are honoured -Filter values on every surface that resolves placeholders — object list -views, dashboard widgets, reports, SDUI page components. Navigation -(`recordId` / `params`) additionally resolves `AppContextSelector` ids -such as `{active_package}`; those are nav-only and are NOT valid inside -filter values, because filters are not evaluated with the sidebar's -selector state. +`{current_user_id}` and `{current_org_id}`: filter values on every surface +that resolves placeholders — object list views, dashboard widgets, +reports, datasets, SDUI page components — and on the server's ObjectQL +read and write paths and analytics doors. + +`{record_id}`: filter values on a component of a `type: 'record'` page, +and nowhere else. `@objectstack/lint`'s `validate-filter-tokens` refuses it +by name ("no record in context on this surface") on list views, dashboard +widgets, reports, datasets, apps, object definitions and every page that is +not `type: 'record'`. The server refuses it on every path, because no +server path has a record in context. + +Navigation (`recordId` / `params`) additionally resolves +`AppContextSelector` ids such as `{active_package}`; those are nav-only and +are NOT valid inside filter values, because filters are not evaluated with +the sidebar's selector state. + +## `{record_id}` is not `{recordId}`, and not the `'record_id'` variable type + +Three spellings look alike and are three different mechanisms: + +- `{record_id}` — this filter token. A whole filter VALUE, resolved to the + id of the record the page shows. +- `{recordId}` — a URL / flow-template placeholder: an action's + `newTabUrl` (`action.zod.ts`) and the flow template dialect + (`@objectstack/lint`'s `flow-template-grammar.ts`). It is interpolated by + those surfaces' own template engines and is NOT a filter token. Written + inside a filter it is refused, with `{record_id}` suggested. +- `'record_id'` — a page-variable TYPE (`PageVariableSchema.type` in + `page.zod.ts`), naming what a page variable holds, e.g. the selection of + an `element:record_picker`. It is read in expressions as `page.`, + never written as a placeholder. ## Out of scope @@ -75,6 +125,9 @@ selector state. - `{date-macros}` — the clock-based sibling; see `./date-macros.zod.ts`. - `titleFormat` field interpolation (`{user_id}` etc.) — that substitutes *record fields*, an unrelated mechanism that happens to share braces. +- Tokens for a record OTHER than the one in view (a related record, a + parent of the record). Each is its own contract with its own resolver, + not an extension of `{record_id}`. **Source:** `packages/spec/src/data/context-tokens.zod.ts` diff --git a/packages/core/src/utils/filter-tokens.test.ts b/packages/core/src/utils/filter-tokens.test.ts index 5d6a6b592ed..737445fb188 100644 --- a/packages/core/src/utils/filter-tokens.test.ts +++ b/packages/core/src/utils/filter-tokens.test.ts @@ -145,6 +145,72 @@ describe('resolveFilterToken — context tokens', () => { }); }); +/** + * `{record_id}` — the record-context token. The server never has a record in + * context, so it refuses by name on every path, whatever the request carries. + * The refusal is the same envelope as a session token the request has no value + * for (`FILTER_TOKEN_UNRESOLVED` / 400): the spelling is right, the context is + * missing, and `token` names which context. + */ +describe('resolveFilterTokens — the record-context token refuses by name', () => { + // A FULL context on purpose: the refusal must not depend on what the + // request happens to carry. + const full = { now: NOW, userId: 'usr_1', orgId: 'org_9', timezone: 'UTC' }; + + function refusal(filter: unknown): UnresolvedFilterTokenError { + let err: unknown; + try { + resolveFilterTokens(filter, full); + } catch (e) { + err = e; + } + expect(err).toBeInstanceOf(UnresolvedFilterTokenError); + return err as UnresolvedFilterTokenError; + } + + it.each([ + ['a MongoDB-style condition', { assignee: '{record_id}' }], + ['an operator comparand', { assignee: { $eq: '{record_id}' } }], + ['the `${…}` spelling', { assignee: '${record_id}' }], + ['a rule-array filter', [{ field: 'assignee', operator: 'equals', value: '{record_id}' }]], + ['a logical branch beside a resolvable token', { $and: [{ owner: '{current_user_id}' }, { account: '{record_id}' }] }], + ])('%s: FILTER_TOKEN_UNRESOLVED / 400, the token named', (_label, filter) => { + const err = refusal(filter); + expect(err.code).toBe('FILTER_TOKEN_UNRESOLVED'); + expect(err.status).toBe(400); + expect(err.name).toBe('UnresolvedFilterTokenError'); + expect(err.token).toBe('record_id'); + expect(err.message).toContain('{record_id}'); + }); + + it('resolveFilterToken refuses it directly too — never `undefined`, never the literal', () => { + expect(() => resolveFilterToken('record_id', full)).toThrow(UnresolvedFilterTokenError); + }); + + it('lit control — a session token in the same request still resolves', () => { + expect(resolveFilterTokens({ owner: '{current_user_id}' }, full)).toEqual({ owner: 'usr_1' }); + }); + + it.each([ + ['{recordid}', 'recordid'], + ['{record-id}', 'record-id'], + ['{recordId}', 'recordId'], + ])('near miss %s stays FILTER_TOKEN_UNKNOWN, with {record_id} suggested', (value, token) => { + let err: unknown; + try { + resolveFilterTokens({ assignee: value }, full); + } catch (e) { + err = e; + } + expect(err).toBeInstanceOf(UnknownFilterTokenError); + const e = err as UnknownFilterTokenError; + expect(e.code).toBe('FILTER_TOKEN_UNKNOWN'); + expect(e.status).toBe(400); + expect(e.token).toBe(token); + expect(e.suggestion).toBe('record_id'); + }); +}); + describe('resolveFilterTokens — tree walk', () => { const ctx = { now: NOW, userId: 'usr_1', orgId: 'org_9' }; diff --git a/packages/core/src/utils/filter-tokens.ts b/packages/core/src/utils/filter-tokens.ts index aee504cc2e9..e88212c3df9 100644 --- a/packages/core/src/utils/filter-tokens.ts +++ b/packages/core/src/utils/filter-tokens.ts @@ -72,10 +72,22 @@ * natural-language spellings are exactly what an author migrating from another * system's macro syntax reaches for first. See `FILTER_TOKEN_WRAPPED_RE` in * `@objectstack/spec`. + * + * # A record-context token always refuses here + * + * `{record_id}` (`RECORD_CONTEXT_TOKENS` in `@objectstack/spec`) is the id of + * the record a `type: 'record'` page is showing. Only the page renderer knows + * that record; no server path has one in context. So a filter that arrives + * here still carrying `{record_id}` throws {@link UnresolvedFilterTokenError} + * naming it, on every path, whatever the request carries. It never resolves + * to `null`, `undefined` or the literal: a count written as "about this + * record" would otherwise come back as "about nobody", or, with the condition + * gone, "about everybody". */ import { classifyFilterToken, + isRecordContextToken, parseDateMacroParam, type DateMacroUnit, } from '@objectstack/spec/data'; @@ -143,10 +155,15 @@ export class UnknownFilterTokenError extends Error { /** * Raised when a token IS in the vocabulary but the request carries no value - * for it — an unauthenticated caller filtering on `{current_user_id}`. + * for it — an unauthenticated caller filtering on `{current_user_id}`, or any + * filter carrying the record-context token `{record_id}`, which no server + * path has a value for (see the module doc). * * Distinct from {@link UnknownFilterTokenError} because the fix is different: - * the metadata is correct, the context is not. Never silently resolves to + * the spelling is correct, the context is not. For `{record_id}` the fix is + * WHERE the filter is authored or resolved: a component on a `type: 'record'` + * page, whose renderer resolves the token before the query leaves the + * browser. `token` names which context is missing. Never silently resolves to * `null`/`undefined`, which on most drivers degrades to `IS NULL` and would * quietly hand back rows the filter was written to exclude. */ @@ -320,6 +337,23 @@ export function resolveFilterToken( return ctx.orgId; } + // ── Record-context tokens ───────────────────────────────────────────── + // Never resolvable here, whatever the request carries: the server does not + // know which record a page is showing. See the module doc. + if (isRecordContextToken(token)) { + throw new UnresolvedFilterTokenError( + token, + 'no record in context on the server. {record_id} is the id of the record a ' + + "`type: 'record'` page is showing, and only that page's renderer knows it: it " + + 'resolves the token before the query leaves the browser. A filter still carrying ' + + 'it here was authored on a surface with no record in context (a list view, a ' + + 'dashboard widget, a report, a dataset, a page that is not a record page), or sent ' + + 'by a client that did not resolve it. Move the filter onto a component of a record ' + + 'page, or filter on a concrete id. Resolving it to null would count no records, and ' + + 'dropping the condition would count them all.', + ); + } + // ── Date macros ─────────────────────────────────────────────────────── const today = proxyDay(now, ctx.timezone); diff --git a/packages/lint/src/validate-filter-tokens.test.ts b/packages/lint/src/validate-filter-tokens.test.ts index b5ebe29b8da..3a76bc230d8 100644 --- a/packages/lint/src/validate-filter-tokens.test.ts +++ b/packages/lint/src/validate-filter-tokens.test.ts @@ -1,6 +1,9 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. import { describe, it, expect } from 'vitest'; +import { PageSchema } from '@objectstack/spec/ui'; + +import { walkAuthoredFilters } from './filter-walk'; import { validateFilterTokens, FILTER_TOKEN_UNKNOWN } from './validate-filter-tokens'; describe('validateFilterTokens', () => { @@ -223,3 +226,207 @@ describe('validateFilterTokens', () => { expect(() => validateFilterTokens({ dashboards: [dash] })).not.toThrow(); }); }); + +/** + * `{record_id}` — the record-context token. It resolves only where a record is + * in context, which on the surfaces this rule walks means a component on a + * `type: 'record'` page. Everywhere else it is refused by name, with the reason + * ("no record in context on this surface"), not the unknown-token message. + */ +describe('validateFilterTokens — {record_id}', () => { + const NO_RECORD = 'no record in context on this surface'; + + function recordPage(type: string | undefined, filter: unknown): Record { + return { + name: 'person_page', + label: 'Person', + ...(type === undefined ? {} : { type }), + object: 'person', + regions: [ + { + name: 'main', + components: [ + { type: 'element:number', properties: { object: 'task', aggregate: 'count', filter } }, + ], + }, + ], + }; + } + + function expectRefusal( + findings: ReturnType, + path: string, + where: string, + ): void { + expect(findings).toHaveLength(1); + const [f] = findings; + expect(f.severity).toBe('error'); + expect(f.rule).toBe(FILTER_TOKEN_UNKNOWN); + expect(f.path).toBe(path); + expect(f.where).toBe(where); + expect(f.message).toContain('{record_id}'); + expect(f.message).toContain(NO_RECORD); + // The reason, not the unknown-token wording. + expect(f.message).not.toContain('is not a resolvable placeholder'); + } + + it('accepts it on a component of a record page, in every filter shape', () => { + expect(validateFilterTokens({ pages: [recordPage('record', { assignee: '{record_id}', status: 'open' })] })).toEqual([]); + expect(validateFilterTokens({ pages: [recordPage('record', [['assignee', '=', '${record_id}']])] })).toEqual([]); + expect( + validateFilterTokens({ + pages: [recordPage('record', [{ field: 'assignee', operator: 'equals', value: '{record_id}' }])], + }), + ).toEqual([]); + }); + + it('accepts it beside the session tokens and date macros on the same record page', () => { + expect( + validateFilterTokens({ + pages: [recordPage('record', { + $and: [{ assignee: '{record_id}' }, { owner: '{current_user_id}' }, { due: { $lt: '{today}' } }], + })], + }), + ).toEqual([]); + }); + + it('accepts it in a slot of a slotted record page', () => { + expect( + validateFilterTokens({ + pages: [{ + name: 'p', label: 'P', type: 'record', kind: 'slotted', object: 'person', + slots: { main: { type: 'record:related_list', properties: { filter: { assignee: '{record_id}' } } } }, + }], + }), + ).toEqual([]); + }); + + it('an untyped page is judged as the schema default, a record page', () => { + // The rule runs on the parsed stack, where `PageSchema` has filled `type`. + // This holds the rule's reading of an absent `type` equal to that default. + const parsed = PageSchema.parse({ name: 'person_page', label: 'Person' }); + expect(parsed.type).toBe('record'); + expect(validateFilterTokens({ pages: [recordPage(undefined, { assignee: '{record_id}' })] })).toEqual([]); + }); + + it.each(['home', 'app', 'utility', 'list'])('refuses it on a %s page', (type) => { + expectRefusal( + validateFilterTokens({ pages: [recordPage(type, { assignee: '{record_id}' })] }), + 'pages[0].regions[0].components[0].properties.filter.assignee', + 'page "person_page"', + ); + }); + + it('refuses it in a list page base filter (interfaceConfig.filterBy)', () => { + expectRefusal( + validateFilterTokens({ + pages: [{ + name: 'tasks', type: 'list', + interfaceConfig: { source: 'task', filterBy: [{ field: 'assignee', operator: 'equals', value: '{record_id}' }] }, + }], + }), + 'pages[0].interfaceConfig.filterBy[0].value', + 'page "tasks"', + ); + }); + + it('refuses it on a list view (top-level view)', () => { + expectRefusal( + validateFilterTokens({ views: [{ name: 'my_tasks', filter: [{ field: 'assignee', operator: 'equals', value: '{record_id}' }] }] }), + 'views[0].filter[0].value', + 'view "my_tasks"', + ); + }); + + it("refuses it on an object's list view", () => { + expectRefusal( + validateFilterTokens({ + objects: [{ name: 'task', listViews: { mine: { filter: [['assignee', '=', '{record_id}']] } } }], + }), + 'objects[0].listViews.mine.filter[0][2]', + 'object "task"', + ); + }); + + it('refuses it on a dashboard widget', () => { + expectRefusal( + validateFilterTokens({ + dashboards: [{ name: 'ops', widgets: [{ id: 'open_tasks', type: 'metric', filter: { assignee: '{record_id}' } }] }], + }), + 'dashboards[0].widgets[0].filter.assignee', + 'dashboard "ops" · widget "open_tasks"', + ); + }); + + it('refuses it on a report', () => { + expectRefusal( + validateFilterTokens({ reports: [{ name: 'r', runtimeFilter: { assignee: '{record_id}' } }] }), + 'reports[0].runtimeFilter.assignee', + 'report "r"', + ); + }); + + it('refuses it on a dataset', () => { + expectRefusal( + validateFilterTokens({ datasets: [{ name: 'ds', filter: { assignee: '{record_id}' } }] }), + 'datasets[0].filter.assignee', + 'dataset "ds"', + ); + }); + + it('refuses it in an app nav item filter', () => { + expectRefusal( + validateFilterTokens({ + apps: [{ name: 'app', navigation: [{ id: 'n', type: 'object', filters: { assignee: '{record_id}' } }] }], + }), + 'apps[0].navigation[0].filters.assignee', + 'app "app"', + ); + }); + + it('judges each page by its own type — record page accepted, list page refused, same stack', () => { + const findings = validateFilterTokens({ + pages: [ + recordPage('record', { assignee: '{record_id}' }), + { ...recordPage('home', { assignee: '{record_id}' }), name: 'home_page' }, + ], + }); + expect(findings.map((f) => f.where)).toEqual(['page "home_page"']); + }); + + it('near miss {recordId} is still unknown on a record page, with {record_id} suggested', () => { + const findings = validateFilterTokens({ pages: [recordPage('record', { assignee: '{recordId}' })] }); + expect(findings).toHaveLength(1); + expect(findings[0].rule).toBe(FILTER_TOKEN_UNKNOWN); + expect(findings[0].hint).toContain('"{record_id}"'); + }); + + it('lit control — the session tokens stay valid on the surfaces that refuse {record_id}', () => { + expect( + validateFilterTokens({ + views: [{ name: 'v', filter: [{ field: 'owner', operator: 'equals', value: '{current_user_id}' }] }], + dashboards: [{ name: 'd', widgets: [{ id: 'w', filter: { org: '{current_org_id}' } }] }], + pages: [recordPage('home', { owner: '{current_user_id}' })], + }), + ).toEqual([]); + }); + + it('the page loop names paths and locations exactly as the shared walk does', () => { + // The `pages` collection is walked page by page so each page's `type` is + // in hand; a page's finding must still read as the shared walk reads it, + // including a map-shaped collection and an unnamed page. + const stacks = [ + { pages: [recordPage('record', { a: '{nope}' }), { regions: [{ components: [{ properties: { filter: { b: '{nope}' } } }] }] }] }, + { pages: { first: recordPage('home', { a: '{nope}' }), second: recordPage('list', { b: '{nope}' }) } }, + ]; + for (const stack of stacks) { + const walked: string[] = []; + walkAuthoredFilters(stack, [{ key: 'pages', kind: 'page' }], ({ value, path, where }) => { + for (const [k] of Object.entries(value as Record)) walked.push(`${where} @ ${path}.${k}`); + }); + const found = validateFilterTokens(stack).map((f) => `${f.where} @ ${f.path}`); + expect(walked.length).toBeGreaterThan(0); + expect(found).toEqual(walked); + } + }); +}); diff --git a/packages/lint/src/validate-filter-tokens.ts b/packages/lint/src/validate-filter-tokens.ts index 5465f87b2f6..6b0a63fe937 100644 --- a/packages/lint/src/validate-filter-tokens.ts +++ b/packages/lint/src/validate-filter-tokens.ts @@ -1,8 +1,14 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -import { classifyFilterToken, CONTEXT_TOKENS } from '@objectstack/spec/data'; +import { + classifyFilterToken, + CONTEXT_TOKENS, + isRecordContextToken, + type RecordContextToken, +} from '@objectstack/spec/data'; -import { walkAuthoredFilters, type FilterSurface } from './filter-walk.js'; +import { scanForFilters, walkAuthoredFilters, type AuthoredFilter, type FilterSurface } from './filter-walk.js'; +import { recordsOf } from './object-graph.js'; /** * Build-time filter-placeholder diagnostics (issue #3574). @@ -60,8 +66,38 @@ import { walkAuthoredFilters, type FilterSurface } from './filter-walk.js'; * * Only whole-string placeholders are considered (`'{token}'` / `'${token}'`, * anchored). A value that merely contains braces is left alone. + * + * ## `{record_id}` — valid on a record page, refused by name everywhere else + * + * The record-context token (`RECORD_CONTEXT_TOKENS`) is the id of the record a + * `type: 'record'` page is showing. Only that page's renderer can resolve it, + * so the verdict depends on the SURFACE: accepted in any filter on a record + * page, and refused on every other surface this rule walks (list views and the + * rest of an object definition, dashboard widgets, reports, datasets, apps, and + * `home` / `app` / `utility` / `list` pages). The refusal says why, "no record + * in context on this surface". The unknown-token message would send the author + * hunting for a spelling mistake that is not there. + * + * Which pages are record pages is read from the page's own `type`, and this + * rule runs on the PARSED stack (`input: 'parsed'` in `authoring-rules.ts`), + * where `PageSchema` has already applied its `'record'` default. That is why + * the `pages` collection is walked page by page here, through the walk's + * exported single-item entry {@link scanForFilters}, rather than through + * {@link walkAuthoredFilters}: the walk reports a filter's value, path and + * label, and deliberately holds no judgement about the item it came from. + * The page loop spells the path and label exactly as the walk does, and a test + * holds the two equal. */ +/** + * Diagnostic rule id: a filter placeholder this surface cannot resolve. + * + * Two causes share it: a placeholder outside every vocabulary (`{current_user}`, + * `{TODAY()}`), and the record-context token `{record_id}` on a surface with + * no record in context. The message and hint say which, so the finding stays + * actionable. A consumer keyed on the id acts the same either way: this + * filter cannot run where it is written. + */ export const FILTER_TOKEN_UNKNOWN = 'filter-token-unknown'; export type FilterTokenSeverity = 'error' | 'warning'; @@ -85,21 +121,86 @@ type AnyRec = Record; const KNOWN_LIST = CONTEXT_TOKENS.join('}, {'); +/** A walked collection, plus how a `{record_id}` refusal names it. */ +interface TokenFilterSurface extends FilterSurface { + readonly noun: string; +} + /** * The presentation collections this rule has scanned since #3574. Declared * here, handed to the shared walk — see the scope note above for why it is not * a constant in `filter-walk.ts`. */ -const TOKEN_FILTER_SURFACES: readonly FilterSurface[] = [ - { key: 'dashboards', kind: 'dashboard' }, - { key: 'objects', kind: 'object' }, - { key: 'views', kind: 'view' }, - { key: 'reports', kind: 'report' }, - { key: 'datasets', kind: 'dataset' }, - { key: 'pages', kind: 'page' }, - { key: 'apps', kind: 'app' }, +const TOKEN_FILTER_SURFACES: readonly TokenFilterSurface[] = [ + { key: 'dashboards', kind: 'dashboard', noun: 'a dashboard' }, + { key: 'objects', kind: 'object', noun: 'an object definition (its list views and field filters)' }, + { key: 'views', kind: 'view', noun: 'a view' }, + { key: 'reports', kind: 'report', noun: 'a report' }, + { key: 'datasets', kind: 'dataset', noun: 'a dataset' }, + // Judged page by page — see `pageRecordScope`. + { key: 'pages', kind: 'page', noun: 'a page' }, + { key: 'apps', kind: 'app', noun: 'an app' }, ]; +/** + * Whether the filters being judged have a record in context, and, when they + * do not, how to name the surface in the refusal. + */ +interface RecordScope { + readonly recordInContext: boolean; + /** e.g. `a dashboard`, `a page of type "list"`. Unused when a record is in context. */ + readonly surface: string; +} + +/** `PageSchema.type`'s default: a record page. */ +const PAGE_TYPE_DEFAULT = 'record'; + +/** + * The record scope of one page: a record is in context on a `type: 'record'` + * page and on no other. + * + * On the parsed stack this rule is registered for, `type` is always present. + * An absent `type` is the same page, before `PageSchema`'s `'record'` default + * was applied, so it is judged as that default. That is the schema's declared + * default, not a tolerated spelling; a test holds it equal to the schema. + */ +function pageRecordScope(page: AnyRec): RecordScope { + const type = page.type === undefined ? PAGE_TYPE_DEFAULT : page.type; + return type === PAGE_TYPE_DEFAULT + ? { recordInContext: true, surface: 'a record page' } + : { recordInContext: false, surface: `a page of type ${JSON.stringify(type)}` }; +} + +/** Same `where` label as the shared walk: the item's `name`, else `id`, else `#i`. */ +function itemLabel(item: AnyRec, i: number): string { + const v = item.name ?? item.id; + return typeof v === 'string' && v.length > 0 ? v : `#${i}`; +} + +function recordContextFinding( + node: string, + token: RecordContextToken, + path: string, + where: string, + scope: RecordScope, +): FilterTokenFinding { + return { + severity: 'error', + rule: FILTER_TOKEN_UNKNOWN, + where, + path, + message: + `Filter value "${node}" stands for the record in context, and there is no record ` + + `in context on this surface (${scope.surface}). {${token}} resolves only in a filter ` + + `on a component of a \`type: 'record'\` page, where the renderer knows which record ` + + `is in view. Anywhere else the server refuses the query rather than counting every ` + + `record or none.`, + hint: + `Move this filter onto a component of a record page (\`type: 'record'\`), or filter on ` + + `a concrete id. To scope to the signed-in user instead, use {current_user_id}.`, + }; +} + /** * Classify every string inside an already-identified filter subtree. * @@ -114,6 +215,7 @@ function walkFilterValues( node: unknown, path: string, where: string, + scope: RecordScope, out: FilterTokenFinding[], seen: Set, ): void { @@ -121,7 +223,9 @@ function walkFilterValues( if (typeof node === 'string') { const cls = classifyFilterToken(node); - if (cls?.kind === 'unknown') { + if (cls?.kind === 'record-context' && !scope.recordInContext) { + out.push(recordContextFinding(node, cls.token, path, where, scope)); + } else if (cls?.kind === 'unknown') { const suggestion = cls.suggestion; out.push({ severity: 'error', @@ -131,7 +235,10 @@ function walkFilterValues( message: `Filter value "${node}" is not a resolvable placeholder. It is sent to the ` + `data engine as a literal string, matches no record, and the surface renders empty.`, - hint: suggestion + hint: suggestion && isRecordContextToken(suggestion) + ? `Did you mean "{${suggestion}}"? It resolves only in a filter on a component of a ` + + `\`type: 'record'\` page, to the id of the record in view.` + : suggestion ? `Did you mean "{${suggestion}}"? Context tokens are {${KNOWN_LIST}}; ` + `time-based values use date macros such as {today} or {30_days_ago}.` : `Resolvable placeholders are the context tokens {${KNOWN_LIST}} and the ` + @@ -149,12 +256,12 @@ function walkFilterValues( seen.add(node); if (Array.isArray(node)) { - node.forEach((v, i) => walkFilterValues(v, `${path}[${i}]`, where, out, seen)); + node.forEach((v, i) => walkFilterValues(v, `${path}[${i}]`, where, scope, out, seen)); return; } for (const [k, v] of Object.entries(node as AnyRec)) { - walkFilterValues(v, `${path}.${k}`, where, out, seen); + walkFilterValues(v, `${path}.${k}`, where, scope, out, seen); } } @@ -169,9 +276,30 @@ export function validateFilterTokens(stack: Record | undefined if (!stack || typeof stack !== 'object') return []; const out: FilterTokenFinding[] = []; - walkAuthoredFilters(stack, TOKEN_FILTER_SURFACES, ({ value, path, where }) => { - walkFilterValues(value, path, where, out, new Set()); - }); + const judge = (scope: RecordScope) => ({ value, path, where }: AuthoredFilter): void => { + walkFilterValues(value, path, where, scope, out, new Set()); + }; + + // One surface at a time, in the declared order, so findings keep the order + // one call over the whole list produced. + for (const surface of TOKEN_FILTER_SURFACES) { + if (surface.kind === 'page') { + recordsOf(stack[surface.key]).forEach((page, i) => { + scanForFilters( + page, + `${surface.key}[${i}]`, + `${surface.kind} "${itemLabel(page, i)}"`, + judge(pageRecordScope(page)), + ); + }); + continue; + } + walkAuthoredFilters( + stack, + [surface], + judge({ recordInContext: false, surface: surface.noun }), + ); + } return out; } diff --git a/packages/objectql/src/engine-filter-tokens.test.ts b/packages/objectql/src/engine-filter-tokens.test.ts index 98f33ec09b4..6857d0a8d93 100644 --- a/packages/objectql/src/engine-filter-tokens.test.ts +++ b/packages/objectql/src/engine-filter-tokens.test.ts @@ -352,6 +352,86 @@ describe('engine filter placeholders (framework#3582)', () => { }); }); + /** + * `{record_id}` — the record-context token. Only a record page's renderer + * knows which record is in view, so on the server it refuses by name on every + * verb, even with a full context, before the driver is reached. The envelope + * is the "known token, no value in this context" one (`FILTER_TOKEN_UNRESOLVED` + * / 400) — never `IS NULL` ("about nobody") and never a dropped condition + * ("about everybody"). + */ + describe('the record-context token {record_id} refuses by name (read and write paths)', () => { + async function refusalOf(run: (ql: ObjectQL) => Promise) { + const { driver } = makeDriver(); + const ql = await makeEngine(driver); + let err: any; + try { + await run(ql); + } catch (e) { + err = e; + } + expect(err?.name).toBe('UnresolvedFilterTokenError'); + expect(err?.code).toBe('FILTER_TOKEN_UNRESOLVED'); + expect(err?.status).toBe(400); + expect(err?.token).toBe('record_id'); + return driver; + } + + it('find(): refused before the driver', async () => { + const driver = await refusalOf((ql) => ql.find('deal', { where: { owner: '{record_id}' }, context: CTX })); + expect(driver.find).not.toHaveBeenCalled(); + }); + + it('count(): refused before the driver', async () => { + const driver = await refusalOf((ql) => ql.count('deal', { where: { owner: '{record_id}' }, context: CTX })); + expect(driver.count).not.toHaveBeenCalled(); + }); + + it('aggregate(): refused in `where` before the driver', async () => { + const driver = await refusalOf((ql) => + ql.aggregate('deal', { + where: { owner: '{record_id}' }, + groupBy: ['owner'], + aggregations: [{ function: 'count', field: 'id', alias: 'n' }], + context: CTX, + }), + ); + expect(driver.aggregate).not.toHaveBeenCalled(); + }); + + it('update(multi): the write path refuses before anything is written', async () => { + const driver = await refusalOf((ql) => + ql.update('deal', { title: 'x' }, { where: { owner: '{record_id}' }, multi: true, context: CTX } as any), + ); + expect(driver.updateMany).not.toHaveBeenCalled(); + expect(driver.update).not.toHaveBeenCalled(); + }); + + it('delete(multi): the write path refuses before anything is deleted', async () => { + const driver = await refusalOf((ql) => + ql.delete('deal', { where: { owner: '{record_id}' }, multi: true, context: CTX } as any), + ); + expect(driver.deleteMany).not.toHaveBeenCalled(); + expect(driver.delete).not.toHaveBeenCalled(); + }); + + it('update by where.id: refused before the by-id fast path binds it as a primary key', async () => { + const driver = await refusalOf((ql) => + ql.update('deal', { title: 'x' }, { where: { id: '{record_id}' }, context: CTX } as any), + ); + expect(driver.update).not.toHaveBeenCalled(); + }); + + it('lit control — {current_user_id} on the same verbs still resolves', async () => { + const { driver, seen } = makeDriver(); + const ql = await makeEngine(driver); + await ql.find('deal', { where: { owner: '{current_user_id}' }, context: CTX }); + await ql.update('deal', { title: 'x' }, { where: { owner: '{current_user_id}' }, multi: true, context: CTX } as any); + expect(seen.findAst?.where).toEqual({ owner: 'usr_1' }); + expect(seen.updateManyAst?.where).toEqual({ owner: 'usr_1' }); + }); + }); + it('does not mutate the caller filter — view metadata is shared across requests', async () => { const { driver } = makeDriver(); const ql = await makeEngine(driver); diff --git a/packages/services/service-analytics/src/__tests__/dataset-filter-tokens.test.ts b/packages/services/service-analytics/src/__tests__/dataset-filter-tokens.test.ts index 0373551925d..15553a0d11e 100644 --- a/packages/services/service-analytics/src/__tests__/dataset-filter-tokens.test.ts +++ b/packages/services/service-analytics/src/__tests__/dataset-filter-tokens.test.ts @@ -39,6 +39,59 @@ function service(captured: { sql: string; params: unknown[] }[]) { const CTX = { userId: 'usr_1', tenantId: 'org_9', timezone: 'UTC' } as ExecutionContext; const THIS_YEAR_START = `${new Date().getUTCFullYear()}-01-01`; +/** + * `{record_id}` — the record-context token. The dataset executor has no record + * in context (only a record page's renderer does), so each of its token + * positions refuses it by name before any SQL is compiled: the + * `FILTER_TOKEN_UNRESOLVED` / 400 envelope, never a bound literal and never a + * dropped condition. + */ +describe('dataset executor — {record_id} refuses by name before any SQL', () => { + async function refusal(run: (svc: AnalyticsService) => Promise) { + const captured: { sql: string; params: unknown[] }[] = []; + const err = await run(service(captured)).catch((e: unknown) => e); + expect(err).toBeInstanceOf(Error); + expect((err as { code?: string }).code).toBe('FILTER_TOKEN_UNRESOLVED'); + expect((err as { status?: number }).status).toBe(400); + expect((err as { token?: string }).token).toBe('record_id'); + expect(captured).toHaveLength(0); + } + + it('in a widget runtimeFilter', async () => { + await refusal((svc) => + svc.queryDataset( + dataset, + { dimensions: ['stage'], measures: ['revenue'], runtimeFilter: { owner: '{record_id}' } }, + CTX, + ), + ); + }); + + it("in the dataset's own intrinsic filter", async () => { + const scoped = DatasetSchema.parse({ ...dataset, name: 'record_pipeline', filter: { account: '{record_id}' } }); + await refusal((svc) => svc.queryDataset(scoped, { dimensions: ['stage'], measures: ['revenue'] }, CTX)); + }); + + it('in a measure-scoped filter', async () => { + const scoped = DatasetSchema.parse({ + ...dataset, + name: 'record_revenue', + measures: [{ name: 'record_revenue', aggregate: 'sum', field: 'amount', filter: { account: '{record_id}' } }], + }); + await refusal((svc) => svc.queryDataset(scoped, { dimensions: ['stage'], measures: ['record_revenue'] }, CTX)); + }); + + it('lit control — {current_user_id} in the same position still binds the viewer', async () => { + const captured: { sql: string; params: unknown[] }[] = []; + await service(captured).queryDataset( + dataset, + { dimensions: ['stage'], measures: ['revenue'], runtimeFilter: { owner: '{current_user_id}' } }, + CTX, + ); + expect(captured[0].params).toContain('usr_1'); + }); +}); + describe('dataset filter placeholders (framework#3582)', () => { it('expands a date macro in a widget runtimeFilter into a bound date', async () => { const captured: { sql: string; params: unknown[] }[] = []; diff --git a/packages/services/service-analytics/src/__tests__/query-filter-tokens.test.ts b/packages/services/service-analytics/src/__tests__/query-filter-tokens.test.ts index f20e30b1f6f..0867ffe308f 100644 --- a/packages/services/service-analytics/src/__tests__/query-filter-tokens.test.ts +++ b/packages/services/service-analytics/src/__tests__/query-filter-tokens.test.ts @@ -219,6 +219,21 @@ describe('direct analytics door — unresolvable placeholders refuse loudly (#12 expect(captured).toHaveLength(0); }); + it('the record-context token {record_id} refuses by name — no record is in context on this door', async () => { + // Even for an authenticated caller with a full context: only a record + // page's renderer knows which record is in view. + const captured: { sql: string; params: unknown[] }[] = []; + const err = await sqlCaptureService(captured) + .query(directQuery({ owner: '{record_id}' }), CTX_A) + .catch((e: unknown) => e); + + expect(err).toBeInstanceOf(Error); + expect((err as { code?: string }).code).toBe('FILTER_TOKEN_UNRESOLVED'); + expect((err as { status?: number }).status).toBe(400); + expect((err as { token?: string }).token).toBe('record_id'); + expect(captured).toHaveLength(0); + }); + it('generateSql refuses identically — the dry run answers what the real run would', async () => { const err = await sqlCaptureService([]) .generateSql(directQuery({ owner: '{current_user}' }), CTX_A) diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index 797535f1c88..512c6e38e80 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -528,6 +528,7 @@ "QueryWithTransportSchema (const)", "RAW_FILE_VALUES_CONTEXT_KEY (const)", "READ_ONLY_BELONGS_ON_DATASOURCE (const)", + "RECORD_CONTEXT_TOKENS (const)", "RECORD_SURFACE_PAGE_THRESHOLD (const)", "REFERENCE_VALUE_TYPES (const)", "RETIRED_FILTER_OPERATORS (const)", @@ -535,6 +536,7 @@ "RPC_QUERY_ALIAS_SLOTS (const)", "RUNTIME_OWNED_FIELD_TYPES (const)", "RangeOperatorSchema (const)", + "RecordContextToken (type)", "RecordFlow (type)", "RecordFlowContainer (type)", "RecordFlowSurface (interface)", @@ -790,6 +792,7 @@ "isOrganizationUnique (function)", "isPlainRecord (function)", "isPublicSharingEnabled (function)", + "isRecordContextToken (function)", "isRefusedTextComparand (function)", "isRuntimeDefaultToken (function)", "isTenancyDisabled (function)", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index 172c24774b8..4001342557d 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -517,6 +517,7 @@ "QueryWithTransportSchema": "src/data/data-engine.zod.ts#QueryWithTransportSchema (const)", "RAW_FILE_VALUES_CONTEXT_KEY": "src/data/field-value.zod.ts#RAW_FILE_VALUES_CONTEXT_KEY (const)", "READ_ONLY_BELONGS_ON_DATASOURCE": "src/data/driver/common.zod.ts#READ_ONLY_BELONGS_ON_DATASOURCE (const)", + "RECORD_CONTEXT_TOKENS": "src/data/context-tokens.zod.ts#RECORD_CONTEXT_TOKENS (const)", "RECORD_SURFACE_PAGE_THRESHOLD": "src/data/record-surface.ts#RECORD_SURFACE_PAGE_THRESHOLD (const)", "REFERENCE_VALUE_TYPES": "src/data/field-value.zod.ts#REFERENCE_VALUE_TYPES (const)", "RETIRED_FILTER_OPERATORS": "src/data/filter.zod.ts#RETIRED_FILTER_OPERATORS (const)", @@ -524,6 +525,7 @@ "RPC_QUERY_ALIAS_SLOTS": "src/data/data-engine.zod.ts#RPC_QUERY_ALIAS_SLOTS (const)", "RUNTIME_OWNED_FIELD_TYPES": "src/data/field.zod.ts#RUNTIME_OWNED_FIELD_TYPES (const)", "RangeOperatorSchema": "src/data/filter.zod.ts#RangeOperatorSchema (const)", + "RecordContextToken": "src/data/context-tokens.zod.ts#RecordContextToken (type)", "RecordFlow": "src/data/record-surface.ts#RecordFlow (type)", "RecordFlowContainer": "src/data/record-surface.ts#RecordFlowContainer (type)", "RecordFlowSurface": "src/data/record-surface.ts#RecordFlowSurface (interface)", @@ -777,6 +779,7 @@ "isOrganizationUnique": "src/data/field.zod.ts#isOrganizationUnique (function)", "isPlainRecord": "src/data/authoring-key-lint.ts#isPlainRecord (function)", "isPublicSharingEnabled": "src/data/object.zod.ts#isPublicSharingEnabled (function)", + "isRecordContextToken": "src/data/context-tokens.zod.ts#isRecordContextToken (function)", "isRefusedTextComparand": "src/data/filter-text-comparand.ts#isRefusedTextComparand (function)", "isRuntimeDefaultToken": "src/data/default-value-tokens.ts#isRuntimeDefaultToken (function)", "isTenancyDisabled": "src/data/object.zod.ts#isTenancyDisabled (function)", diff --git a/packages/spec/src/data/context-tokens.test.ts b/packages/spec/src/data/context-tokens.test.ts index c272f0b3e81..5a37b76e88c 100644 --- a/packages/spec/src/data/context-tokens.test.ts +++ b/packages/spec/src/data/context-tokens.test.ts @@ -7,9 +7,11 @@ import { CONTEXT_TOKEN_SUGGESTIONS, ContextTokenPlaceholderSchema, ContextTokenSchema, + RECORD_CONTEXT_TOKENS, classifyFilterToken, isContextToken, isKnownFilterToken, + isRecordContextToken, } from './context-tokens.zod'; describe('context token contract', () => { @@ -110,13 +112,71 @@ describe('classifyFilterToken', () => { it('every suggestion resolves to a real token', () => { for (const [from, to] of Object.entries(CONTEXT_TOKEN_SUGGESTIONS)) { - expect(isContextToken(to), `${from} → ${to}`).toBe(true); + expect(isContextToken(to) || isRecordContextToken(to), `${from} → ${to}`).toBe(true); // A suggestion key must itself be invalid, or the mapping is incoherent. expect(isKnownFilterToken(from), from).toBe(false); + expect(classifyFilterToken(`{${from}}`)?.kind, from).toBe('unknown'); } }); }); +/** + * `{record_id}` — the record-scoped sibling vocabulary. + * + * It resolves against the SURFACE (the record a `type: 'record'` page shows), + * not the session, so it is its own list and its own classification kind: a + * caller with no record in context refuses it by name instead of calling it + * unknown, and a caller that resolves the session list never picks it up. + */ +describe('classifyFilterToken — the record-context token', () => { + it('recognises {record_id} and ${record_id} by name', () => { + expect(classifyFilterToken('{record_id}')).toEqual({ kind: 'record-context', token: 'record_id' }); + expect(classifyFilterToken('${record_id}')).toEqual({ kind: 'record-context', token: 'record_id' }); + }); + + it('is its own list, not a session context token', () => { + expect(RECORD_CONTEXT_TOKENS).toEqual(['record_id']); + expect(isRecordContextToken('record_id')).toBe(true); + // The session list's consumers (the client resolver, `ContextTokenSchema`, + // the placeholder schema) must not start treating it as a session value. + expect(isContextToken('record_id')).toBe(false); + expect((CONTEXT_TOKENS as readonly string[]).includes('record_id')).toBe(false); + expect(ContextTokenSchema.safeParse('record_id').success).toBe(false); + expect(ContextTokenPlaceholderSchema.safeParse('{record_id}').success).toBe(false); + }); + + it('is not server-resolvable, so the flow hand-off predicate excludes it', () => { + expect(isKnownFilterToken('record_id')).toBe(false); + }); + + it('lit control — the session tokens classify exactly as before', () => { + expect(classifyFilterToken('{current_user_id}')).toEqual({ kind: 'context', token: 'current_user_id' }); + expect(classifyFilterToken('{current_org_id}')).toEqual({ kind: 'context', token: 'current_org_id' }); + expect(isRecordContextToken('current_user_id')).toBe(false); + }); + + // Each near miss is a spelling that is right somewhere else: `{recordId}` is + // the URL / flow-template placeholder, `{record.id}` the flow dialect's + // trigger-record path. + it.each([ + ['{recordid}', 'recordid'], + ['{recordId}', 'recordId'], + ['{record-id}', 'record-id'], + ['{record.id}', 'record.id'], + ['{current_record_id}', 'current_record_id'], + ])('%s is still refused as unknown, with {record_id} suggested', (value, token) => { + expect(classifyFilterToken(value)).toEqual({ kind: 'unknown', token, suggestion: 'record_id' }); + }); + + it('the padded spelling is refused, not trimmed', () => { + expect(classifyFilterToken('{ record_id }')).toEqual({ + kind: 'unknown', + token: ' record_id ', + suggestion: undefined, + }); + }); +}); + /** * #5586 — recognition is placeholder-by-INTENT, not by well-formed token name. * diff --git a/packages/spec/src/data/context-tokens.zod.ts b/packages/spec/src/data/context-tokens.zod.ts index 1a17912b941..f3be2a0764b 100644 --- a/packages/spec/src/data/context-tokens.zod.ts +++ b/packages/spec/src/data/context-tokens.zod.ts @@ -5,7 +5,18 @@ import { DATE_MACRO_WRAPPED_RE, isDateMacroToken } from './date-macros.zod.js'; /** * Context Tokens — the declarative placeholders that resolve against the - * **caller's session** (who am I, which org am I in) rather than the clock. + * **caller's session** (who am I, which org am I in) rather than the clock, + * plus one sibling that resolves against the **surface**: `{record_id}`, the + * record a `type: 'record'` page is showing. + * + * The two resolve against different things, so they are two lists, never one: + * + * | | `CONTEXT_TOKENS` | `RECORD_CONTEXT_TOKENS` | + * |---|---|---| + * | Tokens | `{current_user_id}`, `{current_org_id}` | `{record_id}` | + * | Resolves against | the caller's session | the record the page is bound to | + * | Known on the server | yes — `ExecutionContext` | never — only the page renderer knows which record is in view | + * | Valid on | every filter surface | a component on a `type: 'record'` page, and nowhere else | * * # Why this lives in `spec` * @@ -35,11 +46,24 @@ import { DATE_MACRO_WRAPPED_RE, isDateMacroToken } from './date-macros.zod.js'; * degrades to `IS NULL` on most drivers and would hand back the rows * the filter was written to exclude. * + * `{record_id}` is resolved on ONE side of the wire only: by the page + * renderer, which substitutes the id of the record a `type: 'record'` page + * is showing before the filter leaves the browser. The server never knows + * which record a page is showing, so a filter that reaches + * `resolveFilterTokens()` still carrying `{record_id}` is refused by name + * (`FILTER_TOKEN_UNRESOLVED` / 400) — which is also what an author sees + * from a renderer that does not resolve the token yet. It never becomes + * `null`, `undefined` or the literal string: a number written as "about + * this record" must neither silently become "about everybody" (the + * condition dropped) nor "about nobody" (the token compared as text). + * * # Presentation scope, NOT a security boundary * * This is the single most important thing to understand about these * tokens. `{current_user_id}` scopes what a surface *shows*; it does not - * decide what a caller is *allowed* to read. Enforcement is RLS, which + * decide what a caller is *allowed* to read. `{record_id}` is the same: it + * narrows a record-page component to the record in view, and which of those + * rows the caller may read is still not its decision. Enforcement is RLS, which * uses a different and genuinely server-side vocabulary rooted at * `current_user` (`owner_id = current_user.id`, compiled by * `@objectstack/plugin-security`'s RLS compiler). @@ -59,12 +83,38 @@ import { DATE_MACRO_WRAPPED_RE, isDateMacroToken } from './date-macros.zod.js'; * * # Where the tokens are honoured * - * Filter values on every surface that resolves placeholders — object list - * views, dashboard widgets, reports, SDUI page components. Navigation - * (`recordId` / `params`) additionally resolves `AppContextSelector` ids - * such as `{active_package}`; those are nav-only and are NOT valid inside - * filter values, because filters are not evaluated with the sidebar's - * selector state. + * `{current_user_id}` and `{current_org_id}`: filter values on every surface + * that resolves placeholders — object list views, dashboard widgets, + * reports, datasets, SDUI page components — and on the server's ObjectQL + * read and write paths and analytics doors. + * + * `{record_id}`: filter values on a component of a `type: 'record'` page, + * and nowhere else. `@objectstack/lint`'s `validate-filter-tokens` refuses it + * by name ("no record in context on this surface") on list views, dashboard + * widgets, reports, datasets, apps, object definitions and every page that is + * not `type: 'record'`. The server refuses it on every path, because no + * server path has a record in context. + * + * Navigation (`recordId` / `params`) additionally resolves + * `AppContextSelector` ids such as `{active_package}`; those are nav-only and + * are NOT valid inside filter values, because filters are not evaluated with + * the sidebar's selector state. + * + * # `{record_id}` is not `{recordId}`, and not the `'record_id'` variable type + * + * Three spellings look alike and are three different mechanisms: + * + * - `{record_id}` — this filter token. A whole filter VALUE, resolved to the + * id of the record the page shows. + * - `{recordId}` — a URL / flow-template placeholder: an action's + * `newTabUrl` (`action.zod.ts`) and the flow template dialect + * (`@objectstack/lint`'s `flow-template-grammar.ts`). It is interpolated by + * those surfaces' own template engines and is NOT a filter token. Written + * inside a filter it is refused, with `{record_id}` suggested. + * - `'record_id'` — a page-variable TYPE (`PageVariableSchema.type` in + * `page.zod.ts`), naming what a page variable holds, e.g. the selection of + * an `element:record_picker`. It is read in expressions as `page.`, + * never written as a placeholder. * * # Out of scope * @@ -72,6 +122,9 @@ import { DATE_MACRO_WRAPPED_RE, isDateMacroToken } from './date-macros.zod.js'; * - `{date-macros}` — the clock-based sibling; see `./date-macros.zod.ts`. * - `titleFormat` field interpolation (`{user_id}` etc.) — that substitutes * *record fields*, an unrelated mechanism that happens to share braces. + * - Tokens for a record OTHER than the one in view (a related record, a + * parent of the record). Each is its own contract with its own resolver, + * not an extension of `{record_id}`. */ /** @@ -96,6 +149,42 @@ export function isContextToken(token: string): boolean { return (CONTEXT_TOKENS as readonly string[]).includes(token); } +/** + * The complete set of RECORD-scoped filter tokens: resolved against the + * SURFACE, meaning the record a `type: 'record'` page is showing, never + * against the caller's session. + * + * `record_id` is the id of that record. On a person's record page, + * `{ assignee: '{record_id}' }` counts that person's tasks. Without it, the + * only filter an author can write counts the whole organisation's, under + * that person's name. + * + * A sibling of {@link CONTEXT_TOKENS}, not a member, because every consumer + * of that list resolves it from the session: the client resolver fills it + * from the signed-in user and org, and the server from `ExecutionContext`. + * Neither knows which record a page is showing. So a record-context token + * resolves only in the page renderer. `resolveFilterTokens()` refuses it by + * name on every server path, and lint refuses it on every surface that is not + * a record page. + * + * Deliberately tiny, for the reason `CONTEXT_TOKENS` is. A token for any + * record other than the one in view (a related record, a parent) is its own + * contract, not an entry here. + */ +export const RECORD_CONTEXT_TOKENS = [ + 'record_id', +] as const; + +export type RecordContextToken = (typeof RECORD_CONTEXT_TOKENS)[number]; + +/** + * Is `token` (without braces) a record-context token, one that resolves only + * where a record is in context? See {@link RECORD_CONTEXT_TOKENS}. + */ +export function isRecordContextToken(token: string): boolean { + return (RECORD_CONTEXT_TOKENS as readonly string[]).includes(token); +} + /** * Match the **wrapped** form a filter author actually writes — * `{current_user_id}` or `${current_user_id}`. Shares the date-macro @@ -191,8 +280,15 @@ export const CONTEXT_TOKEN_DESCRIPTIONS: Record = { * `{user_id}` is valid `titleFormat` field interpolation. Lint quotes the * suggestion so the author is corrected at authoring time, where an AI can * still see and act on it. + * + * The `record_id` rows follow the same rule. `recordid` is `{recordId}` + * lower-cased, and `{recordId}` is the URL / flow-template placeholder + * (`newTabUrl`, the flow template dialect), which is a correct spelling + * somewhere else. `record.id` is the flow template dialect's path to its + * triggering record. `record-id` is the kebab shape #5586 recognised, and + * `current_record_id` is the `current_*` shape the session tokens teach. */ -export const CONTEXT_TOKEN_SUGGESTIONS: Readonly> = { +export const CONTEXT_TOKEN_SUGGESTIONS: Readonly> = { current_user: 'current_user_id', current_user_email: 'current_user_id', user_id: 'current_user_id', @@ -202,6 +298,10 @@ export const CONTEXT_TOKEN_SUGGESTIONS: Readonly> = org_id: 'current_org_id', organization_id: 'current_org_id', current_tenant_id: 'current_org_id', + recordid: 'record_id', + 'record.id': 'record_id', + 'record-id': 'record_id', + current_record_id: 'record_id', }; /** @@ -215,6 +315,16 @@ export const CONTEXT_TOKEN_SUGGESTIONS: Readonly> = * Note this is deliberately narrower than what navigation accepts: * `recordId` / `params` also resolve `AppContextSelector` ids, which are * meaningless in a filter. + * + * It is deliberately narrower than {@link classifyFilterToken} too. The + * record-context tokens ({@link RECORD_CONTEXT_TOKENS}) are NOT members, + * because this predicate answers "can the server resolve it?", and no server + * position has a record in context. Its one consumer is such a position: the + * flow template engine's filter hand-off (`interpolateFilter` in + * `@objectstack/service-automation`) passes a token it cannot resolve on to + * ObjectQL only when this predicate says ObjectQL can. A flow addresses its + * own record as `{record.id}`, so an unset `{record_id}` there stays the flow's + * own unresolved-variable refusal. */ export function isKnownFilterToken(token: string): boolean { return isContextToken(token) || isDateMacroToken(token); @@ -235,25 +345,33 @@ export function isKnownFilterToken(token: string): boolean { * literal string, which is the silent-wrong-rows outcome this classification * exists to prevent. The token reported is the raw text between the braces, so * the caller's error names exactly what the author wrote. + * + * `record-context` is its own kind rather than a `context` token because the + * verdict on it depends on WHERE it is written: it resolves on a record page + * and nowhere else (see {@link RECORD_CONTEXT_TOKENS}). A caller that has no + * record in context refuses it by name, never as `unknown`, because the + * spelling is right and the surface is not. */ export function classifyFilterToken( value: unknown, ): | { kind: 'context'; token: ContextToken } + | { kind: 'record-context'; token: RecordContextToken } | { kind: 'date-macro'; token: string } - | { kind: 'unknown'; token: string; suggestion?: ContextToken } + | { kind: 'unknown'; token: string; suggestion?: ContextToken | RecordContextToken } | null { if (typeof value !== 'string') return null; const m = value.match(FILTER_TOKEN_WRAPPED_RE); if (!m) return null; const token = m[1]; if (isContextToken(token)) return { kind: 'context', token: token as ContextToken }; + if (isRecordContextToken(token)) return { kind: 'record-context', token: token as RecordContextToken }; if (isDateMacroToken(token)) return { kind: 'date-macro', token }; // Own-property guard: the table is a plain object literal, so a bare index // resolves `Object.prototype`'s members for an off-vocabulary token — // `{constructor}` put the `Object` FUNCTION and `{__proto__}` - // `Object.prototype` itself into `suggestion`, whose declared type is - // `ContextToken`. A TypeScript consumer holds a compile-time guarantee that + // `Object.prototype` itself into `suggestion`, whose declared type is a + // token-name union. A TypeScript consumer holds a compile-time guarantee that // is false at runtime, and nothing in the type system will ever flag it. // // The reach is not bounded by the identifier shapes: `FILTER_TOKEN_WRAPPED_RE`