@workbasehq/core 0.2.3 → 0.2.5

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@workbasehq/core",
3
- "version": "0.2.3",
3
+ "version": "0.2.5",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./src/index.ts",
@@ -33,7 +33,8 @@
33
33
  "./organization-permissions": "./src/organization-permissions.ts",
34
34
  "./session-contract": "./src/session-contract.ts",
35
35
  "./infra": "./src/infra/index.ts",
36
- "./infra/provision": "./src/infra/provision.ts"
36
+ "./infra/provision": "./src/infra/provision.ts",
37
+ "./query/expressions": "./src/query/expressions.ts"
37
38
  },
38
39
  "dependencies": {
39
40
  "hono": "4.13.13",
@@ -6,17 +6,19 @@ import { ApiError } from './errors'
6
6
  import type { RuntimeEnv } from './types'
7
7
  export async function accountProvisioning(env: RuntimeEnv, config: InstanceConfig, user: { id: string; email: string }, organizationId: string, role: string, now: string): Promise<SqlStatement[]> {
8
8
  if (config.account?.entity !== 'users') return []
9
- const existing = await env.DB.prepare('SELECT organization_id,role FROM users WHERE id=?').bind(user.id).first<{ organization_id: string; role: string }>()
9
+ const storedRole = !config.entities.users.fields.role?.computed
10
+ const existing = await env.DB.prepare(`SELECT organization_id${storedRole ? ',role' : ''} FROM users WHERE id=?`).bind(user.id).first<{ organization_id: string; role: string }>()
10
11
  if (existing) {
11
12
  // A physical domain account has a single organization. Never move it, or
12
13
  // silently reuse a role from another workspace.
13
14
  if (existing.organization_id !== organizationId) throw new ApiError(409, 'account_already_assigned')
14
- if (existing.role !== role) return [{ sql: 'UPDATE users SET role=?,updated_at=?,version=version+1 WHERE id=? AND organization_id=? AND NOT EXISTS (SELECT 1 FROM memberships WHERE user_id=? AND organization_id=?)', bindings: [role, now, user.id, organizationId, user.id, organizationId] }]
15
+ if (storedRole && existing.role !== role) return [{ sql: 'UPDATE users SET role=?,updated_at=?,version=version+1 WHERE id=? AND organization_id=? AND NOT EXISTS (SELECT 1 FROM memberships WHERE user_id=? AND organization_id=?)', bindings: [role, now, user.id, organizationId, user.id, organizationId] }]
15
16
  return []
16
17
  }
17
18
  const values: Record<string, string | number | null> = { id: user.id, email: user.email, organization_id: organizationId, created_at: now, updated_at: now, role, name: user.email }
19
+ for (const field of Object.keys(values)) if (config.entities.users.fields[field]?.computed) delete values[field]
18
20
  for (const [field, definition] of Object.entries(config.entities.users.fields)) {
19
- if (Object.hasOwn(values, field)) continue
21
+ if (definition.computed || Object.hasOwn(values, field)) continue
20
22
  if (definition.default !== undefined) values[field] = typeof definition.default === 'boolean' ? Number(definition.default) : definition.default
21
23
  else if (definition.required) throw new ApiError(422, 'account_provisioning_required')
22
24
  }
package/src/app.ts CHANGED
@@ -88,7 +88,7 @@ function buildApp(input: InstanceInput, env: RuntimeEnv, options: RuntimeOptions
88
88
  return c.json({ instance: config.id, revision: config.revision, core_version: CORE_VERSION, schema }, schema.compatible ? 200 : 503)
89
89
  })
90
90
  // Public build metadata only: never include runtime bindings, credentials or records.
91
- app.get('/console-info', c => c.json({ instance: config.id, displayName: config.displayName, roles: config.roles, ui: { defaultLanguage: config.ui?.defaultLanguage } }))
91
+ app.get('/console-info', c => c.json({ instance: config.id, displayName: config.displayName, roles: config.roles, locale: config.locale, ui: { defaultLanguage: config.ui?.defaultLanguage } }))
92
92
  app.get('/schema', c => c.json(publicSchema(config, options)))
93
93
  consoleRoutes(app, config, env)
94
94
  for (const path of ['/api/*', '/commands/*', '/workflows/*', '/query', '/orgs', '/orgs/*', '/organizations/*', '/me/profile', '/invitations/*']) app.use(path, jsonCookieCSRF(env))
@@ -9,7 +9,7 @@ type ScalarToken = 'string' | 'text' | 'int' | 'float' | 'bool' | 'datetime'
9
9
  export type FieldShorthand = ScalarToken | `${ScalarToken}!` | `ref:${string}` | `enum:${string}`
10
10
  export type RelationShorthand = `${string}@${string}`
11
11
  export type ShorthandEntity = Omit<EntityInput, 'fields' | 'relations' | 'displayField'> & {
12
- displayField?: string | false
12
+ displayField?: EntityInput['displayField'] | false
13
13
  fields: Record<string, FieldInput | FieldShorthand>
14
14
  relations?: Record<string, RelationInput | RelationShorthand>
15
15
  }
package/src/config.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import { coreEnums, type CoreRole } from './query/enum-values'
2
2
  import { z } from 'zod'
3
3
  import { calendarViewsSchema, validateCalendarViews } from './calendar-display'
4
- import { Q, Fn, Cond, type ISequelizable, type ISerializable } from '@jakub.knejzlik/ts-query'
4
+ import { Q, Fn as LibraryFn, Cond, type ISequelizable, type ISerializable } from '@jakub.knejzlik/ts-query'
5
+ import { DISPLAY_VALUE, isExpression, validateComputedExpressions, expressionError } from './query/expressions'
5
6
  import { validateLabelExpressions } from './query/labels'
6
7
  import type { WorkbasePlugin } from './kernel/plugin'
7
8
  import { resolvePlugins } from './kernel/composition'
@@ -13,12 +14,16 @@ import { detailDisplaySchema, validateDetailDisplay } from './detail-display'
13
14
  import { validateDisplayFields, isDisplayFieldError } from './display-field'
14
15
  export { DisplayFieldError, isDisplayFieldError, displayFieldErrors, suggestedDisplayField, validateDisplayFields } from './display-field'
15
16
 
16
- export { Q, Fn, Cond }
17
+ export { Q, Cond }
18
+ /** SQLite date formatting with column operands; values use the library wire encoding. */
19
+ export const Fn = { ...LibraryFn, strftime: (format: string, date: string) => Q.expr(`FN(${JSON.stringify(['STRFTIME', Q.value(format).serialize(), Q.expr(date).serialize()])})`) }
17
20
 
18
- export const CORE_VERSION = '0.2.3'
21
+ export const CORE_VERSION = '0.2.5'
19
22
  const navigationIconSchema = z.enum(['LayoutDashboard', 'Users', 'MapPin', 'Coins', 'Wallet', 'ArrowLeftRight', 'Settings', 'Building2', 'Activity', 'Workflow', 'Database', 'Folder'])
20
23
  const identifier = z.string().regex(/^[a-z][a-z0-9_]*$/)
24
+ export const serializedExpressionSchema = z.union([z.string().min(1).max(32000), z.record(z.string(), z.unknown()).transform(value => JSON.stringify(value))])
21
25
  export const fieldSchema = z.object({
26
+ computed: serializedExpressionSchema.optional(),
22
27
  type: z.enum(['string', 'text', 'int', 'float', 'bool', 'datetime', 'enum', 'ref']),
23
28
  required: z.boolean().default(false), values: z.array(z.string()).optional(), entity: identifier.optional(),
24
29
  default: z.union([z.string(), z.number(), z.boolean(), z.null()]).optional(),
@@ -93,7 +98,8 @@ const schema = z.object({
93
98
  fields: z.record(identifier, fieldSchema),
94
99
  relations: z.record(identifier, z.object({ field: identifier, entity: identifier, many: z.boolean().optional(), through: z.strictObject({ entity: identifier, field: identifier, createCommand: z.string().min(1), deleteCommand: z.string().min(1) }).optional() })).default({}),
95
100
  commandsOnly: z.boolean().optional(),
96
- displayField: identifier.optional(),
101
+ displayField: serializedExpressionSchema.optional(),
102
+ displayExpression: z.string().optional(),
97
103
  // Trusted server AST. displayField is the projected result key, not a stored label.
98
104
  label: z.union([
99
105
  z.custom<ISequelizable & ISerializable>(value => !!value && typeof (value as ISequelizable).toSQL === 'function' && typeof (value as ISerializable).serialize === 'function'),
@@ -149,6 +155,7 @@ export function defineInstance(input: Omit<ShorthandInput, 'roles' | 'entities'
149
155
  if (Object.keys(entity.fields).length > 90) throw new Error('Entity exceeds the supported field/parameter budget')
150
156
  for (const [key, field] of Object.entries(entity.fields)) {
151
157
  if (name === 'users' && ['email', 'password_hash', 'salt'].includes(key)) throw new Error(`Account identity field is private: ${key}`)
158
+ if (field.computed) field.readOnly = true
152
159
  if (baseFields.includes(key)) throw new Error(`Reserved field: ${key}`)
153
160
  if (field.min !== undefined && !['int', 'float'].includes(field.type)) throw new Error('min requires a numeric field')
154
161
  if (field.default !== undefined && field.default !== null) {
@@ -165,7 +172,7 @@ export function defineInstance(input: Omit<ShorthandInput, 'roles' | 'entities'
165
172
  if (field.type === 'ref' && !Object.hasOwn(config.entities, field.entity!)) throw new Error(`Unknown reference: ${field.entity}`)
166
173
  if (field.backfillFrom) {
167
174
  const ref = entity.fields[field.backfillFrom.refField]
168
- if (!ref?.entity || !config.entities[ref.entity]?.fields[field.backfillFrom.valueField]) throw new Error('Invalid backfill reference')
175
+ if (!ref?.entity || ref.computed || !config.entities[ref.entity]?.fields[field.backfillFrom.valueField] || config.entities[ref.entity].fields[field.backfillFrom.valueField].computed) throw new Error('Invalid backfill reference')
169
176
  }
170
177
  }
171
178
  for (const [relationName, r] of Object.entries(entity.relations)) {
@@ -181,7 +188,7 @@ export function defineInstance(input: Omit<ShorthandInput, 'roles' | 'entities'
181
188
  if (!inverse) throw new Error(`Missing inverse pure join relation on ${name}`)
182
189
  }
183
190
  }
184
- for (const c of entity.checks) if (!entity.fields[c.left] || !entity.fields[c.right]) throw new Error('Unknown check field')
191
+ for (const c of entity.checks) if (!entity.fields[c.left] || !entity.fields[c.right] || entity.fields[c.left].computed || entity.fields[c.right].computed) throw new Error('Unknown check field')
185
192
  }
186
193
  for (const [role, grants] of Object.entries(config.permissions)) {
187
194
  if (!config.roles.includes(role as any)) throw new Error(`Unknown role ${role}`)
@@ -199,6 +206,16 @@ export function defineInstance(input: Omit<ShorthandInput, 'roles' | 'entities'
199
206
  for (const [name, entity] of Object.entries(config.entities)) {
200
207
  if (!entity.displayField && input.entities?.[name]?.displayField !== false) entity.displayField = ['name', 'title'].find(field => entity.fields[field])
201
208
  }
209
+ for (const [name, entity] of Object.entries(config.entities)) {
210
+ const expression = entity.displayExpression ?? (entity.displayField && isExpression(entity.displayField) ? entity.displayField : undefined)
211
+ if (expression) {
212
+ if (entity.fields[DISPLAY_VALUE] && !entity.displayExpression) expressionError(name, DISPLAY_VALUE, 'Reserved generated display field', 'Rename computed_display before assigning a display expression.')
213
+ entity.displayExpression = expression
214
+ entity.displayField = DISPLAY_VALUE
215
+ entity.fields[DISPLAY_VALUE] = { type: 'string', required: false, readOnly: true, computed: expression }
216
+ }
217
+ }
218
+ validateComputedExpressions(config)
202
219
  // Presentation hints are validated at load; readable capabilities further narrow them at runtime.
203
220
  const navigation = config.ui?.navigation
204
221
  if (navigation) {
@@ -265,7 +282,7 @@ export function inspectInstance(input: Parameters<typeof defineInstance>[0]) {
265
282
  export function bodyValidator(entity: InstanceConfig['entities'][string], partial = false) {
266
283
  const shape: Record<string, z.ZodType> = {}
267
284
  for (const [name, f] of Object.entries(entity.fields)) {
268
- if (f.readOnly) continue
285
+ if (f.readOnly || f.computed) continue
269
286
  let v: z.ZodType
270
287
  switch (f.type) {
271
288
  case 'int': v = z.number().int().min(f.min ?? Number.MIN_SAFE_INTEGER); break
@@ -299,5 +316,6 @@ export function cloneInstanceConfig(config: InstanceConfig): InstanceConfig {
299
316
  export function serializableInstanceConfig(config: InstanceConfig) {
300
317
  return { ...config, entities: Object.fromEntries(Object.entries(config.entities).map(([name, entity]) => [name, {
301
318
  ...entity, ...(entity.label ? { label: entity.label.serialize() } : {}),
319
+ ...(entity.displayExpression ? { displayField: entity.displayExpression, displayExpression: undefined, fields: Object.fromEntries(Object.entries(entity.fields).filter(([field]) => field !== DISPLAY_VALUE)) } : {}),
302
320
  }])) }
303
321
  }
@@ -1,3 +1,4 @@
1
+ import { readableComputed } from './query/expressions'
1
2
  import type { KernelRegistry } from './kernel/registry'
2
3
  import type { Scope } from './types'
3
4
  import type { ConsoleGrant, ConsoleModelCapabilities } from './console-contract'
@@ -22,7 +23,7 @@ export function consoleAuthorization(kernel: KernelRegistry, scope: Scope, caps:
22
23
  return spec?.type !== 'ref' || !!spec.entity && canRead(spec.entity)
23
24
  }
24
25
  function read(entity: string, field: string): boolean {
25
- if (!readableField(entity, field)) return false
26
+ if (!readableField(entity, field) || !readableComputed(kernel, scope, entity, field)) return false
26
27
  const spec = config.entities[entity]
27
28
  return field !== spec.displayField || !spec.label || labelDependencies(config, entity).every(dependency => readableField(dependency.entity, dependency.field))
28
29
  }
@@ -70,7 +70,7 @@ export function consoleModel(kernel: KernelRegistry, scope: Scope): ConsoleModel
70
70
  checks: entity.checks.filter(check => authority.read(name, check.left) && authority.read(name, check.right)),
71
71
  indexes: [
72
72
  { name: `${name}_org_idx`, fields: ['organization_id', 'id'], unique: false },
73
- ...Object.entries(entity.fields).filter(([, field]) => field.type === 'ref').map(([field]) => ({
73
+ ...Object.entries(entity.fields).filter(([, field]) => field.type === 'ref' && !field.computed).map(([field]) => ({
74
74
  name: `${name}_${field}_idx`, fields: ['organization_id', field], unique: false,
75
75
  })),
76
76
  ].filter(index => index.fields.every(field => authority.read(name, field))),
@@ -85,14 +85,24 @@ export function consoleModel(kernel: KernelRegistry, scope: Scope): ConsoleModel
85
85
  instance: config.id, revision: config.revision,
86
86
  ...(config.displayName ? { displayName: config.displayName } : {}),
87
87
  locale: config.locale, timeZone: config.timeZone,
88
- ...(config.enumLabels ? { enumLabels: Object.fromEntries(Object.entries(config.enumLabels).flatMap(([language, labels]) => {
88
+ ...(config.enumLabels || Object.values(config.entities).some(entity => entity.displayExpression) ? { enumLabels: Object.fromEntries([...new Set(['en', 'cs', ...Object.keys(config.enumLabels ?? {})])].flatMap(language => {
89
+ const labels = config.enumLabels?.[language] ?? {}
89
90
  // Catalogs use language -> translation key, matching query search and i18next.
90
91
  const keys = new Set(Object.entries(config.entities).flatMap(([name, entity]) => Object.entries(entity.fields)
91
92
  .filter(([field]) => authority.literals(name, field)).flatMap(([, field]) => {
92
93
  const values = field.type === 'enum' ? (field.values ?? []).map(value => `value_${value}`) : field.type === 'bool' ? ['yes', 'no'] : []
93
94
  return values.flatMap(key => [key, `${key}_${name}`])
94
95
  })))
96
+ for (const [name, entity] of Object.entries(config.entities)) {
97
+ if (authority.canRead(name)) for (const prefix of ['entity', 'entitySingular', 'entityObject']) keys.add(`${prefix}_${name}`)
98
+ for (const field of Object.keys(entity.fields)) if (authority.literals(name, field)) keys.add(`field_${field}_${name}`)
99
+ }
95
100
  const dictionary = Object.fromEntries(Object.entries(labels).filter(([key]) => keys.has(key)))
101
+ for (const [name, entity] of Object.entries(config.entities)) if (entity.displayExpression && entity.displayField && authority.read(name, entity.displayField)) {
102
+ const title = labels[`entitySingular_${name}`] ?? labels[`entity_${name}`] ?? name.replaceAll('_', ' ').replace(/^./, first => first.toUpperCase())
103
+ dictionary[`field_${entity.displayField}_${name}`] = title
104
+ dictionary[`listField_${entity.displayField}_${name}`] = title
105
+ }
96
106
  return Object.keys(dictionary).length ? [[language, dictionary]] : []
97
107
  })) } : {}),
98
108
  ...(config.ui ? { ui: presentation.modelUI(config.ui) } : {}),
package/src/crud.ts CHANGED
@@ -27,7 +27,7 @@ export function serialize(config: InstanceConfig, name: string, row: Row) {
27
27
  }
28
28
  export function crudRoutes(app: App, config: InstanceConfig, env: RuntimeEnv) {
29
29
  const kernel = kernelFor(config)
30
- const storedFields = (name: string) => fieldsFor(config, name).filter(field => !config.entities[name].label || field !== config.entities[name].displayField)
30
+ const storedFields = (name: string) => fieldsFor(config, name).filter(field => !config.entities[name].fields[field]?.computed).filter(field => !config.entities[name].label || field !== config.entities[name].displayField)
31
31
  const responseRow = async (name: string, scope: Scope, row: Row) => {
32
32
  const readable = new Set(kernel.fieldMask(name, scope))
33
33
  const result = Object.fromEntries(Object.entries(serialize(config, name, row)).filter(([field]) => readable.has(field)))
@@ -104,7 +104,7 @@ export function crudRoutes(app: App, config: InstanceConfig, env: RuntimeEnv) {
104
104
  if (prior) return c.json(await responseRow(name, scope, prior), 201)
105
105
  const now = new Date().toISOString()
106
106
  const row: Row = { id: crypto.randomUUID(), organization_id: scope.organizationId, created_at: now, updated_at: now, version: 1 }
107
- for (const [key, f] of Object.entries(definition.fields)) if (!definition.label || key !== definition.displayField) row[key] = Object.hasOwn(body, key) ? body[key] : f.default ?? null
107
+ for (const [key, f] of Object.entries(definition.fields)) if (!f.computed && (!definition.label || key !== definition.displayField)) row[key] = Object.hasOwn(body, key) ? body[key] : f.default ?? null
108
108
  const keys = Object.keys(row)
109
109
  assertActorFields(config, scope, name, Object.keys(body))
110
110
  try { await mutate(name, scope, { sql: `INSERT INTO ${table} (${keys.map(quote).join(',')}) VALUES (${keys.map(() => '?').join(',')})`, bindings: keys.map(k => typeof row[k] === 'boolean' ? Number(row[k]) : row[k]) }, makeEvent(config, scope, `${name}.created`, name, row.id, {}, row), [
@@ -5,7 +5,7 @@ import { quote } from '../migrations/schema'
5
5
  export async function checkInstanceSchema(db: D1Database, config: Pick<InstanceConfig, 'entities'>, dependencies: Record<string, readonly string[]>) {
6
6
  const tables = new Set([...Object.keys(config.entities), ...Object.keys(dependencies)])
7
7
  for (const table of tables) {
8
- const fields = new Set([...baseFields, ...Object.keys(config.entities[table]?.fields ?? {}), ...(dependencies[table] ?? [])])
8
+ const fields = new Set([...baseFields, ...Object.entries(config.entities[table]?.fields ?? {}).filter(([, field]) => !field.computed).map(([name]) => name), ...(dependencies[table] ?? [])])
9
9
  // Qualify identifiers so SQLite cannot treat an absent quoted column as a string.
10
10
  const columns = [...fields].map(field => `${quote(table)}.${quote(field)}`).join(',')
11
11
  await db.prepare(`SELECT ${columns} FROM ${quote(table)} LIMIT 0`).all()
@@ -31,6 +31,11 @@ export function plan(fromConfig: InstanceConfig | null, toConfig: InstanceConfig
31
31
  const next = to.entities[name]
32
32
  const renamed = new Set<string>()
33
33
  for (const [key, field] of Object.entries(next.fields)) {
34
+ if (field.computed) {
35
+ if (previous.fields[key] && !previous.fields[key].computed) blocked.push(`Converting stored field to computed requires a new field name: ${name}.${key}`)
36
+ continue
37
+ }
38
+ if (previous.fields[key]?.computed) { blocked.push(`Converting computed field to stored requires a new field name: ${name}.${key}`); continue }
34
39
  if (field.renameFrom && field.renameFrom !== key && previous.fields[key] && previous.fields[field.renameFrom]) { blocked.push(`Rename target already exists: ${name}.${key}`); continue }
35
40
  const oldKey = field.renameFrom && !previous.fields[key] ? field.renameFrom : key
36
41
  const old = previous.fields[oldKey]
@@ -62,7 +67,7 @@ export function plan(fromConfig: InstanceConfig | null, toConfig: InstanceConfig
62
67
  }
63
68
  }
64
69
  for (const [key, field] of Object.entries(previous.fields)) {
65
- if (next.fields[key] || renamed.has(key)) continue
70
+ if (field.computed || next.fields[key] || renamed.has(key)) continue
66
71
  destructive.push(`DROP COLUMN ${name}.${key}`)
67
72
  if (field.type === 'ref' || previous.checks.some(c => c.left === key || c.right === key)) blocked.push(`Constraint-bearing column removal requires a manually reviewed migration: ${name}.${key}`)
68
73
  else if (options.allowDestructive) sql.push(`ALTER TABLE ${quote(name)} DROP COLUMN ${quote(key)};`)
@@ -23,11 +23,11 @@ export function createEntity(name: string, entity: InstanceConfig['entities'][st
23
23
  const columns = [
24
24
  'id TEXT PRIMARY KEY', 'organization_id TEXT NOT NULL REFERENCES organizations(id)',
25
25
  'created_at TEXT NOT NULL', 'updated_at TEXT NOT NULL', 'version INTEGER NOT NULL DEFAULT 1',
26
- ...Object.entries(entity.fields).map(([k, f]) => column(k, f)), 'UNIQUE (organization_id, id)',
27
- ...Object.entries(entity.fields).filter(([, f]) => f.type === 'ref').map(([k, f]) => `FOREIGN KEY (organization_id, ${quote(k)}) REFERENCES ${quote(f.entity!)}(organization_id, id)`),
26
+ ...Object.entries(entity.fields).filter(([, f]) => !f.computed).map(([k, f]) => column(k, f)), 'UNIQUE (organization_id, id)',
27
+ ...Object.entries(entity.fields).filter(([, f]) => f.type === 'ref' && !f.computed).map(([k, f]) => `FOREIGN KEY (organization_id, ${quote(k)}) REFERENCES ${quote(f.entity!)}(organization_id, id)`),
28
28
  ...entity.checks.map(c => `CHECK (${quote(c.left)} ${c.op} ${quote(c.right)})`),
29
29
  ]
30
- return `CREATE TABLE ${quote(name)} (\n ${columns.join(',\n ')}\n);\nCREATE INDEX ${quote(`${name}_org_idx`)} ON ${quote(name)}(organization_id, id);\n` + Object.entries(entity.fields).filter(([, f]) => f.type === 'ref').map(([k]) => `CREATE INDEX ${quote(`${name}_${k}_idx`)} ON ${quote(name)}(organization_id, ${quote(k)});`).join('\n')
30
+ return `CREATE TABLE ${quote(name)} (\n ${columns.join(',\n ')}\n);\nCREATE INDEX ${quote(`${name}_org_idx`)} ON ${quote(name)}(organization_id, id);\n` + Object.entries(entity.fields).filter(([, f]) => f.type === 'ref' && !f.computed).map(([k]) => `CREATE INDEX ${quote(`${name}_${k}_idx`)} ON ${quote(name)}(organization_id, ${quote(k)});`).join('\n')
31
31
  }
32
32
  export const systemSchema = `
33
33
  CREATE TABLE atomic_assert (run_id TEXT NOT NULL, rule TEXT NOT NULL, step INTEGER NOT NULL DEFAULT 0, ok INTEGER NOT NULL CHECK (ok = 1), policy_ok INTEGER NOT NULL DEFAULT 1 CHECK (policy_ok = 1), actor_ok INTEGER NOT NULL DEFAULT 1 CHECK (actor_ok = 1), PRIMARY KEY (run_id, step)) WITHOUT ROWID;
package/src/policies.ts CHANGED
@@ -13,7 +13,7 @@ export interface ActorMembership { user_id: string; organization_id: string; rol
13
13
  const projections = new WeakMap<Scope, Readonly<ActorRow>>()
14
14
  const protectedByConfig = new WeakMap<InstanceConfig, ReadonlySet<string>>()
15
15
  export function actorFields(config: InstanceConfig): Record<string, Field['type']> {
16
- return { ...Object.fromEntries(config.account ? fieldsFor(config, config.account.entity).map(name => [name, fieldType(config, config.account!.entity, name)]) : []), id: 'string', role: 'string', organization_id: 'string' }
16
+ return { ...Object.fromEntries(config.account ? fieldsFor(config, config.account.entity).filter(name => !config.entities[config.account!.entity].fields[name]?.computed).map(name => [name, fieldType(config, config.account!.entity, name)]) : []), id: 'string', role: 'string', organization_id: 'string' }
17
17
  }
18
18
  export function validatePolicies(config: InstanceConfig) {
19
19
  const fields = actorFields(config); const protectedFields = new Set<string>(config.account?.assignments ?? [])
@@ -30,12 +30,26 @@ export function validatePolicies(config: InstanceConfig) {
30
30
  protectedFields.add(name)
31
31
  } else if (value && typeof value === 'object') Object.values(value).forEach(child => visit(child, depth + 1))
32
32
  }
33
+ function storedPolicyFields(entity: string, where: Record<string, unknown>): void {
34
+ for (const [field, operand] of Object.entries(where)) {
35
+ if (field === 'and' || field === 'or') { if (Array.isArray(operand)) operand.forEach(child => storedPolicyFields(entity, child)); continue }
36
+ if (field === 'not') { if (operand && typeof operand === 'object') storedPolicyFields(entity, operand as Record<string, unknown>); continue }
37
+ const relation = config.entities[entity].relations[field]
38
+ if (relation && operand && typeof operand === 'object') {
39
+ const source = relation.many ? relation.entity : entity
40
+ if (config.entities[source].fields[relation.field]?.computed) throw new Error(`Row policy cannot traverse computed ref: ${source}.${relation.field}. Fix: use a stored ref to establish row access.`)
41
+ const child = relation.many ? Object.values(operand)[0] : operand
42
+ if (child && typeof child === 'object') storedPolicyFields(relation.entity, child as Record<string, unknown>)
43
+ } else if (config.entities[entity].fields[field]?.computed) throw new Error(`Row policy cannot depend on computed field: ${entity}.${field}. Fix: use stored fields to establish row access before computing values.`)
44
+ }
45
+ }
33
46
  for (const [entity, roles] of Object.entries(config.policies)) {
34
47
  if (!Object.hasOwn(config.entities, entity)) throw new Error(`Unknown policy entity: ${entity}`)
35
48
  for (const [role, policy] of Object.entries(roles)) {
36
49
  if (!config.roles.includes(role)) throw new Error(`Unknown policy role: ${role}`)
37
50
  if (typeof policy === 'string') continue
38
51
  visit(policy.where)
52
+ storedPolicyFields(entity, policy.where)
39
53
  // Validate references separately: a string operand must not accept an unknown actor name as a literal.
40
54
  filterSchema(config, false, 4, actorValue)(entity, 0).parse(policy.where)
41
55
  if (policy.fields?.some(field => !fieldsFor(config, entity).includes(field))) throw new Error(`Unknown policy field: ${entity}`)
@@ -61,7 +75,7 @@ export async function loadActorProjection(config: InstanceConfig, scope: Scope,
61
75
  const member = scope.actor.type === 'user' && membership?.user_id === accountId && membership.organization_id === scope.organizationId
62
76
  ? membership : await first<ActorMembership>('SELECT * FROM memberships WHERE user_id=? AND organization_id=?', [accountId, scope.organizationId])
63
77
  if (!member) return
64
- const extension = config.account ? await first<ActorRow>(`SELECT ${fieldsFor(config, config.account.entity).map(quote).join(',')} FROM ${quote(config.account.entity)} WHERE id=? AND organization_id=?`, [accountId, scope.organizationId]) : {}
78
+ const extension = config.account ? await first<ActorRow>(`SELECT ${fieldsFor(config, config.account.entity).filter(name => !config.entities[config.account!.entity].fields[name]?.computed).map(quote).join(',')} FROM ${quote(config.account.entity)} WHERE id=? AND organization_id=?`, [accountId, scope.organizationId]) : {}
65
79
  if (!extension) return // Unmapped accounts are deny-all, even for a named membership role.
66
80
  const row: ActorRow = { ...extension, id: accountId, role: member.role, organization_id: scope.organizationId }
67
81
  for (const [field, definition] of Object.entries(config.account ? config.entities[config.account.entity].fields : {})) if (definition.type === 'bool' && row[field] !== null) row[field] = Boolean(row[field])
@@ -1,3 +1,5 @@
1
+ import { DisplayPartsExpression, needsDisplayParts, partsAlias } from './display-parts'
2
+ import { expressionInfo, readableComputed, rebindExpression, type ExpressionInfo } from './expressions'
1
3
  import { ApiError } from '../errors'
2
4
  import { Q, Fn, Cond, Condition, toSQLWithBindings, type ISQLFlavor, type SelectQuery, type ISequelizable } from '@jakub.knejzlik/ts-query'
3
5
  import { renderPredicate, type KernelRegistry } from '../kernel/registry'
@@ -62,12 +64,19 @@ function compactBindings(statement: Statement): Statement {
62
64
  })
63
65
  return { sql, bindings }
64
66
  }
65
- const numberedSQLite: ISQLFlavor = Object.assign(Object.create(Q.flavors.sqlite), { parameterPlaceholder: (index: number) => `?${index}` })
67
+ // YEAR/MONTH are numeric in schema validation and cursor keys. SQLite strftime is text.
68
+ const numberedSQLite: ISQLFlavor = Object.assign(Object.create(Q.flavors.sqlite), {
69
+ parameterPlaceholder: (index: number) => `?${index}`,
70
+ escapeFunction(this: ISQLFlavor, ...args: Parameters<ISQLFlavor['escapeFunction']>) {
71
+ const sql = Q.flavors.sqlite.escapeFunction.apply(this, args)
72
+ return ['YEAR', 'MONTH'].includes(args[0].name) ? `CAST(${sql} AS INTEGER)` : sql
73
+ },
74
+ })
66
75
  /** One visibility check per readable FK in the scoped source, shared by all uses. */
67
76
  class ForeignKeyValue extends Condition {
68
- constructor(private column: string, private visible: Condition) { super() }
77
+ constructor(private column: string | ISequelizable, private visible: Condition) { super() }
69
78
  toSQL(flavor: ISQLFlavor) {
70
- return `CASE WHEN ${this.visible.toSQL(flavor)} THEN ${flavor.escapeColumn(this.column)} ELSE NULL END`
79
+ return `CASE WHEN ${this.visible.toSQL(flavor)} THEN ${typeof this.column === 'string' ? flavor.escapeColumn(this.column) : this.column.toSQL(flavor)} ELSE NULL END`
71
80
  }
72
81
  }
73
82
  /** Rebind trusted expression column operands to scoped source/join aliases. */
@@ -90,6 +99,15 @@ class DisplayExpression extends Condition {
90
99
  return this.visible.length ? `CASE WHEN ${Cond.and(this.visible).toSQL(flavor)} THEN ${sql} ELSE NULL END` : sql
91
100
  }
92
101
  }
102
+ /** Validated config ASTs use the same scoped source transformation as every read. */
103
+ class ComputedExpression extends Condition {
104
+ constructor(private info: ExpressionInfo, private columns: Map<string, string | Condition>, private visible: Condition[], private source: (entity: string) => SelectQuery) { super() }
105
+ toSQL(flavor: ISQLFlavor) {
106
+ const rendered = rebindExpression(this.info.ast, this.columns).toSQL(flavor, { transformTable: this.source })
107
+ const sql = this.info.scalarQuery ? `(${rendered})` : rendered
108
+ return this.visible.length ? `CASE WHEN ${Cond.and(this.visible).toSQL(flavor)} THEN ${sql} ELSE NULL END` : sql
109
+ }
110
+ }
93
111
  export function queryOrder(node: Selection): Order[] {
94
112
  const order = node.orderBy ?? []
95
113
  return order.some(o => o.field === 'id') ? order : [...order, { field: 'id', dir: 'asc' }]
@@ -126,7 +144,7 @@ function filterCondition(kernel: KernelRegistry, entity: string, alias: string,
126
144
  for (const [op, operand] of Object.entries(v as object)) {
127
145
  // Keep the masked predicate as the visibility residual. A redundant raw seek
128
146
  // is safe only in positive contexts: FALSE versus UNKNOWN matters under NOT.
129
- if (positive && kernel.config.entities[entity].fields[key]?.type === 'ref') {
147
+ if (positive && kernel.config.entities[entity].fields[key]?.type === 'ref' && !kernel.config.entities[entity].fields[key].computed) {
130
148
  if (op === 'eq' && operand !== null) conditions.push(Cond.equal(col(alias, `__raw_${key}`), value(operand)))
131
149
  if (op === 'in' && (operand as Scalar[]).length && !(operand as Scalar[]).includes(null)) conditions.push(new InCondition(col(alias, `__raw_${key}`), operand as Scalar[]))
132
150
  }
@@ -145,7 +163,7 @@ function filterCondition(kernel: KernelRegistry, entity: string, alias: string,
145
163
  function hasRequiredForeignKeySeek(kernel: KernelRegistry, entity: string, filter: Filter): boolean {
146
164
  return Object.entries(filter).some(([field, operand]) => {
147
165
  if (field === 'and') return (operand as Filter[]).some(child => hasRequiredForeignKeySeek(kernel, entity, child))
148
- if (kernel.config.entities[entity].fields[field]?.type !== 'ref') return false
166
+ if (kernel.config.entities[entity].fields[field]?.type !== 'ref' || kernel.config.entities[entity].fields[field].computed) return false
149
167
  const operators = operand as Record<string, unknown>
150
168
  return (Object.hasOwn(operators, 'eq') && operators.eq !== null)
151
169
  || (Array.isArray(operators.in) && operators.in.length > 0 && !operators.in.includes(null))
@@ -167,7 +185,8 @@ export function assertStatement(statement: Statement, cost?: QueryCost) {
167
185
  }
168
186
  export function renderStatement(kernel: KernelRegistry, scope: Scope, ast: SelectQuery, cost?: QueryCost, requiredDisplays?: Set<string>): Statement {
169
187
  let references = 0
170
- function scopedTable(entity: string, extra?: (alias: string) => Condition, maskForeignKeys = true, displayRequired = requiredDisplays?.has(entity) ?? true): SelectQuery {
188
+ function scopedTable(entity: string, extra?: (alias: string) => Condition, maskForeignKeys = true, displayRequired = requiredDisplays?.has(entity) ?? true, computedDemand?: Set<string>): SelectQuery {
189
+ if (!maskForeignKeys) computedDemand = new Set()
171
190
  if (!Object.hasOwn(kernel.config.entities, entity)) throw new QueryError('query_invalid')
172
191
  // Bounds policy recursion too, before a future policy compiler can introduce cycles.
173
192
  if (++references > L.tableReferences) throw new QueryError('query_too_expensive', [], cost)
@@ -187,10 +206,77 @@ export function renderStatement(kernel: KernelRegistry, scope: Scope, ast: Selec
187
206
  }
188
207
  return visible
189
208
  }
209
+ const computed = new Map<string, Condition>()
210
+ const computing = new Set<string>()
211
+ const presentation = new Map<string, Condition>()
212
+ function computedValue(field: string): Condition {
213
+ const previous = computed.get(field); if (previous) return previous
214
+ if (computing.has(field)) throw new QueryError('query_invalid')
215
+ if (!readableComputed(kernel, scope, entity, field)) return new DisplayExpression(Q.value(null), new Map(), [])
216
+ computing.add(field)
217
+ const info = expressionInfo(kernel.config, entity, field, definition.fields[field].computed!)
218
+ const columns = new Map<string, string | Condition>(); const visible: Condition[] = []; const nested = new Map<string, ISequelizable>()
219
+ const paths = new Map<string, string>()
220
+ const demands = new Map<string, Set<string>>()
221
+ for (const dependency of info.dependencies) {
222
+ if (dependency.qualifier && dependency.qualifier !== 'self') continue
223
+ const key = dependency.hops.map(hop => `/${hop.field}`).join('')
224
+ const demand = demands.get(key) ?? new Set<string>(); demand.add(dependency.field); demands.set(key, demand)
225
+ }
226
+ for (const dependency of info.dependencies) {
227
+ // Subquery aliases resolve against their own scoped projections. `self`
228
+ // always denotes this row; no physical source name is ever rebound.
229
+ if (dependency.qualifier && dependency.qualifier !== 'self') continue
230
+ let parent = alias; let key = ''
231
+ for (const hop of dependency.hops) {
232
+ key += `/${hop.field}`
233
+ let target = paths.get(key)
234
+ if (!target) {
235
+ const table = scopedTable(hop.target, undefined, true, true, demands.get(key) ?? new Set())
236
+ target = `computed_join_${references}_${paths.size}`; paths.set(key, target)
237
+ const operand = parent === alias && definition.fields[hop.field]?.computed ? computedValue(hop.field) : col(parent, hop.field)
238
+ query = query.leftJoin(Q.table(table, target), Cond.equal(col(target, 'id'), typeof operand === 'string' ? Q.expr(operand) : operand))
239
+ visible.push(Cond.isNotNull(col(target, 'id')))
240
+ }
241
+ parent = target
242
+ }
243
+ if (parent === alias && definition.fields[dependency.field]?.computed) {
244
+ const operand = computedValue(dependency.field)
245
+ columns.set(dependency.column, operand)
246
+ visible.push(Cond.isNotNull(operand))
247
+ } else if (parent === alias && definition.fields[dependency.field]?.type === 'ref') {
248
+ const allowed = foreignKeyVisible(dependency.field)
249
+ columns.set(dependency.column, new ForeignKeyValue(col(alias, dependency.field), allowed))
250
+ visible.push(Cond.or([Cond.isNull(col(alias, dependency.field)), allowed]))
251
+ } else {
252
+ columns.set(dependency.column, col(parent, dependency.field))
253
+ if (kernel.config.entities[dependency.entity].label && dependency.field === kernel.config.entities[dependency.entity].displayField) visible.push(Cond.equal(col(parent, '__display_visible'), Q.raw('1')))
254
+ if (kernel.config.entities[dependency.entity].fields[dependency.field]?.computed) visible.push(Cond.isNotNull(col(parent, dependency.field)))
255
+ }
256
+ }
257
+ const source = (target: string) => scopedTable(target, undefined, true, true, info.tables.get(target) ?? new Set())
258
+ if (needsDisplayParts(kernel.config, entity, field)) {
259
+ for (const dep of info.dependencies) if ((!dep.qualifier || dep.qualifier === 'self') && needsDisplayParts(kernel.config, dep.entity, dep.field)) {
260
+ if (!dep.hops.length) { computedValue(dep.field); nested.set(dep.column, presentation.get(dep.field)!) }
261
+ else {
262
+ const parent = paths.get(dep.hops.map(hop => `/${hop.field}`).join(''))!
263
+ nested.set(dep.column, Q.expr(col(parent, partsAlias(dep.field))))
264
+ }
265
+ }
266
+ presentation.set(field, new DisplayPartsExpression(info.parts!, columns, nested, source))
267
+ }
268
+ let result: Condition = new ComputedExpression(info, columns, visible, source)
269
+ if (definition.fields[field].type === 'ref') {
270
+ const operand = result
271
+ const allowed = Cond.exists(scopedTable(definition.fields[field].entity!, child => Cond.equal(col(child, 'id'), operand), false))
272
+ result = new ForeignKeyValue(operand, allowed)
273
+ }
274
+ computed.set(field, result); computing.delete(field); return result
275
+ }
190
276
  const joins = new Map<string, string>()
191
277
  let label: Condition | ReturnType<typeof Q.raw> = Q.raw('NULL')
192
278
  const labelVisibility: Condition[] = []
193
- if (maskForeignKeys && displayRequired && definition.label && readableDisplay(kernel, scope, entity)) {
279
+ if (maskForeignKeys && displayRequired && (!computedDemand || computedDemand.has(definition.displayField!)) && definition.label && readableDisplay(kernel, scope, entity)) {
194
280
  const columns = new Map<string, string | Condition>()
195
281
  // A joined source computes its own label only when this expression consumes
196
282
  // it. Passing through an account to its customer does not need account.label.
@@ -207,11 +293,16 @@ export function renderStatement(kernel: KernelRegistry, scope: Scope, ast: Selec
207
293
  if (!target) {
208
294
  const table = scopedTable(hop.target, undefined, true, displayJoins.has(key))
209
295
  target = `expression_join_${references}_${joins.size}`; joins.set(key, target)
210
- query = query.leftJoin(Q.table(table, target), Cond.columnEqual(col(target, 'id'), col(parent, hop.field)))
296
+ const operand = parent === alias && definition.fields[hop.field]?.computed ? computedValue(hop.field) : col(parent, hop.field)
297
+ query = query.leftJoin(Q.table(table, target), Cond.equal(col(target, 'id'), typeof operand === 'string' ? Q.expr(operand) : operand))
211
298
  }
212
299
  parent = target
213
300
  }
214
- if (parent === alias && definition.fields[path.field]?.type === 'ref') {
301
+ if (parent === alias && definition.fields[path.field]?.computed) {
302
+ const operand = computedValue(path.field)
303
+ columns.set(column, operand)
304
+ labelVisibility.push(Cond.isNotNull(operand))
305
+ } else if (parent === alias && definition.fields[path.field]?.type === 'ref') {
215
306
  const visible = foreignKeyVisible(path.field)
216
307
  columns.set(column, new ForeignKeyValue(col(alias, path.field), visible))
217
308
  labelVisibility.push(Cond.or([Cond.isNull(col(alias, path.field)), visible]))
@@ -232,7 +323,13 @@ export function renderStatement(kernel: KernelRegistry, scope: Scope, ast: Selec
232
323
  if (maskForeignKeys && displayRequired && definition.label) query = query.field(readableDisplay(kernel, scope, entity) ? labelVisibility.length ? Cond.and(labelVisibility) : Q.raw('1') : Q.raw('0'), '__display_visible')
233
324
  for (const field of fields) {
234
325
  const definition = kernel.config.entities[entity].fields[field]
235
- if (kernel.config.entities[entity].label && field === kernel.config.entities[entity].displayField) {
326
+ if (definition?.computed) {
327
+ const projected = !computedDemand || computedDemand.has(field) ? computedValue(field) : Q.raw('NULL')
328
+ query = query.field(projected, field)
329
+ if (maskForeignKeys && (!computedDemand || computedDemand.has(field)) && needsDisplayParts(kernel.config, entity, field)) {
330
+ query = query.field(presentation.get(field) ?? Q.raw('NULL'), partsAlias(field))
331
+ }
332
+ } else if (kernel.config.entities[entity].label && field === kernel.config.entities[entity].displayField) {
236
333
  query = query.field(label, field)
237
334
  } else if (maskForeignKeys && definition?.type === 'ref') {
238
335
  // Target identity must itself be readable. Visibility probes expose no target
@@ -288,6 +385,8 @@ export function buildSelect(kernel: KernelRegistry, scope: Scope, entity: string
288
385
  let aliases = 0
289
386
  let ast = Q.select().from(entity, 'row')
290
387
  for (const field of executionFields(kernel, scope, entity, node, [...extras, ...((node as QueryInput).search?.fields ?? []).filter(key => !labelPath(kernel.config, entity, key))])) ast = ast.field(col('row', field))
388
+ const display = kernel.config.entities[entity].displayField
389
+ if (display && selectedFields(kernel, scope, entity, node).includes(display) && needsDisplayParts(kernel.config, entity, display)) ast = ast.field(col('row', partsAlias(display)))
291
390
  if (node.where) ast = ast.where(filterCondition(kernel, entity, 'row', node.where, () => `rel_${++aliases}`))
292
391
  return ast
293
392
  }
@@ -303,11 +402,11 @@ export function compileAggregate(kernel: KernelRegistry, scope: Scope, query: Qu
303
402
  }
304
403
  /** All values come from scoped joined tables; a missing/denied target has one safe marker. */
305
404
  class LabelObject extends Condition {
306
- constructor(private entity: string, private alias: string, private display?: string) { super() }
405
+ constructor(private entity: string, private alias: string, private display?: string, private parts = false) { super() }
307
406
  toSQL(flavor: ISQLFlavor) {
308
407
  const id = flavor.escapeColumn(col(this.alias, 'id'))
309
408
  const display = this.display ? value(this.display).toSQL(flavor) : 'NULL'
310
- const row = this.display ? `json_object('id', ${id}, ${display}, ${flavor.escapeColumn(col(this.alias, this.display))})` : `json_object('id', ${id})`
409
+ const row = this.display ? `json_object('id', ${id}, ${display}, ${flavor.escapeColumn(col(this.alias, this.display))}${this.parts ? `, '__display', json(${flavor.escapeColumn(col(this.alias, partsAlias(this.display)))})` : ''})` : `json_object('id', ${id})`
311
410
  return `CASE WHEN ${id} IS NULL THEN json_object('status', 'unavailable') ELSE json_object('status', 'ok', 'entity', ${value(this.entity).toSQL(flavor)}, 'display', ${display}, 'row', ${row}) END`
312
411
  }
313
412
  }
@@ -333,7 +432,7 @@ export function compileRoot(kernel: KernelRegistry, scope: Scope, query: QueryIn
333
432
  }
334
433
  parent = alias
335
434
  }
336
- expression = new LabelObject(plan.entity, parent, plan.display)
435
+ expression = new LabelObject(plan.entity, parent, plan.display, !!plan.display && needsDisplayParts(kernel.config, plan.entity, plan.display))
337
436
  }
338
437
  source = source.field(expression, labelAlias(key))
339
438
  }
@@ -383,12 +482,14 @@ export function compileRoot(kernel: KernelRegistry, scope: Scope, query: QueryIn
383
482
  export function compileInclude(kernel: KernelRegistry, scope: Scope, entity: string, node: Selection, parentField: string, ids: Scalar[], cost?: QueryCost) {
384
483
  let child = buildSelect(kernel, scope, entity, node, [parentField])
385
484
  child = child.where(ids.length ? new InCondition(col('row', parentField), ids) : truth(false))
386
- if (kernel.config.entities[entity].fields[parentField]?.type === 'ref' && ids.length && !ids.includes(null)) child = child.where(new InCondition(col('row', `__raw_${parentField}`), ids))
485
+ if (kernel.config.entities[entity].fields[parentField]?.type === 'ref' && !kernel.config.entities[entity].fields[parentField].computed && ids.length && !ids.includes(null)) child = child.where(new InCondition(col('row', `__raw_${parentField}`), ids))
387
486
  const fields = executionFields(kernel, scope, entity, node, [parentField])
388
487
  const sort = queryOrder(node).map(o => `${quote('row')}.${quote(o.field)} ${o.dir.toUpperCase()}`).join(', ')
389
488
  child = child.field(Q.raw(`ROW_NUMBER() OVER (PARTITION BY ${quote('row')}.${quote(parentField)} ORDER BY ${sort})`), '__row_number')
390
489
  let outer = Q.select().from(child, 'ranked')
391
490
  for (const field of fields) outer = outer.field(col('ranked', field))
491
+ const display = kernel.config.entities[entity].displayField
492
+ if (display && selectedFields(kernel, scope, entity, node).includes(display) && needsDisplayParts(kernel.config, entity, display)) outer = outer.field(col('ranked', partsAlias(display)))
392
493
  outer = outer.where(Cond.lessThanOrEqual('ranked.__row_number', value(node.limit ?? L.children)))
393
494
  .orderBy('ranked.__row_number').orderBy(col('ranked', parentField))
394
495
  return renderStatement(kernel, scope, outer, cost, requiredDisplayEntities(kernel, scope, entity, node).required)
@@ -0,0 +1,53 @@
1
+ import { Condition, Q, type ISequelizable, type ISQLFlavor, type SelectQuery } from '@jakub.knejzlik/ts-query'
2
+ import { expressionInfo, rebindExpression, type DisplayParts } from './expressions'
3
+ import type { InstanceConfig } from '../config'
4
+
5
+ /** Presentation is additive: raw SQL values still own search, ordering and cursors.
6
+ * JSON arrays preserve typed date operands without interpreting an expression in JS.
7
+ * Locale and timezone belong to the browser's ordinary field formatter.
8
+ */
9
+ export const partsAlias = (field: string) => `__parts_${field}`
10
+ const needsCache = new WeakMap<object, Map<string, boolean>>()
11
+ export function needsDisplayParts(config: Pick<InstanceConfig, 'entities'>, entity: string, field: string): boolean {
12
+ let cache = needsCache.get(config); if (!cache) { cache = new Map(); needsCache.set(config, cache) }
13
+ const key = `${entity}.${field}`; const known = cache.get(key); if (known !== undefined) return known
14
+ const wire = config.entities[entity].fields[field]?.computed
15
+ if (!wire) { cache.set(key, false); return false }
16
+ const info = expressionInfo(config, entity, field, wire)
17
+ const containsDate = (parts: DisplayParts): boolean => 'concat' in parts ? parts.concat.some(containsDate)
18
+ : 'condition' in parts ? containsDate(parts.yes) || containsDate(parts.no)
19
+ : 'coalesce' in parts ? parts.coalesce.some(item => containsDate(item.parts))
20
+ : parts.type === 'datetime' || parts.type === 'date'
21
+ const result = containsDate(info.parts!) || info.dependencies.some(dep => needsDisplayParts(config, dep.entity, dep.field))
22
+ cache.set(key, result); return result
23
+ }
24
+ export class DisplayPartsExpression extends Condition {
25
+ constructor(private parts: DisplayParts, private columns: Map<string, string | ISequelizable>, private nested: Map<string, ISequelizable>, private source: (entity: string) => SelectQuery) { super() }
26
+ toSQL(flavor: ISQLFlavor) {
27
+ const raw = (wire: string) => {
28
+ const query = wire.startsWith('{') && JSON.parse(wire).type === 'SelectQuery'
29
+ const ast = query ? Q.deserialize(wire, { allowRaw: false }) : Q.expr(wire)
30
+ const sql = rebindExpression(ast, this.columns).toSQL(flavor, { transformTable: this.source })
31
+ return query ? `(${sql})` : sql
32
+ }
33
+ const render = (parts: DisplayParts): string => {
34
+ if ('concat' in parts) return `json_array(${parts.concat.map(child => `json(${render(child)})`).join(', ')})`
35
+ if ('condition' in parts) return `CASE WHEN ${raw(parts.condition)} THEN ${render(parts.yes)} ELSE ${render(parts.no)} END`
36
+ if ('coalesce' in parts) return `CASE ${parts.coalesce.map(item => `WHEN ${raw(item.wire)} IS NOT NULL THEN ${render(item.parts)}`).join(' ')} ELSE json_array(NULL) END`
37
+ const nested = this.nested.get(parts.wire.match(/^#([^#]+)#$/)?.[1] ?? parts.wire)
38
+ if (nested) return nested.toSQL(flavor)
39
+ const sql = raw(parts.wire)
40
+ return parts.type === 'datetime' || parts.type === 'date' ? `json_array(json_object('type', '${parts.type}', 'value', ${sql}))` : `json_array(CAST(${sql} AS TEXT))`
41
+ }
42
+ return render(this.parts)
43
+ }
44
+ }
45
+ /** Flatten SQL's nested concat arrays once, before sending the typed wire value. */
46
+ export function parseDisplayParts(value: string | unknown[]): unknown[] {
47
+ return (typeof value === 'string' ? JSON.parse(value) as unknown[] : value).flat(Infinity).map(part => {
48
+ // SQLite DATETIME/DATEADD return UTC timestamps without an offset. Qualify
49
+ // only presentation values; raw SQL text still owns search and ordering.
50
+ if (part && typeof part === 'object' && 'type' in part && part.type === 'datetime' && 'value' in part && typeof part.value === 'string' && /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/.test(part.value)) return { ...part, value: `${part.value.replace(' ', 'T')}Z` }
51
+ return part == null ? '' : part
52
+ })
53
+ }
@@ -1,3 +1,4 @@
1
+ import { needsDisplayParts, parseDisplayParts, partsAlias } from './display-parts'
1
2
  import { ApiError } from '../errors'
2
3
  import type { KernelRegistry } from '../kernel/registry'
3
4
  import type { Scope } from '../types'
@@ -10,14 +11,26 @@ import { validateQuery, type QueryInput, type Scalar, type Selection } from './s
10
11
  export type Row = Record<string, any>
11
12
  /** Shared projection for entity reads and server-configured dashboard queries. */
12
13
  export function projectQueryRow(kernel: KernelRegistry, scope: Scope, entity: string, node: Selection, row: Row): Row {
13
- return Object.fromEntries(selectedFields(kernel, scope, entity, node).map(field => [field,
14
+ const result = Object.fromEntries(selectedFields(kernel, scope, entity, node).map(field => [field,
14
15
  kernel.config.entities[entity].fields[field]?.type === 'bool' && row[field] !== null ? Boolean(row[field]) : row[field]]))
16
+ const display = kernel.config.entities[entity].displayField
17
+ if (display && result[display] != null && needsDisplayParts(kernel.config, entity, display) && row[partsAlias(display)]) result.__display = parseDisplayParts(row[partsAlias(display)])
18
+ return result
15
19
  }
16
20
  export function projectRootRow(kernel: KernelRegistry, scope: Scope, query: QueryInput, row: Row): Row {
17
21
  return { ...projectQueryRow(kernel, scope, query.entity, query, row), ...(query.labels ? {
18
- __labels: Object.fromEntries(query.labels.map(key => [key, row[labelAlias(key)] ? JSON.parse(row[labelAlias(key)]) : null])),
22
+ __labels: Object.fromEntries(query.labels.map(key => [key, projectLabel(row[labelAlias(key)])])),
19
23
  } : {}) }
20
24
  }
25
+ function projectLabel(value: string | null) {
26
+ if (!value) return null
27
+ const label = JSON.parse(value)
28
+ if (label.row?.__display) {
29
+ if (label.row[label.display] == null) delete label.row.__display
30
+ else label.row.__display = parseDisplayParts(label.row.__display)
31
+ }
32
+ return label
33
+ }
21
34
  export interface QueryResult { data: Row[]; next_cursor: string | null }
22
35
  export type { QueryLog } from './observability'
23
36
  import { emptyQueryLog, recordQuery, type QueryLog } from './observability'
@@ -0,0 +1,354 @@
1
+ import { readableDisplay } from './labels'
2
+ import { Q, SelectQuery, type ISequelizable } from '@jakub.knejzlik/ts-query'
3
+ import type { InstanceConfig } from '../config'
4
+ import type { KernelRegistry } from '../kernel/registry'
5
+ import type { Scope } from '../types'
6
+
7
+ export const DISPLAY_VALUE = 'computed_display'
8
+ export const isExpression = (value: string) => !/^[a-z][a-z0-9_]*$/.test(value)
9
+ type Config = Pick<InstanceConfig, 'entities'>
10
+ type Kind = 'string' | 'number' | 'bool' | 'datetime' | 'null'
11
+ export interface Dependency { column: string; entity: string; field: string; hops: { source: string; field: string; target: string }[]; qualifier?: string; sourcePath?: string }
12
+ export type DisplayParts = { wire: string; type: Kind | 'date' } | { concat: DisplayParts[] } | { condition: string; yes: DisplayParts; no: DisplayParts } | { coalesce: { wire: string; parts: DisplayParts }[] }
13
+ interface ValueInfo { type: Kind; dateOnly: boolean; calendarDate?: boolean; textDependencies?: Dependency[]; parts?: DisplayParts }
14
+ export interface ExpressionInfo extends ValueInfo { sources: string[]; nodes: number; ast: ISequelizable; scalarQuery: boolean; dependencies: Dependency[]; tables: Map<string, Set<string>> }
15
+ export interface ExpressionIssue { code: 'invalid_expression'; entity: string; field: string; message: string; suggestedFix: string }
16
+ export class ExpressionError extends Error {
17
+ readonly code = 'invalid_expression'
18
+ constructor(public errors: ExpressionIssue[]) { super(errors.map(issue => `${issue.message} Fix: ${issue.suggestedFix}`).join('\n')) }
19
+ }
20
+ export function expressionError(entity: string, field: string, message: string, suggestedFix = 'Use schema fields and structured ts-query functions, then validate the proposal.'): never {
21
+ throw new ExpressionError([{ code: 'invalid_expression', entity, field, message: `Invalid expression: ${entity}.${field}; ${message}`, suggestedFix }])
22
+ }
23
+ const functions = ['CONCAT', 'IFNULL', 'COALESCE', 'IF', 'LOWER', 'UPPER', 'TRIM', 'LTRIM', 'RTRIM', 'SUBSTRING', 'SUBSTR', 'LENGTH', 'REPLACE', 'STRFTIME', 'DATE', 'DATETIME', 'TIME', 'JULIANDAY', 'UNIXEPOCH', 'YEAR', 'MONTH', 'DATEADD', 'DATEDIFF', 'ABS', 'ROUND', 'MIN', 'MAX', 'SUM', 'COUNT', 'AVG', 'NULLIF']
24
+ /** Contracts target the SQLite/D1 renderer, rather than the library's cross-dialect API. */
25
+ const arities: Record<string, [number, number]> = {
26
+ CONCAT: [1, 100], IFNULL: [2, 2], COALESCE: [2, 100], NULLIF: [2, 2], IF: [3, 3],
27
+ LOWER: [1, 1], UPPER: [1, 1], TRIM: [1, 2], LTRIM: [1, 2], RTRIM: [1, 2],
28
+ SUBSTRING: [2, 3], SUBSTR: [2, 3], LENGTH: [1, 1], REPLACE: [3, 3],
29
+ STRFTIME: [2, 20], DATE: [1, 20], DATETIME: [1, 20], TIME: [1, 20],
30
+ JULIANDAY: [1, 20], UNIXEPOCH: [1, 20], YEAR: [1, 1], MONTH: [1, 1], DATEADD: [3, 3],
31
+ ABS: [1, 1], ROUND: [1, 2], MIN: [1, 100], MAX: [1, 100], SUM: [1, 1], COUNT: [1, 1], AVG: [1, 1],
32
+ }
33
+ const base: Record<string, Kind> = { id: 'string', organization_id: 'string', created_at: 'datetime', updated_at: 'datetime', version: 'number' }
34
+ const fieldKind = (config: Config, entity: string, field: string): Kind => (Object.hasOwn(base, field) ? base[field] : undefined) ?? ({ int: 'number', float: 'number', bool: 'bool', datetime: 'datetime' } as Record<string, Kind>)[config.entities[entity].fields[field]?.type] ?? 'string'
35
+ const cache = new WeakMap<Config, Map<string, ExpressionInfo>>()
36
+ /** Clone the validated AST, replacing operand nodes rather than identifier escaping.
37
+ * Alias declarations are strings; ORDER BY aliases belong to their own SELECT.
38
+ * Within a SELECT only `self` references bind to the outer entity; local aliases
39
+ * may share their spelling with a ref path in the enclosing expression.
40
+ */
41
+ export function rebindExpression<T>(node: T, columns: Map<string, string | ISequelizable>, inQuery = false, preserved = new Set<unknown>()): T {
42
+ if (!node || typeof node !== 'object' || node instanceof Date || preserved.has(node)) return node
43
+ if (node instanceof SelectQuery) {
44
+ inQuery = true
45
+ const aliases = new Set(node.getFields().map(field => field.alias).filter(alias => alias !== undefined))
46
+ preserved = new Set(node.getOrderBy().filter(order => aliases.has(order.field.serialize())).map(order => order.field))
47
+ } else if ('serialize' in node && typeof node.serialize === 'function') {
48
+ const wire = node.serialize()
49
+ const column = wire.match(/^#([^#]+)#$/)?.[1] ?? wire
50
+ const mapped = !inQuery || column.startsWith('self.') ? columns.get(column) : undefined
51
+ if (mapped) return (typeof mapped === 'string' ? Q.expr(mapped) : mapped) as T
52
+ }
53
+ if (Array.isArray(node)) return node.map(child => rebindExpression(child, columns, inQuery, preserved)) as T
54
+ return Object.assign(Object.create(Object.getPrototypeOf(node)), Object.fromEntries(
55
+ Object.entries(node).map(([key, child]) => [key, rebindExpression(child, columns, inQuery, preserved)]),
56
+ ))
57
+ }
58
+ /** Validate the library wire grammar before deserializing. No arbitrary JS or SQL is interpreted.
59
+ * Query aliases are lexical; an outer row is explicitly named `self` inside a subquery.
60
+ */
61
+ export function expressionInfo(config: Config, entity: string, field: string, wire: string): ExpressionInfo {
62
+ let entries = cache.get(config); if (!entries) { entries = new Map(); cache.set(config, entries) }
63
+ const key = `${entity}.${field}:${wire}`; const known = entries.get(key); if (known) return known
64
+ const fail = (message: string, fix?: string): never => expressionError(entity, field, message, fix)
65
+ if (wire.length > 32000) fail('Expression exceeds 32000 bytes', 'Shorten the expression.')
66
+ const sources: string[] = []; const dependencies: Dependency[] = []; const tables = new Map<string, Set<string>>(); let nodes = 0
67
+ let hasSourceAggregate = false
68
+ type Context = { aliases: Map<string, string>; aliasContexts: Map<string, string>; current?: string; query: boolean; rawRefs?: boolean;
69
+ clause?: 'SELECT' | 'WHERE' | 'JOIN ON' | 'ORDER BY'; selectAggregate?: boolean;
70
+ aggregate?: string; aggregates?: { found: boolean }; outerAliases?: Set<string>; outerReferences?: Set<string>;
71
+ aggregateReferences?: { aliases: Set<string>; references: Set<string> }[] }
72
+ const root: Context = { aliases: new Map([['self', entity]]), aliasContexts: new Map(), current: entity, query: false }
73
+ const reference = (column: string, context: Context): Kind => {
74
+ if (column.includes('*') || !/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$/.test(column)) fail(`Unknown field: ${column}`)
75
+ const parts = column.split('.'); let source = context.current ?? entity; let qualifier: string | undefined
76
+ if (context.query && parts.length > 1 && !context.aliases.has(parts[0])) fail(`Unknown or unavailable schema table alias: ${parts[0]}`, 'Use an alias from FROM or an earlier/current JOIN; move a later JOIN before its first use.')
77
+ if (parts.length > 1 && context.aliases.has(parts[0])) { qualifier = parts.shift()!; source = context.aliases.get(qualifier)! }
78
+ if (qualifier && context.outerAliases?.has(qualifier)) context.outerReferences?.add(qualifier)
79
+ if (qualifier) for (const aggregate of context.aggregateReferences ?? []) {
80
+ if (aggregate.aliases.has(qualifier)) aggregate.references.add(qualifier)
81
+ }
82
+ if (context.query && !qualifier) fail(`Subquery field ${column} needs a schema table alias`, 'Qualify subquery fields, for example p.name; use self.id for the outer row.')
83
+ const hops: Dependency['hops'] = []
84
+ while (parts.length > 1) {
85
+ const name = parts.shift()!; const spec = config.entities[source] && Object.hasOwn(config.entities[source].fields, name) ? config.entities[source].fields[name] : undefined
86
+ if (spec?.type !== 'ref' || !spec.entity) fail(`Unknown ref path: ${source}.${name}`)
87
+ hops.push({ source, field: name, target: spec!.entity! }); source = spec!.entity!
88
+ }
89
+ let name = parts[0]
90
+ const spec = config.entities[source] && Object.hasOwn(config.entities[source].fields, name) ? config.entities[source].fields[name] : undefined
91
+ if (!spec && !Object.hasOwn(base, name)) fail(`Unknown schema field: ${source}.${name}`, 'Choose a field returned by inspect_schema.')
92
+ // A bare to-one ref means the target display value, never its physical FK.
93
+ if (spec?.type === 'ref' && !context.rawRefs) {
94
+ if (qualifier && qualifier !== 'self') fail('Ref paths inside subqueries require an explicit schema join')
95
+ hops.push({ source, field: name, target: spec!.entity! }); source = spec!.entity!
96
+ name = config.entities[source].displayField ?? fail(`Referenced entity ${source} has no displayField`)
97
+ }
98
+ if (qualifier && qualifier !== 'self' && hops.length) fail('Ref paths inside subqueries require an explicit schema join')
99
+ dependencies.push({ column, entity: source, field: name, hops, qualifier, sourcePath: qualifier ? context.aliasContexts.get(qualifier) : undefined })
100
+ if (qualifier && qualifier !== 'self') { const fields = tables.get(source) ?? new Set<string>(); fields.add(name); tables.set(source, fields) }
101
+ return fieldKind(config, source, name)
102
+ }
103
+ function scalar(node: unknown, context: Context, depth: number): ValueInfo {
104
+ const result = scalarValue(node, context, depth)
105
+ return { ...result, parts: result.parts ?? { wire: typeof node === 'string' ? node : Q.value(node as number | boolean).serialize(), type: result.calendarDate ? 'date' : result.type } }
106
+ }
107
+ function scalarValue(node: unknown, context: Context, depth: number): ValueInfo {
108
+ if (++nodes > 512 || depth > 32) fail('Expression exceeds the complexity budget', 'Use fewer functions or subqueries.')
109
+ if (typeof node === 'number') return { type: 'number', dateOnly: false }
110
+ if (typeof node === 'boolean') return { type: 'bool', dateOnly: false }
111
+ if (typeof node !== 'string') return fail('Unknown expression node')
112
+ if (node.startsWith('!!!')) { const value = JSON.parse(node.slice(3)); if (value !== null && !['string', 'number', 'boolean'].includes(typeof value)) fail('Invalid literal'); return { type: value === null ? 'null' : typeof value === 'boolean' ? 'bool' : typeof value === 'number' ? 'number' : 'string', dateOnly: false } }
113
+ if (node.startsWith('!D!')) return { type: 'datetime', dateOnly: true }
114
+ if (node.startsWith('FN(') || node.startsWith('OP(')) {
115
+ if (!node.endsWith(')')) fail('Invalid function encoding')
116
+ const [name, ...args] = JSON.parse(node.slice(3, -1)) as [string, ...unknown[]]
117
+ if (typeof name !== 'string' || !(node.startsWith('OP(') ? ['+', '-', '*', '/'] : functions).includes(name.toUpperCase())) fail(`Unknown or unsafe function: ${name}`)
118
+ const fn = name.toUpperCase()
119
+ if (node.startsWith('FN(')) {
120
+ if (!arities[fn]) fail(`${fn} is not supported by SQLite/D1`, `Use Fn.subtract(Q.expr('FN(["JULIANDAY","end"])'), Q.expr('FN(["JULIANDAY","start"])')) for a day difference.`)
121
+ const [min, max] = arities[fn]
122
+ if (args.length < min || args.length > max) fail(`${fn} expects ${min === max ? min : `${min}–${max}`} arguments; received ${args.length}`, `Supply ${fn} with its documented SQLite argument count.`)
123
+ }
124
+ // SQLite MIN/MAX with multiple arguments are scalar functions. A SELECT
125
+ // below an aggregate starts a new context; scalar wrappers do not.
126
+ const aggregate = node.startsWith('FN(') && (['SUM', 'COUNT', 'AVG'].includes(fn) || ['MIN', 'MAX'].includes(fn) && args.length === 1)
127
+ if (aggregate && (context.clause === 'WHERE' || context.clause === 'JOIN ON')) fail(`Aggregate ${fn} is not allowed in ${context.clause}`, 'Wrap the aggregate in a separate scalar SELECT subquery and use its result in the condition.')
128
+ if (aggregate && context.clause === 'ORDER BY' && !context.selectAggregate) fail(`Aggregate ${fn} in ORDER BY requires an aggregate in the SELECT projection`, 'Select an aggregate in this SELECT, or wrap the ORDER BY aggregate in a separate scalar SELECT subquery.')
129
+ if (aggregate && context.aggregate) fail(`Nested aggregate ${fn} inside ${context.aggregate} in the same SELECT is not supported`, 'Move the inner aggregate into a separate SELECT subquery, or use one aggregate over a scalar expression.')
130
+ if (aggregate && context.aggregates) context.aggregates.found = true
131
+ const operandsScope = { aliases: new Set(context.aliases.keys()), references: new Set<string>() }
132
+ const operandContext = aggregate ? { ...context, aggregate: fn, aggregateReferences: [...(context.aggregateReferences ?? []), operandsScope] } : context
133
+ // COUNT(*) has no column operand and belongs to this SELECT, like COUNT(1).
134
+ const values: ValueInfo[] = args.map(arg => fn === 'COUNT' && arg === '*' ? { type: 'number', dateOnly: false } : scalar(arg, operandContext, depth + 1))
135
+ // SQLite moves an aggregate with exclusively outer column operands to an
136
+ // enclosing SELECT, even across scalar wrappers or nested correlations.
137
+ // Reject that shape before it can collapse entity rows or evade clause rules.
138
+ if (aggregate && operandsScope.references.size && [...operandsScope.references].every(alias => context.outerAliases?.has(alias))) {
139
+ fail(`Aggregate ${fn} references only outer query columns and belongs to an outer SELECT`, 'Aggregate a local FROM/JOIN column in this scalar SELECT; move the calculation outside the aggregate if it only needs the outer row.')
140
+ }
141
+ if (aggregate && context.query && !operandsScope.references.size && [...context.aliases.keys()].some(alias => !context.outerAliases?.has(alias))) hasSourceAggregate = true
142
+ // Ordinary computed expressions are projected into each scoped entity row.
143
+ // An aggregate here would change the cardinality of every list and count,
144
+ // including when this expression is expanded through another computed field.
145
+ if (aggregate && !context.query) fail(`Bare aggregate ${fn} inside a computed expression can change entity row cardinality`, 'Wrap the aggregate in an explicit scalar SELECT subquery, then reference that computed field for composition.')
146
+ const operands = (indices: number[], kinds: Kind[], example: string) => {
147
+ if (indices.some(i => ![...kinds, 'null'].includes(values[i].type))) fail(`${fn} operand type mismatch; expected ${kinds.join(' or ')}`, example)
148
+ }
149
+ const all = values.map((_, i) => i)
150
+ const textDependencies = values.flatMap(value => value.textDependencies ?? [])
151
+ if (['LOWER','UPPER','TRIM','LTRIM','RTRIM','REPLACE','LENGTH'].includes(fn)) operands(all, ['string'], `Use ${fn} with text fields and Q.value('text').`)
152
+ if (['SUBSTR','SUBSTRING'].includes(fn)) { operands([0], ['string'], 'Use SUBSTR(text, numeric start, optional numeric length).'); operands(all.slice(1), ['number'], 'Use numeric substring positions.') }
153
+ if (['SUM','AVG','ABS','ROUND'].includes(fn)) operands(all, ['number'], `Use ${fn} with numeric fields and Q.value(number).`)
154
+ if (['STRFTIME','DATE','DATETIME','TIME','JULIANDAY','UNIXEPOCH','YEAR','MONTH','DATEADD'].includes(fn)) {
155
+ const start = fn === 'STRFTIME' ? 1 : 0
156
+ operands([start], ['datetime','string'], 'Use a datetime field or an ISO date string.')
157
+ if (fn === 'STRFTIME') operands([0], ['string'], "Use Fn.strftime('%Y-%m-%d', 'date').")
158
+ if (fn === 'DATEADD') {
159
+ const literal = (arg: unknown) => typeof arg === 'string' && arg.startsWith('!!!') ? JSON.parse(arg.slice(3)) : undefined
160
+ if (!Number.isSafeInteger(literal(args[1])) || !/^(year|month|day|hour|minute|second)s?$/.test(literal(args[2]) ?? '')) fail('DATEADD requires a literal integer interval and a supported literal unit', "Use Fn.dateAdd('date', 1, 'day').")
161
+ } else operands(all.slice(start + 1), ['string'], "Use literal SQLite date modifier strings, for example Q.value('start of month').")
162
+ }
163
+ if (node.startsWith('OP(')) { if (values.length < 2 || values.some(value => !['number', 'null'].includes(value.type))) fail('Arithmetic type mismatch', 'Use numeric fields and Q.value(number).'); return { type: 'number', dateOnly: false } }
164
+ if (fn === 'IF') { if (values.length !== 3 || values[0].type !== 'bool') fail('IF needs a condition and two values'); if (values[1].type !== values[2].type && !values.slice(1).some(value => value.type === 'null')) fail('IF branch type mismatch'); return { type: values[1].type === 'null' ? values[2].type : values[1].type, dateOnly: values.slice(1).every(value => value.dateOnly), calendarDate: values.slice(1).filter(value => value.type !== 'null').every(value => value.calendarDate), textDependencies: values.slice(1).flatMap(value => value.textDependencies ?? []), parts: { condition: typeof args[0] === 'string' ? args[0] : Q.value(args[0] as boolean).serialize(), yes: values[1].parts!, no: values[2].parts! } } }
165
+ if (['IFNULL','COALESCE','NULLIF','MIN','MAX'].includes(fn)) { const nonnull = values.filter(value => value.type !== 'null'); if (new Set(nonnull.map(value => value.type)).size > 1) fail(`${fn} argument type mismatch`); return { type: nonnull[0]?.type ?? 'null', dateOnly: nonnull.every(value => value.dateOnly), calendarDate: (fn === 'NULLIF' ? [values[0]] : nonnull).every(value => value.calendarDate), textDependencies: fn === 'NULLIF' ? values[0].textDependencies : textDependencies, ...(['IFNULL', 'COALESCE'].includes(fn) ? { parts: { coalesce: values.map((value, i) => ({ wire: typeof args[i] === 'string' ? args[i] : Q.value(args[i] as number | boolean).serialize(), parts: value.parts! })) } } : {}) } }
166
+ if (['COUNT','SUM','AVG','ABS','ROUND','LENGTH','JULIANDAY','UNIXEPOCH','YEAR','MONTH','DATEDIFF'].includes(fn)) return { type: 'number', dateOnly: false }
167
+ if (['STRFTIME','DATE','DATETIME','TIME','DATEADD'].includes(fn)) return { type: fn === 'STRFTIME' ? 'string' : 'datetime', dateOnly: true, calendarDate: fn === 'DATE' }
168
+ return { type: 'string', dateOnly: fn === 'CONCAT' && values.every(value => value.dateOnly || value.type === 'null'), textDependencies, ...(fn === 'CONCAT' ? { parts: { concat: values.map(value => value.parts!) } } : {}) }
169
+ }
170
+ if (node.startsWith('{')) return object(JSON.parse(node), context, depth + 1)
171
+ if (/^[+-]?\d+(?:\.\d+)?$/.test(node)) return { type: 'number', dateOnly: false }
172
+ if (node === 'NULL') return { type: 'null', dateOnly: false }
173
+ if (/^&[^#]*&$/.test(node)) return { type: 'string', dateOnly: false } // Library Fn.string encoding.
174
+ if (node.startsWith('!!')) fail('Raw SQL is forbidden; use structured ts-query expressions')
175
+ const column = node.match(/^#([^#]+)#$/)?.[1] ?? node
176
+ const type = reference(column, context); return { type, dateOnly: type === 'datetime', textDependencies: type === 'string' ? [dependencies[dependencies.length - 1]] : [] }
177
+ }
178
+ function object(node: any, parent: Context, depth: number): ValueInfo {
179
+ if (++nodes > 512 || depth > 32) fail('Expression exceeds the complexity budget', 'Use fewer functions or subqueries.')
180
+ if (!node || typeof node !== 'object' || Array.isArray(node)) return fail('Unknown node')
181
+ if (node.type === 'SelectQuery') {
182
+ if (depth > 4) fail('Subquery nesting exceeds the budget')
183
+ if (node.unionQueries?.length || node.groupBy?.length || node.having?.length || node.offset) fail('Unsupported scalar subquery shape', 'Use one SELECT value, schema sources, WHERE, ORDER BY and LIMIT 1, or an aggregate.')
184
+ if (node.fields?.length !== 1) fail('A scalar subquery must select exactly one field')
185
+ const context: Context = { aliases: new Map(parent.aliases), aliasContexts: new Map(parent.aliasContexts), query: true,
186
+ outerAliases: new Set(parent.aliases.keys()), outerReferences: new Set(), aggregateReferences: parent.aggregateReferences }
187
+ const register = (table: any) => {
188
+ if (table?.type !== 'Table' || typeof table.source !== 'string' || !Object.hasOwn(config.entities, table.source)) fail(`Unknown schema entity: ${table?.source}`, 'Use an entity returned by inspect_schema, never a physical/system table.')
189
+ const alias = table.alias ?? table.source
190
+ if (!/^[a-z][a-z0-9_]*$/.test(alias) || /^(scope_row_|computed_join_|expression_join_|label_join_)/.test(alias) || context.aliases.has(alias)) fail(`Invalid or shadowed subquery alias: ${alias}`)
191
+ context.aliases.set(alias, table.source); context.aliasContexts.set(alias, `${sources.length}/${alias}`); sources.push(table.source); if (!tables.has(table.source)) tables.set(table.source, new Set())
192
+ }
193
+ for (const table of node.tables ?? []) register(table)
194
+ // An ON clause can see the left-hand sources and its own right-hand source.
195
+ // Validate it before registering later joins, including nested correlations.
196
+ for (const join of node.joins ?? []) {
197
+ if (!['INNER','LEFT','CROSS'].includes(join.joinType)) fail('Unsupported join')
198
+ register(join.table)
199
+ if (join.condition) object(join.condition, { ...context, clause: 'JOIN ON' }, depth + 1)
200
+ }
201
+ // Only mandatory equalities connect sources: OR and NOT cannot bound a join.
202
+ const local = [...(node.tables ?? []), ...(node.joins ?? []).map((join: any) => join.table)].map((table: any) => table.alias)
203
+ const edges: [string, string][] = []
204
+ const endpoint = (column: unknown): { alias: string; indexed: boolean } | undefined => {
205
+ if (typeof column !== 'string') return
206
+ const parts = (column.match(/^#([^#]+)#$/)?.[1] ?? column).split('.')
207
+ if (parts.length !== 2 || !context.aliases.has(parts[0])) return
208
+ const source = context.aliases.get(parts[0])!; const spec = config.entities[source].fields[parts[1]]
209
+ return { alias: parts[0], indexed: parts[1] === 'id' || spec?.type === 'ref' && !spec.computed }
210
+ }
211
+ const equality = (condition: any, rightAlias?: string) => {
212
+ if (condition?.type === 'LogicalCondition' && condition.operator === 'AND') for (const child of condition.conditions ?? []) equality(child, rightAlias)
213
+ if (condition?.type !== 'ColumnComparisonCondition' || condition.operator !== '=') return
214
+ const left = endpoint(condition.leftKey); const right = endpoint(condition.rightKey)
215
+ if (!left || !right || left.alias === right.alias || !(left.indexed || right.indexed)) return
216
+ // A LEFT ON only bounds its own right-hand source. Its predicates do
217
+ // not remove unmatched rows from sources already on the left.
218
+ if (!rightAlias || right.alias === rightAlias) edges.push([left.alias, right.alias])
219
+ if (!rightAlias || left.alias === rightAlias) edges.push([right.alias, left.alias])
220
+ }
221
+ for (const where of node.where ?? []) equality(where)
222
+ for (const join of node.joins ?? []) {
223
+ if (join.joinType === 'INNER') equality(join.condition)
224
+ if (join.joinType === 'LEFT') equality(join.condition, join.table.alias)
225
+ }
226
+ for (const where of node.where ?? []) object(where, { ...context, clause: 'WHERE' }, depth + 1)
227
+ const aggregates = { found: false }
228
+ const result = scalar(node.fields[0].name, { ...context, clause: 'SELECT', aggregates }, depth + 1)
229
+ for (const order of node.orderBy ?? []) {
230
+ // An unqualified ORDER BY output alias names the projection, not a source
231
+ // column. Validate that expression under this SELECT's aggregate context.
232
+ const projection = node.fields.find((field: any) => field.alias === order.field)
233
+ scalar(projection ? projection.name : order.field, { ...context, clause: 'ORDER BY', selectAggregate: aggregates.found }, depth + 1)
234
+ }
235
+ const correlated = parent.query && context.outerReferences!.size > 0
236
+ const connected = new Set([...parent.aliases.keys(), ...(correlated ? [] : local.slice(0, 1))])
237
+ let changed = true
238
+ while (changed) { changed = false; for (const [from, to] of edges) if (connected.has(from) && !connected.has(to)) { connected.add(to); changed = true } }
239
+ if (local.some((alias: string) => !connected.has(alias))) fail(correlated ? 'Nested correlated expression sources require a mandatory equality on id or a stored ref field' : 'Cartesian expression sources require an equality on id or a stored ref field', "Join each additional source or correlate it in WHERE, for example Cond.columnEqual('p2.id', 'p.id'); a LEFT JOIN ON only bounds its right-hand source.")
240
+ if (node.limit !== 1 && !aggregates.found) fail('Scalar subquery needs LIMIT 1 or an aggregate', 'Add .limit(1), or select a single aggregate such as Fn.count; multi-argument MIN/MAX are scalar functions.')
241
+ return { ...result, parts: { wire: JSON.stringify(node), type: result.calendarDate ? 'date' : result.type } }
242
+ }
243
+ const expr = (value: unknown) => scalar(value, { ...parent, rawRefs: true }, depth + 1)
244
+ // Value slots use deserializeValue: plain strings are literal data, even
245
+ // when they resemble functions or conditions. Typed/raw encodings still validate.
246
+ const data = (value: unknown) => { if (typeof value === 'string' && (value.startsWith('!!') || value.startsWith('!D!'))) expr(value) }
247
+ switch (node.type) {
248
+ case 'BinaryCondition': expr(node.key); data(node.value); break
249
+ case 'ColumnComparisonCondition': expr(node.leftKey); expr(node.rightKey); break
250
+ case 'LogicalCondition': for (const child of node.conditions ?? []) object(child, parent, depth + 1); break
251
+ case 'NotCondition': object(node.condition, parent, depth + 1); break
252
+ case 'NullCondition': case 'LikeCondition': expr(node.key); break
253
+ case 'BetweenCondition': expr(node.key); data(node.from); data(node.to); break
254
+ case 'ExistsCondition': case 'NotExistsCondition': object(node.subquery, parent, depth + 1); break
255
+ case 'InCondition': case 'NotInCondition': expr(node.key); if (node.subquery) object(node.subquery, parent, depth + 1); else (node.values ?? []).forEach(data); break
256
+ default: fail(`Unknown node type: ${node.type}`)
257
+ }
258
+ return { type: 'bool', dateOnly: false }
259
+ }
260
+ try {
261
+ // Follow the wire grammar, preserving value slots and LIKE patterns exactly.
262
+ // Only expression operands can encode functions/conditions; table aliases
263
+ // must survive the compiler's scoped-table transformation.
264
+ const canonical = (node: any): any => {
265
+ if (typeof node === 'string') {
266
+ if (node.startsWith('{')) return JSON.stringify(canonical(JSON.parse(node)))
267
+ if (node.startsWith('FN(') || node.startsWith('OP(')) {
268
+ const [name, ...args] = JSON.parse(node.slice(3, -1))
269
+ return `${node.slice(0, 3)}${JSON.stringify([typeof name === 'string' ? name.toUpperCase() : name, ...args.map(canonical)])})`
270
+ }
271
+ return node
272
+ }
273
+ if (!node || typeof node !== 'object') return node
274
+ const result = { ...node }
275
+ switch (node.type) {
276
+ case 'Table': result.alias ??= result.source; break
277
+ case 'SelectQuery':
278
+ result.tables = node.tables?.map(canonical)
279
+ result.fields = node.fields?.map((field: any) => ({ ...field, name: canonical(field.name) }))
280
+ result.joins = node.joins?.map((join: any) => ({ ...join, table: canonical(join.table), condition: canonical(join.condition) }))
281
+ result.where = node.where?.map(canonical)
282
+ result.orderBy = node.orderBy?.map((order: any) => ({ ...order, field: canonical(order.field) }))
283
+ break
284
+ case 'BinaryCondition': case 'NullCondition': case 'LikeCondition': case 'BetweenCondition':
285
+ result.key = canonical(node.key); break
286
+ case 'ColumnComparisonCondition':
287
+ result.leftKey = canonical(node.leftKey); result.rightKey = canonical(node.rightKey); break
288
+ case 'LogicalCondition': result.conditions = node.conditions?.map(canonical); break
289
+ case 'NotCondition': result.condition = canonical(node.condition); break
290
+ case 'ExistsCondition': case 'NotExistsCondition': result.subquery = canonical(node.subquery); break
291
+ case 'InCondition': case 'NotInCondition':
292
+ result.key = canonical(node.key)
293
+ if (node.subquery) result.subquery = canonical(node.subquery)
294
+ break
295
+ }
296
+ return result
297
+ }
298
+ wire = canonical(wire)
299
+ const scalarQuery = wire.trimStart().startsWith('{') && JSON.parse(wire).type === 'SelectQuery'
300
+ const result = scalarQuery ? object(JSON.parse(wire), root, 0) : scalar(wire, root, 0)
301
+ const wrapper = scalarQuery ? wire : JSON.stringify({ type: 'SelectQuery', tables: [], fields: [{ name: wire }] })
302
+ const query = Q.deserialize(wrapper, { allowRaw: false, functions, maxDepth: 4 }) as SelectQuery
303
+ // COUNT(1)/COUNT(*) depend on scoped source rows without naming a column.
304
+ if (!dependencies.length && !hasSourceAggregate) fail('Expression must reference at least one schema field', 'Add a field operand such as title or customer.name.')
305
+ const info = { sources, nodes, ast: scalarQuery ? query : query.getFields()[0].name as ISequelizable, scalarQuery, dependencies, ...result, parts: result.parts ?? { wire, type: result.calendarDate ? 'date' : result.type }, tables }
306
+ entries.set(key, info); return info
307
+ } catch (error) { if (error instanceof ExpressionError) throw error; return fail(`Raw SQL or invalid serialized node: ${error instanceof Error ? error.message : String(error)}`) }
308
+ }
309
+ export function fieldExpression(config: Config, entity: string, field: string): string | undefined {
310
+ const spec = config.entities[entity]
311
+ return spec.fields[field]?.computed ?? (spec.label && spec.displayField === field ? spec.label.serialize() : undefined)
312
+ }
313
+ export function validateComputedExpressions(config: InstanceConfig) {
314
+ const visit = (entity: string, field: string, stack: string[]): { descriptive: boolean; hops: number } => {
315
+ const key = `${entity}.${field}`
316
+ if (stack.includes(key)) expressionError(entity, field, `Computed expression cycle: ${[...stack, key].join(' -> ')}`, 'Remove a circular field dependency.')
317
+ const wire = fieldExpression(config, entity, field)
318
+ if (!wire) return { descriptive: fieldKind(config, entity, field) === 'string', hops: 0 }
319
+ const info = expressionInfo(config, entity, field, wire)
320
+ const expected = fieldKind(config, entity, field)
321
+ if (info.type !== 'null' && expected !== info.type) expressionError(entity, field, `Result type ${info.type} does not match field type ${expected}`, 'Change the field type or use an expression returning that type.')
322
+ const next = [...stack, key]; let hops = 0
323
+ const provenance = new Map<Dependency, boolean>()
324
+ for (const dependency of info.dependencies) {
325
+ let count = dependency.hops.length
326
+ for (const hop of dependency.hops) if (fieldExpression(config, hop.source, hop.field)) count += visit(hop.source, hop.field, next).hops
327
+ const result = visit(dependency.entity, dependency.field, next)
328
+ hops = Math.max(hops, count + result.hops)
329
+ provenance.set(dependency, result.descriptive)
330
+ }
331
+ return { descriptive: info.type === 'string' && !!info.textDependencies?.some(dep => provenance.get(dep)), hops }
332
+ }
333
+ for (const [entity, spec] of Object.entries(config.entities)) for (const [field, definition] of Object.entries(spec.fields)) if (definition.computed) {
334
+ if (definition.default !== undefined || definition.backfillFrom || definition.renameFrom) expressionError(entity, field, 'Computed fields cannot have storage defaults, backfills or renames', 'Remove storage options; a computed ref must retain its target entity.')
335
+ const result = visit(entity, field, [])
336
+ if (field === spec.displayField) {
337
+ if (result.hops > 1) expressionError(entity, field, 'displayField ref paths may traverse at most one hop', 'Use a direct ref and a target field without another ref traversal.')
338
+ if (!result.descriptive) expressionError(entity, field, 'A displayField expression must produce descriptive text, not only a date or number', 'Concatenate the formatted date with a customer or service name.')
339
+ }
340
+ }
341
+ }
342
+ export function readableComputed(kernel: KernelRegistry, scope: Scope, entity: string, field: string, seen = new Set<string>()): boolean {
343
+ const key = `${entity}.${field}`; if (seen.has(key)) return false
344
+ if (!kernel.can(scope, entity, 'read') || !kernel.fieldMask(entity, scope).includes(field)) return false
345
+ const spec = kernel.config.entities[entity]
346
+ const reference = spec.fields[field]
347
+ if (reference?.type === 'ref' && (!kernel.can(scope, reference.entity!, 'read') || !kernel.fieldMask(reference.entity!, scope).includes('id'))) return false
348
+ const wire = reference?.computed
349
+ if (!wire) return !spec.label || field !== spec.displayField || !!readableDisplay(kernel, scope, entity)
350
+ const next = new Set(seen).add(key)
351
+ const info = expressionInfo(kernel.config, entity, field, wire)
352
+ return [...info.tables.keys()].every(source => kernel.can(scope, source, 'read') && kernel.fieldMask(source, scope).includes('id')) && info.dependencies.every(dep =>
353
+ dep.hops.every(hop => kernel.fieldMask(hop.source, scope).includes(hop.field) && (!kernel.config.entities[hop.source].fields[hop.field].computed || readableComputed(kernel, scope, hop.source, hop.field, next)) && kernel.can(scope, hop.target, 'read') && kernel.fieldMask(hop.target, scope).includes('id')) && (!kernel.config.entities[dep.entity].fields[dep.field]?.entity || (kernel.can(scope, kernel.config.entities[dep.entity].fields[dep.field].entity!, 'read') && kernel.fieldMask(kernel.config.entities[dep.entity].fields[dep.field].entity!, scope).includes('id'))) && readableComputed(kernel, scope, dep.entity, dep.field, next))
354
+ }
@@ -1,3 +1,4 @@
1
+ import { readableComputed, expressionInfo } from './expressions'
1
2
  import { Q, walk, type ISequelizable } from '@jakub.knejzlik/ts-query'
2
3
  import type { InstanceConfig } from '../config'
3
4
  import type { KernelRegistry } from '../kernel/registry'
@@ -73,7 +74,7 @@ export function validateLabelExpressions(config: InstanceConfig) {
73
74
  */
74
75
  export function readableDisplay(kernel: KernelRegistry, scope: Scope, entity: string): string | undefined {
75
76
  const spec = kernel.config.entities[entity]
76
- if (!spec.displayField || !kernel.fieldMask(entity, scope).includes(spec.displayField)) return undefined
77
+ if (!spec.displayField || !kernel.fieldMask(entity, scope).includes(spec.displayField) || spec.fields[spec.displayField]?.computed && !readableComputed(kernel, scope, entity, spec.displayField)) return undefined
77
78
  if (spec.label && expressionColumns(spec.label).some(column => {
78
79
  const path = expressionPath(kernel.config, entity, column)
79
80
  return path.hops.some(hop => !kernel.fieldMask(hop.source, scope).includes(hop.field) || !kernel.can(scope, hop.target, 'read') || !kernel.fieldMask(hop.target, scope).includes('id'))
@@ -88,8 +89,16 @@ export function labelDependencies(config: Pick<InstanceConfig, 'entities'>, enti
88
89
  const result = new Map<string, { entity: string; field: string }>()
89
90
  function visit(name: string) {
90
91
  const definition = config.entities[name]
91
- if (!definition.label) return
92
- for (const column of expressionColumns(definition.label)) {
92
+ const computed = definition.displayField && definition.fields[definition.displayField]?.computed
93
+ if (!definition.label && !computed) return
94
+ if (computed) {
95
+ for (const dep of expressionInfo(config, name, definition.displayField!, computed).dependencies) {
96
+ const items = [...dep.hops.flatMap(hop => [{ entity: hop.source, field: hop.field }, { entity: hop.target, field: 'id' }]), { entity: dep.entity, field: dep.field }]
97
+ for (const item of items) result.set(`${item.entity}.${item.field}`, item)
98
+ }
99
+ return
100
+ }
101
+ for (const column of expressionColumns(definition.label!)) {
93
102
  const path = expressionPath(config, name, column)
94
103
  for (const hop of path.hops) for (const dependency of [{ entity: hop.source, field: hop.field }, { entity: hop.target, field: 'id' }]) result.set(`${dependency.entity}.${dependency.field}`, dependency)
95
104
  const dependency = { entity: path.entity, field: path.field }
@@ -5,4 +5,4 @@ export const QUERY_LIMITS = Object.freeze({
5
5
  levelRows: 2_000, rows: 5_000, statements: 16, bindings: 100,
6
6
  tableReferences: 64, sqlLength: 64_000, inputBytes: 64_000, cursorBytes: 8_000,
7
7
  })
8
- export interface QueryCost { depth: number; relations: number; fieldRows: number; exists: number; nodes: number }
8
+ export interface QueryCost { expressionSources?: number; depth: number; relations: number; fieldRows: number; exists: number; nodes: number }
@@ -6,6 +6,7 @@ import { invalid, QueryError, type QueryPath } from './errors'
6
6
  import { QUERY_LIMITS as L, type QueryCost } from './limits'
7
7
  import { isRestQuery } from './facade'
8
8
  import { labelPath } from './labels'
9
+ import { expressionInfo, fieldExpression, readableComputed } from './expressions'
9
10
 
10
11
  export type Scalar = string | number | boolean | null
11
12
  export interface Filter { [key: string]: unknown }
@@ -151,6 +152,35 @@ export function validateQuery(kernel: KernelRegistry, scope: Scope, input: unkno
151
152
  function foreignKeyCost(name: string) {
152
153
  cost.exists += kernel.fieldMask(name, scope).filter(field => kernel.config.entities[name].fields[field]?.type === 'ref').length
153
154
  }
155
+ // Charge expanded sources per evaluation context, including transitive computed fields.
156
+ // A repeated table alias counts again even when it names the same schema entity.
157
+ const expressionContexts = new Map<string, Set<string>>()
158
+ function expressionCost(name: string, field: string, context: string, rows: number, stack = new Set<string>()) {
159
+ const key = `${name}.${field}`
160
+ const seen = expressionContexts.get(context) ?? new Set<string>(); expressionContexts.set(context, seen)
161
+ if (seen.has(key) || stack.has(key) || !readableComputed(kernel, scope, name, field)) return
162
+ seen.add(key)
163
+ const wire = fieldExpression(kernel.config, name, field); if (!wire) return
164
+ const info = expressionInfo(kernel.config, name, field, wire)
165
+ const hopSources = new Set<string>()
166
+ for (const dep of info.dependencies) {
167
+ let sourcePath = dep.sourcePath ?? ''
168
+ for (const hop of dep.hops) { sourcePath += `/${hop.field}`; hopSources.add(sourcePath) }
169
+ }
170
+ const sources = info.sources.length + hopSources.size
171
+ cost.expressionSources = (cost.expressionSources ?? 0) + sources
172
+ cost.relations += sources; cost.nodes += info.nodes; cost.fieldRows += rows * sources
173
+ for (const source of info.sources) foreignKeyCost(source)
174
+ const next = new Set(stack).add(key)
175
+ for (const dep of info.dependencies) {
176
+ let dependencyContext = dep.sourcePath ? `${context}/${key}/source/${dep.sourcePath}` : context
177
+ for (const hop of dep.hops) {
178
+ expressionCost(hop.source, hop.field, dependencyContext, rows, next)
179
+ dependencyContext += `/ref/${hop.field}`
180
+ }
181
+ expressionCost(dep.entity, dep.field, dependencyContext, rows, next)
182
+ }
183
+ }
154
184
  function readable(name: string, field: string, path: QueryPath) {
155
185
  if (!kernel.fieldMask(name, scope).includes(field)) throw new QueryError('field_forbidden', path)
156
186
  }
@@ -163,27 +193,28 @@ export function validateQuery(kernel: KernelRegistry, scope: Scope, input: unkno
163
193
  if (!kernel.fieldMask(fkEntity, scope).includes(r.field) || !kernel.fieldMask(r.entity, scope).includes('id')) throw new QueryError('relation_forbidden', path)
164
194
  permission(r.entity, path); cost.relations++; return r
165
195
  }
166
- function where(name: string, node: Filter, depth: number, path: QueryPath, nesting = 0) {
196
+ function where(name: string, node: Filter, depth: number, path: QueryPath, nesting = 0, expressionContext = path.join('/'), rows = 1) {
167
197
  cost.nodes++; cost.depth = Math.max(cost.depth, depth)
168
198
  if (nesting > L.filterDepth) throw new QueryError('query_too_expensive', path, cost)
169
199
  for (const [key, value] of Object.entries(node)) {
170
- if (key === 'and' || key === 'or') (value as Filter[]).forEach((v, i) => where(name, v, depth, [...path, key, i], nesting + 1))
171
- else if (key === 'not') where(name, value as Filter, depth, [...path, key], nesting + 1)
200
+ if (key === 'and' || key === 'or') (value as Filter[]).forEach((v, i) => where(name, v, depth, [...path, key, i], nesting + 1, expressionContext, rows))
201
+ else if (key === 'not') where(name, value as Filter, depth, [...path, key], nesting + 1, expressionContext, rows)
172
202
  else if (Object.hasOwn(kernel.config.entities[name].relations, key)) {
173
203
  const r = relation(name, key, [...path, key]); cost.exists++
174
204
  foreignKeyCost(r.entity)
175
205
  const quantifier = r.many ? Object.keys(value as object)[0] : undefined
176
206
  where(r.entity, (quantifier ? (value as Record<string, Filter>)[quantifier] : value) as Filter, depth + 1,
177
- [...path, key, ...(quantifier ? [quantifier] : [])], nesting + 1)
178
- } else readable(name, key, [...path, key])
207
+ [...path, key, ...(quantifier ? [quantifier] : [])], nesting + 1, `${expressionContext}/${key}`, rows)
208
+ } else { readable(name, key, [...path, key]); expressionCost(name, key, expressionContext, rows) }
179
209
  }
180
210
  }
181
211
  function selection(name: string, node: Selection, depth: number, parents: number, path: QueryPath, single = false) {
182
212
  foreignKeyCost(name)
183
213
  permission(name, path); cost.depth = Math.max(cost.depth, depth)
184
214
  const limit = single ? 1 : node.limit ?? L.children
215
+ const context = path.join('/'); const rows = parents * limit
185
216
  const fields = node.select ?? kernel.fieldMask(name, scope)
186
- fields.forEach((f, i) => readable(name, f, [...path, 'select', i]))
217
+ fields.forEach((f, i) => { readable(name, f, [...path, 'select', i]); expressionCost(name, f, context, rows) })
187
218
  // Stable ordering, cursor keys and relation assembly all require readable id.
188
219
  readable(name, 'id', [...path, 'orderBy'])
189
220
  const labelKeys = [...new Set([...(node.labels ?? []), ...Object.keys((node as QueryInput).labelWhere ?? {}), ...((node as QueryInput).search?.fields ?? []).filter(key => labelPath(kernel.config, name, key)), ...(node.orderBy ?? []).filter(o => o.label).map(o => o.field)])]
@@ -198,12 +229,14 @@ export function validateQuery(kernel: KernelRegistry, scope: Scope, input: unkno
198
229
  joinedPath += `/${hop.field}`
199
230
  if (!joinedPaths.has(joinedPath)) { joinedPaths.add(joinedPath); cost.relations++; foreignKeyCost(hop.target) }
200
231
  }
232
+ if (plan.display) expressionCost(plan.entity, plan.display, `${context}/label/${key}`, rows)
233
+ for (const hop of plan.hops) expressionCost(hop.source, hop.field, context, rows)
201
234
  cost.fieldRows += parents * limit * 2
202
235
  }
203
- for (const key of (node as QueryInput).search?.fields ?? []) if (!labelPath(kernel.config, name, key)) readable(name, key, [...path, 'search', 'fields'])
204
- node.orderBy?.forEach((o, i) => { if (!o.label) readable(name, o.field, [...path, 'orderBy', i, 'field']) })
236
+ for (const key of (node as QueryInput).search?.fields ?? []) if (!labelPath(kernel.config, name, key)) { readable(name, key, [...path, 'search', 'fields']); expressionCost(name, key, context, rows) }
237
+ node.orderBy?.forEach((o, i) => { if (!o.label) { readable(name, o.field, [...path, 'orderBy', i, 'field']); expressionCost(name, o.field, context, rows) } })
205
238
  cost.fieldRows += parents * limit * fields.length
206
- if (node.where) where(name, node.where, depth, [...path, 'where'])
239
+ if (node.where) where(name, node.where, depth, [...path, 'where'], 0, context, rows)
207
240
  for (const [key, child] of Object.entries(node.include ?? {})) {
208
241
  const r = relation(name, key, [...path, 'include', key])
209
242
  selection(r.entity, child, depth + 1, parents * limit, [...path, 'include', key], !r.many)