@workbasehq/core 0.2.3 → 0.2.4

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.4",
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.4'
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))),
@@ -92,6 +92,10 @@ export function consoleModel(kernel: KernelRegistry, scope: Scope): ConsoleModel
92
92
  const values = field.type === 'enum' ? (field.values ?? []).map(value => `value_${value}`) : field.type === 'bool' ? ['yes', 'no'] : []
93
93
  return values.flatMap(key => [key, `${key}_${name}`])
94
94
  })))
95
+ for (const [name, entity] of Object.entries(config.entities)) {
96
+ if (authority.canRead(name)) for (const prefix of ['entity', 'entitySingular', 'entityObject']) keys.add(`${prefix}_${name}`)
97
+ for (const field of Object.keys(entity.fields)) if (authority.literals(name, field)) keys.add(`field_${field}_${name}`)
98
+ }
95
99
  const dictionary = Object.fromEntries(Object.entries(labels).filter(([key]) => keys.has(key)))
96
100
  return Object.keys(dictionary).length ? [[language, dictionary]] : []
97
101
  })) } : {}),
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,4 @@
1
+ import { expressionInfo, readableComputed, rebindExpression, type ExpressionInfo } from './expressions'
1
2
  import { ApiError } from '../errors'
2
3
  import { Q, Fn, Cond, Condition, toSQLWithBindings, type ISQLFlavor, type SelectQuery, type ISequelizable } from '@jakub.knejzlik/ts-query'
3
4
  import { renderPredicate, type KernelRegistry } from '../kernel/registry'
@@ -62,12 +63,19 @@ function compactBindings(statement: Statement): Statement {
62
63
  })
63
64
  return { sql, bindings }
64
65
  }
65
- const numberedSQLite: ISQLFlavor = Object.assign(Object.create(Q.flavors.sqlite), { parameterPlaceholder: (index: number) => `?${index}` })
66
+ // YEAR/MONTH are numeric in schema validation and cursor keys. SQLite strftime is text.
67
+ const numberedSQLite: ISQLFlavor = Object.assign(Object.create(Q.flavors.sqlite), {
68
+ parameterPlaceholder: (index: number) => `?${index}`,
69
+ escapeFunction(this: ISQLFlavor, ...args: Parameters<ISQLFlavor['escapeFunction']>) {
70
+ const sql = Q.flavors.sqlite.escapeFunction.apply(this, args)
71
+ return ['YEAR', 'MONTH'].includes(args[0].name) ? `CAST(${sql} AS INTEGER)` : sql
72
+ },
73
+ })
66
74
  /** One visibility check per readable FK in the scoped source, shared by all uses. */
67
75
  class ForeignKeyValue extends Condition {
68
- constructor(private column: string, private visible: Condition) { super() }
76
+ constructor(private column: string | ISequelizable, private visible: Condition) { super() }
69
77
  toSQL(flavor: ISQLFlavor) {
70
- return `CASE WHEN ${this.visible.toSQL(flavor)} THEN ${flavor.escapeColumn(this.column)} ELSE NULL END`
78
+ return `CASE WHEN ${this.visible.toSQL(flavor)} THEN ${typeof this.column === 'string' ? flavor.escapeColumn(this.column) : this.column.toSQL(flavor)} ELSE NULL END`
71
79
  }
72
80
  }
73
81
  /** Rebind trusted expression column operands to scoped source/join aliases. */
@@ -90,6 +98,15 @@ class DisplayExpression extends Condition {
90
98
  return this.visible.length ? `CASE WHEN ${Cond.and(this.visible).toSQL(flavor)} THEN ${sql} ELSE NULL END` : sql
91
99
  }
92
100
  }
101
+ /** Validated config ASTs use the same scoped source transformation as every read. */
102
+ class ComputedExpression extends Condition {
103
+ constructor(private info: ExpressionInfo, private columns: Map<string, string | Condition>, private visible: Condition[], private source: (entity: string) => SelectQuery) { super() }
104
+ toSQL(flavor: ISQLFlavor) {
105
+ const rendered = rebindExpression(this.info.ast, this.columns).toSQL(flavor, { transformTable: this.source })
106
+ const sql = this.info.scalarQuery ? `(${rendered})` : rendered
107
+ return this.visible.length ? `CASE WHEN ${Cond.and(this.visible).toSQL(flavor)} THEN ${sql} ELSE NULL END` : sql
108
+ }
109
+ }
93
110
  export function queryOrder(node: Selection): Order[] {
94
111
  const order = node.orderBy ?? []
95
112
  return order.some(o => o.field === 'id') ? order : [...order, { field: 'id', dir: 'asc' }]
@@ -126,7 +143,7 @@ function filterCondition(kernel: KernelRegistry, entity: string, alias: string,
126
143
  for (const [op, operand] of Object.entries(v as object)) {
127
144
  // Keep the masked predicate as the visibility residual. A redundant raw seek
128
145
  // is safe only in positive contexts: FALSE versus UNKNOWN matters under NOT.
129
- if (positive && kernel.config.entities[entity].fields[key]?.type === 'ref') {
146
+ if (positive && kernel.config.entities[entity].fields[key]?.type === 'ref' && !kernel.config.entities[entity].fields[key].computed) {
130
147
  if (op === 'eq' && operand !== null) conditions.push(Cond.equal(col(alias, `__raw_${key}`), value(operand)))
131
148
  if (op === 'in' && (operand as Scalar[]).length && !(operand as Scalar[]).includes(null)) conditions.push(new InCondition(col(alias, `__raw_${key}`), operand as Scalar[]))
132
149
  }
@@ -145,7 +162,7 @@ function filterCondition(kernel: KernelRegistry, entity: string, alias: string,
145
162
  function hasRequiredForeignKeySeek(kernel: KernelRegistry, entity: string, filter: Filter): boolean {
146
163
  return Object.entries(filter).some(([field, operand]) => {
147
164
  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
165
+ if (kernel.config.entities[entity].fields[field]?.type !== 'ref' || kernel.config.entities[entity].fields[field].computed) return false
149
166
  const operators = operand as Record<string, unknown>
150
167
  return (Object.hasOwn(operators, 'eq') && operators.eq !== null)
151
168
  || (Array.isArray(operators.in) && operators.in.length > 0 && !operators.in.includes(null))
@@ -167,7 +184,8 @@ export function assertStatement(statement: Statement, cost?: QueryCost) {
167
184
  }
168
185
  export function renderStatement(kernel: KernelRegistry, scope: Scope, ast: SelectQuery, cost?: QueryCost, requiredDisplays?: Set<string>): Statement {
169
186
  let references = 0
170
- function scopedTable(entity: string, extra?: (alias: string) => Condition, maskForeignKeys = true, displayRequired = requiredDisplays?.has(entity) ?? true): SelectQuery {
187
+ function scopedTable(entity: string, extra?: (alias: string) => Condition, maskForeignKeys = true, displayRequired = requiredDisplays?.has(entity) ?? true, computedDemand?: Set<string>): SelectQuery {
188
+ if (!maskForeignKeys) computedDemand = new Set()
171
189
  if (!Object.hasOwn(kernel.config.entities, entity)) throw new QueryError('query_invalid')
172
190
  // Bounds policy recursion too, before a future policy compiler can introduce cycles.
173
191
  if (++references > L.tableReferences) throw new QueryError('query_too_expensive', [], cost)
@@ -187,10 +205,65 @@ export function renderStatement(kernel: KernelRegistry, scope: Scope, ast: Selec
187
205
  }
188
206
  return visible
189
207
  }
208
+ const computed = new Map<string, Condition>()
209
+ const computing = new Set<string>()
210
+ function computedValue(field: string): Condition {
211
+ const previous = computed.get(field); if (previous) return previous
212
+ if (computing.has(field)) throw new QueryError('query_invalid')
213
+ if (!readableComputed(kernel, scope, entity, field)) return new DisplayExpression(Q.value(null), new Map(), [])
214
+ computing.add(field)
215
+ const info = expressionInfo(kernel.config, entity, field, definition.fields[field].computed!)
216
+ const columns = new Map<string, string | Condition>(); const visible: Condition[] = []
217
+ const paths = new Map<string, string>()
218
+ const demands = new Map<string, Set<string>>()
219
+ for (const dependency of info.dependencies) {
220
+ if (dependency.qualifier && dependency.qualifier !== 'self') continue
221
+ const key = dependency.hops.map(hop => `/${hop.field}`).join('')
222
+ const demand = demands.get(key) ?? new Set<string>(); demand.add(dependency.field); demands.set(key, demand)
223
+ }
224
+ for (const dependency of info.dependencies) {
225
+ // Subquery aliases resolve against their own scoped projections. `self`
226
+ // always denotes this row; no physical source name is ever rebound.
227
+ if (dependency.qualifier && dependency.qualifier !== 'self') continue
228
+ let parent = alias; let key = ''
229
+ for (const hop of dependency.hops) {
230
+ key += `/${hop.field}`
231
+ let target = paths.get(key)
232
+ if (!target) {
233
+ const table = scopedTable(hop.target, undefined, true, true, demands.get(key) ?? new Set())
234
+ target = `computed_join_${references}_${paths.size}`; paths.set(key, target)
235
+ const operand = parent === alias && definition.fields[hop.field]?.computed ? computedValue(hop.field) : col(parent, hop.field)
236
+ query = query.leftJoin(Q.table(table, target), Cond.equal(col(target, 'id'), typeof operand === 'string' ? Q.expr(operand) : operand))
237
+ visible.push(Cond.isNotNull(col(target, 'id')))
238
+ }
239
+ parent = target
240
+ }
241
+ if (parent === alias && definition.fields[dependency.field]?.computed) {
242
+ const operand = computedValue(dependency.field)
243
+ columns.set(dependency.column, operand)
244
+ visible.push(Cond.isNotNull(operand))
245
+ } else if (parent === alias && definition.fields[dependency.field]?.type === 'ref') {
246
+ const allowed = foreignKeyVisible(dependency.field)
247
+ columns.set(dependency.column, new ForeignKeyValue(col(alias, dependency.field), allowed))
248
+ visible.push(Cond.or([Cond.isNull(col(alias, dependency.field)), allowed]))
249
+ } else {
250
+ columns.set(dependency.column, col(parent, dependency.field))
251
+ 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')))
252
+ if (kernel.config.entities[dependency.entity].fields[dependency.field]?.computed) visible.push(Cond.isNotNull(col(parent, dependency.field)))
253
+ }
254
+ }
255
+ let result: Condition = new ComputedExpression(info, columns, visible, target => scopedTable(target, undefined, true, true, info.tables.get(target) ?? new Set()))
256
+ if (definition.fields[field].type === 'ref') {
257
+ const operand = result
258
+ const allowed = Cond.exists(scopedTable(definition.fields[field].entity!, child => Cond.equal(col(child, 'id'), operand), false))
259
+ result = new ForeignKeyValue(operand, allowed)
260
+ }
261
+ computed.set(field, result); computing.delete(field); return result
262
+ }
190
263
  const joins = new Map<string, string>()
191
264
  let label: Condition | ReturnType<typeof Q.raw> = Q.raw('NULL')
192
265
  const labelVisibility: Condition[] = []
193
- if (maskForeignKeys && displayRequired && definition.label && readableDisplay(kernel, scope, entity)) {
266
+ if (maskForeignKeys && displayRequired && (!computedDemand || computedDemand.has(definition.displayField!)) && definition.label && readableDisplay(kernel, scope, entity)) {
194
267
  const columns = new Map<string, string | Condition>()
195
268
  // A joined source computes its own label only when this expression consumes
196
269
  // it. Passing through an account to its customer does not need account.label.
@@ -207,11 +280,16 @@ export function renderStatement(kernel: KernelRegistry, scope: Scope, ast: Selec
207
280
  if (!target) {
208
281
  const table = scopedTable(hop.target, undefined, true, displayJoins.has(key))
209
282
  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)))
283
+ const operand = parent === alias && definition.fields[hop.field]?.computed ? computedValue(hop.field) : col(parent, hop.field)
284
+ query = query.leftJoin(Q.table(table, target), Cond.equal(col(target, 'id'), typeof operand === 'string' ? Q.expr(operand) : operand))
211
285
  }
212
286
  parent = target
213
287
  }
214
- if (parent === alias && definition.fields[path.field]?.type === 'ref') {
288
+ if (parent === alias && definition.fields[path.field]?.computed) {
289
+ const operand = computedValue(path.field)
290
+ columns.set(column, operand)
291
+ labelVisibility.push(Cond.isNotNull(operand))
292
+ } else if (parent === alias && definition.fields[path.field]?.type === 'ref') {
215
293
  const visible = foreignKeyVisible(path.field)
216
294
  columns.set(column, new ForeignKeyValue(col(alias, path.field), visible))
217
295
  labelVisibility.push(Cond.or([Cond.isNull(col(alias, path.field)), visible]))
@@ -232,7 +310,10 @@ export function renderStatement(kernel: KernelRegistry, scope: Scope, ast: Selec
232
310
  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
311
  for (const field of fields) {
234
312
  const definition = kernel.config.entities[entity].fields[field]
235
- if (kernel.config.entities[entity].label && field === kernel.config.entities[entity].displayField) {
313
+ if (definition?.computed) {
314
+ const projected = !computedDemand || computedDemand.has(field) ? computedValue(field) : Q.raw('NULL')
315
+ query = query.field(projected, field)
316
+ } else if (kernel.config.entities[entity].label && field === kernel.config.entities[entity].displayField) {
236
317
  query = query.field(label, field)
237
318
  } else if (maskForeignKeys && definition?.type === 'ref') {
238
319
  // Target identity must itself be readable. Visibility probes expose no target
@@ -383,7 +464,7 @@ export function compileRoot(kernel: KernelRegistry, scope: Scope, query: QueryIn
383
464
  export function compileInclude(kernel: KernelRegistry, scope: Scope, entity: string, node: Selection, parentField: string, ids: Scalar[], cost?: QueryCost) {
384
465
  let child = buildSelect(kernel, scope, entity, node, [parentField])
385
466
  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))
467
+ 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
468
  const fields = executionFields(kernel, scope, entity, node, [parentField])
388
469
  const sort = queryOrder(node).map(o => `${quote('row')}.${quote(o.field)} ${o.dir.toUpperCase()}`).join(', ')
389
470
  child = child.field(Q.raw(`ROW_NUMBER() OVER (PARTITION BY ${quote('row')}.${quote(parentField)} ORDER BY ${sort})`), '__row_number')
@@ -0,0 +1,349 @@
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
+ interface ValueInfo { type: Kind; dateOnly: boolean; textDependencies?: Dependency[] }
13
+ export interface ExpressionInfo extends ValueInfo { sources: string[]; nodes: number; ast: ISequelizable; scalarQuery: boolean; dependencies: Dependency[]; tables: Map<string, Set<string>> }
14
+ export interface ExpressionIssue { code: 'invalid_expression'; entity: string; field: string; message: string; suggestedFix: string }
15
+ export class ExpressionError extends Error {
16
+ readonly code = 'invalid_expression'
17
+ constructor(public errors: ExpressionIssue[]) { super(errors.map(issue => `${issue.message} Fix: ${issue.suggestedFix}`).join('\n')) }
18
+ }
19
+ export function expressionError(entity: string, field: string, message: string, suggestedFix = 'Use schema fields and structured ts-query functions, then validate the proposal.'): never {
20
+ throw new ExpressionError([{ code: 'invalid_expression', entity, field, message: `Invalid expression: ${entity}.${field}; ${message}`, suggestedFix }])
21
+ }
22
+ 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']
23
+ /** Contracts target the SQLite/D1 renderer, rather than the library's cross-dialect API. */
24
+ const arities: Record<string, [number, number]> = {
25
+ CONCAT: [1, 100], IFNULL: [2, 2], COALESCE: [2, 100], NULLIF: [2, 2], IF: [3, 3],
26
+ LOWER: [1, 1], UPPER: [1, 1], TRIM: [1, 2], LTRIM: [1, 2], RTRIM: [1, 2],
27
+ SUBSTRING: [2, 3], SUBSTR: [2, 3], LENGTH: [1, 1], REPLACE: [3, 3],
28
+ STRFTIME: [2, 20], DATE: [1, 20], DATETIME: [1, 20], TIME: [1, 20],
29
+ JULIANDAY: [1, 20], UNIXEPOCH: [1, 20], YEAR: [1, 1], MONTH: [1, 1], DATEADD: [3, 3],
30
+ ABS: [1, 1], ROUND: [1, 2], MIN: [1, 100], MAX: [1, 100], SUM: [1, 1], COUNT: [1, 1], AVG: [1, 1],
31
+ }
32
+ const base: Record<string, Kind> = { id: 'string', organization_id: 'string', created_at: 'datetime', updated_at: 'datetime', version: 'number' }
33
+ 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'
34
+ const cache = new WeakMap<Config, Map<string, ExpressionInfo>>()
35
+ /** Clone the validated AST, replacing operand nodes rather than identifier escaping.
36
+ * Alias declarations are strings; ORDER BY aliases belong to their own SELECT.
37
+ * Within a SELECT only `self` references bind to the outer entity; local aliases
38
+ * may share their spelling with a ref path in the enclosing expression.
39
+ */
40
+ export function rebindExpression<T>(node: T, columns: Map<string, string | ISequelizable>, inQuery = false, preserved = new Set<unknown>()): T {
41
+ if (!node || typeof node !== 'object' || node instanceof Date || preserved.has(node)) return node
42
+ if (node instanceof SelectQuery) {
43
+ inQuery = true
44
+ const aliases = new Set(node.getFields().map(field => field.alias).filter(alias => alias !== undefined))
45
+ preserved = new Set(node.getOrderBy().filter(order => aliases.has(order.field.serialize())).map(order => order.field))
46
+ } else if ('serialize' in node && typeof node.serialize === 'function') {
47
+ const wire = node.serialize()
48
+ const column = wire.match(/^#([^#]+)#$/)?.[1] ?? wire
49
+ const mapped = !inQuery || column.startsWith('self.') ? columns.get(column) : undefined
50
+ if (mapped) return (typeof mapped === 'string' ? Q.expr(mapped) : mapped) as T
51
+ }
52
+ if (Array.isArray(node)) return node.map(child => rebindExpression(child, columns, inQuery, preserved)) as T
53
+ return Object.assign(Object.create(Object.getPrototypeOf(node)), Object.fromEntries(
54
+ Object.entries(node).map(([key, child]) => [key, rebindExpression(child, columns, inQuery, preserved)]),
55
+ ))
56
+ }
57
+ /** Validate the library wire grammar before deserializing. No arbitrary JS or SQL is interpreted.
58
+ * Query aliases are lexical; an outer row is explicitly named `self` inside a subquery.
59
+ */
60
+ export function expressionInfo(config: Config, entity: string, field: string, wire: string): ExpressionInfo {
61
+ let entries = cache.get(config); if (!entries) { entries = new Map(); cache.set(config, entries) }
62
+ const key = `${entity}.${field}:${wire}`; const known = entries.get(key); if (known) return known
63
+ const fail = (message: string, fix?: string): never => expressionError(entity, field, message, fix)
64
+ if (wire.length > 32000) fail('Expression exceeds 32000 bytes', 'Shorten the expression.')
65
+ const sources: string[] = []; const dependencies: Dependency[] = []; const tables = new Map<string, Set<string>>(); let nodes = 0
66
+ let hasSourceAggregate = false
67
+ type Context = { aliases: Map<string, string>; aliasContexts: Map<string, string>; current?: string; query: boolean; rawRefs?: boolean;
68
+ clause?: 'SELECT' | 'WHERE' | 'JOIN ON' | 'ORDER BY'; selectAggregate?: boolean;
69
+ aggregate?: string; aggregates?: { found: boolean }; outerAliases?: Set<string>; outerReferences?: Set<string>;
70
+ aggregateReferences?: { aliases: Set<string>; references: Set<string> }[] }
71
+ const root: Context = { aliases: new Map([['self', entity]]), aliasContexts: new Map(), current: entity, query: false }
72
+ const reference = (column: string, context: Context): Kind => {
73
+ if (column.includes('*') || !/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$/.test(column)) fail(`Unknown field: ${column}`)
74
+ const parts = column.split('.'); let source = context.current ?? entity; let qualifier: string | undefined
75
+ 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.')
76
+ if (parts.length > 1 && context.aliases.has(parts[0])) { qualifier = parts.shift()!; source = context.aliases.get(qualifier)! }
77
+ if (qualifier && context.outerAliases?.has(qualifier)) context.outerReferences?.add(qualifier)
78
+ if (qualifier) for (const aggregate of context.aggregateReferences ?? []) {
79
+ if (aggregate.aliases.has(qualifier)) aggregate.references.add(qualifier)
80
+ }
81
+ 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.')
82
+ const hops: Dependency['hops'] = []
83
+ while (parts.length > 1) {
84
+ const name = parts.shift()!; const spec = config.entities[source] && Object.hasOwn(config.entities[source].fields, name) ? config.entities[source].fields[name] : undefined
85
+ if (spec?.type !== 'ref' || !spec.entity) fail(`Unknown ref path: ${source}.${name}`)
86
+ hops.push({ source, field: name, target: spec!.entity! }); source = spec!.entity!
87
+ }
88
+ let name = parts[0]
89
+ const spec = config.entities[source] && Object.hasOwn(config.entities[source].fields, name) ? config.entities[source].fields[name] : undefined
90
+ if (!spec && !Object.hasOwn(base, name)) fail(`Unknown schema field: ${source}.${name}`, 'Choose a field returned by inspect_schema.')
91
+ // A bare to-one ref means the target display value, never its physical FK.
92
+ if (spec?.type === 'ref' && !context.rawRefs) {
93
+ if (qualifier && qualifier !== 'self') fail('Ref paths inside subqueries require an explicit schema join')
94
+ hops.push({ source, field: name, target: spec!.entity! }); source = spec!.entity!
95
+ name = config.entities[source].displayField ?? fail(`Referenced entity ${source} has no displayField`)
96
+ }
97
+ if (qualifier && qualifier !== 'self' && hops.length) fail('Ref paths inside subqueries require an explicit schema join')
98
+ dependencies.push({ column, entity: source, field: name, hops, qualifier, sourcePath: qualifier ? context.aliasContexts.get(qualifier) : undefined })
99
+ if (qualifier && qualifier !== 'self') { const fields = tables.get(source) ?? new Set<string>(); fields.add(name); tables.set(source, fields) }
100
+ return fieldKind(config, source, name)
101
+ }
102
+ function scalar(node: unknown, context: Context, depth: number): ValueInfo {
103
+ if (++nodes > 512 || depth > 32) fail('Expression exceeds the complexity budget', 'Use fewer functions or subqueries.')
104
+ if (typeof node === 'number') return { type: 'number', dateOnly: false }
105
+ if (typeof node === 'boolean') return { type: 'bool', dateOnly: false }
106
+ if (typeof node !== 'string') return fail('Unknown expression node')
107
+ 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 } }
108
+ if (node.startsWith('!D!')) return { type: 'datetime', dateOnly: true }
109
+ if (node.startsWith('FN(') || node.startsWith('OP(')) {
110
+ if (!node.endsWith(')')) fail('Invalid function encoding')
111
+ const [name, ...args] = JSON.parse(node.slice(3, -1)) as [string, ...unknown[]]
112
+ if (typeof name !== 'string' || !(node.startsWith('OP(') ? ['+', '-', '*', '/'] : functions).includes(name.toUpperCase())) fail(`Unknown or unsafe function: ${name}`)
113
+ const fn = name.toUpperCase()
114
+ if (node.startsWith('FN(')) {
115
+ 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.`)
116
+ const [min, max] = arities[fn]
117
+ 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.`)
118
+ }
119
+ // SQLite MIN/MAX with multiple arguments are scalar functions. A SELECT
120
+ // below an aggregate starts a new context; scalar wrappers do not.
121
+ const aggregate = node.startsWith('FN(') && (['SUM', 'COUNT', 'AVG'].includes(fn) || ['MIN', 'MAX'].includes(fn) && args.length === 1)
122
+ 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.')
123
+ 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.')
124
+ 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.')
125
+ if (aggregate && context.aggregates) context.aggregates.found = true
126
+ const operandsScope = { aliases: new Set(context.aliases.keys()), references: new Set<string>() }
127
+ const operandContext = aggregate ? { ...context, aggregate: fn, aggregateReferences: [...(context.aggregateReferences ?? []), operandsScope] } : context
128
+ // COUNT(*) has no column operand and belongs to this SELECT, like COUNT(1).
129
+ const values: ValueInfo[] = args.map(arg => fn === 'COUNT' && arg === '*' ? { type: 'number', dateOnly: false } : scalar(arg, operandContext, depth + 1))
130
+ // SQLite moves an aggregate with exclusively outer column operands to an
131
+ // enclosing SELECT, even across scalar wrappers or nested correlations.
132
+ // Reject that shape before it can collapse entity rows or evade clause rules.
133
+ if (aggregate && operandsScope.references.size && [...operandsScope.references].every(alias => context.outerAliases?.has(alias))) {
134
+ 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.')
135
+ }
136
+ if (aggregate && context.query && !operandsScope.references.size && [...context.aliases.keys()].some(alias => !context.outerAliases?.has(alias))) hasSourceAggregate = true
137
+ // Ordinary computed expressions are projected into each scoped entity row.
138
+ // An aggregate here would change the cardinality of every list and count,
139
+ // including when this expression is expanded through another computed field.
140
+ 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.')
141
+ const operands = (indices: number[], kinds: Kind[], example: string) => {
142
+ if (indices.some(i => ![...kinds, 'null'].includes(values[i].type))) fail(`${fn} operand type mismatch; expected ${kinds.join(' or ')}`, example)
143
+ }
144
+ const all = values.map((_, i) => i)
145
+ const textDependencies = values.flatMap(value => value.textDependencies ?? [])
146
+ if (['LOWER','UPPER','TRIM','LTRIM','RTRIM','REPLACE','LENGTH'].includes(fn)) operands(all, ['string'], `Use ${fn} with text fields and Q.value('text').`)
147
+ 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.') }
148
+ if (['SUM','AVG','ABS','ROUND'].includes(fn)) operands(all, ['number'], `Use ${fn} with numeric fields and Q.value(number).`)
149
+ if (['STRFTIME','DATE','DATETIME','TIME','JULIANDAY','UNIXEPOCH','YEAR','MONTH','DATEADD'].includes(fn)) {
150
+ const start = fn === 'STRFTIME' ? 1 : 0
151
+ operands([start], ['datetime','string'], 'Use a datetime field or an ISO date string.')
152
+ if (fn === 'STRFTIME') operands([0], ['string'], "Use Fn.strftime('%Y-%m-%d', 'date').")
153
+ if (fn === 'DATEADD') {
154
+ const literal = (arg: unknown) => typeof arg === 'string' && arg.startsWith('!!!') ? JSON.parse(arg.slice(3)) : undefined
155
+ 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').")
156
+ } else operands(all.slice(start + 1), ['string'], "Use literal SQLite date modifier strings, for example Q.value('start of month').")
157
+ }
158
+ 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 } }
159
+ 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), textDependencies: values.slice(1).flatMap(value => value.textDependencies ?? []) } }
160
+ 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), textDependencies: fn === 'NULLIF' ? values[0].textDependencies : textDependencies } }
161
+ if (['COUNT','SUM','AVG','ABS','ROUND','LENGTH','JULIANDAY','UNIXEPOCH','YEAR','MONTH','DATEDIFF'].includes(fn)) return { type: 'number', dateOnly: false }
162
+ if (['STRFTIME','DATE','DATETIME','TIME','DATEADD'].includes(fn)) return { type: fn === 'STRFTIME' ? 'string' : 'datetime', dateOnly: true }
163
+ return { type: 'string', dateOnly: fn === 'CONCAT' && values.every(value => value.dateOnly || value.type === 'null'), textDependencies }
164
+ }
165
+ if (node.startsWith('{')) return object(JSON.parse(node), context, depth + 1)
166
+ if (/^[+-]?\d+(?:\.\d+)?$/.test(node)) return { type: 'number', dateOnly: false }
167
+ if (node === 'NULL') return { type: 'null', dateOnly: false }
168
+ if (/^&[^#]*&$/.test(node)) return { type: 'string', dateOnly: false } // Library Fn.string encoding.
169
+ if (node.startsWith('!!')) fail('Raw SQL is forbidden; use structured ts-query expressions')
170
+ const column = node.match(/^#([^#]+)#$/)?.[1] ?? node
171
+ const type = reference(column, context); return { type, dateOnly: type === 'datetime', textDependencies: type === 'string' ? [dependencies[dependencies.length - 1]] : [] }
172
+ }
173
+ function object(node: any, parent: Context, depth: number): ValueInfo {
174
+ if (++nodes > 512 || depth > 32) fail('Expression exceeds the complexity budget', 'Use fewer functions or subqueries.')
175
+ if (!node || typeof node !== 'object' || Array.isArray(node)) return fail('Unknown node')
176
+ if (node.type === 'SelectQuery') {
177
+ if (depth > 4) fail('Subquery nesting exceeds the budget')
178
+ 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.')
179
+ if (node.fields?.length !== 1) fail('A scalar subquery must select exactly one field')
180
+ const context: Context = { aliases: new Map(parent.aliases), aliasContexts: new Map(parent.aliasContexts), query: true,
181
+ outerAliases: new Set(parent.aliases.keys()), outerReferences: new Set(), aggregateReferences: parent.aggregateReferences }
182
+ const register = (table: any) => {
183
+ 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.')
184
+ const alias = table.alias ?? table.source
185
+ 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}`)
186
+ 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())
187
+ }
188
+ for (const table of node.tables ?? []) register(table)
189
+ // An ON clause can see the left-hand sources and its own right-hand source.
190
+ // Validate it before registering later joins, including nested correlations.
191
+ for (const join of node.joins ?? []) {
192
+ if (!['INNER','LEFT','CROSS'].includes(join.joinType)) fail('Unsupported join')
193
+ register(join.table)
194
+ if (join.condition) object(join.condition, { ...context, clause: 'JOIN ON' }, depth + 1)
195
+ }
196
+ // Only mandatory equalities connect sources: OR and NOT cannot bound a join.
197
+ const local = [...(node.tables ?? []), ...(node.joins ?? []).map((join: any) => join.table)].map((table: any) => table.alias)
198
+ const edges: [string, string][] = []
199
+ const endpoint = (column: unknown): { alias: string; indexed: boolean } | undefined => {
200
+ if (typeof column !== 'string') return
201
+ const parts = (column.match(/^#([^#]+)#$/)?.[1] ?? column).split('.')
202
+ if (parts.length !== 2 || !context.aliases.has(parts[0])) return
203
+ const source = context.aliases.get(parts[0])!; const spec = config.entities[source].fields[parts[1]]
204
+ return { alias: parts[0], indexed: parts[1] === 'id' || spec?.type === 'ref' && !spec.computed }
205
+ }
206
+ const equality = (condition: any, rightAlias?: string) => {
207
+ if (condition?.type === 'LogicalCondition' && condition.operator === 'AND') for (const child of condition.conditions ?? []) equality(child, rightAlias)
208
+ if (condition?.type !== 'ColumnComparisonCondition' || condition.operator !== '=') return
209
+ const left = endpoint(condition.leftKey); const right = endpoint(condition.rightKey)
210
+ if (!left || !right || left.alias === right.alias || !(left.indexed || right.indexed)) return
211
+ // A LEFT ON only bounds its own right-hand source. Its predicates do
212
+ // not remove unmatched rows from sources already on the left.
213
+ if (!rightAlias || right.alias === rightAlias) edges.push([left.alias, right.alias])
214
+ if (!rightAlias || left.alias === rightAlias) edges.push([right.alias, left.alias])
215
+ }
216
+ for (const where of node.where ?? []) equality(where)
217
+ for (const join of node.joins ?? []) {
218
+ if (join.joinType === 'INNER') equality(join.condition)
219
+ if (join.joinType === 'LEFT') equality(join.condition, join.table.alias)
220
+ }
221
+ for (const where of node.where ?? []) object(where, { ...context, clause: 'WHERE' }, depth + 1)
222
+ const aggregates = { found: false }
223
+ const result = scalar(node.fields[0].name, { ...context, clause: 'SELECT', aggregates }, depth + 1)
224
+ for (const order of node.orderBy ?? []) {
225
+ // An unqualified ORDER BY output alias names the projection, not a source
226
+ // column. Validate that expression under this SELECT's aggregate context.
227
+ const projection = node.fields.find((field: any) => field.alias === order.field)
228
+ scalar(projection ? projection.name : order.field, { ...context, clause: 'ORDER BY', selectAggregate: aggregates.found }, depth + 1)
229
+ }
230
+ const correlated = parent.query && context.outerReferences!.size > 0
231
+ const connected = new Set([...parent.aliases.keys(), ...(correlated ? [] : local.slice(0, 1))])
232
+ let changed = true
233
+ while (changed) { changed = false; for (const [from, to] of edges) if (connected.has(from) && !connected.has(to)) { connected.add(to); changed = true } }
234
+ 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.")
235
+ 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.')
236
+ return result
237
+ }
238
+ const expr = (value: unknown) => scalar(value, { ...parent, rawRefs: true }, depth + 1)
239
+ // Value slots use deserializeValue: plain strings are literal data, even
240
+ // when they resemble functions or conditions. Typed/raw encodings still validate.
241
+ const data = (value: unknown) => { if (typeof value === 'string' && (value.startsWith('!!') || value.startsWith('!D!'))) expr(value) }
242
+ switch (node.type) {
243
+ case 'BinaryCondition': expr(node.key); data(node.value); break
244
+ case 'ColumnComparisonCondition': expr(node.leftKey); expr(node.rightKey); break
245
+ case 'LogicalCondition': for (const child of node.conditions ?? []) object(child, parent, depth + 1); break
246
+ case 'NotCondition': object(node.condition, parent, depth + 1); break
247
+ case 'NullCondition': case 'LikeCondition': expr(node.key); break
248
+ case 'BetweenCondition': expr(node.key); data(node.from); data(node.to); break
249
+ case 'ExistsCondition': case 'NotExistsCondition': object(node.subquery, parent, depth + 1); break
250
+ case 'InCondition': case 'NotInCondition': expr(node.key); if (node.subquery) object(node.subquery, parent, depth + 1); else (node.values ?? []).forEach(data); break
251
+ default: fail(`Unknown node type: ${node.type}`)
252
+ }
253
+ return { type: 'bool', dateOnly: false }
254
+ }
255
+ try {
256
+ // Follow the wire grammar, preserving value slots and LIKE patterns exactly.
257
+ // Only expression operands can encode functions/conditions; table aliases
258
+ // must survive the compiler's scoped-table transformation.
259
+ const canonical = (node: any): any => {
260
+ if (typeof node === 'string') {
261
+ if (node.startsWith('{')) return JSON.stringify(canonical(JSON.parse(node)))
262
+ if (node.startsWith('FN(') || node.startsWith('OP(')) {
263
+ const [name, ...args] = JSON.parse(node.slice(3, -1))
264
+ return `${node.slice(0, 3)}${JSON.stringify([typeof name === 'string' ? name.toUpperCase() : name, ...args.map(canonical)])})`
265
+ }
266
+ return node
267
+ }
268
+ if (!node || typeof node !== 'object') return node
269
+ const result = { ...node }
270
+ switch (node.type) {
271
+ case 'Table': result.alias ??= result.source; break
272
+ case 'SelectQuery':
273
+ result.tables = node.tables?.map(canonical)
274
+ result.fields = node.fields?.map((field: any) => ({ ...field, name: canonical(field.name) }))
275
+ result.joins = node.joins?.map((join: any) => ({ ...join, table: canonical(join.table), condition: canonical(join.condition) }))
276
+ result.where = node.where?.map(canonical)
277
+ result.orderBy = node.orderBy?.map((order: any) => ({ ...order, field: canonical(order.field) }))
278
+ break
279
+ case 'BinaryCondition': case 'NullCondition': case 'LikeCondition': case 'BetweenCondition':
280
+ result.key = canonical(node.key); break
281
+ case 'ColumnComparisonCondition':
282
+ result.leftKey = canonical(node.leftKey); result.rightKey = canonical(node.rightKey); break
283
+ case 'LogicalCondition': result.conditions = node.conditions?.map(canonical); break
284
+ case 'NotCondition': result.condition = canonical(node.condition); break
285
+ case 'ExistsCondition': case 'NotExistsCondition': result.subquery = canonical(node.subquery); break
286
+ case 'InCondition': case 'NotInCondition':
287
+ result.key = canonical(node.key)
288
+ if (node.subquery) result.subquery = canonical(node.subquery)
289
+ break
290
+ }
291
+ return result
292
+ }
293
+ wire = canonical(wire)
294
+ const scalarQuery = wire.trimStart().startsWith('{') && JSON.parse(wire).type === 'SelectQuery'
295
+ const result = scalarQuery ? object(JSON.parse(wire), root, 0) : scalar(wire, root, 0)
296
+ const wrapper = scalarQuery ? wire : JSON.stringify({ type: 'SelectQuery', tables: [], fields: [{ name: wire }] })
297
+ const query = Q.deserialize(wrapper, { allowRaw: false, functions, maxDepth: 4 }) as SelectQuery
298
+ // COUNT(1)/COUNT(*) depend on scoped source rows without naming a column.
299
+ if (!dependencies.length && !hasSourceAggregate) fail('Expression must reference at least one schema field', 'Add a field operand such as title or customer.name.')
300
+ const info = { sources, nodes, ast: scalarQuery ? query : query.getFields()[0].name as ISequelizable, scalarQuery, dependencies, ...result, tables }
301
+ entries.set(key, info); return info
302
+ } catch (error) { if (error instanceof ExpressionError) throw error; return fail(`Raw SQL or invalid serialized node: ${error instanceof Error ? error.message : String(error)}`) }
303
+ }
304
+ export function fieldExpression(config: Config, entity: string, field: string): string | undefined {
305
+ const spec = config.entities[entity]
306
+ return spec.fields[field]?.computed ?? (spec.label && spec.displayField === field ? spec.label.serialize() : undefined)
307
+ }
308
+ export function validateComputedExpressions(config: InstanceConfig) {
309
+ const visit = (entity: string, field: string, stack: string[]): { descriptive: boolean; hops: number } => {
310
+ const key = `${entity}.${field}`
311
+ if (stack.includes(key)) expressionError(entity, field, `Computed expression cycle: ${[...stack, key].join(' -> ')}`, 'Remove a circular field dependency.')
312
+ const wire = fieldExpression(config, entity, field)
313
+ if (!wire) return { descriptive: fieldKind(config, entity, field) === 'string', hops: 0 }
314
+ const info = expressionInfo(config, entity, field, wire)
315
+ const expected = fieldKind(config, entity, field)
316
+ 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.')
317
+ const next = [...stack, key]; let hops = 0
318
+ const provenance = new Map<Dependency, boolean>()
319
+ for (const dependency of info.dependencies) {
320
+ let count = dependency.hops.length
321
+ for (const hop of dependency.hops) if (fieldExpression(config, hop.source, hop.field)) count += visit(hop.source, hop.field, next).hops
322
+ const result = visit(dependency.entity, dependency.field, next)
323
+ hops = Math.max(hops, count + result.hops)
324
+ provenance.set(dependency, result.descriptive)
325
+ }
326
+ return { descriptive: info.type === 'string' && !!info.textDependencies?.some(dep => provenance.get(dep)), hops }
327
+ }
328
+ for (const [entity, spec] of Object.entries(config.entities)) for (const [field, definition] of Object.entries(spec.fields)) if (definition.computed) {
329
+ 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.')
330
+ const result = visit(entity, field, [])
331
+ if (field === spec.displayField) {
332
+ 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.')
333
+ 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.')
334
+ }
335
+ }
336
+ }
337
+ export function readableComputed(kernel: KernelRegistry, scope: Scope, entity: string, field: string, seen = new Set<string>()): boolean {
338
+ const key = `${entity}.${field}`; if (seen.has(key)) return false
339
+ if (!kernel.can(scope, entity, 'read') || !kernel.fieldMask(entity, scope).includes(field)) return false
340
+ const spec = kernel.config.entities[entity]
341
+ const reference = spec.fields[field]
342
+ if (reference?.type === 'ref' && (!kernel.can(scope, reference.entity!, 'read') || !kernel.fieldMask(reference.entity!, scope).includes('id'))) return false
343
+ const wire = reference?.computed
344
+ if (!wire) return !spec.label || field !== spec.displayField || !!readableDisplay(kernel, scope, entity)
345
+ const next = new Set(seen).add(key)
346
+ const info = expressionInfo(kernel.config, entity, field, wire)
347
+ return [...info.tables.keys()].every(source => kernel.can(scope, source, 'read') && kernel.fieldMask(source, scope).includes('id')) && info.dependencies.every(dep =>
348
+ 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))
349
+ }
@@ -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)