shutro 0.0.0-stage → 0.2.0

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.
Files changed (165) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +99 -2
  3. package/dist/audit/index.d.ts +59 -0
  4. package/dist/audit/index.js +96 -0
  5. package/dist/cli/bin.d.ts +2 -0
  6. package/dist/cli/bin.js +11 -0
  7. package/dist/cli/cli.d.ts +10 -0
  8. package/dist/cli/cli.js +164 -0
  9. package/dist/cli/config.d.ts +18 -0
  10. package/dist/cli/config.js +49 -0
  11. package/dist/cli/errors.d.ts +16 -0
  12. package/dist/cli/errors.js +23 -0
  13. package/dist/cli/generate/generate.d.ts +33 -0
  14. package/dist/cli/generate/generate.js +84 -0
  15. package/dist/cli/generate/render.d.ts +23 -0
  16. package/dist/cli/generate/render.js +249 -0
  17. package/dist/cli/index.d.ts +12 -0
  18. package/dist/cli/index.js +12 -0
  19. package/dist/cli/init.d.ts +2 -0
  20. package/dist/cli/init.js +65 -0
  21. package/dist/cli/inspect.d.ts +10 -0
  22. package/dist/cli/inspect.js +82 -0
  23. package/dist/cli/packages.d.ts +6 -0
  24. package/dist/cli/packages.js +6 -0
  25. package/dist/cli/project.d.ts +18 -0
  26. package/dist/cli/project.js +39 -0
  27. package/dist/cli/resolve.d.ts +2 -0
  28. package/dist/cli/resolve.js +28 -0
  29. package/dist/core/compute/graph.d.ts +52 -0
  30. package/dist/core/compute/graph.js +162 -0
  31. package/dist/core/data/data.d.ts +59 -0
  32. package/dist/core/data/data.js +119 -0
  33. package/dist/core/data/load.d.ts +37 -0
  34. package/dist/core/data/load.js +236 -0
  35. package/dist/core/env/env.d.ts +468 -0
  36. package/dist/core/env/env.js +916 -0
  37. package/dist/core/env/identity.d.ts +43 -0
  38. package/dist/core/env/identity.js +65 -0
  39. package/dist/core/env/inspector.d.ts +55 -0
  40. package/dist/core/env/inspector.js +85 -0
  41. package/dist/core/env/time.d.ts +12 -0
  42. package/dist/core/env/time.js +38 -0
  43. package/dist/core/errors.d.ts +256 -0
  44. package/dist/core/errors.js +360 -0
  45. package/dist/core/events/events.d.ts +44 -0
  46. package/dist/core/events/events.js +58 -0
  47. package/dist/core/events/workers.d.ts +56 -0
  48. package/dist/core/events/workers.js +155 -0
  49. package/dist/core/index.d.ts +51 -0
  50. package/dist/core/index.js +42 -0
  51. package/dist/core/model/company.d.ts +6 -0
  52. package/dist/core/model/company.js +31 -0
  53. package/dist/core/model/faces.d.ts +42 -0
  54. package/dist/core/model/faces.js +1 -0
  55. package/dist/core/model/field.d.ts +479 -0
  56. package/dist/core/model/field.js +461 -0
  57. package/dist/core/model/generated.d.ts +77 -0
  58. package/dist/core/model/generated.js +1 -0
  59. package/dist/core/model/id.d.ts +33 -0
  60. package/dist/core/model/id.js +4 -0
  61. package/dist/core/model/model.d.ts +387 -0
  62. package/dist/core/model/model.js +566 -0
  63. package/dist/core/model/partition.d.ts +31 -0
  64. package/dist/core/model/partition.js +71 -0
  65. package/dist/core/model/related.d.ts +17 -0
  66. package/dist/core/model/related.js +60 -0
  67. package/dist/core/model/typed.d.ts +107 -0
  68. package/dist/core/model/typed.js +46 -0
  69. package/dist/core/money/currency.d.ts +39 -0
  70. package/dist/core/money/currency.js +37 -0
  71. package/dist/core/money/decimal.d.ts +26 -0
  72. package/dist/core/money/decimal.js +51 -0
  73. package/dist/core/money/fx.d.ts +68 -0
  74. package/dist/core/money/fx.js +124 -0
  75. package/dist/core/money/money.d.ts +84 -0
  76. package/dist/core/money/money.js +173 -0
  77. package/dist/core/money/quantity.d.ts +67 -0
  78. package/dist/core/money/quantity.js +108 -0
  79. package/dist/core/money/rounding.d.ts +11 -0
  80. package/dist/core/money/rounding.js +12 -0
  81. package/dist/core/recordset/aggregate.d.ts +22 -0
  82. package/dist/core/recordset/aggregate.js +258 -0
  83. package/dist/core/recordset/audit.d.ts +33 -0
  84. package/dist/core/recordset/audit.js +262 -0
  85. package/dist/core/recordset/compute.d.ts +36 -0
  86. package/dist/core/recordset/compute.js +414 -0
  87. package/dist/core/recordset/constraints.d.ts +9 -0
  88. package/dist/core/recordset/constraints.js +61 -0
  89. package/dist/core/recordset/domain.d.ts +31 -0
  90. package/dist/core/recordset/domain.js +300 -0
  91. package/dist/core/recordset/onchange.d.ts +43 -0
  92. package/dist/core/recordset/onchange.js +240 -0
  93. package/dist/core/recordset/recordset.d.ts +110 -0
  94. package/dist/core/recordset/recordset.js +789 -0
  95. package/dist/core/recordset/relations.d.ts +15 -0
  96. package/dist/core/recordset/relations.js +13 -0
  97. package/dist/core/recordset/rls.d.ts +15 -0
  98. package/dist/core/recordset/rls.js +108 -0
  99. package/dist/core/recordset/security.d.ts +56 -0
  100. package/dist/core/recordset/security.js +269 -0
  101. package/dist/core/recordset/sequences.d.ts +31 -0
  102. package/dist/core/recordset/sequences.js +154 -0
  103. package/dist/core/recordset/source.d.ts +9 -0
  104. package/dist/core/recordset/source.js +19 -0
  105. package/dist/core/recordset/sqlErrors.d.ts +6 -0
  106. package/dist/core/recordset/sqlErrors.js +39 -0
  107. package/dist/core/recordset/transitions.d.ts +10 -0
  108. package/dist/core/recordset/transitions.js +80 -0
  109. package/dist/core/recordset/types.d.ts +415 -0
  110. package/dist/core/recordset/types.js +8 -0
  111. package/dist/core/recordset/values.d.ts +33 -0
  112. package/dist/core/recordset/values.js +177 -0
  113. package/dist/core/recordset/writes.d.ts +42 -0
  114. package/dist/core/recordset/writes.js +786 -0
  115. package/dist/core/registry/ddl.d.ts +31 -0
  116. package/dist/core/registry/ddl.js +174 -0
  117. package/dist/core/registry/extension.d.ts +94 -0
  118. package/dist/core/registry/extension.js +90 -0
  119. package/dist/core/registry/module.d.ts +89 -0
  120. package/dist/core/registry/module.js +98 -0
  121. package/dist/core/registry/registry.d.ts +130 -0
  122. package/dist/core/registry/registry.js +591 -0
  123. package/dist/core/security/runtime.d.ts +102 -0
  124. package/dist/core/security/runtime.js +232 -0
  125. package/dist/driver-pg/driver.d.ts +88 -0
  126. package/dist/driver-pg/driver.js +177 -0
  127. package/dist/driver-pg/errors.d.ts +72 -0
  128. package/dist/driver-pg/errors.js +182 -0
  129. package/dist/driver-pg/index.d.ts +7 -0
  130. package/dist/driver-pg/index.js +7 -0
  131. package/dist/i18n/index.d.ts +25 -0
  132. package/dist/i18n/index.js +51 -0
  133. package/dist/migrate/apply.d.ts +78 -0
  134. package/dist/migrate/apply.js +167 -0
  135. package/dist/migrate/catalog.d.ts +10 -0
  136. package/dist/migrate/catalog.js +122 -0
  137. package/dist/migrate/diff.d.ts +98 -0
  138. package/dist/migrate/diff.js +160 -0
  139. package/dist/migrate/errors.d.ts +21 -0
  140. package/dist/migrate/errors.js +31 -0
  141. package/dist/migrate/index.d.ts +18 -0
  142. package/dist/migrate/index.js +18 -0
  143. package/dist/migrate/render.d.ts +5 -0
  144. package/dist/migrate/render.js +101 -0
  145. package/dist/migrate/schema.d.ts +61 -0
  146. package/dist/migrate/schema.js +233 -0
  147. package/dist/security/index.d.ts +147 -0
  148. package/dist/security/index.js +278 -0
  149. package/dist/sequence/index.d.ts +63 -0
  150. package/dist/sequence/index.js +106 -0
  151. package/dist/sql/ast.d.ts +49 -0
  152. package/dist/sql/ast.js +47 -0
  153. package/dist/sql/builder/builder.d.ts +215 -0
  154. package/dist/sql/builder/builder.js +308 -0
  155. package/dist/sql/builder/expression.d.ts +80 -0
  156. package/dist/sql/builder/expression.js +126 -0
  157. package/dist/sql/compile.d.ts +18 -0
  158. package/dist/sql/compile.js +41 -0
  159. package/dist/sql/errors.d.ts +13 -0
  160. package/dist/sql/errors.js +16 -0
  161. package/dist/sql/index.d.ts +19 -0
  162. package/dist/sql/index.js +19 -0
  163. package/dist/sql/tag.d.ts +47 -0
  164. package/dist/sql/tag.js +123 -0
  165. package/package.json +82 -4
@@ -0,0 +1,300 @@
1
+ /**
2
+ * Compiles a search domain (RFC 0005 §7.1) plus automatic scoping (`active`, companies) into WHERE fragments:
3
+ * field conditions ANDed, `or` / `and` / `not`, dotted relation paths (`'partner.name'`, `'order.user'`) and
4
+ * `{ lines: { any | none: domain } }` on x2many fields. Relations compile to sub-selects, never joins, so rows are
5
+ * never duplicated (RFC 0005 R8).
6
+ */
7
+ import { sql } from '../../sql/index.js';
8
+ import { Decimal as DecimalJs } from 'decimal.js';
9
+ import { InvalidDomainError } from '../errors.js';
10
+ import { relatedPath } from '../model/related.js';
11
+ import { junctionTable } from './relations.js';
12
+ const OPERATORS = new Set([
13
+ 'eq',
14
+ 'ne',
15
+ 'lt',
16
+ 'lte',
17
+ 'gt',
18
+ 'gte',
19
+ 'in',
20
+ 'notIn',
21
+ 'isNull',
22
+ 'like',
23
+ 'ilike',
24
+ 'childOf',
25
+ 'parentOf',
26
+ ]);
27
+ function bind(value) {
28
+ if (DecimalJs.isDecimal(value))
29
+ return value.toFixed();
30
+ return value;
31
+ }
32
+ function column(model, key, translation) {
33
+ const field = model.fields[key];
34
+ const col = model.columns[key];
35
+ if (field === undefined) {
36
+ throw new InvalidDomainError(`'${key}' is not a field of ${model.name}.`, `Fields: ${Object.keys(model.fields).join(', ')}.`);
37
+ }
38
+ if (field.encrypted) {
39
+ throw new InvalidDomainError(`'${key}' of ${model.name} is encrypted and cannot be filtered or sorted on.`, 'Encrypted values are opaque to the database; filter in memory after loading, or store a searchable hash in another field.');
40
+ }
41
+ if (col === undefined) {
42
+ throw new InvalidDomainError(`'${key}' of ${model.name} is a ${field.kind} field and cannot be filtered on directly.`, 'Filter x2many relations with any / all / none (full domain compiler), and non-stored computes in memory.');
43
+ }
44
+ if (field.companyDependent) {
45
+ // The current company's value, else the default: what readers see (RFC 0005 §7.4).
46
+ if (translation?.company === undefined)
47
+ throw new InvalidDomainError(`'${key}' is company-dependent and needs the current company.`, 'Search inside shutro.run({ company }).');
48
+ const literal = typeof field.default === 'function' ? null : (field.default ?? null);
49
+ const value = sql `(${sql.id(col)}->>${String(translation.company)})`;
50
+ return {
51
+ field,
52
+ column: literal === null
53
+ ? sql.cast(value, field.valueType)
54
+ : sql `COALESCE(${sql.cast(value, field.valueType)}, ${sql.param(bind(literal), field.valueType)})`,
55
+ };
56
+ }
57
+ if (field.translate && translation !== undefined) {
58
+ // COALESCE(col->>lang, col->>source): what readers see, so filters and sorts match reads (RFC 0005 §7.4).
59
+ return {
60
+ field,
61
+ column: sql `COALESCE(${sql.id(col)}->>${translation.lang}, ${sql.id(col)}->>${translation.source})`,
62
+ };
63
+ }
64
+ return { field, column: sql.id(col) };
65
+ }
66
+ function condition(col, op, value, key) {
67
+ switch (op) {
68
+ case 'eq':
69
+ return value === null ? sql `${col} IS NULL` : sql `${col} = ${bind(value)}`;
70
+ case 'ne':
71
+ return value === null ? sql `${col} IS NOT NULL` : sql `${col} IS DISTINCT FROM ${bind(value)}`;
72
+ case 'lt':
73
+ return sql `${col} < ${bind(value)}`;
74
+ case 'lte':
75
+ return sql `${col} <= ${bind(value)}`;
76
+ case 'gt':
77
+ return sql `${col} > ${bind(value)}`;
78
+ case 'gte':
79
+ return sql `${col} >= ${bind(value)}`;
80
+ case 'in': {
81
+ if (!Array.isArray(value))
82
+ throw new InvalidDomainError(`'${key}': in needs an array.`, "Use { in: ['draft', 'sale'] }.");
83
+ return value.length === 0 ? sql `FALSE` : sql `${col} = ANY(${value.map(bind)})`;
84
+ }
85
+ case 'notIn': {
86
+ if (!Array.isArray(value))
87
+ throw new InvalidDomainError(`'${key}': notIn needs an array.`, "Use { notIn: ['cancel'] }.");
88
+ return value.length === 0
89
+ ? sql `TRUE`
90
+ : sql `(${col} IS NULL OR ${col} <> ALL(${value.map(bind)}))`;
91
+ }
92
+ case 'isNull':
93
+ return value === true ? sql `${col} IS NULL` : sql `${col} IS NOT NULL`;
94
+ case 'like':
95
+ return sql `${col} LIKE ${value}`;
96
+ case 'ilike':
97
+ return sql `${col} ILIKE ${value}`;
98
+ default:
99
+ throw new InvalidDomainError(`'${op}' is not a domain operator (field '${key}').`, `Use one of: ${[...OPERATORS].join(', ')}.`);
100
+ }
101
+ }
102
+ function isOperators(value) {
103
+ return (typeof value === 'object' &&
104
+ value !== null &&
105
+ !Array.isArray(value) &&
106
+ !(value instanceof Date) &&
107
+ !DecimalJs.isDecimal(value) &&
108
+ Object.getPrototypeOf(value) === Object.prototype);
109
+ }
110
+ /** Compiles the user's domain into conditions (ANDed). */
111
+ export function compileDomain(model, where, translation, resolve, scope) {
112
+ const conditions = [];
113
+ for (const [key, value] of Object.entries(where ?? {})) {
114
+ if (value === undefined)
115
+ continue;
116
+ if (key === 'or' || key === 'and') {
117
+ if (!Array.isArray(value))
118
+ throw new InvalidDomainError(`'${key}' needs an array of domains.`, "Use { or: [{ state: 'draft' }, { user: 7 }] }.");
119
+ const parts = value.map((d) => {
120
+ const inner = compileDomain(model, d, translation, resolve, scope);
121
+ return inner.length === 0 ? sql `TRUE` : sql `(${sql.join(inner, sql ` AND `)})`;
122
+ });
123
+ if (parts.length > 0)
124
+ conditions.push(sql `(${sql.join(parts, key === 'or' ? sql ` OR ` : sql ` AND `)})`);
125
+ continue;
126
+ }
127
+ if (key === 'not') {
128
+ const inner = compileDomain(model, value, translation, resolve, scope);
129
+ if (inner.length > 0)
130
+ conditions.push(sql `NOT (${sql.join(inner, sql ` AND `)})`);
131
+ continue;
132
+ }
133
+ const dot = key.indexOf('.');
134
+ if (dot > 0) {
135
+ // 'partner.name': the condition on the related model, as a sub-select.
136
+ conditions.push(relation(model, key.slice(0, dot), { [key.slice(dot + 1)]: value }, 'any', translation, resolve, scope));
137
+ continue;
138
+ }
139
+ const relField = model.fields[key];
140
+ if (relField !== undefined && (relField.kind === 'one2many' || relField.kind === 'many2many')) {
141
+ if (!isOperators(value) || Object.keys(value).some((k) => k !== 'any' && k !== 'none'))
142
+ throw new InvalidDomainError(`'${key}' is a ${relField.kind}: filter it with { any: domain } or { none: domain }.`, `E.g. { ${key}: { any: { quantity: { gt: 10 } } } }.`);
143
+ for (const mode of ['any', 'none']) {
144
+ const inner = value[mode];
145
+ if (inner !== undefined)
146
+ conditions.push(relation(model, key, inner, mode, translation, resolve, scope));
147
+ }
148
+ continue;
149
+ }
150
+ // A non-stored computed field with a search function filters through the domain it returns.
151
+ const searchFn = model.columns[key] === undefined ? model.fields[key]?.search : undefined;
152
+ if (searchFn !== undefined) {
153
+ const terms = isOperators(value) ? Object.entries(value) : [['eq', value]];
154
+ for (const [op, operand] of terms) {
155
+ if (operand === undefined)
156
+ continue;
157
+ const inner = compileDomain(model, searchFn(op, operand), translation, resolve, scope);
158
+ conditions.push(inner.length === 0 ? sql `TRUE` : sql `(${sql.join(inner, sql ` AND `)})`);
159
+ }
160
+ continue;
161
+ }
162
+ // A non-stored related field (delegation included) filters through its path.
163
+ const mirrored = model.columns[key] === undefined ? relatedPath(model.fields[key]?.compute) : undefined;
164
+ if (mirrored !== undefined) {
165
+ const dot = mirrored.indexOf('.');
166
+ conditions.push(relation(model, mirrored.slice(0, dot), { [mirrored.slice(dot + 1)]: value }, 'any', translation, resolve, scope));
167
+ continue;
168
+ }
169
+ const { column: col } = column(model, key, translation);
170
+ if (isOperators(value)) {
171
+ for (const [op, operand] of Object.entries(value)) {
172
+ if (operand === undefined)
173
+ continue;
174
+ if (!OPERATORS.has(op)) {
175
+ throw new InvalidDomainError(`'${op}' is not a domain operator (field '${key}').`, `Use one of: ${[...OPERATORS].join(', ')}.`);
176
+ }
177
+ if (op === 'childOf' || op === 'parentOf') {
178
+ conditions.push(hierarchyCondition(model, key, op, operand, resolve));
179
+ continue;
180
+ }
181
+ conditions.push(condition(col, op, operand, key));
182
+ }
183
+ }
184
+ else {
185
+ conditions.push(condition(col, 'eq', value, key));
186
+ }
187
+ }
188
+ return conditions;
189
+ }
190
+ /**
191
+ * `childOf` / `parentOf` on `id` of a hierarchical model, or on a many2one to one: records in the subtrees of the
192
+ * given ids (themselves included) / their ancestors (themselves included), as prefix matches on the path column.
193
+ */
194
+ function hierarchyCondition(model, key, op, operand, resolve) {
195
+ const field = model.fields[key];
196
+ const tree = key === 'id'
197
+ ? model
198
+ : field?.kind === 'many2one'
199
+ ? resolve?.(field.target ?? '')
200
+ : undefined;
201
+ const spec = tree?.hierarchy;
202
+ if (tree === undefined || spec === undefined)
203
+ throw new InvalidDomainError(`'${op}' needs a hierarchy: '${key}' of ${model.name} is not the id of, or a many2one to, a model with hierarchy.`, "Declare hierarchy: { parent: 'parent', path: 'parentPath' } on the tree model.");
204
+ const ids = (Array.isArray(operand) ? operand : [operand]).map((v) => {
205
+ if (typeof v !== 'number' || !Number.isSafeInteger(v))
206
+ throw new InvalidDomainError(`'${op}' takes ids, got ${JSON.stringify(v)}.`, `E.g. { ${key}: { ${op}: [5, 9] } }.`);
207
+ return v;
208
+ });
209
+ const t = sql.id(tree.table);
210
+ const path = sql.id(tree.columns[spec.path] ?? '');
211
+ const h = sql.id('h');
212
+ const c = sql.id('c');
213
+ const given = sql `${h}.${sql.id('id')} = ANY(${sql.array(ids, 'bigint')})`;
214
+ const match = (node) => op === 'childOf'
215
+ ? sql `${node}.${path} LIKE ANY (SELECT ${h}.${path} || '%' FROM ${t} AS ${h} WHERE ${given})`
216
+ : sql `EXISTS (SELECT 1 FROM ${t} AS ${h} WHERE ${given} AND ${h}.${path} LIKE ${node}.${path} || '%')`;
217
+ if (key === 'id')
218
+ return match(t);
219
+ const col = sql.id(model.columns[key] ?? '');
220
+ return sql `${col} IN (SELECT ${c}.${sql.id('id')} FROM ${t} AS ${c} WHERE ${match(c)})`;
221
+ }
222
+ /**
223
+ * A condition through relation `key`: records related to at least one (`any`) or no (`none`) record of the target
224
+ * matching `inner`.
225
+ */
226
+ function relation(model, key, inner, mode, translation, resolve, scope) {
227
+ const field = model.fields[key];
228
+ const targetName = field?.target;
229
+ if (field === undefined || targetName === undefined) {
230
+ throw new InvalidDomainError(`'${key}' is not a relation of ${model.name}, so it cannot start a path.`, `Paths go through many2one, one2many or many2many fields of ${model.name}.`);
231
+ }
232
+ if (resolve === undefined) {
233
+ throw new InvalidDomainError(`Relation path '${key}.…' needs the registry.`, 'This compiler call has no model resolver.');
234
+ }
235
+ const target = resolve(targetName);
236
+ const conditions = [
237
+ ...compileDomain(target, inner, translation, resolve, scope),
238
+ ...(scope?.(target) ?? []),
239
+ ];
240
+ const where = conditions.length === 0 ? sql.empty : sql ` WHERE ${sql.join(conditions, sql ` AND `)}`;
241
+ const from = translation?.from?.(target) ?? sql.id(target.table);
242
+ const targets = sql `SELECT ${sql.id('id')} FROM ${from}${where}`;
243
+ let match;
244
+ if (field.kind === 'many2one') {
245
+ const col = sql.id(model.columns[key] ?? '');
246
+ return mode === 'any'
247
+ ? sql `${col} IN (${targets})`
248
+ : sql `(${col} IS NULL OR ${col} NOT IN (${targets}))`;
249
+ }
250
+ if (field.kind === 'one2many') {
251
+ const inverse = sql.id(target.columns[field.inverseField ?? ''] ?? '');
252
+ const and = conditions.length === 0 ? sql.empty : sql ` AND ${sql.join(conditions, sql ` AND `)}`;
253
+ match = sql `SELECT ${inverse} FROM ${from} WHERE ${inverse} IS NOT NULL${and}`;
254
+ }
255
+ else {
256
+ const j = junctionTable(model, field, target);
257
+ match = sql `SELECT ${sql.id(j.sourceColumn)} FROM ${sql.id(j.table)} WHERE ${sql.id(j.targetColumn)} IN (${targets})`;
258
+ }
259
+ return mode === 'any'
260
+ ? sql `${sql.id('id')} IN (${match})`
261
+ : sql `${sql.id('id')} NOT IN (${match})`;
262
+ }
263
+ /** Conditions the environment adds to every search (RFC 0005 §7.4): archived records and company scope. */
264
+ export function scopingConditions(model, env) {
265
+ const conditions = [];
266
+ if (model.archivable && env.flags.activeTest) {
267
+ const active = model.columns['active'];
268
+ if (active !== undefined)
269
+ conditions.push(sql `${sql.id(active)} = TRUE`);
270
+ }
271
+ if (model.companyScoped !== undefined && env.flags.checkCompany) {
272
+ const company = model.columns['company'];
273
+ if (company !== undefined) {
274
+ const inCompanies = sql `${sql.id(company)} = ANY(${[...env.companyIds]})`;
275
+ conditions.push(model.companyScoped.required
276
+ ? inCompanies
277
+ : sql `(${inCompanies} OR ${sql.id(company)} IS NULL)`);
278
+ }
279
+ }
280
+ return conditions;
281
+ }
282
+ /** `ORDER BY` from `'field'`, `'field asc'`, `'field desc'` entries, with an `id` tiebreaker. */
283
+ export function compileOrder(model, order, translation) {
284
+ const terms = [];
285
+ const specs = order ?? model.order.map((o) => `${o.field} ${o.direction}`);
286
+ let hasId = false;
287
+ for (const spec of specs) {
288
+ const [key, direction = 'asc', ...rest] = spec.split(' ');
289
+ if (key === undefined || rest.length > 0 || (direction !== 'asc' && direction !== 'desc')) {
290
+ throw new InvalidDomainError(`order entry '${spec}' is malformed.`, "Use 'field', 'field asc' or 'field desc'.");
291
+ }
292
+ const { column: col } = column(model, key, translation);
293
+ if (key === 'id')
294
+ hasId = true;
295
+ terms.push(direction === 'desc' ? sql `${col} DESC` : sql `${col} ASC`);
296
+ }
297
+ if (!hasId)
298
+ terms.push(sql `${sql.id('id')} ASC`);
299
+ return sql.join(terms);
300
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Onchange (RFC 0009 §7.3–7.4): a draft is a virtual record in the cache (negative id). Handlers run for the changed
3
+ * fields, then the real compute engine computes the draft and its virtual child rows. Nothing is written; the virtual
4
+ * records are purged afterwards.
5
+ */
6
+ import type { ScopeInternals } from '../env/env.js';
7
+ import type { AnyModel } from '../model/model.js';
8
+ import { type ComputeHost } from './compute.js';
9
+ /** What the draft runtime needs from the recordset runtime. */
10
+ export interface OnchangeHost extends ComputeHost {
11
+ /** Stored, non-x2many keys with sibling currency / unit fields. */
12
+ defaults(model: AnyModel): Set<string>;
13
+ /** Children ids of an x2many of a real record. */
14
+ children(model: AnyModel, id: number, key: string): Promise<number[]>;
15
+ /** Plain JSON rows (as `read()` returns them) of records. */
16
+ read(model: AnyModel, ids: readonly number[], keys: readonly string[]): Record<string, unknown>[];
17
+ }
18
+ /** The input of `env.model(M).onchange()`. */
19
+ export interface OnchangeInputRaw {
20
+ readonly id?: number | undefined;
21
+ readonly values: Readonly<Record<string, unknown>>;
22
+ readonly changed: readonly string[];
23
+ }
24
+ /** The output of `env.model(M).onchange()`. */
25
+ export interface OnchangeResultRaw {
26
+ /** Scalar and many2one fields whose plain value differs from the input. */
27
+ readonly values: Readonly<Record<string, unknown>>;
28
+ readonly warnings: readonly string[];
29
+ /** Plain rows of the virtual children created by x2many `create` commands, per field. */
30
+ readonly children: Readonly<Record<string, readonly Record<string, unknown>[]>>;
31
+ }
32
+ /** The draft handed to onchange handlers (untyped runtime; typed as `Draft<S, M>`). */
33
+ export interface DraftRaw {
34
+ readonly id: number | null;
35
+ readonly env: ScopeInternals['env'];
36
+ get(key: string): unknown;
37
+ set(key: string, value: unknown): void;
38
+ /** The related record of a many2one (loaded), or null. */
39
+ record(key: string): Promise<unknown>;
40
+ warn(message: string): void;
41
+ }
42
+ /** `env.model(M).onchange(input)`. */
43
+ export declare function runOnchange(host: OnchangeHost, model: AnyModel, input: OnchangeInputRaw): Promise<OnchangeResultRaw>;
@@ -0,0 +1,240 @@
1
+ /**
2
+ * Onchange (RFC 0009 §7.3–7.4): a draft is a virtual record in the cache (negative id). Handlers run for the changed
3
+ * fields, then the real compute engine computes the draft and its virtual child rows. Nothing is written; the virtual
4
+ * records are purged afterwards.
5
+ */
6
+ import { computeFields } from './compute.js';
7
+ import { assertAccess, canField } from './security.js';
8
+ import { fail, normalize } from './values.js';
9
+ function translationOf(host) {
10
+ return { lang: host.internals.env.lang, source: host.internals.sourceLang };
11
+ }
12
+ function defaultOf(field, env) {
13
+ return typeof field.default === 'function'
14
+ ? field.default(env)
15
+ : field.default;
16
+ }
17
+ function isX2Many(field) {
18
+ return field.kind === 'one2many' || field.kind === 'many2many';
19
+ }
20
+ function scalarKeys(model) {
21
+ return Object.keys(model.fields).filter((k) => !isX2Many(model.fields[k]));
22
+ }
23
+ /** Writes one draft value into the cache: `null` is always allowed, everything else is normalized like a write. */
24
+ function setDraftValue(model, values, key, value, translation) {
25
+ const field = model.fields[key];
26
+ if (field === undefined || key === 'id')
27
+ fail(model, [key], `'${key}' is not a field.`, `Fields: ${Object.keys(model.fields).join(', ')}.`);
28
+ if (value === null || value === undefined) {
29
+ values.set(key, null);
30
+ return;
31
+ }
32
+ // A virtual parent (negative id) is a valid draft reference.
33
+ if (field.kind === 'many2one' && typeof value === 'number' && value < 0) {
34
+ values.set(key, value);
35
+ return;
36
+ }
37
+ values.set(key, normalize(model, key, field, value, (k) => values.get(k), translation));
38
+ }
39
+ /** Fills a virtual record with defaults (or a real record's values), then the given values. */
40
+ async function materialize(host, model, id, given, preset, children) {
41
+ const { internals } = host;
42
+ const vid = internals.nextVirtualId();
43
+ const values = host.values(model.name, vid, true);
44
+ const stored = [...host.defaults(model)].filter((k) => k !== 'id' && model.columns[k] !== undefined);
45
+ if (id !== undefined) {
46
+ await host.load(model, [id], { fields: new Set(stored), relations: new Map() });
47
+ const current = host.values(model.name, id);
48
+ for (const key of stored)
49
+ values.set(key, current.get(key) ?? null);
50
+ for (const key of Object.keys(model.fields)) {
51
+ if (isX2Many(model.fields[key]))
52
+ values.set(key, await host.children(model, id, key));
53
+ }
54
+ }
55
+ else {
56
+ for (const key of stored) {
57
+ const field = model.fields[key];
58
+ // Defaults are normalized like given values ('1' → Decimal), so computes on drafts see real types.
59
+ if (field.computed)
60
+ values.set(key, null);
61
+ else
62
+ setDraftValue(model, values, key, defaultOf(field, internals.env) ?? null, translationOf(host));
63
+ }
64
+ for (const key of Object.keys(model.fields)) {
65
+ if (isX2Many(model.fields[key]))
66
+ values.set(key, []);
67
+ }
68
+ }
69
+ for (const [key, value] of Object.entries(preset))
70
+ setDraftValue(model, values, key, value, translationOf(host));
71
+ for (const [key, value] of Object.entries(given)) {
72
+ if (value === undefined)
73
+ continue;
74
+ const field = model.fields[key];
75
+ if (field !== undefined && isX2Many(field)) {
76
+ const commands = (value ?? {});
77
+ const target = internals.registry.get(field.target ?? '').model;
78
+ const list = [...(values.get(key) ?? [])];
79
+ if (Array.isArray(commands['set']))
80
+ list.splice(0, list.length, ...commands['set']);
81
+ if (Array.isArray(commands['link']))
82
+ for (const linked of commands['link'])
83
+ if (!list.includes(linked))
84
+ list.push(linked);
85
+ const created = [];
86
+ if (Array.isArray(commands['create'])) {
87
+ const inverse = field.kind === 'one2many'
88
+ ? (field.inverseField ?? '')
89
+ : '';
90
+ for (const row of commands['create']) {
91
+ const cid = await materialize(host, target, undefined, row, inverse === '' ? {} : { [inverse]: vid }, new Map());
92
+ created.push(cid);
93
+ }
94
+ }
95
+ list.push(...created);
96
+ values.set(key, list);
97
+ children.set(key, created);
98
+ continue;
99
+ }
100
+ setDraftValue(model, values, key, value, translationOf(host));
101
+ }
102
+ return vid;
103
+ }
104
+ /** Computes every computed field of `model` for `ids`, in rank order (fields sharing a compute go together). */
105
+ async function computeAll(host, model, ids) {
106
+ const fields = host.internals.registry.compute.fields
107
+ .filter((f) => f.model === model.name)
108
+ .sort((a, b) => a.rank - b.rank);
109
+ const done = new Set();
110
+ for (const f of fields) {
111
+ if (done.has(f.compute))
112
+ continue;
113
+ done.add(f.compute);
114
+ // A draft may not have a required relation yet (a new line without its order): skip the compute for those
115
+ // records, so inside a compute a required many2one in `depends` is always set (feedback #4). The field stays
116
+ // empty in the draft until the relation is given.
117
+ const ready = ids.filter((id) => {
118
+ const values = host.values(model.name, id);
119
+ return f.paths.every((path) => {
120
+ const first = path[0];
121
+ if (first === undefined || path.length < 2 || first.kind !== 'many2one')
122
+ return true;
123
+ if (model.fields[first.key]?.required !== true)
124
+ return true;
125
+ const value = values?.get(first.key);
126
+ return value !== null && value !== undefined;
127
+ });
128
+ });
129
+ await computeFields(host, model, ready, [f]);
130
+ }
131
+ }
132
+ /** Runs `model`'s onchange handlers on the virtual record `vid` for `changed`, cascading once per key. */
133
+ async function runHandlers(host, model, vid, id, changed, warnings) {
134
+ const { internals } = host;
135
+ const values = host.values(model.name, vid);
136
+ const queue = [...changed];
137
+ const done = new Set();
138
+ const draft = {
139
+ id,
140
+ env: internals.env,
141
+ get: (key) => values.get(key),
142
+ set(key, value) {
143
+ setDraftValue(model, values, key, value, translationOf(host));
144
+ if (!done.has(key) && !queue.includes(key))
145
+ queue.push(key);
146
+ },
147
+ async record(key) {
148
+ const field = model.fields[key];
149
+ const target = field?.target;
150
+ const related = values.get(key);
151
+ if (field?.kind !== 'many2one' || target === undefined || typeof related !== 'number')
152
+ return null;
153
+ const set = await host.recordset(internals.registry.get(target).model, [related]).load();
154
+ return set.first();
155
+ },
156
+ warn: (message) => {
157
+ warnings.push(message);
158
+ },
159
+ };
160
+ while (queue.length > 0) {
161
+ const key = queue.shift();
162
+ if (done.has(key))
163
+ continue;
164
+ done.add(key);
165
+ const fn = model.onchange[key];
166
+ if (fn !== undefined)
167
+ await fn(draft, internals.env);
168
+ }
169
+ }
170
+ /** `env.model(M).onchange(input)`. */
171
+ export async function runOnchange(host, model, input) {
172
+ const { internals } = host;
173
+ // Form assistance for a record being created (no id) or edited: the same access as saving it would need, so a
174
+ // reader cannot run a model's onchange logic (and see its results) on records they could never save.
175
+ assertAccess(internals, model, 'read');
176
+ assertAccess(internals, model, input.id === undefined || input.id === null ? 'create' : 'write');
177
+ const warnings = [];
178
+ const childIds = new Map();
179
+ const wasRecomputing = internals.compute.recomputing;
180
+ internals.compute.recomputing = true; // suspends recompute and constraint checks for nested flushes (RFC 0009 §7.4)
181
+ const created = [];
182
+ try {
183
+ const vid = await materialize(host, model, input.id, input.values, {}, childIds);
184
+ created.push({ model: model, id: vid });
185
+ for (const [key, ids] of childIds) {
186
+ const target = internals.registry.get(model.fields[key].target ?? '').model;
187
+ for (const id of ids)
188
+ created.push({ model: target, id });
189
+ }
190
+ const values = host.values(model.name, vid);
191
+ // Only fields the user may read come back (and are compared): restricted ones stay out of the draft's result.
192
+ const keys = scalarKeys(model).filter((k) => k !== 'id' && canField(internals, model, k, 'read'));
193
+ // Loads nothing (every column is in the cache) but brings the currency / unit objects the reads need.
194
+ await host.load(model, [vid], {
195
+ fields: new Set(keys.filter((k) => model.columns[k] !== undefined)),
196
+ relations: new Map(),
197
+ });
198
+ const [beforeRow] = host.read(model, [vid], keys.filter((k) => values.has(k)));
199
+ // Handlers, cascading once per key: the draft's, then each new child row's for the fields it was given
200
+ // (feedback #10), so a line's product handler runs inside the order being edited and sees its values.
201
+ await runHandlers(host, model, vid, input.id ?? null, input.changed, warnings);
202
+ for (const [key, ids] of childIds) {
203
+ const field = model.fields[key];
204
+ const target = internals.registry.get(field.target ?? '').model;
205
+ const rows = (input.values[key]?.create ?? []);
206
+ for (const [i, cid] of ids.entries())
207
+ await runHandlers(host, target, cid, null, Object.keys(rows[i] ?? {}), warnings);
208
+ }
209
+ // Computes: children first, then the draft.
210
+ for (const [key, ids] of childIds) {
211
+ if (ids.length === 0)
212
+ continue;
213
+ const target = internals.registry.get(model.fields[key].target ?? '').model;
214
+ await computeAll(host, target, ids);
215
+ }
216
+ await computeAll(host, model, [vid]);
217
+ // Everything whose plain value differs from the draft as given (handler-set and computed fields).
218
+ const columnsOf = (m, ks) => new Set(ks.filter((k) => m.columns[k] !== undefined));
219
+ await host.load(model, [vid], { fields: columnsOf(model, keys), relations: new Map() }); // currency objects set by handlers
220
+ const [row] = host.read(model, [vid], keys);
221
+ const out = {};
222
+ for (const key of keys) {
223
+ if (JSON.stringify(row?.[key] ?? null) !== JSON.stringify(beforeRow?.[key] ?? null))
224
+ out[key] = row?.[key];
225
+ }
226
+ const children = {};
227
+ for (const [key, ids] of childIds) {
228
+ const target = internals.registry.get(model.fields[key].target ?? '').model;
229
+ const childKeys = scalarKeys(target).filter((k) => k !== 'id' && canField(internals, target, k, 'read'));
230
+ await host.load(target, ids, { fields: columnsOf(target, childKeys), relations: new Map() });
231
+ children[key] = host.read(target, ids, childKeys).map(({ id: _id, ...rest }) => rest);
232
+ }
233
+ return { values: out, warnings, children };
234
+ }
235
+ finally {
236
+ internals.compute.recomputing = wasRecomputing;
237
+ for (const { model: m, id } of created)
238
+ internals.forget(m.name, id);
239
+ }
240
+ }