@mistriwork/engine 1.0.0-rc.49 → 1.0.0-rc.51

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.
@@ -63,6 +63,31 @@ export declare const isForeignKeyViolation: (error: unknown) => boolean;
63
63
  * refusal; what the operator reads names the constraint and nothing of the row.
64
64
  */
65
65
  export declare const foreignKeyRefusal: (error: unknown) => ScopeRefusal;
66
+ /** The columns of `table` whose unique rule refused a write, or undefined where the error names another table, an
67
+ * expression, an exclusion, or nothing it can read. */
68
+ export declare function uniqueColumns(error: unknown, table: Pick<TableMeta, 'name' | 'schema'>): string[] | undefined;
69
+ /**
70
+ * Whether a unique refusal on `columns` names a row the principal reads: some group of its rule fixes every one of
71
+ * those columns' values (`=` and nothing else), and the row written holds exactly those values. Any row the unique rule
72
+ * compared equal to it then holds them too, and is inside the same group, so long as the index compares those columns
73
+ * no more loosely than the scope does. That is what the engine cannot read off the error, so only a comparison that is
74
+ * attested counts:
75
+ * - on SQLite (`sqlite`), a column the scope compares by its bytes (`binary`): a tenant's owner column, which every
76
+ * unique index of a tenant table must compare BINARY (the tenant write source's assertUniqueKeys). Any other
77
+ * condition is compared under the column's collation, where `UNIQUE (email COLLATE NOCASE)` finds 'X' equal to an
78
+ * 'x' the scope tells apart, so the refusal stays generic;
79
+ * - on PostgreSQL, a condition under the column's own collation: an index compares by it unless it names another, and
80
+ * a tenant's owner column must be deterministic in every unique index (tenantPostgresCatalog.ts).
81
+ * A tenant's own table answers so, by the owner column its unique indexes include: the conflicting row is the tenant's
82
+ * own. A rule that reads the whole table answers so whatever the index compares.
83
+ */
84
+ export declare function uniqueConflictSeen(rule: RowScope[string], columns: readonly string[], row: Readonly<Record<string, unknown>>, sqlite: boolean): boolean;
85
+ /**
86
+ * A unique rule's refusal of a scoped write, where the row it conflicts with may be one the principal cannot read:
87
+ * said as the scope's own refusal, so neither the column nor the fact that the value is taken outside its rows is
88
+ * named. The operator reads the table and the columns, never the value.
89
+ */
90
+ export declare const uniqueRefusal: (table: Pick<TableMeta, 'id'>, columns: readonly string[] | undefined) => ScopeRefusal;
66
91
  /** A table's triggers as a refusal names them: `the trigger "audit_order"`, `the triggers "a", "b"`. */
67
92
  export declare const triggerNames: (names: readonly string[]) => string;
68
93
  export { blocksEveryWrite, sayBlocked, sayRuns, sayTriggers, type ScopeTrigger } from './scopeTriggers.js';
@@ -158,6 +183,31 @@ export declare function sameTables(scope: Readonly<Record<string, unknown>>, bou
158
183
  * words stay value-free, the reason recorded beneath them for the owner. */
159
184
  export declare class ScopeRefusal extends Refusal {
160
185
  }
186
+ /** The sentence a delete hears when every row still referencing it is one its principal cannot read. */
187
+ export declare const IN_USE = "This record is in use and can't be deleted.";
188
+ /**
189
+ * A delete refused because rows still reference the row, said as the record's state rather than as the scope: the
190
+ * person can act on it. Its words name only what the principal reads — the referencing table and how many of its
191
+ * rows point here, counted under the principal's own rows — and, where every remaining reference is one the scope
192
+ * hides (another tenant's row on a shared parent, a row the policy keeps from them), name nothing: {@link IN_USE}.
193
+ * That the delete is refused at all is the one thing such a row still says, and it cannot be otherwise: deleting it
194
+ * would reach that row. The total across every row is recorded for the operator only.
195
+ */
196
+ export declare class ReferencedRefusal extends ScopeRefusal {
197
+ /** What the principal reads of the references: the table and its count, or nothing when it reads none. */
198
+ readonly seen?: {
199
+ readonly table: string;
200
+ readonly count: number;
201
+ } | undefined;
202
+ constructor(
203
+ /** What the principal reads of the references: the table and its count, or nothing when it reads none. */
204
+ seen?: {
205
+ readonly table: string;
206
+ readonly count: number;
207
+ } | undefined);
208
+ }
209
+ /** The ReferencedRefusal a failure was rebuilt over, however many value-free wrappers lie between. */
210
+ export declare function referencedBeneath(error: unknown): ReferencedRefusal | undefined;
161
211
  /**
162
212
  * The principal's scope and the reads it compiles to, for a transaction that
163
213
  * may create a parent and then its children. A scope is resolved before the
@@ -1,6 +1,6 @@
1
1
  import { Refusal } from '../adapter.js';
2
2
  import { buildWhere } from '../../shared/filter.js';
3
- import { authorFault, recordRefusalCause } from '../../shared/refusal.js';
3
+ import { authorFault, recordRefusalCause, refusalCause, sayRefusal } from '../../shared/refusal.js';
4
4
  import { coerceForColumn, columnKind } from '../../shared/schema.js';
5
5
  import { blockingTriggers, firedBy, sayRuns, sayTriggers, sayWrite } from './scopeTriggers.js';
6
6
  import { detachStoredText, overlaid, storedText, storedTextOf } from './storedText.js';
@@ -21,6 +21,74 @@ export const foreignKeyRefusal = (error) => {
21
21
  const constraint = error?.constraint;
22
22
  return recordRefusalCause(new ScopeRefusal('This operation is not available in the current row scope.'), `The database's foreign key${typeof constraint === 'string' ? ` ${JSON.stringify(constraint)}` : ''} refused the write: a row it points at is not in the principal's rows, or does not exist.`);
23
23
  };
24
+ /** Whether a failure is a unique rule refusing a write: SQLite's PRIMARY KEY and UNIQUE, PostgreSQL's 23505 and 23P01. */
25
+ const isUniqueViolation = (error) => {
26
+ const { code, errcode } = (error ?? {});
27
+ return errcode === 1555 || errcode === 2067 || code === '23505' || code === '23P01';
28
+ };
29
+ /* A column as each engine names it in a unique refusal, and nothing else: the names only, never the values
30
+ (engine/src/server/constraints.ts reads the same, for a form's field, where the adapters cannot import it). */
31
+ const COLUMN_NAME = /^[A-Za-z_][\w$]{0,127}$/;
32
+ /** The columns of `table` whose unique rule refused a write, or undefined where the error names another table, an
33
+ * expression, an exclusion, or nothing it can read. */
34
+ export function uniqueColumns(error, table) {
35
+ const e = (error ?? {});
36
+ let names;
37
+ if (e.code === '23505') {
38
+ // A trigger or a cascade can break another table's rule: only the table written is judged.
39
+ if (e.table !== table.name || (typeof e.schema === 'string' && table.schema && e.schema !== table.schema))
40
+ return undefined;
41
+ const head = typeof e.detail === 'string' ? /^Key \(([^()]*)\)=\(/.exec(e.detail) : null;
42
+ names = head?.[1].split(',').map((name) => name.trim());
43
+ }
44
+ else if (typeof e.message === 'string') {
45
+ const said = /^UNIQUE constraint failed: (.+)$/.exec(e.message);
46
+ names = said?.[1].split(',').map((part) => {
47
+ const at = part.trim();
48
+ return at.startsWith(`${table.name}.`) ? at.slice(table.name.length + 1) : '';
49
+ });
50
+ }
51
+ return names?.length && names.every((name) => COLUMN_NAME.test(name)) ? [...new Set(names)] : undefined;
52
+ }
53
+ /**
54
+ * Whether a unique refusal on `columns` names a row the principal reads: some group of its rule fixes every one of
55
+ * those columns' values (`=` and nothing else), and the row written holds exactly those values. Any row the unique rule
56
+ * compared equal to it then holds them too, and is inside the same group, so long as the index compares those columns
57
+ * no more loosely than the scope does. That is what the engine cannot read off the error, so only a comparison that is
58
+ * attested counts:
59
+ * - on SQLite (`sqlite`), a column the scope compares by its bytes (`binary`): a tenant's owner column, which every
60
+ * unique index of a tenant table must compare BINARY (the tenant write source's assertUniqueKeys). Any other
61
+ * condition is compared under the column's collation, where `UNIQUE (email COLLATE NOCASE)` finds 'X' equal to an
62
+ * 'x' the scope tells apart, so the refusal stays generic;
63
+ * - on PostgreSQL, a condition under the column's own collation: an index compares by it unless it names another, and
64
+ * a tenant's owner column must be deterministic in every unique index (tenantPostgresCatalog.ts).
65
+ * A tenant's own table answers so, by the owner column its unique indexes include: the conflicting row is the tenant's
66
+ * own. A rule that reads the whole table answers so whatever the index compares.
67
+ */
68
+ export function uniqueConflictSeen(rule, columns, row, sqlite) {
69
+ if (rule === true)
70
+ return true;
71
+ if (rule === false)
72
+ return false;
73
+ return rule.groups.some((group) => group.length > 0 &&
74
+ group.every((condition) => !isViaCondition(condition) &&
75
+ condition.op === '=' &&
76
+ condition.other === undefined &&
77
+ condition.collation === undefined &&
78
+ condition.equality === undefined &&
79
+ (!sqlite || rule.binary?.includes(condition.column) === true) &&
80
+ columns.includes(condition.column) &&
81
+ condition.value !== undefined &&
82
+ !Array.isArray(condition.value) &&
83
+ Object.hasOwn(row, condition.column) &&
84
+ row[condition.column] === condition.value));
85
+ }
86
+ /**
87
+ * A unique rule's refusal of a scoped write, where the row it conflicts with may be one the principal cannot read:
88
+ * said as the scope's own refusal, so neither the column nor the fact that the value is taken outside its rows is
89
+ * named. The operator reads the table and the columns, never the value.
90
+ */
91
+ export const uniqueRefusal = (table, columns) => recordRefusalCause(new ScopeRefusal('This operation is not available in the current row scope.'), `A unique rule on "${table.id}"${columns ? ` (${columns.map((column) => JSON.stringify(column)).join(', ')})` : ''} refused the write, and the row it conflicts with may be outside the principal's rows.`);
24
92
  /** A table's triggers as a refusal names them: `the trigger "audit_order"`, `the triggers "a", "b"`. */
25
93
  export const triggerNames = (names) => `the trigger${names.length === 1 ? '' : 's'} ${names.map((name) => JSON.stringify(name)).join(', ')}`;
26
94
  /* The trigger vocabulary, for `mistri check` (commandTriggerChecks.ts), which says the same refusal ahead of time. */
@@ -114,6 +182,39 @@ export class ScopeRefusal extends Refusal {
114
182
  const refuse = (reason) => {
115
183
  throw recordRefusalCause(new ScopeRefusal('This operation is not available in the current row scope.'), reason);
116
184
  };
185
+ /** The sentence a delete hears when every row still referencing it is one its principal cannot read. */
186
+ export const IN_USE = "This record is in use and can't be deleted.";
187
+ /**
188
+ * A delete refused because rows still reference the row, said as the record's state rather than as the scope: the
189
+ * person can act on it. Its words name only what the principal reads — the referencing table and how many of its
190
+ * rows point here, counted under the principal's own rows — and, where every remaining reference is one the scope
191
+ * hides (another tenant's row on a shared parent, a row the policy keeps from them), name nothing: {@link IN_USE}.
192
+ * That the delete is refused at all is the one thing such a row still says, and it cannot be otherwise: deleting it
193
+ * would reach that row. The total across every row is recorded for the operator only.
194
+ */
195
+ export class ReferencedRefusal extends ScopeRefusal {
196
+ seen;
197
+ constructor(
198
+ /** What the principal reads of the references: the table and its count, or nothing when it reads none. */
199
+ seen) {
200
+ super(seen
201
+ ? `${seen.count === 1 ? 'A record' : `${seen.count} records`} in "${seen.table}" still ${seen.count === 1 ? 'points' : 'point'} at this one. Change or remove ${seen.count === 1 ? 'it' : 'them'} first, then try again.`
202
+ : IN_USE);
203
+ this.seen = seen;
204
+ this.name = 'ReferencedRefusal';
205
+ sayRefusal(this, this.message);
206
+ }
207
+ }
208
+ /** The ReferencedRefusal a failure was rebuilt over, however many value-free wrappers lie between. */
209
+ export function referencedBeneath(error) {
210
+ let at = error;
211
+ for (let depth = 0; at !== null && typeof at === 'object' && depth < 16; depth++) {
212
+ if (at instanceof ReferencedRefusal)
213
+ return at;
214
+ at = refusalCause(at) ?? (at instanceof Error ? at.cause : undefined);
215
+ }
216
+ return undefined;
217
+ }
117
218
  const isViaCondition = (condition) => typeof condition.via?.resource === 'string';
118
219
  const keyText = (key) => Object.entries(key)
119
220
  .map(([column, value]) => `${column} ${JSON.stringify(value)}`)
@@ -199,6 +300,28 @@ referencesOf) {
199
300
  reads = own.reads(scope, false);
200
301
  guards = own.reads(scope, true);
201
302
  };
303
+ /* A row still referenced, said in what the principal reads of it. The total above counts every row on the writer, as
304
+ the cascade would reach them; how many of those the principal reads is counted again under its own rows, by each
305
+ referencing column as the child compares — where the foreign key matches more than that (a parent collation the
306
+ child lacks), fewer are named, never more, and none named is the sentence that names nothing. */
307
+ const referencedRefusal = async (table, key, referenced) => {
308
+ const cause = `A scoped command may not delete the "${table.id}" row ${keyText(key)}: ${referenced
309
+ .map(({ fk, total }) => `"${fk.from.table}" still references it (${total} ${total === 1 ? 'row' : 'rows'} in all)`)
310
+ .join(', ')}.`;
311
+ for (const { fk, values } of referenced) {
312
+ const seen = await reads
313
+ .count(fk.from.table, { groups: [fk.from.columns.map((column, index) => ({ column, op: '=', value: values[index] }))] })
314
+ .catch((error) => {
315
+ // A table the principal does not read at all reads none of the references: refused as the one that names nothing.
316
+ if (error instanceof Refusal)
317
+ return 0;
318
+ throw error;
319
+ });
320
+ if (seen > 0)
321
+ return recordRefusalCause(new ReferencedRefusal({ table: fk.from.table, count: seen }), cause);
322
+ }
323
+ return recordRefusalCause(new ReferencedRefusal(), cause);
324
+ };
202
325
  const target = (id, write) => {
203
326
  const table = catalog.schema.tables.find((table) => table.id === id);
204
327
  if (!table)
@@ -527,11 +650,23 @@ referencesOf) {
527
650
  /* The statements themselves. A foreign key that refuses one answers as a hidden parent does (foreignKeyRefusal):
528
651
  the checks before a write compare what it names, and this is everything they cannot see — a default's part of a
529
652
  reference, a value a trigger writes, a deferred check. */
530
- const statement = (sent) => sent.catch((error) => {
531
- throw isForeignKeyViolation(error) ? foreignKeyRefusal(error) : error;
653
+ /* A unique rule that refuses one names its column, and on PostgreSQL the value, of a row that may be outside the
654
+ principal's rows: that the value is taken there is what the scope keeps. It is let through only where the
655
+ conflicting row is one the principal reads (uniqueConflictSeen); otherwise it is the scope's own refusal. */
656
+ const statement = (sent, table, row) => sent.catch((error) => {
657
+ if (isForeignKeyViolation(error))
658
+ throw foreignKeyRefusal(error);
659
+ if (isUniqueViolation(error) && table) {
660
+ const columns = uniqueColumns(error, table);
661
+ // With a scope present, a table it does not name has no rows the principal reads (shared/rowScope.ts).
662
+ const rule = scope === undefined ? true : Object.hasOwn(scope, table.id) ? scope[table.id] : false;
663
+ if (!columns || !uniqueConflictSeen(rule, columns, row ?? {}, typeof error.errcode === 'number'))
664
+ throw uniqueRefusal(table, columns);
665
+ }
666
+ throw error;
532
667
  });
533
- const insertRow = (request) => statement(records.insert(request));
534
- const updateRow = (request) => statement(records.update(request));
668
+ const insertRow = (table, request) => statement(records.insert(request), table, request.values ?? {});
669
+ const updateRow = (table, request, row) => statement(records.update(request), table, row);
535
670
  const afterward = async (afterwards, images) => {
536
671
  for (const next of afterwards ?? [])
537
672
  await next(images);
@@ -551,7 +686,7 @@ referencesOf) {
551
686
  const given = unproven(parentChecks(table, request.values ?? {}, undefined, true));
552
687
  if (!locks?.together)
553
688
  await verify(given);
554
- const result = locks?.together ? await parentsFirst(given, () => insertRow(request)) : await insertRow(request);
689
+ const result = locks?.together ? await parentsFirst(given, () => insertRow(table, request)) : await insertRow(table, request);
555
690
  const filter = keyFilter(table, result.key);
556
691
  /* The new row locked and read back, and where the writer sends together
557
692
  its references checked in the same flight, from the row the INSERT
@@ -588,7 +723,8 @@ referencesOf) {
588
723
  const set = new Set(Object.keys(request.values ?? {}));
589
724
  const afterwards = proof && (await proof.before(table, { kind: 'update', set: [...set] }, proof.images.update(table, before, request.values)));
590
725
  // What the update sets is given; every other column of a reference it sets in part is as stored, bound as its text.
591
- const given = unproven(parentChecks(table, overlaid(before, request.values), set, true));
726
+ const written = overlaid(before, request.values);
727
+ const given = unproven(parentChecks(table, written, set, true));
592
728
  if (!locks?.together)
593
729
  await verify(given);
594
730
  /* The row read again after the write, sent the moment the write is: it
@@ -605,7 +741,9 @@ referencesOf) {
605
741
  let result;
606
742
  try {
607
743
  // The references it sets leave ahead of it, in its flight (parentsFirst).
608
- result = locks?.together ? await parentsFirst(given, () => updateRow(request)) : await updateRow(request);
744
+ result = locks?.together
745
+ ? await parentsFirst(given, () => updateRow(table, request, written))
746
+ : await updateRow(table, request, written);
609
747
  }
610
748
  finally {
611
749
  withdraw?.();
@@ -637,6 +775,7 @@ referencesOf) {
637
775
  are counted: across every row of each table, on the writer itself,
638
776
  since the principal sees every row the bound holds there and a row
639
777
  outside the bound pointing in is the one a cascade must never reach. */
778
+ const referenced = [];
640
779
  for (const fk of children) {
641
780
  const values = fk.to.columns.map((column) => row[column]);
642
781
  if (values.some((value) => value === null))
@@ -644,9 +783,14 @@ referencesOf) {
644
783
  if (!values.every(comparable))
645
784
  return refuse(`"${table.id}".${fk.to.columns.join('+')} holds a value that is not a text or a number.`);
646
785
  const key = { groups: [Object.entries(request.key).map(([column, value]) => ({ column, op: '=', value }))] };
647
- if ((await counted?.(fk, key)) !== 0)
648
- return refuse(`A scoped command may not delete the "${table.id}" row ${keyText(request.key)}: "${fk.from.table}" still references it.`);
786
+ const total = await counted?.(fk, key);
787
+ if (total === undefined)
788
+ return refuse(`A scoped command may not delete the "${table.id}" row ${keyText(request.key)}: its references were not counted.`);
789
+ if (total !== 0)
790
+ referenced.push({ fk, values, total });
649
791
  }
792
+ if (referenced.length)
793
+ throw await referencedRefusal(table, request.key, referenced);
650
794
  const afterwards = proof && (await proof.before(table, { kind: 'delete' }, proof.images.delete(row)));
651
795
  const result = await statement(records.remove(request));
652
796
  if (result.affected !== 1)
@@ -31,6 +31,7 @@ export const CAPTION_KEYS = new Set([
31
31
  'alt',
32
32
  'message',
33
33
  'note',
34
+ 'statement',
34
35
  'before',
35
36
  'after',
36
37
  ]);
@@ -18,10 +18,12 @@
18
18
  * account's email, as a fixed action's `set` writes it), comparisons,
19
19
  * `and`/`or`/`not`, `in (…)`, `is empty`, arithmetic, and dates: a date minus a date is
20
20
  * days, a date plus a number is that many days later, and a unit says others
21
- * (`ends_on + term months`, `now - 30 minutes`). Five functions: `coalesce(a, b, …)`
21
+ * (`ends_on + term months`, `now - 30 minutes`). Six functions: `coalesce(a, b, …)`
22
22
  * the first that has a value, `round(x)` and `round(x, 2)`, `abs(x)`, and
23
23
  * `min(a, b, …)` and `max(a, b, …)` of numbers or dates, which have no value
24
- * where one of theirs has none, as arithmetic has (`max(owed - paid, 0)`).
24
+ * where one of theirs has none, as arithmetic has (`max(owed - paid, 0)`), and
25
+ * `concat(a, b, …)`, text joined, where a part with no value reads as empty
26
+ * (`concat(first, ' ', last)`). There is no `||`: SQLite and PostgreSQL differ on what it does with a null.
25
27
  * That covers a due flag, an age, a renewal day, a balance.
26
28
  * Anything heavier is a database view or a generated column, which the
27
29
  * catalog reads as a column already.
@@ -99,7 +101,7 @@ export interface ComputedJson {
99
101
  keys: string[];
100
102
  }
101
103
  /** The functions an expression may call (computedParse.ts COMPUTED_FUNCTIONS): each written alike on every engine and worked out alike in JavaScript. */
102
- export type ComputedFunction = 'coalesce' | 'round' | 'min' | 'max' | 'abs';
104
+ export type ComputedFunction = 'coalesce' | 'round' | 'min' | 'max' | 'abs' | 'concat';
103
105
  interface ComputedSpan {
104
106
  k: 'span';
105
107
  of: ComputedNode;
@@ -117,6 +117,14 @@ export function computedKind(node, kindOf) {
117
117
  }
118
118
  case 'call': {
119
119
  const kinds = n.args.map(kind);
120
+ /* Text only: a number or a day said as text is written differently by each engine (3.0, 3), so joining one
121
+ would answer differently on SQLite and PostgreSQL. */
122
+ if (n.fn === 'concat') {
123
+ const other = kinds.find((each) => each !== 'text');
124
+ if (other)
125
+ throw new Error(`concat(…) joins text, and has a ${other}.`);
126
+ return 'text';
127
+ }
120
128
  if (n.fn === 'round' || n.fn === 'abs') {
121
129
  if (kinds.some((each) => each !== 'number'))
122
130
  throw new Error(`${n.fn}(…) reads numbers.`);
@@ -307,6 +315,9 @@ export function compileComputed(computed, style, column, kindOf) {
307
315
  return `ABS(${args[0]})`;
308
316
  if (n.fn === 'coalesce')
309
317
  return `COALESCE(${args.join(', ')})`;
318
+ /* A part with no value reads as empty, which the dialect's own `||` would not (a null swallows the whole). */
319
+ if (n.fn === 'concat')
320
+ return style.concat(args.map((arg) => `COALESCE(${arg}, '')`));
310
321
  if (n.fn === 'round') {
311
322
  const places = args[1] ?? '0';
312
323
  /* A half rounds away from zero, of the figure as written: 1.005 is 1.01. PostgreSQL rounds a numeric so (a
@@ -6,7 +6,7 @@
6
6
  */
7
7
  import { ComputedError } from './computed.js';
8
8
  /** The functions an expression may call: each written alike on every engine and worked out alike in JavaScript. */
9
- const COMPUTED_FUNCTIONS = ['coalesce', 'round', 'min', 'max', 'abs'];
9
+ const COMPUTED_FUNCTIONS = ['coalesce', 'round', 'min', 'max', 'abs', 'concat'];
10
10
  const isFunction = (word) => COMPUTED_FUNCTIONS.includes(word);
11
11
  /* The greatest number of places `round` keeps: past it a figure is no longer one an engine says exactly. */
12
12
  const ROUND_PLACES = 10;
@@ -251,12 +251,20 @@ export function parseComputed(text, isColumn) {
251
251
  expect(')');
252
252
  const fn = lower;
253
253
  const many = fn === 'coalesce' || fn === 'min' || fn === 'max';
254
- if (many ? args.length < 2 : fn === 'round' ? args.length < 1 || args.length > 2 : args.length !== 1)
255
- throw new ComputedError(many
256
- ? `${fn}(…) takes two values or more: ${fn}(a, b).`
254
+ if (fn === 'concat'
255
+ ? args.length < 1
256
+ : many
257
+ ? args.length < 2
257
258
  : fn === 'round'
258
- ? 'round(…) takes a number and, if you like, how many places: round(total) or round(total, 2).'
259
- : `${fn}(…) takes one number.`, token.at);
259
+ ? args.length < 1 || args.length > 2
260
+ : args.length !== 1)
261
+ throw new ComputedError(fn === 'concat'
262
+ ? "concat(…) takes one text or more: concat(first, ' ', last)."
263
+ : many
264
+ ? `${fn}(…) takes two values or more: ${fn}(a, b).`
265
+ : fn === 'round'
266
+ ? 'round(…) takes a number and, if you like, how many places: round(total) or round(total, 2).'
267
+ : `${fn}(…) takes one number.`, token.at);
260
268
  if (fn === 'round' && args[1] && !(args[1].k === 'number' && Number.isInteger(args[1].value) && args[1].value <= ROUND_PLACES))
261
269
  throw new ComputedError(`round(…)'s places are a whole number from 0 to ${ROUND_PLACES}, written out: round(total, 2).`, token.at);
262
270
  return { k: 'call', fn, args };
@@ -102,6 +102,8 @@ export function evaluateComputed(node, values, read = (path) => {
102
102
  const args = n.args.map(value);
103
103
  if (n.fn === 'coalesce')
104
104
  return args.find((each) => each !== null) ?? null;
105
+ if (n.fn === 'concat')
106
+ return args.map((each) => (each === null ? '' : String(each))).join('');
105
107
  if (args.some((each) => each === null))
106
108
  return null;
107
109
  if (n.fn === 'abs')
@@ -11,18 +11,19 @@ import type { ComputedValue } from './computed.js';
11
11
  /** Data only: local columns, no paths, expressions, clock or executable hooks. */
12
12
  export type FormScalar = string | number | boolean | null;
13
13
  /** The comparisons a compiled condition holds: the query language's own, named for the evaluator. */
14
- export type FormOperator = 'eq' | 'ne' | 'lt' | 'lte' | 'gt' | 'gte';
14
+ export type FormOperator = 'eq' | 'ne' | 'lt' | 'lte' | 'gt' | 'gte' | 'has';
15
15
  /**
16
16
  * A condition in the query language — the one a page section's `when` and an
17
17
  * action's `when` speak — read against a record's own values rather than run
18
18
  * as SQL: "completed = false", "stage = closed_won and probability < 100".
19
19
  * One language for every condition an App writes; what a form or a rule can
20
20
  * evaluate in memory is its comparisons of local columns (`=`, `!=`, `<`,
21
- * `<=`, `>`, `>=`, `in`, `is (not) empty`) under `and`, `or` and brackets.
21
+ * `<=`, `>`, `>=`, `in`, `is (not) empty`) under `and`, `or` and brackets, and for an answer of several choices
22
+ * `has` (`services has cleaning`, `services has (cleaning, repairs)`: it holds any of them).
22
23
  */
23
24
  export type FormCondition = string;
24
25
  /** One compiled comparison: true when the field compares with any of the values (one, or an `in` list), or with
25
- * the record's own `other` column. */
26
+ * the record's own `other` column; for `has`, when the field's list of answers holds any of the values. */
26
27
  interface Comparison {
27
28
  field: string;
28
29
  operator: FormOperator;
@@ -76,9 +76,11 @@ function comparison(condition, where, paths) {
76
76
  return { field: condition.column, operator: 'ne', values: [null] };
77
77
  if (condition.op === 'in')
78
78
  return { field: condition.column, operator: 'eq', values: values(condition.value) };
79
+ if (condition.op === 'has')
80
+ return { field: condition.column, operator: 'has', values: values(condition.value) };
79
81
  const op = QUERY_OPERATORS[condition.op];
80
82
  if (!op) {
81
- throw new Error(`${where}: "${condition.op}" matches text, which a condition here cannot; compare with =, !=, <, <=, >, >=, in or is empty.`);
83
+ throw new Error(`${where}: "${condition.op}" matches text, which a condition here cannot; compare with =, !=, <, <=, >, >=, in, has (a list of several choices) or is empty.`);
82
84
  }
83
85
  return { field: condition.column, operator: op, values: values(condition.value) };
84
86
  }
@@ -279,13 +281,21 @@ export function comparisonResult(p, row, columns) {
279
281
  const column = columnNamed(columns, p.field);
280
282
  if (!column)
281
283
  return 'unknown';
284
+ if (p.operator === 'has') {
285
+ /* An answer of several choices is a list; its values compare as text, so a number option is asked as it is written. */
286
+ const answers = rowValue(row, p.field);
287
+ if (!Array.isArray(answers))
288
+ return 'unknown';
289
+ return p.values.some((value) => answers.some((answer) => String(answer) === String(value)));
290
+ }
282
291
  if (p.other !== undefined) {
283
292
  const other = columnNamed(columns, p.other);
284
293
  return !other || family(column) !== family(other)
285
294
  ? 'unknown'
286
295
  : compare(normalize(column, rowValue(row, p.field)), p.operator, normalize(other, rowValue(row, p.other)));
287
296
  }
288
- const results = p.values.map((value) => compare(normalize(column, rowValue(row, p.field)), p.operator, normalize(column, value)));
297
+ const operator = p.operator;
298
+ const results = p.values.map((value) => compare(normalize(column, rowValue(row, p.field)), operator, normalize(column, value)));
289
299
  return results.includes('unknown') ? 'unknown' : results.some((r) => r === true);
290
300
  }
291
301
  export function conditionResult(condition, row, columns) {
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The fixed words the platform says on an App's command and public forms, which the App's own catalog may say instead
3
+ * (`messages/<locale>.ts`, a `mistri.*` key). Without them an App translated into Spanish still said "Step 2 of 3",
4
+ * "Back" and "(optional)" in English around its own words. Each key's English is what the platform says when the
5
+ * App's catalog has no word for it in the reader's language, so a key is opt-in and an App without one changes
6
+ * nothing. The server checks an App's `mistri.*` keys against this table (server/app/appMessages.ts readCatalogs)
7
+ * and serves the ones it has, in the reader's words, as plain `{name}` templates (`words`); the client says them in
8
+ * place of its own (`appWord`, kit client/messages.ts).
9
+ */
10
+ export declare const FRAMEWORK_WORDS: {
11
+ readonly 'mistri.form.step': 'Step {step} of {count}';
12
+ readonly 'mistri.form.stepNamed': 'Step {step} of {count}: {label}';
13
+ readonly 'mistri.form.back': 'Back';
14
+ readonly 'mistri.form.optional': '(optional)';
15
+ readonly 'mistri.form.required': '(required)';
16
+ readonly 'mistri.form.reference': 'Your reference';
17
+ readonly 'mistri.form.signAgain': 'Sign again';
18
+ readonly 'mistri.form.yes': 'Yes';
19
+ readonly 'mistri.form.no': 'No';
20
+ readonly 'mistri.form.monthHint': 'MM/YYYY';
21
+ readonly 'mistri.form.dateTimeHint': 'YYYY-MM-DD HH:MM';
22
+ readonly 'mistri.status.offerEmail': 'We can email a code to the address on this application. It opens its details once, for 10 minutes.';
23
+ readonly 'mistri.status.offerText': 'We can send a code to the phone number on this application. It opens its details once, for 10 minutes.';
24
+ readonly 'mistri.status.askEmail': 'Email me a code';
25
+ readonly 'mistri.status.askText': 'Send me a code';
26
+ readonly 'mistri.status.sentEmail': 'We sent a code to your email.';
27
+ readonly 'mistri.status.sentText': 'We sent a code by text message.';
28
+ readonly 'mistri.status.codeEmail': 'Code from the email';
29
+ readonly 'mistri.status.codeText': 'Code from the message';
30
+ };
31
+ export type FrameworkWordKey = keyof typeof FRAMEWORK_WORDS;
32
+ /** A catalog key the platform reserves: an App's catalog may say it only as one of FRAMEWORK_WORDS. */
33
+ export declare const isFrameworkWordKey: (key: string) => boolean;
34
+ /** The `{name}` arguments a built-in word's English reads: all an App's word for it may read. */
35
+ export declare function frameworkWordArgs(key: FrameworkWordKey): Set<string>;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * The fixed words the platform says on an App's command and public forms, which the App's own catalog may say instead
3
+ * (`messages/<locale>.ts`, a `mistri.*` key). Without them an App translated into Spanish still said "Step 2 of 3",
4
+ * "Back" and "(optional)" in English around its own words. Each key's English is what the platform says when the
5
+ * App's catalog has no word for it in the reader's language, so a key is opt-in and an App without one changes
6
+ * nothing. The server checks an App's `mistri.*` keys against this table (server/app/appMessages.ts readCatalogs)
7
+ * and serves the ones it has, in the reader's words, as plain `{name}` templates (`words`); the client says them in
8
+ * place of its own (`appWord`, kit client/messages.ts).
9
+ */
10
+ export const FRAMEWORK_WORDS = {
11
+ 'mistri.form.step': 'Step {step} of {count}',
12
+ 'mistri.form.stepNamed': 'Step {step} of {count}: {label}',
13
+ 'mistri.form.back': 'Back',
14
+ 'mistri.form.optional': '(optional)',
15
+ 'mistri.form.required': '(required)',
16
+ 'mistri.form.reference': 'Your reference',
17
+ 'mistri.form.signAgain': 'Sign again',
18
+ 'mistri.form.yes': 'Yes',
19
+ 'mistri.form.no': 'No',
20
+ 'mistri.form.monthHint': 'MM/YYYY',
21
+ 'mistri.form.dateTimeHint': 'YYYY-MM-DD HH:MM',
22
+ 'mistri.status.offerEmail': 'We can email a code to the address on this application. It opens its details once, for 10 minutes.',
23
+ 'mistri.status.offerText': 'We can send a code to the phone number on this application. It opens its details once, for 10 minutes.',
24
+ 'mistri.status.askEmail': 'Email me a code',
25
+ 'mistri.status.askText': 'Send me a code',
26
+ 'mistri.status.sentEmail': 'We sent a code to your email.',
27
+ 'mistri.status.sentText': 'We sent a code by text message.',
28
+ 'mistri.status.codeEmail': 'Code from the email',
29
+ 'mistri.status.codeText': 'Code from the message',
30
+ };
31
+ /** A catalog key the platform reserves: an App's catalog may say it only as one of FRAMEWORK_WORDS. */
32
+ export const isFrameworkWordKey = (key) => key.startsWith('mistri.');
33
+ /** The `{name}` arguments a built-in word's English reads: all an App's word for it may read. */
34
+ export function frameworkWordArgs(key) {
35
+ return new Set([...FRAMEWORK_WORDS[key].matchAll(/\{(\w+)\}/g)].map((match) => match[1]));
36
+ }
@@ -5,7 +5,7 @@ import { columnKind, findTable } from './schema.js';
5
5
  import { dateWindow } from './queryDates.js';
6
6
  import { maskQuoted } from './maskQuoted.js';
7
7
  import { ME_SET, TENANT_FIELD, columnOperand, meOperand, meSetOperand, tenantHolds, tenantOperand, } from './queryOperands.js';
8
- import { TAGS_TYPE } from './tagLists.js';
8
+ import { CHOICES_TYPE, TAGS_TYPE } from './tagLists.js';
9
9
  import { DEFINED_PATH_TYPE } from './definedFields.js';
10
10
  const RANGE_OPS = new Set(['<', '<=', '>', '>=']);
11
11
  export { dateWindow } from './queryDates.js';
@@ -611,6 +611,9 @@ function compileCondition(raw, ctx) {
611
611
  const tagged = compiled.conditions?.find((c) => c.op !== 'has' && ctx.table?.columns.find((col) => col.name === c.column)?.type === TAGS_TYPE);
612
612
  if (tagged)
613
613
  return { error: `"${tagged.column}" is a record's tags: ask it with has, as in ${tagged.column} has bug.` };
614
+ const listed = compiled.conditions?.find((c) => c.op !== 'has' && ctx.table?.columns.find((col) => col.name === c.column)?.type === CHOICES_TYPE);
615
+ if (listed)
616
+ return { error: `"${listed.column}" holds several choices: ask it with has, as in ${listed.column} has cleaning.` };
614
617
  return compiled;
615
618
  }
616
619
  /**
@@ -759,8 +762,10 @@ function compileClause(raw, ctx) {
759
762
  /* `tags has bug`, `tags has (bug, docs)`: a record's tags (TableMeta.tags)
760
763
  hold any of the labels. A set, so a list never needs `in`. */
761
764
  if (op === 'has') {
762
- if (column?.type !== TAGS_TYPE && column?.type !== DEFINED_PATH_TYPE)
763
- return { error: `"has" asks a record's tags or a key of a JSON column, and "${name}" is neither.` };
765
+ /* A parse with no table reads the words alone (a form's condition before its fields are known), so it cannot
766
+ say what the column is; the form judges that itself, against the fields it has. */
767
+ if (ctx.table && column?.type !== TAGS_TYPE && column?.type !== DEFINED_PATH_TYPE && column?.type !== CHOICES_TYPE)
768
+ return { error: `"has" asks a record's tags, a key of a JSON column or a form's several choices, and "${name}" is none of them.` };
764
769
  const list = valueRaw
765
770
  .trim()
766
771
  .replace(/^[([]\s*/, '')
@@ -3,6 +3,10 @@ interface DateWindow {
3
3
  start: Date;
4
4
  end: Date;
5
5
  }
6
+ /** `today + 30 days` inside a longer text, each one found. */
7
+ export declare const DATE_ARITHMETIC: RegExp;
8
+ /** The day `today ± N units` names, from `today` (YYYY-MM-DD); a month or a year past the month's end lands on its last day. */
9
+ export declare function shiftedDay(today: string, sign: string, count: number, unit: string): string;
6
10
  /**
7
11
  * `now` is a parameter rather than a call to the clock, so the compiler is a
8
12
  * pure function of its inputs. That is what makes the tests below able to
@@ -13,6 +13,37 @@ function addDays(d, n) {
13
13
  c.setDate(c.getDate() + n);
14
14
  return c;
15
15
  }
16
+ /* ---------- today plus or minus N units ----------
17
+
18
+ One grammar for the day `today - 18 years` names, read by the query language (a window of that one day) and by a
19
+ command's conditions (`shared/commandDraft.ts`, which works the day out before it compiles), so the two cannot
20
+ come to mean different days. */
21
+ const ARITHMETIC_UNITS = {
22
+ day: 'day',
23
+ days: 'day',
24
+ week: 'day',
25
+ weeks: 'day',
26
+ month: 'month',
27
+ months: 'month',
28
+ year: 'year',
29
+ years: 'year',
30
+ };
31
+ const ARITHMETIC_SOURCE = String.raw `today\s*([+-])\s*(\d{1,4})\s*(days?|weeks?|months?|years?)`;
32
+ /** `today + 30 days` inside a longer text, each one found. */
33
+ export const DATE_ARITHMETIC = new RegExp(String.raw `\b${ARITHMETIC_SOURCE}\b`, 'gi');
34
+ const WHOLE_ARITHMETIC = new RegExp(`^${ARITHMETIC_SOURCE}$`, 'i');
35
+ /** The day `today ± N units` names, from `today` (YYYY-MM-DD); a month or a year past the month's end lands on its last day. */
36
+ export function shiftedDay(today, sign, count, unit) {
37
+ const [y, m, d] = today.split('-').map(Number);
38
+ const by = (sign === '-' ? -1 : 1) * count * (unit.toLowerCase().startsWith('week') ? 7 : 1);
39
+ const kind = ARITHMETIC_UNITS[unit.toLowerCase()];
40
+ if (kind === 'day')
41
+ return new Date(Date.UTC(y, m - 1, d + by)).toISOString().slice(0, 10);
42
+ const months = kind === 'year' ? by * 12 : by;
43
+ const first = new Date(Date.UTC(y, m - 1 + months, 1));
44
+ const last = new Date(Date.UTC(first.getUTCFullYear(), first.getUTCMonth() + 1, 0)).getUTCDate();
45
+ return new Date(Date.UTC(first.getUTCFullYear(), first.getUTCMonth(), Math.min(d, last))).toISOString().slice(0, 10);
46
+ }
16
47
  /**
17
48
  * `now` is a parameter rather than a call to the clock, so the compiler is a
18
49
  * pure function of its inputs. That is what makes the tests below able to
@@ -51,6 +82,16 @@ export function dateWindow(phrase, now) {
51
82
  const year = today.getFullYear() + (p === 'last year' ? -1 : 0);
52
83
  return { label: p, start: new Date(year, 0, 1), end: new Date(year + 1, 0, 1) };
53
84
  }
85
+ /* One day, not a span: `due = today + 30 days` is that whole day, and `next 30 days` stays the "within" form. */
86
+ const arithmetic = WHOLE_ARITHMETIC.exec(p);
87
+ if (arithmetic) {
88
+ const pad = (n) => String(n).padStart(2, '0');
89
+ const [, sign, count, unit] = arithmetic;
90
+ const day = shiftedDay(`${today.getFullYear()}-${pad(today.getMonth() + 1)}-${pad(today.getDate())}`, sign, Number(count), unit);
91
+ const [y, m, d] = day.split('-').map(Number);
92
+ const start = new Date(y, m - 1, d);
93
+ return { label: p, start, end: addDays(start, 1) };
94
+ }
54
95
  const span = p.match(/^(last|next|previous)\s+(\d+)\s+(minute|hour|day|week|month|year)s?$/);
55
96
  if (span) {
56
97
  const [, dir, amountRaw, unit] = span;
@@ -20,6 +20,9 @@ import type { ColumnMeta } from './schema.js';
20
20
  export declare const TAGS_COLUMN = "tags";
21
21
  /** The type a record's tags carry where a column's would be: no column has it. */
22
22
  export declare const TAGS_TYPE = "tags";
23
+ /** The type a form's several-choices answer (`field.choices`) carries where a column's would be: a list the draft
24
+ * holds, asked with `has` (`services has cleaning`) and never compared whole. Only a form's draft has one. */
25
+ export declare const CHOICES_TYPE = "choices";
23
26
  /** A record's tags as the catalog serves them and a view carries them: no request ever supplies one. */
24
27
  export interface TagSet {
25
28
  /** The link table's id. */
@@ -2,6 +2,9 @@
2
2
  export const TAGS_COLUMN = 'tags';
3
3
  /** The type a record's tags carry where a column's would be: no column has it. */
4
4
  export const TAGS_TYPE = 'tags';
5
+ /** The type a form's several-choices answer (`field.choices`) carries where a column's would be: a list the draft
6
+ * holds, asked with `has` (`services has cleaning`) and never compared whole. Only a form's draft has one. */
7
+ export const CHOICES_TYPE = 'choices';
5
8
  /** The tags read as a column: never written, never null (a record without tags has none). */
6
9
  export function tagsColumnMeta(name = TAGS_COLUMN) {
7
10
  return { name, type: TAGS_TYPE, nullable: false, primaryKey: false, writable: false };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mistriwork/engine",
3
- "version": "1.0.0-rc.49",
3
+ "version": "1.0.0-rc.51",
4
4
  "description": "The engine both products stand on: the adapters (SQLite, Postgres), the catalog, the query language, keyset pages, the HTTP kit and the shared rules. No React.",
5
5
  "homepage": "https://mistriwork.dev",
6
6
  "bugs": {
@@ -189,6 +189,7 @@
189
189
  "./shared/firstPaint.js": "./dist/shared/firstPaint.js",
190
190
  "./shared/form.js": "./dist/shared/form.js",
191
191
  "./shared/formValues.js": "./dist/shared/formValues.js",
192
+ "./shared/frameworkWords.js": "./dist/shared/frameworkWords.js",
192
193
  "./shared/funnel.js": "./dist/shared/funnel.js",
193
194
  "./shared/httpOperations.js": "./dist/shared/httpOperations.js",
194
195
  "./shared/iconGlyphs.js": "./dist/shared/iconGlyphs.js",
package/schema/model.d.ts CHANGED
@@ -79,6 +79,9 @@ export interface AppCommandChoice {
79
79
  icon?: string;
80
80
  /** A line under the label, on a card. */
81
81
  help?: string;
82
+ /** Set by the server on a table's row it served (`source.served`): the columns its `where` compares, so the page
83
+ offers the rows the answers given match without a read of its own. Never written in an App. */
84
+ row?: Readonly<Record<string, string | number | boolean | null>>;
82
85
  }
83
86
 
84
87
  /** A shape a text value must have; each refuses anything else. */
@@ -130,12 +133,32 @@ export interface CommandSensitive { keep: 'last4' | 'hash' | 'none' | 'handler'
130
133
  export type CommandLiveLines = Readonly<Record<string, string>>;
131
134
  /** Choices read from a table rather than written out: its rows' key (`by`, its primary key) and the column each is
132
135
  shown by, read under the reader's grants and validated against the table where the command runs. */
136
+ /** One side of a choice's `where` comparison: a literal, or the answer to a field of the form (`{ answer: 'region' }`). */
137
+ export type CommandChoiceOperand = string | number | boolean | null | { readonly answer: string };
138
+ /** One comparison of a choice's `where`: a column of `from` against operands; several for `in`, `[null]` for `is empty`. */
139
+ export interface CommandChoiceTest {
140
+ readonly column: string;
141
+ readonly operator: 'eq' | 'ne' | 'lt' | 'lte' | 'gt' | 'gte';
142
+ readonly values: readonly CommandChoiceOperand[];
143
+ }
144
+ /** A choice's `where`, compiled: OR of ANDs of comparisons. */
145
+ export type CommandChoiceMatch = readonly (readonly CommandChoiceTest[])[];
133
146
  export interface CommandChoiceSource {
134
147
  from: string;
135
148
  by: string;
136
149
  labelColumn: string;
137
- /** The order the rows are offered in: a column of `from` and a direction. Absent, the rows are in the order of `labelColumn`. */
150
+ /** The column each row is shown by in a locale, keyed by the locale's tag as the App's catalogs name it
151
+ (`{ es: 'name_es' }`); a row with nothing there is shown by `labelColumn`. */
152
+ labelColumns?: Readonly<Record<string, string>>;
153
+ /** The order the rows are offered in: a column of `from` and a direction. Absent, the rows are in the order of `labelColumn`
154
+ (in a locale `labelColumns` names, of the words shown, in that locale's order). */
138
155
  sort?: { column: string; direction: 'asc' | 'desc' };
156
+ /** The rows offered, narrowed by other answers of the form, as the App wrote it (`'region = region and active = true'`):
157
+ a name on the right of a comparison that is a field of the form is that field's answer, any other name a column
158
+ of `from`. Until every answer it reads is given, nothing is offered. */
159
+ where?: string;
160
+ /** `where`, compiled by the server: OR of ANDs of its comparisons. */
161
+ match?: CommandChoiceMatch;
139
162
  /** Set by the server on a public form it served this field's rows with: `options` is the whole answer, an empty list
140
163
  meaning none to offer, and the page reads nothing of its own. Never written in an App. */
141
164
  served?: true;