@mistriwork/engine 1.0.0-rc.18 → 1.0.0-rc.20

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.
@@ -4,7 +4,7 @@
4
4
  * compiled against. Shared so views and breakdowns compile under a scope
5
5
  * through the same builder as a plain read.
6
6
  */
7
- import { buildWhere, OPS } from './filter.js';
7
+ import { buildWhere, OPS, POSTGRES_STYLE } from './filter.js';
8
8
  import { Refusal } from './refusal.js';
9
9
  import { findTable } from './schema.js';
10
10
  import { isFixedScopeCatalog } from './scopeCatalog.js';
@@ -19,13 +19,95 @@ export const ROW_SCOPE_LIMITS = Object.freeze({
19
19
  string: 16_384,
20
20
  characters: 262_144,
21
21
  });
22
+ /**
23
+ * `via('support_case_id', 'support_case')`: the row shows when its `support_case_id` is the `id` of a `support_case` row
24
+ * the reader may see. The target's key defaults to `id`; a composite key is arrays of equal length
25
+ * (`via(['tenant_id', 'case_no'], 'support_case', ['tenant_id', 'no'])`). `where` narrows the target's rows further
26
+ * (`[[{ column: 'status', op: '=', value: 'open' }]]`): never wider, since it filters the scoped relation.
27
+ */
28
+ export function via(column, resource, key = 'id', where) {
29
+ return { column, op: 'in', via: { resource, column: key, ...(where ? { where } : {}) } };
30
+ }
31
+ /** A rule with every `via` target renamed by `rename` (a resource's id to its physical table's): the condition's own columns are the table's, and stay. */
32
+ export function renameViaTargets(rule, rename) {
33
+ if (rule === true || rule === false)
34
+ return rule;
35
+ // A captured scope is frozen to its leaves and a bound transaction holds it as such: a rule with no relationship test
36
+ // is handed back as it came, and one that is rebuilt is frozen again (its untouched conditions already are).
37
+ if (!rule.groups.some((group) => group.some(isVia)))
38
+ return rule;
39
+ return Object.freeze({
40
+ ...rule,
41
+ groups: Object.freeze(rule.groups.map((group) => Object.freeze(group.map((condition) => isVia(condition)
42
+ ? Object.freeze({ ...condition, via: Object.freeze({ ...condition.via, resource: rename(condition.via.resource) }) })
43
+ : condition)))),
44
+ });
45
+ }
46
+ /** A `via` whose target key, or whose own column, no index leads: an EXISTS per row is then a scan per row. Advice for
47
+ * the operator, never a refusal: slow, not wrong. Read off the catalog's own index list, so a table whose adapter does
48
+ * not report indexes (`indexed` absent) is not judged. One line per rule, in policy order. */
49
+ export function rowScopeViaAdvisories(schema, scope) {
50
+ // Per policy object: asked on every request, and a snapshot is held across them (a new catalog is a new answer).
51
+ let held = advised.get(scope);
52
+ if (!held)
53
+ advised.set(scope, (held = new WeakMap()));
54
+ let lines = held.get(schema);
55
+ if (!lines)
56
+ held.set(schema, (lines = viaAdvisories(schema, scope)));
57
+ return lines;
58
+ }
59
+ const advised = new WeakMap();
60
+ function viaAdvisories(schema, scope) {
61
+ const lines = [];
62
+ const led = (table, column) => table?.indexed === undefined
63
+ ? undefined
64
+ : table.indexed.includes(column) || table.columns.some((c) => c.name === column && c.primaryKey);
65
+ for (const [id, rule] of Object.entries(scope)) {
66
+ if (rule === true || rule === false)
67
+ continue;
68
+ for (const group of rule.groups)
69
+ for (const condition of group) {
70
+ if (!isVia(condition))
71
+ continue;
72
+ const from = findTable(schema, id), to = findTable(schema, condition.via.resource);
73
+ const missing = [
74
+ ...columnsOf(condition.via.column).flatMap((key) => (led(to, key) === false ? [`${condition.via.resource}.${key}`] : [])),
75
+ ...(condition.via.resource !== id
76
+ ? columnsOf(condition.column).flatMap((own) => (led(from, own) === false ? [`${id}.${own}`] : []))
77
+ : []),
78
+ ];
79
+ if (missing.length)
80
+ lines.push(`the row scope of "${id}" reads through "${condition.via.resource}", and no index leads ${missing.join(' or ')}: each row's test scans the other table. Index ${missing.join(' and ')}.`);
81
+ }
82
+ }
83
+ return lines;
84
+ }
22
85
  const invalid = () => {
23
86
  throw new Refusal('Invalid row scope.');
24
87
  };
88
+ /** A `via` rule refused, saying which rule and why: a bare "Invalid row scope." sent an author to guess at a graph. */
89
+ const refuse = (reason) => {
90
+ throw new Refusal(`Invalid row scope: ${reason}`);
91
+ };
92
+ /** How many hops a chain of `via` targets may be: deeper is almost certainly a modeling mistake and builds a deep CTE chain. */
93
+ const VIA_DEPTH = 8;
94
+ /** How many columns one composite `via` key may name. */
95
+ const VIA_KEY = 8;
96
+ /* The family a built-in PostgreSQL column compares in: every number is one, as is every kind of text. Absent for a type
97
+ whose operators are its own (an enum, citext), which is not judged. */
98
+ const columnFamily = (table, name) => {
99
+ const built = POSTGRES_STYLE.builtin?.(typeOfColumn(table, name));
100
+ if (!built)
101
+ return undefined;
102
+ return ['int2', 'int4', 'int8', 'numeric', 'float4', 'float8'].includes(built.name) ? 'number' : built.text ? 'text' : built.name;
103
+ };
104
+ const typeOfColumn = (table, name) => table.columns.find((column) => column.name === name)?.type ?? '';
105
+ const isVia = (condition) => !!condition && typeof condition === 'object' && Object.hasOwn(condition, 'via');
106
+ const columnsOf = (column) => (typeof column === 'string' ? [column] : column);
25
107
  /* Past a size bound the scope is refused, never cut short, and the refusal says which bound, by how much and what to
26
108
  do instead: "Invalid row scope." alone sent a policy author to guess, and one capped its own list to fit — a silent
27
109
  truncation of who may see what, which is the thing the bound exists to refuse. */
28
- const NEXT_STEP = 'Narrow the policy, or scope by a relationship instead of a list: give each scoped table a single-value column (its owner or tenant) and compare it with "=" (docs: Row access, "Bounds").';
110
+ const NEXT_STEP = 'Narrow the policy, or scope through the parent with `via` instead of listing its keys (docs: Row access, "Bounds").';
29
111
  const counted = (n) => n.toLocaleString('en-US');
30
112
  const pastBound = (what, size, bound, unit, per, more = false) => {
31
113
  const over = more ? 'more than ' : '';
@@ -40,7 +122,7 @@ function valuesIn(input, cap) {
40
122
  while (pending.length && count < cap) {
41
123
  const [value, depth] = pending.pop();
42
124
  count += 1;
43
- if (!value || typeof value !== 'object' || depth >= 8)
125
+ if (!value || typeof value !== 'object' || depth >= 10)
44
126
  continue;
45
127
  for (const key of Reflect.ownKeys(value)) {
46
128
  if (Array.isArray(value) && key === 'length')
@@ -65,7 +147,7 @@ export function captureRowScope(input) {
65
147
  const all = valuesIn(input, cap);
66
148
  return pastBound('the scope holds', all, ROW_SCOPE_LIMITS.nodes, 'values', 'in one scope', all >= cap);
67
149
  }
68
- if (depth > 8)
150
+ if (depth > 10)
69
151
  return invalid();
70
152
  if (typeof value === 'string') {
71
153
  characters += value.length;
@@ -184,6 +266,55 @@ export function snapshotRowScope(schema, input) {
184
266
  return known;
185
267
  rowScopeCounters.checked++;
186
268
  let conditions = 0;
269
+ const count = () => {
270
+ if (++conditions <= ROW_SCOPE_LIMITS.conditions)
271
+ return;
272
+ // The copy is plain frozen data, so counting every group is safe; it says how far past the bound it went.
273
+ const all = Object.values(scope).reduce((sum, entry) => sum +
274
+ (record(entry) && Array.isArray(entry.groups)
275
+ ? entry.groups.reduce((n, g) => n +
276
+ (Array.isArray(g)
277
+ ? g.reduce((m, c) => m + 1 + (record(c) && record(c.via) && Array.isArray(c.via.where) ? c.via.where.flat().length : 0), 0)
278
+ : 0), 0)
279
+ : 0), 0);
280
+ pastBound('the scope holds', all, ROW_SCOPE_LIMITS.conditions, 'conditions', 'in one scope');
281
+ };
282
+ /* A condition over the table's own columns and a literal: what a group holds, and what a `via.where` holds of the target. */
283
+ const literal = (table, condition) => {
284
+ if (Object.keys(condition).some((key) => !['column', 'op', 'value'].includes(key)))
285
+ return invalid();
286
+ if (typeof condition.column !== 'string' || !table.columns.some((column) => column.name === condition.column))
287
+ return invalid();
288
+ if (typeof condition.op !== 'string' || !OPS.has(condition.op))
289
+ return invalid();
290
+ if (condition.op === 'isNull' || condition.op === 'isNotNull') {
291
+ if (Object.hasOwn(condition, 'value'))
292
+ return invalid();
293
+ }
294
+ else if (condition.op === 'in') {
295
+ if (!Array.isArray(condition.value) || condition.value.some((value) => typeof value !== 'string' && typeof value !== 'number'))
296
+ return invalid();
297
+ }
298
+ else if (['contains', 'startsWith', 'endsWith', 'like'].includes(condition.op)) {
299
+ if (typeof condition.value !== 'string')
300
+ return invalid();
301
+ }
302
+ else if (!['string', 'number', 'boolean'].includes(typeof condition.value))
303
+ return invalid();
304
+ };
305
+ const keyOf = (where, table, value) => {
306
+ const names = typeof value === 'string' ? [value] : value;
307
+ if (!Array.isArray(names) ||
308
+ !names.length ||
309
+ names.length > VIA_KEY ||
310
+ names.some((name) => typeof name !== 'string' || !table.columns.some((column) => column.name === name)) ||
311
+ new Set(names).size !== names.length)
312
+ return refuse(`${where} names a column that "${table.id}" does not have, or names none, or names one twice.`);
313
+ return names;
314
+ };
315
+ // Each policy's relationship targets, for the graph checks below.
316
+ const edges = new Map();
317
+ const selfOf = new Set();
187
318
  for (const [id, policy] of Object.entries(scope)) {
188
319
  const table = findTable(schema, id);
189
320
  if (!table)
@@ -202,41 +333,112 @@ export function snapshotRowScope(schema, input) {
202
333
  new Set(policy.binary).size !== policy.binary.length)
203
334
  return invalid();
204
335
  }
336
+ const targets = new Set();
337
+ let treeColumns;
338
+ let tree = 0;
205
339
  for (const group of policy.groups) {
206
340
  if (!Array.isArray(group) || !group.length)
207
341
  return invalid();
342
+ let selfs = 0;
343
+ let vias = 0;
208
344
  for (const condition of group) {
209
- if (++conditions > ROW_SCOPE_LIMITS.conditions) {
210
- // The copy is plain frozen data, so counting every group is safe; it says how far past the bound it went.
211
- const all = Object.values(scope).reduce((sum, entry) => sum +
212
- (record(entry) && Array.isArray(entry.groups) ? entry.groups.reduce((n, g) => n + (Array.isArray(g) ? g.length : 0), 0) : 0), 0);
213
- return pastBound('the scope holds', all, ROW_SCOPE_LIMITS.conditions, 'conditions', 'in one scope');
214
- }
345
+ count();
215
346
  if (!record(condition))
216
347
  return invalid();
217
- if (Object.keys(condition).some((key) => !['column', 'op', 'value'].includes(key)))
348
+ if (!Object.hasOwn(condition, 'via')) {
349
+ literal(table, condition);
350
+ continue;
351
+ }
352
+ const rule = `${id}: a "via" on ${JSON.stringify(condition.column)}`;
353
+ if (Object.keys(condition).some((key) => !['column', 'op', 'via'].includes(key)))
218
354
  return invalid();
219
- if (typeof condition.column !== 'string' || !table.columns.some((column) => column.name === condition.column))
355
+ if (condition.op !== 'in')
356
+ return refuse(`${rule} takes only the operator "in", not ${JSON.stringify(condition.op)}: a negated test would admit a row whose parent is out of scope or missing.`);
357
+ const via = condition.via;
358
+ if (!record(via) || Object.keys(via).some((key) => !['resource', 'column', 'where'].includes(key)))
220
359
  return invalid();
221
- if (typeof condition.op !== 'string' || !OPS.has(condition.op))
360
+ if (typeof via.resource !== 'string')
222
361
  return invalid();
223
- if (condition.op === 'isNull' || condition.op === 'isNotNull') {
224
- if (Object.hasOwn(condition, 'value'))
362
+ const target = findTable(schema, via.resource);
363
+ if (!target)
364
+ return refuse(`${rule} names "${via.resource}", which this catalog does not have.`);
365
+ const from = keyOf(rule, table, condition.column);
366
+ const to = keyOf(rule, target, via.column);
367
+ if (from.length !== to.length)
368
+ return refuse(`${rule} compares ${from.length} column${from.length === 1 ? '' : 's'} with ${to.length} of "${target.id}".`);
369
+ // PostgreSQL has no operator between a text key and a number: every read would fail, so the policy is refused here.
370
+ if ((table.sourceDialect ?? schema.dialect) === 'postgres' && (target.sourceDialect ?? schema.dialect) === 'postgres')
371
+ from.forEach((name, at) => {
372
+ const mine = columnFamily(table, name), theirs = columnFamily(target, to[at]);
373
+ if (mine && theirs && mine !== theirs)
374
+ refuse(`${rule} compares ${table.id}.${name} (${typeOfColumn(table, name)}) with ${target.id}.${to[at]} (${typeOfColumn(target, to[at])}): the types do not compare.`);
375
+ });
376
+ if (via.where !== undefined) {
377
+ if (!Array.isArray(via.where) || !via.where.length)
225
378
  return invalid();
379
+ for (const alternative of via.where) {
380
+ if (!Array.isArray(alternative) || !alternative.length)
381
+ return invalid();
382
+ for (const test of alternative) {
383
+ count();
384
+ if (!record(test))
385
+ return invalid();
386
+ if (Object.hasOwn(test, 'via'))
387
+ return refuse(`${rule} filters "${target.id}" by another "via"; the target's own scope already chains.`);
388
+ literal(target, test);
389
+ }
390
+ }
226
391
  }
227
- else if (condition.op === 'in') {
228
- if (!Array.isArray(condition.value) || condition.value.some((value) => typeof value !== 'string' && typeof value !== 'number'))
229
- return invalid();
392
+ vias++;
393
+ if (target.id === table.id) {
394
+ selfs++;
395
+ tree++;
396
+ if (via.where !== undefined)
397
+ return refuse(`${rule} points at its own table with a "where"; put the filter beside it in the group, where it narrows each level.`);
398
+ const key = JSON.stringify(to);
399
+ if (treeColumns !== undefined && treeColumns !== key)
400
+ return refuse(`${id}: every "via" a table makes to itself must name the same key, so one walk can serve them.`);
401
+ treeColumns = key;
230
402
  }
231
- else if (['contains', 'startsWith', 'endsWith', 'like'].includes(condition.op)) {
232
- if (typeof condition.value !== 'string')
233
- return invalid();
234
- }
235
- else if (!['string', 'number', 'boolean'].includes(typeof condition.value))
236
- return invalid();
403
+ else
404
+ targets.add(target.id);
237
405
  }
406
+ if (selfs > 1)
407
+ return refuse(`${id}: a group may hold one "via" to its own table, not ${selfs}.`);
408
+ if (selfs && vias > selfs)
409
+ return refuse(`${id}: a "via" to its own table must be the only "via" in its group.`);
238
410
  }
411
+ if (tree) {
412
+ if (tree === policy.groups.length)
413
+ return refuse(`${id}: every group walks down from its own rows, so none could ever admit a first row. Add a group with no "via" to "${id}" as the base.`);
414
+ selfOf.add(id);
415
+ }
416
+ edges.set(id, targets);
239
417
  }
418
+ /* The graph of tables a scope reads through. A table that names itself is a tree (one hop of depth); any other
419
+ loop is refused, with the loop said. Depth is the longest chain of hops. */
420
+ const depths = new Map();
421
+ const walking = [];
422
+ const depthOf = (id) => {
423
+ const known = depths.get(id);
424
+ if (known !== undefined)
425
+ return known;
426
+ const at = walking.indexOf(id);
427
+ if (at >= 0)
428
+ return refuse(`"via" rules loop back: ${[...walking.slice(at), id].map((name) => `"${name}"`).join(' -> ')}.`);
429
+ walking.push(id);
430
+ let deepest = 0;
431
+ for (const target of edges.get(id) ?? [])
432
+ deepest = Math.max(deepest, 1 + depthOf(target));
433
+ walking.pop();
434
+ const depth = deepest + (selfOf.has(id) ? 1 : 0);
435
+ if (depth > VIA_DEPTH)
436
+ return refuse(`"via" rules from "${id}" chain ${depth} hops; the bound is ${VIA_DEPTH}. A chain that deep is almost certainly a modeling mistake.`);
437
+ depths.set(id, depth);
438
+ return depth;
439
+ };
440
+ for (const id of edges.keys())
441
+ depthOf(id);
240
442
  // Kept only against a catalog nothing can change; checked against one that can, it is checked again next time.
241
443
  if (fixed) {
242
444
  const against = snapshots.get(scope);
@@ -310,13 +512,64 @@ export class ScopedRelations {
310
512
  params = [];
311
513
  finished = false;
312
514
  ordinal = 0;
313
- constructor(schema, style, scope) {
515
+ /** The catalog a `via` target resolves against: the policy's own, whole. A read's catalog is pruned to what the
516
+ * reader may read, and a membership table they may not read (or a column of one) is missing there; reading it
517
+ * through a `via` only decides whether a row shows, which is what a policy author is allowed to decide. */
518
+ whole;
519
+ recursive = false;
520
+ building = new Set();
521
+ constructor(schema, style, scope, policy = schema) {
314
522
  this.schema = schema;
315
523
  this.style = style;
316
- this.scope = scope === undefined ? undefined : snapshotRowScope(schema, scope);
524
+ this.whole = policy;
525
+ this.scope = scope === undefined ? undefined : snapshotRowScope(policy, scope);
317
526
  this.reserved = new Set(reservedNames(schema));
318
527
  }
528
+ /** A table's meta, from the read's catalog and failing that the policy's (a `via` target the reader cannot read). */
529
+ meta(id) {
530
+ return findTable(this.schema, id) ?? findTable(this.whole, id);
531
+ }
532
+ fresh() {
533
+ let name;
534
+ do {
535
+ name = `_tw_scope$${++this.ordinal}`;
536
+ } while (this.reserved.has(name.toLowerCase()));
537
+ this.reserved.add(name.toLowerCase());
538
+ return name;
539
+ }
540
+ /* A `via` condition as the EXISTS over the target's scoped relation. The target is planned first (it and its
541
+ parameters precede this table's definition, so a CTE only names earlier ones and the placeholders stay in text
542
+ order), and a target's `where` is one more definition there (`filtered`), so the EXISTS binds nothing. */
543
+ related(table, condition) {
544
+ const q = this.style.quote;
545
+ const target = this.meta(condition.via.resource);
546
+ if (!target || !target.columns.length)
547
+ return invalid();
548
+ const source = condition.via.where
549
+ ? this.narrow(target.id, { groups: condition.via.where.map((group) => [...group]) })
550
+ : this.relation(target.id);
551
+ const from = columnsOf(condition.column);
552
+ const to = columnsOf(condition.via.column);
553
+ const typed = (meta, name) => this.style.builtin?.(meta.columns.find((column) => column.name === name)?.type ?? '');
554
+ const pairs = to.map((key, at) => {
555
+ /* The database's own operator where both sides are built-in types, as a column compared with a column is
556
+ (filter.ts): a bare `=` resolves through the search_path. */
557
+ const op = typed(target, key) && typed(table, from[at]) ? 'OPERATOR(pg_catalog.=)' : '=';
558
+ return `${q('_tw_p')}.${q(key)} ${op} ${q('_tw_o')}.${q(from[at])}`;
559
+ });
560
+ return {
561
+ column: from.join(','),
562
+ op: 'in',
563
+ via: { text: `EXISTS (SELECT 1 FROM ${source} ${q('_tw_p')} WHERE ${pairs.join(' AND ')})` },
564
+ };
565
+ }
566
+ /** A table's relation under the scope; a table this read's catalog does not hold is refused, though a `via` may read it. */
319
567
  table = (id) => {
568
+ if (this.scope !== undefined && !findTable(this.schema, id))
569
+ return invalid();
570
+ return this.relation(id);
571
+ };
572
+ relation(id) {
320
573
  if (this.scope === undefined)
321
574
  return qualifiedTable(this.schema, id, this.style);
322
575
  const existing = this.names.get(id);
@@ -324,28 +577,70 @@ export class ScopedRelations {
324
577
  return this.style.quote(existing);
325
578
  if (this.finished)
326
579
  throw new Error('Row scope relations must be planned before outer parameters.');
327
- const table = findTable(this.schema, id);
580
+ const table = this.meta(id);
328
581
  if (!table || !table.columns.length)
329
582
  return invalid();
330
- // '$' cannot occur in JoinPlan's sanitized aliases; catalog names still
331
- // need a case-insensitive collision check to avoid CTE self-shadowing.
332
- let name;
333
- do {
334
- name = `_tw_scope$${++this.ordinal}`;
335
- } while (this.reserved.has(name.toLowerCase()));
336
- this.reserved.add(name.toLowerCase());
337
- this.names.set(id, name);
583
+ if (this.building.has(id))
584
+ return invalid();
338
585
  const policy = this.scope[id] ?? false;
339
- const where = typeof policy === 'boolean'
340
- ? { text: policy ? '' : ` WHERE ${this.style.never ?? '1 = 0'}`, params: [] }
341
- : buildWhere(withoutRepeats(policy), this.style, this.params.length + 1, (column) => this.style.quote(column) + (policy.binary?.includes(column) ? ' COLLATE BINARY' : ''), undefined, undefined, undefined, false, (column) => table.columns.find((c) => c.name === column)?.type);
342
- const columns = table.columns.map((column) => this.style.quote(column.name)).join(', ');
586
+ const q = this.style.quote;
587
+ const columns = table.columns.map((column) => q(column.name)).join(', ');
588
+ const qualified = qualifiedTable(findTable(this.schema, id) ? this.schema : this.whole, id, this.style);
589
+ if (typeof policy === 'boolean') {
590
+ const name = this.fresh();
591
+ this.names.set(id, name);
592
+ const where = policy ? '' : ` WHERE ${this.style.never ?? '1 = 0'}`;
593
+ this.definitions.push(`${q(name)} AS${this.style.cteHint ?? ''} (SELECT ${columns} FROM ${qualified}${where})`);
594
+ return q(name);
595
+ }
596
+ // Target first: every relation this one reads through is planned (with its parameters) before this one's.
597
+ this.building.add(id);
598
+ const resolve = (group) => group.map((c) => (isVia(c) ? (c.via.resource === id ? c : this.related(table, c)) : c));
599
+ const groups = policy.groups.map(resolve);
600
+ this.building.delete(id);
601
+ const typeOf = (column) => table.columns.find((c) => c.name === column)?.type;
602
+ const builtIn = (column) => this.style.builtin?.(typeOf(column) ?? '');
603
+ const own = (alias) => (column) => (alias ? `${q(alias)}.` : '') + q(column) + (policy.binary?.includes(column) ? ' COLLATE BINARY' : '');
604
+ const name = this.fresh();
605
+ this.names.set(id, name);
606
+ const hint = this.style.cteHint ?? '';
607
+ // What resolve left as it was: a table's walk down itself (a resolved test carries its text, not a resource).
608
+ const walks = (c) => isVia(c) && typeof c.via.resource === 'string';
609
+ if (groups.some((group) => group.some(walks))) {
610
+ // A table that walks down its own tree: a recursive definition of the keys it admits, then the rows with those keys.
611
+ const base = groups.filter((group) => !group.some(walks));
612
+ const steps = groups.filter((group) => group.some(walks));
613
+ const keys = columnsOf(steps[0].find(walks).via.column);
614
+ const walk = this.fresh();
615
+ this.recursive = true;
616
+ const keyList = keys.map((key) => q(key)).join(', ');
617
+ const first = buildWhere(withoutRepeats({ groups: base }), this.style, this.params.length + 1, own('_tw_o'), undefined, undefined, undefined, false, typeOf, true);
618
+ this.params.push(...first.params);
619
+ const alternatives = steps.map((group) => {
620
+ const via = group.find(walks);
621
+ /* The database's own operator where both sides are built-in types (filter.ts): a bare `=` resolves through the search_path. */
622
+ const join = columnsOf(via.column).map((column, at) => `${q('_tw_c')}.${q(column)} ${builtIn(column) && builtIn(keys[at]) ? 'OPERATOR(pg_catalog.=)' : '='} ${q('_tw_w')}.${q(keys[at])}`);
623
+ const others = withoutRepeats({ groups: [group.filter((c) => !walks(c))] });
624
+ const where = buildWhere(others, this.style, this.params.length + 1, own('_tw_c'), undefined, undefined, undefined, false, typeOf, true);
625
+ this.params.push(...where.params);
626
+ return `(${[...join, ...(where.text ? [where.text.slice(' WHERE '.length)] : [])].join(' AND ')})`;
627
+ });
628
+ this.definitions.push(`${q(walk)}(${keyList}) AS (SELECT ${keys.map((key) => `${q('_tw_o')}.${q(key)}`).join(', ')} FROM ${qualified} ${q('_tw_o')}${first.text}` +
629
+ ` UNION SELECT ${keys.map((key) => `${q('_tw_c')}.${q(key)}`).join(', ')} FROM ${qualified} ${q('_tw_c')} JOIN ${q(walk)} ${q('_tw_w')} ON ${alternatives.join(' OR ')})`);
630
+ const same = keys
631
+ .map((key) => `${q('_tw_k')}.${q(key)} ${builtIn(key) ? 'OPERATOR(pg_catalog.=)' : '='} ${q('_tw_o')}.${q(key)}`)
632
+ .join(' AND ');
633
+ this.definitions.push(`${q(name)} AS${hint} (SELECT ${columns} FROM ${qualified} ${q('_tw_o')} WHERE EXISTS (SELECT 1 FROM ${q(walk)} ${q('_tw_k')} WHERE ${same}))`);
634
+ return q(name);
635
+ }
636
+ const related = groups.some((group) => group.some((c) => c.via !== undefined));
637
+ const where = buildWhere(withoutRepeats({ groups: groups }), this.style, this.params.length + 1, related ? own('_tw_o') : own(), undefined, undefined, undefined, false, typeOf, true);
343
638
  // The style's hint (cteHint) goes between AS and the body: Postgres inlines the CTE, so the
344
639
  // scope's predicate meets the read's own filter, sort and limit instead of a copied slice.
345
- this.definitions.push(`${this.style.quote(name)} AS${this.style.cteHint ?? ''} (SELECT ${columns} FROM ${qualifiedTable(this.schema, id, this.style)}${where.text})`);
640
+ this.definitions.push(`${q(name)} AS${hint} (SELECT ${columns} FROM ${qualified}${related ? ` ${q('_tw_o')}` : ''}${where.text})`);
346
641
  this.params.push(...where.params);
347
- return this.style.quote(name);
348
- };
642
+ return q(name);
643
+ }
349
644
  narrowed = new Map();
350
645
  /**
351
646
  * A table's rows narrowed by an authored filter over its own columns — the
@@ -359,21 +654,22 @@ export class ScopedRelations {
359
654
  * narrows within the reader's rows, never beside them.
360
655
  */
361
656
  filtered = (id, filter, written) => {
657
+ if (this.scope !== undefined && !findTable(this.schema, id))
658
+ return invalid();
659
+ return this.narrow(id, filter, written);
660
+ };
661
+ narrow(id, filter, written) {
362
662
  const key = `${id}\u0000${JSON.stringify(filter)}\u0000${Object.keys(written ?? {}).join(',')}`;
363
663
  const existing = this.narrowed.get(key);
364
664
  if (existing)
365
665
  return this.style.quote(existing);
366
666
  if (this.finished)
367
667
  throw new Error('Filtered relations must be planned before outer parameters.');
368
- const source = this.table(id);
369
- const table = findTable(this.schema, id);
668
+ const source = this.relation(id);
669
+ const table = this.meta(id);
370
670
  if (!table || !table.columns.length)
371
671
  return invalid();
372
- let name;
373
- do {
374
- name = `_tw_scope$${++this.ordinal}`;
375
- } while (this.reserved.has(name.toLowerCase()));
376
- this.reserved.add(name.toLowerCase());
672
+ const name = this.fresh();
377
673
  this.narrowed.set(key, name);
378
674
  const q = this.style.quote;
379
675
  /* A path (`sales_order_id.status`) is the column it lands on, read by one scalar subquery that walks
@@ -422,9 +718,11 @@ export class ScopedRelations {
422
718
  this.definitions.push(`${q(name)} AS (SELECT ${columns} FROM ${source}${row ? ` ${q(row)}` : ''}${where.text})`);
423
719
  this.params.push(...where.params);
424
720
  return this.style.quote(name);
425
- };
721
+ }
426
722
  finish() {
427
723
  this.finished = true;
428
- return { text: this.definitions.length ? `WITH ${this.definitions.join(',\n ')}\n` : '', params: [...this.params] };
724
+ // One recursive definition makes the whole WITH recursive; the others read as they did (a CTE may name an earlier one).
725
+ const head = this.recursive ? 'WITH RECURSIVE' : 'WITH';
726
+ return { text: this.definitions.length ? `${head} ${this.definitions.join(',\n ')}\n` : '', params: [...this.params] };
429
727
  }
430
728
  }
@@ -359,6 +359,11 @@ export interface AppFileDef {
359
359
  object?: string;
360
360
  /** A text column given the SHA-256 of the bytes (hex) on every upload: the file's tag wherever its bytes are. */
361
361
  hash?: string;
362
+ /**
363
+ * Columns the server writes on every upload and a request never does: `me` the signed-in person (as a New form's
364
+ * `me` default writes it) and `now` the server's clock. A body that names one is overwritten.
365
+ */
366
+ stamps?: Readonly<Record<string, 'me' | 'now'>>;
362
367
  /** Where a new upload's bytes go: `content` ('database', the default) or `bucket`. A row is read from wherever it says. */
363
368
  storage?: 'database' | 'bucket';
364
369
  /** The S3-compatible bucket the bytes are kept in; its credentials are the server's (MISTRI_S3_*), never the App's. */
@@ -707,6 +707,13 @@ function stateFindings(theme, name, at, palette, all) {
707
707
  names its own block (nav.current) is measured on that instead. */
708
708
  if (recipes.nav === 'pill' && !palette.navCurrent)
709
709
  check("navAccent/accentSoft over navGround (the pill menu's current entry)", color('navAccent'), soft && nav ? over(soft, nav) : undefined);
710
+ /* A round avatar look draws the sidebar's identity mark in the menu's accent on a 12% tint of that accent, laid on
711
+ the menu's ground (lumenLook.css). A part that names the mark's ink or ground replaces that pair (partsLook.css),
712
+ and the parts loop below measures the one drawn instead. */
713
+ const navAccent = color('navAccent');
714
+ const markPart = theme.parts?.identityMark;
715
+ if (recipes.avatar === 'round' && markPart?.ink === undefined && markPart?.ground === undefined)
716
+ check('navAccent/its own tint over navGround (the identity mark)', navAccent, tintOver(navAccent, nav));
710
717
  /* The search is a field on the surface in the page's ink (themeFamilies.css), a pair the page's checks read; the
711
718
  dark bar alone draws it on an 8% ink tint of its own ground in its muted ink (brandLook.css). */
712
719
  if (recipes.bar === 'dark')
@@ -758,13 +765,17 @@ function stateFindings(theme, name, at, palette, all) {
758
765
  for (const [part, style] of Object.entries(theme.parts ?? {})) {
759
766
  if (!style || (style.ground === undefined && style.ink === undefined))
760
767
  continue;
761
- const ink = style.ink ? pathRole(style.ink) : partInk(part);
768
+ const round = recipes.avatar === 'round';
769
+ const ink = style.ink ? pathRole(style.ink) : partInk(part, round);
762
770
  const ground = style.ground ? pathRole(style.ground) : partGround(part, palette);
763
771
  if (!ink || !ground)
764
772
  continue;
765
773
  const said = (role) => rolePath(role);
766
774
  const label = `parts.${part}: ${ink} on ${ground}`;
767
- const foreground = color(ink), background = color(ground);
775
+ /* A round mark left on its own ground is drawn on a 12% tint of the menu's accent over the menu (lumenLook.css),
776
+ not on the menu's ground itself. */
777
+ const tinted = part === 'identityMark' && round && !style.ground;
778
+ const foreground = color(ink), background = tinted ? tintOver(color('navAccent'), color('navGround')) : color(ground);
768
779
  if (!foreground || !background)
769
780
  continue;
770
781
  const ratio = measuredContrast(foreground, background);
@@ -781,9 +792,15 @@ function stateFindings(theme, name, at, palette, all) {
781
792
  }
782
793
  return result;
783
794
  }
795
+ /** The round identity mark's ground: its accent at 12% over the menu (lumenLook.css). */
796
+ function tintOver(accent, ground) {
797
+ return accent && ground ? over(mixColor(accent, [0, 0, 0, 0], 0.12), ground) : undefined;
798
+ }
784
799
  /** The ink a part's words are drawn in when its style says none: the menu's for the menu's parts, the link's for a
785
800
  link; a primary button's is the ink drawn on the accent fill. */
786
- function partInk(part) {
801
+ function partInk(part, round) {
802
+ if (part === 'identityMark')
803
+ return round ? 'navAccent' : 'navInk';
787
804
  if (part === 'button.primary')
788
805
  return 'onAccent';
789
806
  if (/^(?:nav|bar|logo)\b/.test(part))
@@ -792,6 +809,8 @@ function partInk(part) {
792
809
  }
793
810
  /** The ground a part is drawn on when its style says none. */
794
811
  function partGround(part, palette) {
812
+ if (part === 'identityMark')
813
+ return 'navGround';
795
814
  if (/^(?:nav|bar|logo)\b/.test(part))
796
815
  return 'navGround';
797
816
  if (part === 'button.primary')
@@ -211,7 +211,7 @@ export declare function typeAttributes(type: ThemeTypeDefinition | undefined): R
211
211
  * The published parts a theme may dress one by one (themeParts.ts says what each may take and how it is worn). Here,
212
212
  * with the words the root wears for them, because the first paint sets `data-parts` as it sets the recipes'.
213
213
  */
214
- export declare const THEME_PARTS: readonly ["ground", "bar", "bar.search", "nav", "nav.item", "nav.current", "nav.group", "logo", "page.title", "tabs", "tab.current", "section", "section.title", "stat", "stat.figure", "fields", "field.label", "table", "table.head", "table.row", "status", "tag", "button.primary", "button.secondary", "button.quiet", "link", "board.lane", "board.card", "workflow.step", "banner", "steps.step", "avatar", "menu", "dialog", "chart"];
214
+ export declare const THEME_PARTS: readonly ["ground", "bar", "bar.search", "nav", "nav.item", "nav.current", "nav.group", "logo", "page.title", "tabs", "tab.current", "section", "section.title", "stat", "stat.figure", "fields", "field.label", "table", "table.head", "table.row", "status", "tag", "button.primary", "button.secondary", "button.quiet", "link", "board.lane", "board.card", "workflow.step", "banner", "steps.step", "avatar", "identityMark", "menu", "dialog", "chart"];
215
215
  /** What a part style may say, in the order its words are written. */
216
216
  export declare const PART_PROPERTIES: readonly ['ground', 'ink', 'edge', 'radius', 'lift', 'face', 'weight', 'case'];
217
217
  /** The root's `data-parts`: one word per property a part says (`stat:ground button.primary:case`); undefined when none. */
@@ -216,6 +216,7 @@ export const THEME_PARTS = [
216
216
  'banner',
217
217
  'steps.step',
218
218
  'avatar',
219
+ 'identityMark',
219
220
  'menu',
220
221
  'dialog',
221
222
  'chart',
@@ -131,7 +131,9 @@ export declare class JoinPlan {
131
131
  * columns, then the filter, then the sort. Aliases are handed out on first
132
132
  * use, so the same view always produces the same statement.
133
133
  */
134
- export declare function compileView(schema: DatabaseSchema, view: ViewDef, style: SqlStyle, offset?: number | unknown, scope?: RowScope): CompiledView;
134
+ export declare function compileView(schema: DatabaseSchema, view: ViewDef, style: SqlStyle, offset?: number | unknown, scope?: RowScope,
135
+ /** The catalog a row scope's `via` targets resolve in, where the reader's own is pruned (rowScope.ts ScopedRelations). */
136
+ policy?: DatabaseSchema): CompiledView;
135
137
  export interface ParsedView {
136
138
  filter: ViewFilter;
137
139
  columns: string[];
@@ -165,7 +167,7 @@ export declare function parseViewQuery(schema: DatabaseSchema, baseId: string, t
165
167
  * design rests on: a view never multiplies, so counting it is counting the
166
168
  * table it started from. With `limit`, it stops after that many.
167
169
  */
168
- export declare function compileViewCount(schema: DatabaseSchema, view: ViewDef, style: SqlStyle, scope?: RowScope, limit?: number): SqlFragment;
170
+ export declare function compileViewCount(schema: DatabaseSchema, view: ViewDef, style: SqlStyle, scope?: RowScope, limit?: number, policy?: DatabaseSchema): SqlFragment;
169
171
  /**
170
172
  * Render a view as the SQL it will become, values inline.
171
173
  *